Search code examples
cstackshellcode

Shellcoder's Handbook: first shellcode example


I'm a little confused how the first shellcode example works. I've run it through GDB and I have verified it is correct, but I'm not sure how it ends up working in the first place. Here is what the code looks like:

char shellcode[] =
"\xeb\x13\x59\x31\xc0\xb0\x04\x31\xdb\x43\x31\xd2\xb2\x0f\xcd\x80"
"\xb0\x01\x4b\xcd\x80\xe8\xe8\xff\xff\xff\x48\x65\x6c\x6c\x6f"
"\x20\x77\x6f\x72\x6c\x64\x0a\x0d";

int main()
{
    int *ret;
    ret = (int *)&ret + 2;
    (*ret) = (int)shellcode;

    return 0;
}

(I actually have replaced the shellcode which initially spawns a shell to one that prints "Hello world", but that shouldn't make much of a difference.)

How can ret work if its only an integer pointer, something that should only be 4 bytes long? The shellcode itself is roughly 40 bytes long! If anything, all ret should retreive is the first 4 bytes of the shellcode, not execute the whole thing!

Can someone please explain to me how this works?


Solution

  • It's compiler-dependent (and chip-dependent), but I think what is happening is that it is relying on the fact that at the location on the stack 2 int's up from where your automatic variables start is the return address you should jump back to when returning from the process. It's replacing that address with the address of the shellcode[] array, so when main() returns, it will execute the instructions there.