2

I have already run this command. But my shellcode is not working for me:

gcc -fno-stack-protector -z execstack test.c -o test
./test
Segmentation fault (core dumped)

Here is my shellcode

#include <stdio.h>
 
unsigned char code[] = "\xb8\x0a\x00\x00\x00\xc3";
 
int main(int argc, char **argv) {   int foo_value = 0;
 
int (*foo)() = (int(*)())code;   foo_value = foo();
 
printf("%d\n", foo_value); }

Here is my operating system:

uname -a
Linux AAAA 5.13.0-30-generic #33~20.04.1-Ubuntu SMP Mon Feb 7 14:25:10 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux

I have already identified the location using the following command:

gcc -c -O3 ex.c
objdump ex.o -d
ex.o:     file format elf64-x86-64

Disassembly of section .text:

0000000000000000 <foo>:    
0:    f3 0f 1e fa             endbr64     
4:    b8 0a 00 00 00          mov    $0xa,%eax
9:    c3                      retq
1
  • 2
    You have code as a global variable. Global data is not executable (by default). Your GCC parameter only disables the execution prevention of stack contents (local, non-static variables), but not of global variables. Mar 2, 2022 at 11:00

2 Answers 2

3

The argument -z execstack only allows stack to execute code, but the code is a global variable, which is not on stack, so you can do some simple changes to make your code work.

For example,

#include <stdio.h>

int main(int argc, char **argv) {
    int foo_value = 0;
    unsigned char code[] = "\xb8\x0a\x00\x00\x00\xc3";
    int (*foo)() = (int(*)())code;
    foo_value = foo();
    printf("%d\n", foo_value);
}
2

A simple HACK for gcc would be to make the char array as const That makes the bytes go in .rodata which is usally mapped within the same pages as .text and has the same rx permission.

This worked for me without any additional flag.

[/tmp] cat x.c
#include <stdio.h>

const unsigned char code[] = "\xb8\x0a\x00\x00\x00\xc3";

int main(int argc, char **argv) {
  int foo_value = 0;

  int(*foo)() = (int (*) ())&code;
  foo_value = foo();

  printf("%d\n", foo_value);
}
[/tmp] make x
cc     x.c   -o x
[/tmp] ./x
10
1
  • FYI: in my case it leads to Segmentation fault when using -fno-stack-protector -z execstack. GCC 9.4.0, Ubuntu 20.04.5 LTS. Any ideas? The code is in .rodata.
    – pmor
    Nov 29, 2022 at 9:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.