I have the following program (in C):
char shellcode[] = "\xb8\x01\x00\x00\x00\xbb\x00\x00\x00\x00\xcd\x80";
void run_shellcode() {
int* ret;
ret = (int*)(&ret) + 2;
*ret = (int)shellcode;
}
int main() {
run_shellcode();
}
The basis is an example from a lecture about network security available here:
https://hhunetsec.de/2015/02-BufferOverflows.pdf
What the program does is the following. int* ret
is a pointer variable on the stack of the function run_shellcode
. From the variable its own address is taken, added two (pointer arithmetic) and written in the address itself. The resulting address is two addresses above the original address of ret
and is the return address of the function. Then the variable is dereferenced and the address of the string overwrites the return address of the function. In this way the code is supposed to execute the machine code in shellcode
.
I tried to reproduce this example, but am failing constantly with segmentation fault. The machine code in the string is just a call of the exit system call (despite the name "shellcode") and looks pretty good in disassembler:
(gdb) disass /r shellcode
Dump of assembler code for function shellcode:
0x080495ec <shellcode+0>: b8 01 00 00 00 mov $0x1,%eax
0x080495f1 <shellcode+5>: bb 00 00 00 00 mov $0x0,%ebx
0x080495f6 <shellcode+10>: cd 80 int $0x80
0x080495f8 <shellcode+12>: 00 00 add %al,(%eax)
It is compiled in the following way:
gcc -g -m32 -fno-stack-protector -o hello_5 hello_5.c
The debugger also shows that it actually jumps to shellcode
, but then segmentation fault follows. I tried different machine code that actually works otherwise, but always failed in this example.
I suppose there is some protection mechanism that prevents executing? Did I make a mistake somewhere? Can I get it run somehow?
I'm not a student of that university where the lecture comes from, so I can't ask for help there.