What does this chunk of cast code do?

Asked

Viewed 271 times

8

code taken from the site Linux x86_64 execve Shellcode

#include<stdio.h>
#include<string.h>

unsigned char code[] = \
    "\x48\x89\xc6"                 // mov    %rax,%rsi
    "\x48\x89\xf2"                 // mov    %rsi,%rdx
    "\x49\xbc\x2f\x62\x69\x6e\x2f" // movabs $0x68732f6e69622f,%r12
    "\x73\x68\x00"               
    "\x41\x54"                     // push   %r12
    "\x54"                         // push   %rsp
    "\x5f"                         // pop    %rdi
    "\xb0\x3b"                     // mov    $0x3b,%al
    "\x0f\x05"                     // syscall 
;

main()
{

    printf("Shellcode Length:  %d\n", (int)strlen(code));

    int (*ret)() = (int(*)())code;

    ret();

}

what this line of code is doing?

int (*ret)() = (int(*)())code;

2 answers

8


This is a technique to perform the function written in machine code or otherwise where the name of the function is not known, but if you know where it is.

Note that code is a variable with the machine code mounted from that Assembly code in the comments. How to call this through C? Calls can only be through functions. So we have to interpret this array bytes as if it were a function. C has a way to refer to functions anonymously.

In this case you will have a variable called ret which is of the type "function that returns an integer". The final parentheses in the variable name and the pointer (after all every function is a pointer to a code) is what indicates that in the background is a function.

The (int(*)()) is a cast to make this array bytes is converted to a function. Not that a conversion is even made, it will only be interpreted that way by the compiler. This is done to match what is expected in the variable.

So you can run an arbitrary code. It could even come from external sources, which can be a danger. In some cases the operating system may prevent the execution of arbitrary codes.

4

int(*ret)()

Declaration of a called pointer function ret, the function takes unspecified arguments and returns an integer.

(int(*)())code

Converts the array code for a pointer to a function of that type.

So convert the array address code to a pointer of a function, which then allows you to call it and execute the code .

Translation of: What does int (Ret)() = (int()())code Mean?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.