这段代码中发生了什么?(执行一个字符缓冲区)

What happens in this code? (Executing a char buffer)

本文关键字:执行 一个 缓冲区 字符 发生了 段代码 代码 什么      更新时间:2023-10-16

谁能给我一个完整的解释在这第二行代码中发生了什么?

我知道包含shellcode的缓冲区的地址被强制转换为执行的函数指针。但是我对所涉及的所有大括号和步骤有点困惑,所以我需要更详细的解释。

unsigned char buf[] = "x90x90x90x90x90x90x90x90";
((void(*)())buf)();

我试着这样向自己解释:

buf                     //address of the buffer containing code
void(*)()               //"type" function pointer returning void, no parameters
(void(*)()) buf         //cast buf to said type
( (void(*)()) buf )()   //take the outcome of the cast and execute it by appending ()

正确吗?

编辑:

我知道DEP会阻止执行,即使它执行,程序也会崩溃,因为它会在nop之后执行"随机垃圾"。我的问题是关于函数调用的语法

  1. buf(数组名转换为指针)转换为void(*)()函数指针

    (void(*)())buf
    
  2. 通过指针

    调用该函数
    (function_pointer)();
    

注意这是错误的,因为操作符优先级规则

(void(*)()) buf() // Function call has a higher precedence over type cast

所以需要另一对括号

最终执行它(如果DEP允许,这取决于系统)和(如果x86) Nop-Nop-Nop,等等。

你是对的。

作为旁注:NOP代码也会使你的应用程序崩溃:没有返回语句,IP不会在负载完成时恢复。

正确吗?我希望能得到更详细/正确的解释。

这里有一个更简洁的替代:

unsigned char buf[] = "x90x90x90x90x90x90x90x90";
// ((void(*)())buf)();
// equivalent code:
typedef void (*void_callback)(); // declare the function pointer as a named type
void_callback callback = reinterpret_cast<void_callback>(buf);
callback();