Format String Bugs (CWE-134)
printf(fmt, …) trusts its first argument completely: every % directive in it tells printf to fetch another argument, and printf has no way to know how many arguments the caller really passed. When a program writes printf(user_input) instead of printf("%s", user_input), the user's text is the format. Ordinary text prints normally, so the bug survives every test written with ordinary text. A %p or %x in the input makes printf fetch arguments that were never passed (whatever is in the argument registers and on the stack), which leaks pointers and secrets; the %n directive, which writes the number of characters printed so far through a pointer argument, turns the same bug into a memory write. Format string bugs were a major vulnerability class around 2000 (wu-ftpd, many daemons that passed log messages to syslog); Clang and distribution builds of GCC (Ubuntu's, for example) now warn about them by default, which makes them rare in maintained code and still common in old or embedded code.
The bug in a toy program
The toy logs audit messages. The message is built elsewhere from user input and passed straight to printf. The function has a lab-only "secret" local, session_key = 0x5ec2e7, to show what a leak looks like. The second message is what a curious user might type: a row of %p directives, which print arguments as pointers. This is the harmless, read-only form of the bug:
cat > fmt.c <<'SRC'
#include <stdio.h>
static void audit(const char *msg, long uid, long code) {
long session_key = 0x5ec2e7; /* a "secret" local, lab-only */
(void)session_key;
printf(msg); /* BUG: user data used as the format */
printf("\n");
}
int main(void) {
audit("login ok for 1001", 1001, 7);
audit("%p %p %p %p %p %p %p %p %p %p %p", 1001, 7);
return 0;
}
SRC
gcc -g -O0 -Wall fmt.c -o fmt 2>&1 | grep warning
./fmt
echo "== which directive printed the secret?"
./fmt | tail -1 | tr ' ' '\n' | grep -n 5ec2e7fmt.c:6:5: warning: format not a string literal and no format arguments [-Wformat-security]
login ok for 1001
0x3e9 0x7 0x565fae6182b2 0x31 (nil) (nil) 0x7 0x3e9 0x565fa1144020 (nil) 0x5ec2e7
== which directive printed the secret?
11:0x5ec2e7
What the output means
On x86-64 Linux, printf's first argument (the format) is in rdi; the next five come from the registers rsi, rdx, rcx, r8, r9, and further ones from the caller's stack. Each %p takes the next one, whether or not it exists:
| Directive | Came from | Value | What it is |
|---|---|---|---|
| 1, 2 | rsi, rdx |
0x3e9, 0x7 |
uid = 1001 and code = 7, still in registers from the call to audit |
| 3 | rcx |
0x…2b2 |
a heap pointer left in rcx by the previous printf: the end of the text it wrote into stdout's buffer. It tells an attacker where the heap is |
| 4–6 | r8, r9, stack |
0x31, (nil) |
leftovers |
| 7–10 | audit's stack frame |
0x7, 0x3e9, 0x…020, (nil) |
the saved copies of code and uid, the saved msg pointer (an address inside the program's read-only data: it reveals where PIE placed the program, which defeats ASLR), padding |
| 11 | audit's stack frame |
0x5ec2e7 |
the secret local |
So eleven two-character directives reveal a heap address, an address inside the program and a local secret. Real targets leak canaries, saved return addresses and heap pointers the same way. Replacing %p with %n would make printf write through one of those stack values used as a pointer; this course doesn't demonstrate it, but that is why this class was rated as code execution, not just disclosure.
The compiler saw it coming: warning: format not a string literal and no format arguments [-Wformat-security]. Ubuntu's GCC enables -Wformat -Wformat-security by default.
Root cause
Data was passed where code was expected. A format string is a tiny program that printf interprets; letting the user supply it is the same mistake as SQL built by concatenation (Web Application Security) or eval on user input.
The fix
Never pass a non-constant string as a format. Use a constant format with %s, or a function that doesn't interpret formats at all:
#include <stdio.h>
static void audit(const char *msg, long uid, long code) {
printf("%s\n", msg); /* the format is a constant */
fputs(msg, stdout); fputc('\n', stdout); /* or: no format at all */
printf("audit uid=%ld code=%ld msg=\"%s\"\n", uid, code, msg); /* structured */
}
int main(void) {
audit("login ok for 1001", 1001, 7);
audit("%p %p %p %n", 1001, 7);
return 0;
}login ok for 1001
login ok for 1001
audit uid=1001 code=7 msg="login ok for 1001"
%p %p %p %n
%p %p %p %n
audit uid=1001 code=7 msg="%p %p %p %n"
The directives are printed as text. The structured version is better still: a log line with labelled fields can't be confused with the message.
For your own logging wrappers, tell the compiler that an argument is a format, so the same warnings apply to every caller:
void log_msg(int level, const char *fmt, ...) __attribute__((format(printf, 2, 3)));How format string bugs are detected
- Compiler warnings:
-Wformat -Wformat-security(GCC and Clang),-Wformat-nonliteral(stricter: any non-literal format), and-Werror=format-securityin CI. The Compiler Warnings lesson collects the set. - Run-time: glibc's
FORTIFY_SOURCE(level 2 and above) aborts with*** %n in writable segment detected ***when a format containing%nlives in writable memory, which is where user-supplied formats are. Windows' CRT disables%nby default. - Review and grep:
printf(,fprintf(…, x),sprintf,snprintf,syslog(priority, x),err/warnand custom wrappers whose format argument is a variable. CodeQL has a query for uncontrolled format strings. - Testing: put
%p%p%p%s%s%sin every text input of a fuzzing dictionary;%son garbage pointers crashes, which reveals the bug.
The CWE
CWE-134: Use of Externally-Controlled Format String. Leaks are also CWE-200; writes through %n are out-of-bounds writes (CWE-787).
Pitfalls
syslog(LOG_INFO, msg)has the same signature shape asprintfand the same bug; so doessnprintf(buf, n, user).- "The input is validated": a filter that removes
%breaks legitimate messages and is easy to bypass (multi-byte encodings, other directives). Fix the call. - Format strings in other languages: Python's
str.formatwith user formats can read object attributes ({0.__class__}), and C#'sString.Formatthrows on malformed input. Different impact, same rule: formats are code.
Practice
1. Why did the first message, "login ok for 1001", print correctly?
It contains no %, so printf printed it literally and fetched no arguments. That is why ordinary tests never reveal the bug.
2. How could you make the leak reach the secret with fewer characters?
glibc supports positional arguments: %11$p prints the 11th argument directly. That is also why limiting the input length doesn't fix the bug.
3. A colleague fixes the bug with printf(msg, NULL). Is it fixed?
No. The format is still user data; the extra NULL only changes what the first %p prints. Use printf("%s", msg).
Test yourself
Why does printf(user_input) leak data when the input contains %p?
- printf reads the input twice
- Each %p makes printf fetch another argument from registers and the stack, whether or not one was passed
- %p is an error
- The compiler adds arguments
Which of the leaked values defeats ASLR?
- 0x3e9
- 0x7
- The saved msg pointer, an address inside the program's read-only data
- (nil)
Which compiler option makes this bug fail the build?
- -O2
- -Werror=format-security
- -fstack-protector
- -g
Which directive turns a format string leak into a memory write?
- %s
- %x
- %n
- %%