Hacking - The Art of Exploitation, 2nd Edition

(Romina) #1
Exploitation 169

address operator is used to write this data into the variables count_one and
count_two, respectively. The values are then outputted, revealing that 46 bytes
are found before the first %n and 113 before the second.
The stack example at the end is a convenient segue into an explanation
of the stack’s role with format strings:

printf("A is %d and is at %08x. B is %x.\n", A, &A, B);

When this printf() function is called (as with any function), the argu-
ments are pushed to the stack in reverse order. First the value of B, then the
address of A, then the value of A, and finally the address of the format string.
The stack will look like the diagram here.

format parameters? Try removing the last argument from the printf()
line for the stack example so it matches the line shown below.

printf("A is %d and is at %08x. B is %x.\n", A, &A);

This can be done in an editor or with a little bit of sed magic.


reader@hacking:~/booksrc $ sed -e 's/, B)/)/' fmt_uncommon.c > fmt_uncommon2.c
reader@hacking:~/booksrc $ diff fmt_uncommon.c fmt_uncommon2.c
14c14
< printf("A is %d and is at %08x. B is %x.\n", A, &A, B);



printf("A is %d and is at %08x. B is %x.\n", A, &A);
reader@hacking:~/booksrc $ gcc fmt_uncommon2.c
reader@hacking:~/booksrc $ ./a.out
The number of bytes written up to this point X is being stored in count_one, and the number of
bytes up to here X is being stored in count_two.
count_one: 46
count_two: 113
A is 5 and is at bffffc24. B is b7fd6ff4.
reader@hacking:~/booksrc $



The result is b7fd6ff4. What the hell is b7fd6ff4? It turns out that since
there wasn’t a value pushed to the stack, the format function just pulled data
from where the third argument should have been (by adding to the current
frame pointer). This means 0xb7fd6ff4 is the first value found below the
stack frame for the format function.

The format function iterates through the
format string one character at a time. If the
character isn’t the beginning of a format
parameter (which is designated by the per-
cent sign), the character is copied to the
output. If a format parameter is encountered,
the appropriate action is taken, using the
argument in the stack corresponding to that
parameter.
But what if only two arguments are pushed
to the stack with a format string that uses three

Address of A

Value of B

Bottom of the Stack

Value of A

Address of format string

Top of the Stack
Free download pdf