I've started reading about buffer overflow and how hackers use it to execute custom code instead of the regular compiled one and now I'm trying to reproduce some basic situations, with a vurnerable function that copy data into a char array with the unsafe strcpy.
The point is that when I change the return address with one of an assembly instrution of a function defined in the program it works fine, while when I inject code directly in bytes it returned SEGMENTATION FAULT.
I'm using the Kali distribution x64 v3.18
I've disabled the address space layout randomization (ASLR):
echo 0 > /proc/sys/kernel/randomize_va_space
And disabled the stack protection code added by the compiler:
gcc -g -fno-stack-protector exbof.c -o exbof
Code:
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv){
char buffer[500] = {0};
strcpy(buffer, argv[1]);
return 0;
}
Usage:
./exbof `perl -e 'print "x90"x216; // nop sled
print CUSTOM_CODE; // my code
print "xff"x(500 - 216 - CODE_LENGTH); // fill empty space
print "xff"xOFFSET // distance between the last byte
// of buffer and the return address
printf("\\x%lx", BUFFER_ADDRESS + int(rand(26)) * 8);'`
Output:
Segmentation Fault
In GDB:
Program received signal SIGSEGV, Segmentation fault.
0x00007fffffffxyzt in ?? ()
I've used GDB to debug it and the code write the new address corrrectly in the stack.
I'm using a shellcode exec found online, but I've also tried to inject a piece of code in bytes from my program and when I checked with GDB the assembly code injected turned out to be valid code and exactly the same of the original one.
It seems to me that any address out of the .text memory segment doesn't work.
Suggestions?
Solution:
As suggested by @andars, it's necessary to set up the flag that mark the stack as executable.
So, if you want to try this and start playing with buffer overflows, you have to:
disable the address space layout randomization (ASLR):
echo 0 > /proc/sys/kernel/randomize_va_space
disable the stack protection code added by the compiler:
gcc -g -fno-stack-protector your_program.c -o your_program
set up a flag in the program header to mark the stack as executable:
execstack -s your_program
or you can do it directly at assembly time or at link time:
gcc -g -fno-stack-protector -z execstack your_program.c -o your_program