0

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:

Disassembly of main

Disassembly of 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:

Stack Content Before gets

Then I entered the value 0123456789012345678901234, which exceeds char buf[4], so stack overflow happens, this is what the stack looks like:

enter image description here

My question is: why does the overflow not start from $rsp? Why does it skip 4 bytes?

Jester
  • 56,577
  • 4
  • 81
  • 125
Leyiang
  • 530
  • 4
  • 7
  • 2
    Because of the `lea -0xc(%rbp), %rax`. The compiler allocated 16 bytes (rounded up for alignment) and decided to use it like 4 bytes of padding, 4 bytes for `buf` and 8 bytes for `result`. Could have put the padding elsewhere. – Jester Jun 16 '23 at 13:46
  • 2
    Just a general comment: whenever possible, please post output like your debugger transcripts as copy/pasted text instead of screenshot images. Text is much better for people who use things like screen readers, and it also makes it easier for other people to copy/paste into other programs for analysis. – Nate Eldredge Jun 16 '23 at 18:57
  • 1
    Separate from your question, GDB already disables ASLR by default for processes you run inside it; `ernel.randomize_va_space=0` only matters if you need absolute addresses to be consistent outside GDB. – Peter Cordes Jun 16 '23 at 19:07
  • 1
    Near duplicate of [Why does my buffer have more memory allocated on the stack than I asked for?](https://stackoverflow.com/q/69865272), but that array is larger than 16 bytes so GCC aligns it by 16, unlike here. Also related [Why does GCC allocate more space than necessary on the stack, beyond what's needed for alignment?](https://stackoverflow.com/q/63009070) although that's not what's going on. The total amount of space here was necessary, it's just about where inside that space it puts the array. – Peter Cordes Jun 16 '23 at 19:12

0 Answers0