15

I'm not really getting how this code does what it does:

char shellcode[] = "\xbb\x00\x00\x00\x00"           
                   "\xb8\x01\x00\x00\x00"                  
                   "\xcd\x80";                  

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

Okay, I know:

int *ret;

sets a pointer of int. and:

ret = (int *)&ret + 2;

sets the address of ret and 2 bytes (I think.)

But I don't get what this means:

(int *)&ret

I know what &ret means but not what (int *)&ret means. Also, how does it execute the shellcode by assigning the value of shellcode to ret?

UPDATE: What is the difference between:

(int *)&ret  + 2

and:

&ret + 2
2
  • 3
    Curious why so many downvotes... the shellcode looks pretty harmless.
    – FatalError
    Commented Mar 22, 2012 at 3:39
  • what will happen if i run this. is this malware
    – Scover
    Commented Nov 30, 2023 at 15:22

1 Answer 1

17

The 'string' shellcode contains some machine code of some sort.

The int *ret; defines a variable ret which is a pointer to an int.

The assignment ret = (int *)&ret + 2; makes ret point to a location the size of two int from its own actual location (or address); this is an address in the stack, presumably where the return address of the function (main()) is stored on the stack.

The assignment *ret = (int)shellcode; assigns the address of the shell code to the return address. Therefore, when the main() function exits, the return address is the shell code, which does whatever it does instead of exiting the program normally.

The casts cover up a multitude of sins. The code makes a large number of non-portable assumptions which are probably justified on the target environment but not necessarily anywhere else.


What's the difference between: &ret+2 and (int *)&ret + 2?

Type, mainly; this is one of the multitude of sins mentioned previously. &ret has the type int ** (pointer to pointer to int) instead of int * which is the type of ret itself. Since sizeof(int *) == sizeof(int **) on all actual machines, the cast merely quells a complaint from the compiler (about assigning the wrong type of pointer to ret) without changing the numerical result.

0

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.