Search code examples
assemblystack-overflowexploitshellcode

Need to exploit buffer overflow. Can't figure out how to uncorrupt the stack after executing exploit code?


Basically the function I am exploiting is this:

int getbufn()
{
     char buf[512];
     Gets(buf);
     return 1;
}

When I run the main program the function executes 5 times and each time the location of buf changes and so does the location of %ebp. What I am supposed to do is place a specific hex value, lets say 0xFFFFFFFF, into a variable and the main program checks each time to see if that variable is there. If it is it executes again until all 5 times are done and the program exits quietly.

The problem I am having is that right before the check for the hex value there is a check for another value that is constant, lets say 0x12345678. If I have corrupted 0x12345678 and it's not there, the program explodes on me.

I have figured out that 0x12345678 is stored in -0x10(%ebp) so I know it is based off %ebp and I know the address of %ebp each time but I can only get the exploit to work the first time. I do this by basically nopsled-ing 496 bytes and the having this machine code in byte format:

mov  0xFFFFFFFF, %eax
movl address old ebp, %ebp
push correct return adress in function main
ret

which ends up being 5 words and a byte for return long which I fill with 0x313131 to make it 6 words long. At this point my exploit string is 520 bytes long which is exactly how much the buffer is below %ebp and so I add on the address of old ebp and an address somewhere inside my nopsled overwriting the current value at %ebp as well as the return address for getbufn.

The problem is when the program executes a 2nd time %ebp is in an address 0x10 lower than its previous address so my way of uncorrupting %ebp doesn't work and main detects that 0x12345678 is not at -0x10(%ebp). How do I uncorrupt %ebp?


Solution

  • pmjordan is right, you should be able to calculate where %ebp is in relation to %esp. Remember, the %esp is your current stack pointer and %ebp is where your stack pointer was for the previous function. Instead of having a static %ebp, you need to have a dynamic one calculated from %esp (or really just looking at what is stored at memory located in %esp offset by the stack variables). The pseudo code would be something like:

    1. calculate the offset of %ebp from %esp
    2. read the value stored at that memory location and store for yourself
    3. do your exploit
    4. restore the old value of %ebp stored in step 2
    5. ret