A format string bug happens when a program passes user input directly as the first argument to printf: printf(buffer) instead of printf("%s", buffer). It looks harmless — the program just echoes what you typed — until you type format specifiers yourself.
Spotting the bug
Send a few format specifiers as input and see what comes back:
$ ./vuln
Enter your name: %p %p %p %p
Hello 0x7ffd5e1a2b40 (nil) 0x7f3c1a2d4a37 0x5
If the program prints hex values instead of the literal text %p %p %p %p, the input is being interpreted as a format string. printf believes it was given arguments to print, so it reads them from wherever arguments would be — registers and then the stack.
Walking the stack with %p
Each %p prints the next "argument" as a pointer. On x86-64, the first five come from registers, and from there on you're reading the stack. To read a specific position directly, use the positional form %N$p:
%6$p # 6th argument → first value on the stack (x86-64)
%7$p # the next one
A quick loop over positions 1 to 50 often turns up a flag stored in a local variable: look for values that decode to ASCII, like 0x7b4654436f636970, which is picoCTF{ backwards (little-endian).
Reading strings with %s
%s treats the argument as a pointer and prints the string it points to. If the stack holds a pointer to the flag — common when the program read flag.txt into a buffer — then %N$s at the right position prints it directly. A wrong position usually crashes the program, so try positions one at a time.
Automating it with pwntools
from pwn import *
for i in range(1, 40):
p = process("./vuln")
p.sendline(f"%{i}$p".encode())
print(i, p.recvall().decode(errors="ignore"))
p.close()
Running one connection per offset keeps crashes from stopping the loop. Once you spot interesting values, convert them with p64(value) to see the bytes in order.
Beyond leaking
The %n specifier writes the number of characters printed so far to an address taken from the stack — which turns a read bug into a write bug, used to overwrite a GOT entry or a return address. That's the next step after mastering leaks; pwntools' fmtstr_payload() builds those payloads for you.
Wrapping up
The fix is one argument: printf("%s", buffer). When you see the bug, start with %p to map the stack, then %s to follow pointers. For the tooling, see our guides to pwntools and GDB with pwndbg.