I'm trying to understand very basic stack-based buffer overflow I'm running Debian wheezy on a x86_64 Macbook Pro.
I have the following unsafe program:
#include <stdlib.h>
#include <stdio.h>
CanNeverExecute()
{
printf("I can never execute\n");
exit(0);
}
GetInput()
{
char buffer[512];
gets(buffer);
puts(buffer);
}
main()
{
GetInput();
return 0;
}
I compiled with -z execstack
and -fno-stack-protector
for my tests.
I have been able to launch the program through gdb, get the address of CanNeverExecute
function which is never called, and overflow the buffer to replace the return address by this address. I got printed "I can never execute", which is, so far, so good.
Now I'm trying to exploit this buffer overflow by introducing shellcode in the stack. I'm currently trying directly into gdb: break in GetInput
function, set buffer value through gdb and jump to buffer adress with jump
command.
But I have a problem when setting the buffer:
I have a breakpoint just after gets function, and I ran the programm with 512 a
characters as input.
In gdb, I do:
(gdb) p buffer
$1 = 'a' <repeats 512 times>
The input was read without any problem, and my buffer is 512 a
I then try to modify its value. If I do this:
(gdb) set var buffer=""
and try to print buffer, its length is now 511! How come??
(gdb) p buffer
$2 = '\000' <repeats 511 times>et:
And when I try to set it back to, for instance, 512 a
, I get:
Too many array elements
I can set it to 511 a
though, it is really that las byte that doesn't work... How come, is there a simple explanation?