hacktricks/reversing-and-exploiting/linux-exploiting-basic-esp/format-strings/README.md

5.1 KiB

Format Strings

Learn AWS hacking from zero to hero with htARTE (HackTricks AWS Red Team Expert)!

Basic Information

In C printf is function that can be used to print some string. The first parameter this function expects is the raw text with the formatters. The following parameters expected are the values to substitute the formatters from the raw text.

The vulnerability appears when an attacker text is put as the first argument to this function. The attacker will be able to craft a special input abusing the printf format string capabilities to write any data in any address. Being able this way to execute arbitrary code.

Formatters:

%08x —> 8 hex bytes
%d —> Entire
%u —> Unsigned
%s —> String
%n —> Number of written bytes
%hn —> Occupies 2 bytes instead of 4
<n>$X —> Direct access, Example: ("%3$d", var1, var2, var3) —> Access to var3

%n writes the number of written bytes in the indicated address. Writing as much bytes as the hex number we need to write is how you can write any data.

AAAA%.6000d%4\$n —> Write 6004 in the address indicated by the 4º param
AAAA.%500\$08x —> Param at offset 500

Exploit Flow

As explained before this vulnerability allows to write anything in any address (arbitrary write).

The goal is going to be to overwrite the address of a function in the GOT table that is going to be called later. Ideally we could set the address to a shellcode located in a executable section, but highly probable you won't be able to write a shellcode in a executable section.
So a different option is to overwrite a function that receives its arguments from the user and point it to the system function.

To write the address, usually 2 steps are done: You first writes 2Bytes of the address and then the other 2. To do so $hn is used.

HOB is called to the 2 higher bytes of the address
LOB is called to the 2 lower bytes of the address

So, because of how format string works you need to write first the smallest of [HOB, LOB] and then the other one.

If HOB < LOB
[address+2][address]%.[HOB-8]x%[offset]\$hn%.[LOB-HOB]x%[offset+1]

If HOB > LOB
[address+2][address]%.[LOB-8]x%[offset+1]\$hn%.[HOB-LOB]x%[offset]

HOB LOB HOB_shellcode-8 NºParam_dir_HOB LOB_shell-HOB_shell NºParam_dir_LOB

`python -c 'print "\x26\x97\x04\x08"+"\x24\x97\x04\x08"+ "%.49143x" + "%4$hn" + "%.15408x" + "%5$hn"'`

Pwntools Template

You can find a template to prepare a exploit for this kind of vulnerability in:

{% content-ref url="format-strings-template.md" %} format-strings-template.md {% endcontent-ref %}

Learn AWS hacking from zero to hero with htARTE (HackTricks AWS Red Team Expert)!