BUFFER OVERFLOW
Writing past the end rewrites control flow
A function copies its input into an 8-byte stack buffer with strcpy and no length check. It is compiled with -fstack-protector, which places a random canary value between the buffer and the saved frame pointer. A 32-character input overwrites the canary, the saved frame pointer and the return address. What happens?
A function’s local buffer lives on the stack, right below the saved frame pointer and the return address. strcpy copies until it finds a NUL. It has no idea how big the destination is. Give it a long enough input and it walks out of the buffer and over the return address. When the function returns, it jumps wherever those bytes now point.
There are two kinds of defence. A stack canary detects the overwrite in the epilogue and aborts before ret. A bounded copy never makes the overwrite at all.
void parse(const char *input) {
char buf[8];
strcpy(buf, input); // copies until NUL: no idea how big buf is
}
// Frame, low → high: buf[0..7] | saved fp | return address | caller...
// 16 chars + NUL already reach the return address.void parse(const char *input) {
char buf[8];
safe_copy(buf, sizeof buf, input); // writes at most 7 chars + NUL
}
size_t safe_copy(char *dst, size_t n, const char *src) {
if (n == 0) return 0;
size_t i = 0;
for (; i + 1 < n && src[i]; i++) dst[i] = src[i];
dst[i] = '\0';
return i;
}
// Defense in depth (none replaces the bounds check):
// -fstack-protector canary between locals and saved fp/ret; checked before ret
// ASLR, NX stack, CFI / shadow stacks make a corrupted ret harder to use Watch the return-address row and the invariant strip. NO PROTECTION jumps to 0xATTACKER. STACK CANARY takes the same 32 bytes, the return address is just as overwritten, and the program aborts instead of returning. BOUNDED COPY writes 8 bytes and returns to main. Drag INPUT LENGTH and watch each region fill.
No canary, plain strcpy. Find the shortest INPUT LENGTH whose copy first touches the return address: exactly one byte of it overwritten.
GOAL: exactly 1 of the 8 return-address bytes is overwritten
Write safeCopy(dst, dstSize, src). dst is an array of single characters; src is a string. Copy as much of src as fits, never write at or past index dstSize, and always NUL-terminate ('\0') when dstSize > 0. Return the number of characters copied. The grader puts guard cells right after dst.
C and C++ parsers for network input, file formats and firmware: strcpy, gets, sprintf, and memcpy with a length field the attacker controls. The symptom is a crash with *** stack smashing detected *** or a segfault at a nonsense address.
“What is a stack buffer overflow and how do you defend against it?” Draw the frame (buffer, canary, saved frame pointer, return address), say why the overwrite redirects control on ret, and name the layers: bounds-checked copies and memory-safe languages fix it; canaries, ASLR, NX and CFI mitigate it.
USED IN
Chapters that build on this lesson.