Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Buffer overflow using snprintf

Tags:

c

buffer

This is an assignment but I am having problems with the basic understanding.

The vulnerable code:

int choc(char *arg)
{
  char buf[400];
  snprintf(buf, sizeof buf, arg);
  return 0;
}

I understand that arg needs to be a format string which will overwrite the return address with the address of the code I want to execute. But I am having trouble creating the format string.

So, things which the format string needs to have:

  1. the address of the return instruction, which I need to overwrite
  2. A list of %x
  3. The value which I would write on the return address. This would be the address of the code I want to execute.

In order to get the return address, I just need to look at the address of the 'ret' instruction in gdb right? What exactly is the purpose to the %x? And how do I encode the address of the code I want to execute in the format string?

A test I did: Using gdb I found that the address of my buf is 0xbffffba0. I generated arg to be "\xa0\xfb\xff\xbf_%x.%x.%n"; Shouldn't this write some value to the start of the buff at the address 0xbffffba0? However I get a segfault. What am I doing wrong?

Any help would be appreciated!

like image 724
Catie Avatar asked Nov 13 '22 07:11

Catie


1 Answers

The "\xa0\xfb\xff\xbf" should not be the address of buf, but rather the location of the return address on the stack (which is the value you wish to overwrite). You'll have to find that value using gdb.

You then need to put enough %x in your format string such that your %n will read that value off the stack and write to the address you specified. You also need to to use the correct field sizes such that %n will actually write the correct value.

like image 69
Per Johansson Avatar answered Dec 19 '22 08:12

Per Johansson