Controlling Execution
Stack-Based Buffer Overflows · Exploitation Fundamentals track
10 min read
In this module
From Bug to Exploit
In the previous lesson, you saw how writing past a buffer clobbers the return address. A crashing program is bad, but what makes buffer overflows truly dangerous is that an attacker can choose what the return address is overwritten with. Instead of random corruption, the attacker carefully crafts the overflow data to redirect execution wherever they want.
Choosing the Target Address
If an attacker knows the stack layout, they can calculate exactly how many bytes to write before hitting the return address. The bytes filling the buffer are padding. The bytes landing on the return address are the payload: the address the attacker wants the CPU to jump to.
In the simulation below, the attacker overwrites the return address with the address of their own code (the injected label), causing execution to skip the normal return path entirely.
For the best simulation experience, use a desktop browser.
Assembly
Registers
ALU
Memory
| Address | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| 10 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| 20 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| 30 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| 40 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| 50 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| 60 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| 70 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| 80 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| 90 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| A0 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| B0 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| C0 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| D0 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| E0 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| F0 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
Pipeline
Cycle 0Step through and watch: the buffer slots at 200, 201 and 202 get filled with zeros (padding), then address 203 gets overwritten with 34 instead of 30. When the simulated return jumps through it, execution lands on injected (R2 = 66) and the normal return never runs. The attacker has chosen where execution goes.
Shellcode is a small sequence of machine instructions written by an attacker and injected into the target program's memory - typically inside the overflowed buffer itself. The name comes from early exploits whose goal was to spawn a command shell, giving the attacker interactive access to the system.
Worked Example: Finding the Offset on x86-64
On a real target you rarely know the layout in advance. You measure it. The trick is to send input where every 8-byte chunk is different, so whichever chunk ends up in the return address tells you its position.
Send this 48-character string to a program that copies it into a stack buffer:
AAAAAAAABBBBBBBBCCCCCCCCDDDDDDDDEEEEEEEEFFFFFFFFThe program crashes. In gdb, you might expect rip to show the overwritten value, but on x86-64 it usually doesn't. 0x4545454545454545 isn't a canonical address (the CPU only accepts addresses whose top 16 bits are all copies of bit 47), so ret faults before jumping, and rip still points at the ret itself. The value is still on top of the stack, though, waiting to be popped:
(gdb) x/gx $rsp0x7fffffffe0c8: 0x45454545454545450x45 is E, the fifth chunk. Four chunks of 8 bytes came before it, so the return address sits 32 bytes from the start of the buffer. In this function that's a 24-byte buffer plus 8 bytes of saved rbp, but you don't need to know that. The measurement tells you.
Now build the real payload: 32 bytes of padding, then the address you want, packed little-endian. To jump to a function at 0x401196:
"A" * 32 + 96 11 40 00 00 00 00 00The low byte 96 goes first. That's the step people most often get wrong, writing the address the way it reads instead of the way it's stored.
Predict: with the same input, the stack top shows 0x4646464646464646 instead. What's the offset to the return address?
40 bytes. 0x46 is F, the sixth chunk, so five full chunks (5 × 8 = 40 bytes) came before it. The buffer is either bigger in this build, or the compiler added padding or a canary to the frame. Measure each target; never reuse an offset from a different build.
The pwntools Workflow
Doing this by hand works once. By the third binary you'll want a script, and the standard tool for that is pwntools, a Python library built for exactly this job. Everything below runs against a non-PIE x86-64 binary called vuln with a win() function, the shape of the Stack Smash lab.
Step 1: load the binary
from pwn import *
elf = context.binary = ELF('./vuln')ELF parses the file: its symbols, its sections, its PLT and GOT. Assigning it to context.binary also tells pwntools the target is 64-bit little-endian, which every packing helper afterwards relies on. elf.sym.win (or elf.symbols['win']) is now the address of win.
Step 2: measure the offset with cyclic
The hand-made AAAAAAAABBBBBBBB... string from earlier runs out after 26 chunks and can't tell you where inside a chunk you landed. cyclic generates a de Bruijn sequence instead: a string in which every run of n bytes appears exactly once.
io = process(elf.path)io.sendline(cyclic(200, n=8))io.wait()Pass n=8 on x86-64. The default is n=4, sized for 32-bit registers. With n=8 the string starts aaaaaaaabaaaaaaacaaaaaaa..., so any 8 bytes you pull out of a crashed frame identify a unique position. Attach gdb (or run the binary under it with the same input), and once more read the top of the stack, since the non-canonical value makes ret fault before it jumps:
(gdb) x/gx $rsp0x7fffffffe0c8: 0x616161616161616a>>> cyclic_find(0x616161616161616a, n=8)720x6a is j, the tenth letter, so nine 8-byte chunks came first: 72 bytes. That matches the lab's 64-byte buffer plus 8 bytes of saved rbp. If core dumps are enabled (ulimit -c unlimited), pwntools can skip gdb entirely: core = io.corefile loads the dump, and cyclic_find(core.read(core.rsp, 8), n=8) does the same lookup.
Step 3: pack the address
payload = b'A' * 72 + p64(elf.sym.win)p64 packs an integer into 8 little-endian bytes, so p64(0x401196) is 96 11 40 00 00 00 00 00, exactly what you assembled by hand above. Its inverse, u64, turns 8 bytes back into an integer, which you'll use when a program leaks an address to you. flat is the shorthand once payloads grow:
payload = flat({72: elf.sym.win})A dictionary maps offsets to values. Integers are packed to the word size from context, and every byte you didn't specify is filled from a cyclic pattern. Watch out: the filler uses the default 4-byte pattern (aaaabaaacaaa...), so if the exploit crashes in a strange place, look up what landed in a register with plain cyclic_find on its low 4 bytes, without n=8.
Step 4: local and remote with one script
if args.REMOTE: io = remote(args.HOST, int(args.PORT))else: io = process(elf.path)
io.recvuntil(b'name: ')io.sendline(payload)io.interactive()process starts the binary locally and remote opens a TCP connection, and both return a tube with the same methods: send, sendline, recvuntil, recvline, interactive. Run python3 exploit.py to test locally and python3 exploit.py REMOTE HOST=lab.example PORT=31337 against the real service. args picks up any upper-case word from the command line. Same payload, same code path, which is the point: an exploit you debugged locally should behave identically remotely, provided the binary and its libc are the same.
Step 5: let ROP do the bookkeeping
rop = ROP(elf)rop.raw(rop.find_gadget(['ret']).address)rop.call('win')print(rop.dump())payload = flat({72: rop.chain()})ROP scans the binary for gadgets and lays out a chain for you. rop.dump() prints each stack slot with what it's for, which is the fastest way to spot a mistake. The extra ret at the front is there for stack alignment, and it deserves a proper explanation.
The 16-Byte Alignment Trap
The System V AMD64 ABI, the calling convention Linux uses on x86-64, says rsp must be a multiple of 16 at every call instruction. The call then pushes an 8-byte return address, so every function starts with rsp ending in 8 in hex. Compilers rely on that. Some SSE instructions, movaps among them, fault outright on a 16-byte memory operand that isn't 16-byte aligned, and glibc's system contains one that writes to the stack.
A legitimate call win would push 8 bytes. Your overflow reaches win through ret, which pops 8 bytes instead, so win starts with rsp off by 8. If win only prints a flag you may never notice. If it calls system("/bin/sh"), the program dies inside system with a segmentation fault on a movaps instruction, and plenty of people have spent an evening convinced their offset was wrong. One ret gadget before win fixes it: it pops one extra slot, moving rsp by 8, and does nothing else. A ret is the single byte c3, so every binary has hundreds of them.
Predict: the payload is flat({72: elf.sym.win}). In vuln, the slot holding the return address is at an address ending in 8. What does rsp end in when win starts, and is that aligned?
It ends in 0, and that's misaligned. vuln's ret pops the slot at ...8, leaving rsp 8 bytes higher, at ...0. A function entered by call expects ...8. Put a ret gadget in the slot at ...8 and win in the one after it: the first ret jumps to the gadget, the gadget's ret pops win, and rsp lands on ...8 as the ABI requires.
The Full Attack Chain
A classic stack buffer overflow exploit follows three steps:
- Find the vulnerability - a function that copies input into a fixed-size stack buffer without checking the length.
- Craft the payload - fill the buffer with shellcode (the attacker's instructions), then overwrite the return address with the address of the buffer itself.
- Trigger the return - when the function executes RET, the CPU pops the corrupted return address and jumps into the buffer, executing the attacker's shellcode.
The attacker's injected code now runs with whatever privileges the vulnerable program had. If the program runs as an administrator, the attacker gains administrator access.
On a modern system, step 2 usually changes. The stack is marked non-executable, so jumping into shellcode on the stack just crashes. Attackers instead point the return address at code that already exists: a function the program never meant to call (a "win" function in a CTF), or a chain of existing instruction fragments, which is where Return-Oriented Programming picks up.
Why This Works
The CPU has no concept of "code" versus "data." It fetches bytes from wherever the program counter points and executes them. If the return address points into the buffer, the CPU dutifully executes whatever bytes are there, including the attacker's carefully assembled shellcode.
Labs for This Lesson
The Stack Smash: Basic Buffer Overflow lab is the workflow above with real stakes: find the offset, pack the address of win, capture the flag. Write the pwntools script even though a one-line python3 -c would do; you'll reuse it for every lab after this one. Stack Smash: Function Pointer Overwrite then asks you to hit a pointer before the return address, which needs exactly one change to the flat dictionary.
Try the Simulations
Safe Buffer Write
A function writes exactly into its 3-slot buffer on the stack. The return address is untouched and RET works normally.
Buffer Overflow
Write one element too many into a 3-slot buffer. The fourth write clobbers the return address - the CPU would jump to the wrong place.
Controlled Overflow
An attacker deliberately overwrites the return address with a chosen value, redirecting execution to their target address.