3 ms·
Background: A %n format specifier in a printf call stores the number of characters written so far into a specified variable. For example: #include <stdio.
by _kst_ 2y ago
Background: A %n format specifier in a printf call stores the number of characters written so far into a specified variable. For example:
#include <stdio.h>
int main(void) {
int count;
printf("%s%n\n", "hello, world", &count);
printf("count = %d\n", count);
}
The output is:
hello, world
count = 12
%n can be exploited to write data to an arbitrary memory location, but only if the format string is something other than a string literal.
%n can be exploited, but it's entirely possible to use it safely.
- lifthrasiir 2y agoI think another problem exposed by %n was that you can't easily compose format strings. Sure, `printf(str)` where `str` is a user input would be easy to detect and can be automatically turned into `printf("%s", str)` with some macro hack, but `printf(fmt, ...)` where `fmt` is composed from multiple partial format strings would be harder to reason.