Hacking - The Art of Exploitation, 2nd Edition

(Romina) #1

170 0x300


This is an interesting detail that should be remembered. It certainly
would be a lot more useful if there were a way to control either the number
of arguments passed to or expected by a format function. Luckily, there is a
fairly common programming mistake that allows for the latter.

0x352 The Format String Vulnerability......................................................


Sometimes programmers use printf(string) instead of printf("%s", string) to
print strings. Functionally, this works fine. The format function is passed the
address of the string, as opposed to the address of a format string, and it iterates
through the string, printing each character. Examples of both methods are
shown in fmt_vuln.c.

fmt_vuln.c


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {
char text[1024];
static int test_val = -72;

if(argc < 2) {
printf("Usage: %s <text to print>\n", argv[0]);
exit(0);
}
strcpy(text, argv[1]);

printf("The right way to print user-controlled input:\n");
printf("%s", text);

printf("\nThe wrong way to print user-controlled input:\n");
printf(text);

printf("\n");

// Debug output
printf("[*] test_val @ 0x%08x = %d 0x%08x\n", &test_val, test_val,
test_val);

exit(0);
}

The following output shows the compilation and execution of fmt_vuln.c.


reader@hacking:~/booksrc $ gcc -o fmt_vuln fmt_vuln.c
reader@hacking:~/booksrc $ sudo chown root:root ./fmt_vuln
reader@hacking:~/booksrc $ sudo chmod u+s ./fmt_vuln
reader@hacking:~/booksrc $ ./fmt_vuln testing
The right way to print user-controlled input:
testing

Free download pdf