Sunday, February 13, 2011

Smashing the stack

This part mainly concentrates on how we can change the return address present in the stack when a function is called. On changing the return address, we can skip the instructions that are supposed to be executed in normal fashion.
The simple C code is as follows(this is executed on gcc 4.4.1)
#include
void fun(int a,int b,int c)
{
int buf2[2]={3,4};
int buf1[2]={1,2};
int *x;
x=buf1+6;//1st part
(*x)+=13;//2nd part
}
int main()
{
int x=0;
fun(1,2,3);
printf("This will not be printed");
return 0;
}

Using gdb we can simply break the code and check the stack when and where we want. The stack picture for above program is as follows

Top of stack bottom of stack
[buf1][buf2][pointer_of_x][stack_pointer][return_address]3 2 1
bottom memory address Top memory address

This can be seen on gdb by breaking the code at line 7 and there by typing
gdb>x/32xw $esp

The code in 1st part helps in seeking the pointer to the return address, and the code in the second part helps us in moving the pointer to some instruction in main program. To write 2nd part we have to disassemble main program using :
gdb> disas main

we get something like this

0x0804841e : push %ebp
0x0804841f : mov %esp,%ebp
0x08048421 : and $0xfffffff0,%esp
0x08048424 : sub $0x20,%esp
0x08048427 : movl $0x0,0x1c(%esp)
0x0804842f : movl $0x3,0x8(%esp)
0x08048437 : movl $0x2,0x4(%esp)
0x0804843f : movl $0x1,(%esp)
0x08048446 : call 0x80483e4
0x0804844b : mov $0x8048520,%eax
0x08048450 : mov %eax,(%esp)
0x08048453 : call 0x804831c
0x08048458 : mov $0x0,%eax
0x0804845d : leave
0x0804845e : ret
End of assembler dump.

now we are adding 13 in second part as we are trying to skip print statement and directly move on to main+59 line (simply 58-45=13)

Similarly other c code is as follows...

#include
void fun(int a, int b, int c)
{
int buffer2[4]={7,8,9,10};
int e=13;
int d=3;
int *ret;
int buffer1[3]={4,5,6};
ret = buffer1 + 9;//this goes to return pointers address
(*ret) += 34;//changes contents of return address by seein disas main
}
int main()
{
int x;
x = 0;
fun(1,2,3);
x = 1;
printf("The value of x:%d\n",x);
return 0;
}
lets meet up in the next discussion on how this can be implemented as an attack in our day to day life....

1 comments:

anirudhak said...

super dude.........