linux – Help with Format String Exploit

I'm working on a 32-bit binary that reads a user's input and uses it as a format string for printf.

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

The problem is that I can not overwrite the address with the expected value.

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

Example:

Memory address to be overwritten: 0xaabbccdd

$ echo -n $ (python -c & # 39; print " xdd  xcc  xbb  xaa" + "% x" * 6 & # 39;) | ./compartment

  ̻ ffffd0a81814ffffd34556557000aabbccdd

Therefore, I know that when I enter% x, 6 times, the address I want to overwrite will appear on the stack. Then, using 6% x, I can interact with this memory address.

To read the content of 0xaabbccdd, I would:

$ echo -n $ (python -c & # 39; print " xdd  xcc  xbb  xaa" + "% x" * 5 + "% & # 39;) | ./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 is:

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

then,% n should write (20 + 4) = 24 bytes in memory address 0xaabbccdd with the following format string:

echo -n $ (python -c & # 39; print " xdd  xcc  xbb  xaa" + "% x" * 5 + "% n & # 39;) | ./bin

Instead, it overwrites the value, 0x20.

I can not understand, why those extra 2 bytes?

It is assumed that% n writes the number of bytes printed by printf so far.