C
Buffer overflow
Learn the buffer overflow vulnerability.
What is a buffer overflow?
A buffer overflow happens when a write goes past an array's bounds. It is a common security flaw, especially with unbounded functions like strcpy and gets.
C arrays do no bounds checking; writing a ninth byte to char buf[8] is a memory error the compiler cannot catch. In a stack overflow an attacker can overwrite the return address and hijack control flow. That is why modern compilers add protections like canary and ASLR. Safe functions (fgets, strncpy) take an explicit size.
Stack layout and return address
On a function call the stack holds local variables, saved registers and the return address, in that order. A buffer overflow breaks this layout.
If a local array overflows, the next bytes overwrite other variables, then the return address. An attacker replacing it with a malicious address makes the function jump there on return. This is why strncpy replaces strcpy and fgets replaces gets. The compiler's -fstack-protector option places a random canary before the return address; on return, a mismatch stops the program.
Exercise Check buffer bounds
Define void check_buf(const char *name, int size, int used). If used > size, print printf("%s: OVERFLOW\n", name);; otherwise print printf("%s: OK\n", name);. In main call it three times: ("buf", 8, 5), ("input", 16, 16), ("dst", 4, 8).
Show example solution
#include <stdio.h>
void check_buf(const char *name, int size, int used) {
if (used > size) {
printf("%s: OVERFLOW\n", name);
} else {
printf("%s: OK\n", name);
}
}
int main(void) {
check_buf("buf", 8, 5);
check_buf("input", 16, 16);
check_buf("dst", 4, 8);
return 0;
}
Test yourself
-
When does a buffer overflow occur?
- When the CPU is fast
- When memory is empty
- When a buffer bound is exceeded
- When a file is closed
Show answer
When a buffer bound is exceeded — Writing past the array's capacity causes an overflow.
-
Complete the unsafe strcpy call
char buf[8]; strcpy(buf, ____);
Show answer
char buf[8]; strcpy(buf, input);
-
Match stack concepts
- buffer
- Buffer
- stack
- Stack
- return address
- Return address
- overflow
- Overflow
Next lesson: Stack canary