Format String Vulnerabilities

When a C program lets you control the format string passed to printf, you don't just get to choose what gets printed. You get to read the stack, dereference arbitrary memory, and even write to arbitrary addresses. This is the bug class that makes printf secretly one of the most dangerous functions in the C library.

1. The Bug: User-Controlled Format String

The bug isn't in printf. printf does exactly what its docs say. The bug is when a programmer passes user input as the format string instead of as an argument.

2. Leaking the Stack with %x

Each %x in the format string makes printf pull the next argument from where it expects arguments to live. If you didn't provide any arguments, it pulls whatever happens to be sitting in those stack slots: leftover values from earlier function calls, pointers, secrets, anything.

3. Arbitrary Read with %s

%s doesn't just read the next stack slot, it treats that slot as a pointer and dereferences it, reading bytes from that address until a null byte. If the attacker controls what's at that stack slot, they can read any readable memory.

4. Arbitrary Write with %n

Here's where it goes from "info leak" to "remote code execution". The %n specifier doesn't print anything. It WRITES the number of characters printed so far into the address on the stack. Control the address, control what gets written.

5. Putting It Together: Why This Owns You

Now combine the read primitive and the write primitive. A typical exploit chains them: leak a function pointer to defeat ASLR, then overwrite a different function pointer to redirect control. Below, the same techniques described step by step against a hypothetical target.