Systems Security & Exploitation

a stack buffer overflow

Imagine a hotel mailbox row where each guest's slot holds exactly ten letters. If the front desk keeps stuffing letters into one slot past the tenth, they spill over into the NEXT guest's slot, scrambling their mail. A stack buffer overflow is the same accident in memory: a program writes more bytes into a fixed-size local array than the array can hold, and the extra bytes overwrite whatever sits next to it in the same stack frame.

Here is the concrete picture. When a function runs, its local variables live in a region of process memory called the stack (this is the stack as a MEMORY REGION that grows and shrinks with calls, not the LIFO data structure). The compiler reserves, say, char buf[16] for an input. If the code does something like strcpy(buf, attacker_input) with a 40-byte input, bytes 17 through 40 are written PAST the end of buf. Because the stack also stores saved registers and the function's return address near the locals, those overflowing bytes can clobber the return address — the place the CPU jumps to when the function finishes. An attacker who controls the input can therefore control where execution goes next.

It matters because this is the oldest and most studied memory-corruption bug in C and C++, languages that do no automatic bounds checking. The root cause is almost always a missing or wrong length check on a copy: strcpy(), gets(), sprintf(), or a hand-written loop that trusts the input size. The honest framing: the overflow itself is undefined behavior, and the C standard imposes no requirement on what happens — the visible crash, silent corruption, or hijack are all permitted consequences, not guaranteed ones.

void greet(char *name) { char buf[16]; strcpy(buf, name); // no length check: name longer than 15 overflows buf printf("hi %s\n", buf); } // greet of a 64-byte string overwrites saved registers and the return address

strcpy copies until a null terminator, with no regard for buf's size — the classic stack overflow primitive.

A stack overflow (this bug) is different from stack EXHAUSTION (running out of stack from too-deep recursion) — both are casually called 'stack overflow', but only the first overwrites neighbouring data.

Also called
stack-based buffer overflowstack overrun堆疊型緩衝區溢位