Search code examples
cshellcode

Pointers to function


What does this code mean?

char code[] = "bytecode will go here!";
int main(int argc, char **argv) {
    int (*func)(); /* This is pointer to function */
    func = (int (*)())code; /* What does this line mean? */
    (int)(*func)(); /* Calling function by pointer */
}

Solution

  • func = (int (*)()) code;
    

    code, being an array, is implicitly converted to a pointer to its first element (it decays to such a pointer). This pointer is then cast to a pointer to a function.

    This cast causes undefined behaviour. But "most of the time", it will probably result in a function pointer pointing to the address of the array. When you call it, then control jumps to this array. If it contains string data, you'll most likely get an invalid opcode or a segmentation fault. But if that array contains some user input a malicious user could've put (compiled) code into it, doing all sorts of funny (or less funny) stuff.

    As an example, consider the above code running in some sort of server, being fed user input over some website. Then one could replace the program with, for example /bin/sh and thus gain shell access on that server.