• caglararli@hotmail.com
  • 05386281520

How does this simple buffer overflow work?

Çağlar Arlı      -    38 Views

How does this simple buffer overflow work?

I've got this simple code

vuln.c

#include <stdio.h>
#include <string.h>

int main(int argc, char** argv)
{
    char buffer[500];
    strcpy(buffer, argv[1]);
    printf("%s", buffer);
    return 0;
}

I am trying to perform a buffer overflow and

  • Fill the buffer with a malicious code
  • Modify the return address to redirect to the malicious code

Ideally, I believe that when I overwrite my 500 buffer, next I will be overwriting the base pointer, followed by the return address.

Here's how I tried to overflow the buffer

gcc vuln.c
./a.out $(python -c 'print "\x41" * 501')

Since I am putting 501 "A"s into the buffer, it should overflow theoretically, right? But this is not happening. I don't get a segmentation fault, instead, I get the output of "AAAA.." and the program exits normally. (I didn't count the number of As..).

So I fired up GDB and start playing with the number of As until I do get a segmentation fault. And I find that I get a segmentation fault when I put 520 "A"s! How?

With 520 A's, GDB's info registers gives me enter image description here

And with 521 A's, running the same GDB command, I get enter image description here

As you can see, in image 1, the base point is filled with \x41 (hex for A) and in image 2, the BP is filled with \x41s and the IP begins to be filled as well.

I don't understand this. So my question is - why 520? And why did it not overflow on 501?