Hacking - The Art of Exploitation, 2nd Edition

(Romina) #1
Countermeasures 367

Amazingly, these instructions, combined with the AND eax instruction,


are sufficient to build loader code that will inject the shellcode onto the stack
and then execute it. The general technique is, first, to set ESP back behind the


executing loader code (in higher memory addresses), and then to build the


shellcode from end to start by pushing values onto the stack, as shown here.


Since the stack grows up (from higher memory addresses to lower memory
addresses), the ESP will move backward as values are pushed to the stack,


and the EIP will move forward as the loader code executes. Eventually,


EIP and ESP will meet up, and the EIP will continue executing into the
freshly built shellcode.


o

First, ESP must be set behind the printable loader shellcode. A little


debugging with GDB shows that after gaining control of program execution,
ESP is 555 bytes before the start of the overflow buffer (which will contain the


loader code). The ESP register must be moved so it’s after the loader code,


while still leaving room for the new shellcode and for the loader shellcode


itself. About 300 bytes should be enough room for this, so let’s add 860 bytes
to ESP to put it 305 bytes past the start of the loader code. This value doesn’t


need to be exact, since provisions will be made later to allow for some slop.


Since the only usable instruction is subtraction, addition can be simulated by
subtracting so much from the register that it wraps around. The register only


has 32 bits of space, so adding 860 to a register is the same as subtracting 860


from 2^32 , or 4,294,966,436. However, this subtraction must only use printable


values, so we split it up across three instructions that all use printable operands.


sub eax, 0x39393333 ; Assembles into -3399
sub eax, 0x72727550 ; Assembles into -Purr
sub eax, 0x54545421 ; Assembles into -!TTT


As the GDB output confirms, subtracting these three values from a 32-bit


number is the same as adding 860 to it.


1)

2)

3)

Loader Code Shellcode

EIP ESP

Loader Code Shellcode being built

EIP ESP

Loader Code

EIP ESP
Free download pdf