You can also use #define to define your shellcode. Thus, the pre-processor will embed the code directly in the main
#define SHELLCODE "\x31\xc0\xb0\x1d\xcd\x80" int main() { (*(void(*)())SHELLCODE)(); }
An older shellcode style does not work on newer systems due to security concerns. You may also have to compile with stack protection disabled:
gcc -z execstack -fno-stack-protector shellcode.c -o shellcode
Here is a fully working example that uses the exit system call that I tested on the 3.2.0.3 x86_64 kernel:
#include<stdio.h> #define SHELLCODE "\x48\xc7\xc0\x3c\x00\x00\x00\x48\xc7\xc7\xe7\x03\x00\x00\x0f\05" main() { int (*function)(); // cast shellcode as a function function = (int(*)())SHELLCODE; // execute shellcode function (int)(*function)(); return 0; }
Shellcode uses 64-bit registers, so it will not work on a 32-bit machine. To make sure the code works, you can check it with strace:
strace shellcode execve("./shellcode", ["shellcode"], []) = 0 .... munmap(0x7ffff7fd5000, 144436) = 0 _exit(999) <---- we passed 999 to exit, our shellcode works!
source share