2

when trying to follow a tutorial on string exploits in C, I had the following questions which I do not seem to find an answer to.

  1. "If we were to pass the string AAAA%10$n, we would write the value 4 to the address 0x41414141!". This is an excerpt from a tutorial. But how come we write a 4? I do realize that AAAA in hex becomes 0x41414141 but then %10$n is written. What does this 10 mean, what does this dollar mean and where does the 4 come from?
  2. The final solution to an exploit for a wargame is given below. It however seems I can completely drop the %238x (what was the purpose of this anyway?) and here the end of the string is %10$hn. what does 'hn' here mean? The C reference documentation refers to 'hn' as "unsigned short *". Is this even a datatype?

$(python -c 'print "\x40\x99\x04\x08%238x%10$hn"')

Wouter Vandenputte
  • 1,948
  • 4
  • 26
  • 50

2 Answers2

5

1) %10$n isn't written, it is a format specifier. And it has no output, but only the side effect to write the number of outputted chars up to this specifier to an integer provided by the 10th argument to printf. Since you didn't provide 10 arguments to printf, it fetches something other from the stack and uses it as address. The tutorial seems to assume, that AAAA is located there and interpreted as address 0x41414141.

2) %hn means to not write an integer (4-byte usually), but only a short value (usually 2 bytes) at the given address. It is easier, to write 2 2-byte values with this method instead of 1 4-byte value, since you had to print up to 4M chars to write the value you want.

Ctx
  • 18,090
  • 24
  • 36
  • 51
0

Adding to ctx's answer, the value 4 comes from the length of the string before the parameter %n; in this case, its AAAA is 4 characters long.