I am trying to follow along with a tutorial about buffer overflow (Buffer Overflow Primer by Vivek Ramachandran). I am literally following his code, which works for him in the demo, and which has worked for me until this point.
The goal of the C program below is to assign shellcode for the exit system call to a variable, and then to replace the default return address for the main function, which points to __lib_start_main, with the memory address of the shellcode variable, such that the program executes the shellcode upon completing the main function, and then exits the program gracefully, with a value of 20 (as in execiting "exit(20)"). Unfortunately, the program ends with a segmentation fault instead. I am running this on 32-bit Linux Mint. I'm using gcc to compile the code, and have compiled it with the --ggdb and -mpreferred-stack-boundary=2 options, and I've tried both with and without the -fno-stack-protector option.
Here is the code:
#include<stdio.h>
char shellcode[] = "\xbb\x16\x00\x00\x00"
"\xb8\x01\x00\x00\x00"
"\xcd\x80";
int main(){
int *ret;
ret = (int *)&ret +2;
(*ret) = (int)shellcode;
}
I have run this through gdb, and everything seems to check out: The memory location of the shellcode variable is 0x804a01c
Thanks in advance!
Adding the following option when compiling resolved the issue:
-z execstack