Search code examples
cstack-overflowbuffer-overflow

C Stack Buffer Overflow


I am trying to replicate a stack buffer overflow. This is my code

#include <stdio.h>

int main(int argc, char *argv[]) {
  char x[1];
  gets(x);
  printf("%s\n", x);
}

I am compiling this on a 32 bit machine, which means each memory address is 4 bytes long. Since each character is 1 byte (verified using sizeof), I am expecting a stack buffer overflow when I enter "AAAAA" as input (1 byte more than what x can hold). However, nothing happens till I enter 13 As, at which point I get an "Illegal Instruction" error. 14 As results in a "Segmentation fault".

Questions

  1. Why am I not getting a segmentation fault at 5 As?
  2. What is the difference between Illegal Instruction and Segmentation Fault?
  3. What is a good tool (other than gdb) to visualize the stack?

I've looked at Trouble replicating a stack buffer overflow exploit, but I had trouble understanding the answer.

Here's my assembly dump:

(gdb) disassemble main
Dump of assembler code for function main:
   0x0804844d <+0>: push   %ebp
   0x0804844e <+1>: mov    %esp,%ebp
   0x08048450 <+3>: and    $0xfffffff0,%esp
   0x08048453 <+6>: sub    $0x20,%esp
   0x08048456 <+9>: lea    0x1f(%esp),%eax
   0x0804845a <+13>:    mov    %eax,(%esp)
   0x0804845d <+16>:    call   0x8048310 <gets@plt>
=> 0x08048462 <+21>:    lea    0x1f(%esp),%eax
   0x08048466 <+25>:    mov    %eax,(%esp)
   0x08048469 <+28>:    call   0x8048320 <puts@plt>
   0x0804846e <+33>:    leave  
   0x0804846f <+34>:    ret    
End of assembler dump.

Solution

    1. the stack is 16-byte aligned right after the main function executed ( at line 3 ). so you cannot just calculate exact address for saved return address, you can just try from 5 bytes to 21 bytes.
    2. Illegal instruction is such bytes which didn't match with any defined instruction. every instruction is represented in machine code (Ex: push ebp is 0x55 , etc) but for example, 0xff 0xff is not matched with any instruction in x86 machine. but segmentation fault is occured when any memory access is invalid.