2
votes

I was looking at this example w.r.t executing code in the stack:

#include <stdio.h>
  #include <stdlib.h>
  #include <string.h>
  char shellcode[] = “\xeb\xfe”;
  int main(int argc, char *argv[]){
          void (*f)();
          char x[4];
          memcpy(x, shellcode, sizeof(shellcode));
          f = (void (*)()) x;
          f();
}

This causes a segmentation fault. My understanding this is because the shellcode runs out of memory for the rest of the bytes as x only has a size of 4 bytes. And this results in creating a write operation of copying to stack memory and that causes a seg. fault as stack memory is read only. Is my understanding correct ?

1
Stack is not read only, but it is most likely not executable. - Joachim Isaksson
And there are only 3 bytes to copy. A \x means the next two characters indicate the hexadecimal value of the byte which is actually put in the program. - ughoavgfhw

1 Answers

2
votes

Precisely what OS are you running this on?

To quote from the Mac Hacker's Handbook:

Leopard does not set the XD bit on any parts of memory besides the stack. It is unclear if this is a bug, an oversight, or intentional, but even if the software's memory permissions are set to be nonexecutable, you can still execute anywhere except the stack. The following simple program illustrates that point.

[ your snippet follows ]

(Emphasis mine.)

The code should segfault if permissions are set to nonexecutable (or if permissions are omitted altogether). It didn't on Leopard, which even the author questions. What you observed is perfectly normal behavior for a modern OS.

I would add: Try running it through a debugger. \xeb\xfe is an infinite loop but you technically shouldn't even loop once. The OS should slap you on the wrist (which is apparently happening here).