I am currently reading CSAPP, and for Practice Problem 3.46, as part of the task, we need to test a segment of vulnerable C code using GDB in order to investigate its inner workings.
/** vulnerable code from the task **/
char *get_line()
{
char buf[4];
char *result;
gets(buf);
result = malloc(strlen(buf));
strcpy(result, buf);
return result;
}
/** main function that I added **/
int main(void)
{
get_line();
return 0;
}
I compiled the C code with -fno-stack-protector
& -g
to turn off the stack protector and preserve debugging information.
Additionally, I turned address-space randomization off for easy observing sudo sysctl -w kernel.randomize_va_space=0
Disassembly of main and get_line:
At the line gets(buf)
I have set a breakpoint. Prior to the invocation of the gets
function, the stack looks like this:
Then I entered the value 0123456789012345678901234
, which exceeds char buf[4]
, so stack overflow happens, this is what the stack looks like: