Skip to content

Stack Buffer Overflow

3. The classic stack buffer overflow

Imagine a simple C function like this:

#include <stdio.h>
#include <string.h>

void reachMe() {
    printf("You reached reachMe()! Here's the flag.\n");
    // print flag, or something important
}

void vuln() {
    char buf[32]; // fixed-size buffer

    printf("Enter your input:\n");
    gets(buf);    // SUPER unsafe: no bounds checking
    printf("You entered: %s\n", buf);
}

int main() {
    vuln();
    return 0;
}
  • It declares a small character array as a buffer, for example 32 bytes (char buf[32]).
  • It then reads user input into that buffer without checking the length, using something unsafe like gets().

If you type in more than 32 characters, the extra characters don’t just disappear. They keep being written into memory past the buffer:

  1. First, they overwrite other local variables,
  2. Then they overwrite the saved base pointer (the saved RBP),
  3. And finally, they overwrite the saved return address. If you carefully control those extra characters, you can:
  4. Leave the first part as random junk or padding,
  5. And then place a fake return address – the address of some function you want to run.

For example, the binary might contain a function named “reachMe()” that is never called normally. The challenge is: “make the program call reachMe() by exploiting the overflow.”

So your plan is:

  1. Fill the buffer until you reach the return address.
  2. Overwrite the return address with the address of reachMe().

When the vulnerable function finishes and executes ret, instead of going back to its caller, it jumps straight into reachMe().