C 指向函数的指针

C 指向函数的指针,c,shellcode,C,Shellcode,这个代码是什么意思 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 */

这个代码是什么意思

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 */
}
code
作为一个数组,隐式转换为指向其第一个元素的指针(它衰减为这样的指针)。然后将该指针转换为指向函数的指针

此类型转换导致未定义的行为。但“大多数情况下”,它可能会导致函数指针指向数组的地址。当您调用它时,控件将跳转到此数组。如果它包含字符串数据,您很可能会得到无效的操作码或分段错误。但如果该数组包含一些用户输入,恶意用户可能会将(编译的)代码放入其中,做各种有趣(或不那么有趣)的事情


作为一个例子,考虑在某些服务器上运行的上述代码,在某些网站上输入用户输入。然后可以用替换程序,从而获得该服务器上的shell访问权。

这是shell代码的示例。 在这里:

func是一个函数点,它指向“代码数组”的地址


调用func时,程序将跳转到数组的地址。

您看到的是一个示例

您的函数所做的是获取字节码字符串并将其转换回函数指针,就像我们上面所做的那样。然后,您可以通过取消对指针的引用并通过添加括号和函数所采用的任何参数来调用该函数


当然,在常规编程中不需要这样做,但在特殊情况下很少需要这样做。

这是一个很好的例子,说明了您可能不应该做的事情。。。。函数指针强制转换几乎总是UB。它将
code[]
数组的第一个元素的地址分配给函数指针funcSourav Ghosh,UB是什么?@SebastianRockefeller UB=未定义行为。“未定义行为”是C和C++中非常重要的概念。关于c/c++的四个问题中有一个是关于UB的。@DanielJour是的,当然是我编造的,但正如你说的,这可能是真的。这是一个评论,而不是答案。Daniel Jour,谢谢,这很清楚,但是如果数组存储在数据段而不是代码段中,那么如何执行code[]数组中的代码?你能解释一下函数是如何存储在内存中的吗?是什么让这个技巧成为可能?
func = (int (*)()) code;
func = (int (*)()) code; /* What does this line mean? */                           
void print_hello()
{
    printf("hello");
}

int main()
{
    void (*hello_func_ptr)() = &print_hello;

    //we convert what the function points to to a string of "byte code"
    char *func_byte_code = (char *)hello_func_ptr; 

    // prints out byte code of the function
    printf(func_byte_code); 

    // we cast the string byte code to a function pointer
    void (*func_from_byte_code)() = (void (*)())func_byte_code;

    // we call the function we got from casting the byte code to a function pointer  
    (*func_from_byte_code)(); // prints "hello"!
    return 0;
}