yasgur99
yasgur99

Reputation: 858

Why is this shellcode causing a segmentation fault?

When I run the following code:

#include <stdio.h>
#include <string.h>

char code[] = "\x31\xc0\x48\xbb\xd1\x9d\x96\x91\xd0\x8c\x97\xff\x48\xf7\xdb\x53\x54\x5f\x99\x52\x57\x54\x5e\xb0\x3b\x0f\x05";

int main()
{
    printf("len:%d bytes\n", strlen(code));
    (*(void(*)()) code)();
    return 0;
}

Using the gcc compiler, I first simply compiled using

 gcc program.c -o program

When I ran that I got a Segmentation Fault. Next, I tried to compile using

gcc -fno-stack-protector -z execstack -o test test.c

That worked and I got the shell. What I am wondering is why I need to pass those commands while compiling for it to work. My goal is to make it work without having to pass those commands. How can I achieve that goal?

Upvotes: 0

Views: 896

Answers (1)

fuz
fuz

Reputation: 93014

Writeable data in static storage (such as your code array) usually ends up in the .data section which is usually marked “not executable.” Mark the array as const so it ends up in .rodata resp. .text and can be executed.

Upvotes: 4

Related Questions