Part 2 of 7 · 3 min read
Buffer overflow
Think of a row of mail slots, each sized for one letter. A clerk who pushes a long parcel into the first slot also pushes against the slots beside it and damages their contents. The analogy stops in one place: the neighbouring slots of a program hold data such as the address where the function will return, and a damaged address makes the program jump somewhere new.
In plain words: A buffer overflow happens when a program writes more bytes into an array than the array holds, so the extra bytes land in the memory beside it. In C, functions such as strcpy copy until a zero byte and never check the size of the target. On the stack (Level 1), a local array sits near other values of the same function call, among them the return address, the place where the function continues when it ends. If the extra bytes change that value, the program continues at an address chosen by whoever supplied the input. If the program runs with high rights (page 2), that person gains them. The earlier pages made rights small, and this page explains why a bug can still wreck the limit.
A worked example. The program below has this bug on purpose. Its buffer holds 8 bytes, and the copy does not check the length.
#include <stdio.h>
#include <string.h>
static void copy(const char *s) {
char buf[8];
strcpy(buf, s); /* no length check: the bug */
printf("copied: %s\n", buf);
}
int main(int argc, char **argv) {
copy(argc > 1 ? argv[1] : "hi");
puts("returned normally");
return 0;
}
Run with the short input hi it prints copied: hi and returned normally. Run with a 48-character input and no protection (compiled with -fno-stack-protector), it ended with a segmentation fault and exit status 139. The 40 extra bytes overwrote the saved return address, and the return went to an address that is not code. A different input could have chosen the address on purpose, and that is the attack. This page stops at the crash.
The key lines. The bug is the missing length check. Everything else on this page makes the bug harder to use, and only fixing the check removes it.
Buffer overflow
A buffer overflow is a memory error in which a program writes past the end of an array or other fixed-size block, so the extra data overwrites neighbouring memory. When that memory holds a return address or a function pointer, the input can change what the program runs.
Example: copying a 48-byte string into an 8-byte array with strcpy overwrites 40 bytes beyond the array.
Check yourself:
1. What makes strcpy unsafe for a fixed-size array?
2. Which value near a local array makes an overflow dangerous?
3. Why can an attacker with no rights still gain rights through such a bug?