9

I wrote a simple ASM file and ran it in a C file I'd written. I got a segentation fault. However, when I execute the compiled ASM file, I get no error.

I am running 64 bit and using 32 bit shellcode. Is that the issue?

It can't be, because I'm getting a segmentation fault with this:

char shellcode[] = "\x90"; //simple NOP in ASM
int main(int argc, char **argv)
{
  int (*ret)();
  ret = (int (*)()) shellcode;
  (int)(*ret)();
}

Can someone please run this and tell me whether or not they get a segmentation fault. I have used 3 or 4 other C files as well. None have worked.

Update:

((void(*)(void))code)();

Seems to be working in place of those three lines.

Goodies
  • 4,439
  • 3
  • 31
  • 57

4 Answers4

12

As mentioned above the shellcode is in non-executable memory. Try recompiling the program with the -fno-stack-protector and the -z execstack flags enabled.

That is:

gcc -fno-stack-protector -z execstack -O OutputFileName yourShellCode.c

Ray
  • 293
  • 1
  • 3
  • 12
  • Alternatively, one can also run `execstack OutputFileName` on a binary already compiled without these supplementary parameters. – WhiteWinterWolf Jul 05 '16 at 20:02
3

Two issues:

  1. The shell code might be in non-executable memory. In order to make it executable, you need to either ask the OS to make it executable (e.g. with mprotect(2) or VirtualProtect()), or allocate new executable memory and copy it there (e.g. with mmap(2) or VirtualAlloc().
  2. Your shell code doesn't return/exit. After the CPU executes your NOP there (0x90), it's going to keep on executing code in the memory that comes after that NOP instruction. Most likely, this will crash quickly, but it might do other random, unpredictable things.

To fix #2, you need to explicitly either execute a return instruction (C3 on x86/x86-64) to return from your shell code, or you need to do something which never returns, like call the exit(3) function.

Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
3

Maybe you should change your variable :

   char shellcode[]

To:

   const char shellcode[]

Like in this question: segmentation-fault-error-when-exe-c

This one worked for me! :)

Community
  • 1
  • 1
KimSki
  • 31
  • 3
  • that did it! OS: Arch Linux x86_64 Kernel Release: 4.9.8-1-ARCH Uptime: 2:41 WM: i3 DE: None Packages: 765 RAM: 2405 MB / 5963 MB Processor Type: Intel(R) Core(TM) i5 CPU M 430 @ 2.27GHz $EDITOR: None Root: 16G / 69G (23%) (ext4) – Evgeny Danilenko Mar 25 '17 at 16:03
2

Try put the shellcode in the main function to make it a local variable:

int main(int argc, char **argv)
{
  const char shellcode[] = "<your shellcode>";
  int (*ret)();
  ret = (int (*)()) shellcode;
  (int)(*ret)();
}

Then compile it with flags -fno-stack-protector and -z execstack:

gcc <filename>.c -fno-stack-protector -z execstack -o <filename>

I found this idea on stackexchange and it worked for me.

Jurakin
  • 832
  • 1
  • 5
  • 19