Format String Vulnerabilities
What you'll learn: How attackers exploit misused format specifiers to read memory, write arbitrary values, and hijack program execution.
What is a Format String Vulnerability?
A format string vulnerability occurs when user-controlled input is passed directly as the format argument to functions like printf(), sprintf(), or fprintf(). Normally, these functions expect a hardcoded format string (like "Hello %s\n"). When attackers control this string, they can use format specifiers as commands to read from or write to memory.
Think of it like giving someone the instruction manual for your safe instead of just the combination—they suddenly control far more than intended.
How It Works
Reading Memory
Using %x or %p specifiers, attackers can dump values from the stack:
// Vulnerable code
printf(user_input); // user_input = "%x %x %x %x"
// Leaks stack values
Writing Memory
The %n specifier writes the number of bytes printed so far to a memory address on the stack. By controlling the format string, attackers can write arbitrary values to arbitrary locations:
// Attacker crafts: "\x10\x20\x30\x40%100x%n"
// Writes value 100+ to address 0x40302010
Achieving Code Execution
By overwriting function pointers, return addresses, or Global Offset Table (GOT) entries, attackers redirect execution flow to shellcode or other malicious code.
The Attack Chain
- Leak information using
%xor%sto find stack layout and addresses - Craft payload to position target address on stack
- Use
%nto write to that address (overwrite return pointer, function pointer, etc.) - Trigger execution to hijack control flow
Key Takeaway: Format string vulnerabilities transform a simple output function into a powerful read/write primitive, enabling memory disclosure and arbitrary code execution—always use hardcoded format strings and never trust user input as format arguments.