What does this piece of cast code do?

6

code taken from 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 is this line of code doing?

int (*ret)() = (int(*)())code;
    
asked by Maniero 21.06.2016 в 22:08
source

2 answers

6

This is a technique to execute the function written in machine code or another way where the name of the function is not known, but if it knows where it is.

Note that code is a variable with 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 of bytes as if it were a function. C has a way of referencing functions anonymously.

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

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

So you can execute arbitrary code. It could come from outside sources, which can be a danger. In some cases the operating system may prevent the execution of arbitrary code.

    
answered by 21.06.2016 / 22:24
source
3
int(*ret)()

A statement of a pointer function called ret is made, the function takes unspecified arguments and returns an integer.

(int(*)())code

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

So it converts the address of the code array 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?

    
answered by 21.06.2016 в 22:22