c - 为什么需要execstack才能在堆上执行代码?

标签 c gcc

我编写了下面的代码来测试 shellcode(用于取消链接 /tmp/passwd)以在安全类中进行分配。

当我用 gcc -o test -g test.c 编译时,我在跳转到 shellcode 时遇到段错误。

当我使用 execstack -s test 对二进制文件进行后处理时,我不再遇到段错误并且 shellcode 正确执行,删除了 /tmp/passwd

我正在运行 gcc 4.7.2。要求堆栈可执行以使堆可执行似乎是个坏主意,因为后者的合法用例比前者多得多。

这是预期的行为吗?如果是这样,理由是什么?

#include <stdio.h>                                     
#include <stdlib.h>                                    


char* shellcode;                                       


int main(){                                            
    shellcode = malloc(67);                            
    FILE* code = fopen("shellcode.bin", "rb");      
    fread(shellcode, 1, 67, code);                     

    int (*fp)(void) = (int (*) (void)) shellcode;      
    fp();                                              
}    

这是xxd shellcode.bin的输出:

0000000: eb28 5e89 760c 31c0 8846 0bfe c0fe c0fe  .(^.v.1..F......           
0000010: c0fe c0fe c0fe c0fe c0fe c0fe c0fe c089  ................           
0000020: f3cd 8031 db89 d840 cd80 e8d3 ffff ff2f  ...1...@......./           
0000030: 746d 702f 7061 7373 7764                 tmp/passwd                 

最佳答案

真正的“意外”行为是设置标志使 和堆栈一样可执行。该标志旨在与生成基于堆栈的 thunk 的可执行文件一起使用(例如当您获取嵌套函数的地址时的 gcc)并且不应该真正影响堆。但是 Linux 通过全局使所有可读页面可执行来实现这一点。

如果你想要更细粒度的控制,你可以使用 mprotect 系统调用来控制每页的可执行权限——添加如下代码:

uintptr_t pagesize = sysconf(_SC_PAGE_SIZE);
#define PAGE_START(P) ((uintptr_t)(P) & ~(pagesize-1))
#define PAGE_END(P)   (((uintptr_t)(P) + pagesize - 1) & ~(pagesize-1))
mprotect((void *)PAGE_START(shellcode), PAGE_END(shellcode+67) - PAGE_START(shellcode),
         PROT_READ|PROT_WRITE|PROT_EXEC);

关于c - 为什么需要execstack才能在堆上执行代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50184682/

相关文章:

c - 为什么MinGW的stdio.h文件会导致语法错误?

使用 g++ 4.6 和 boost::unordered_map 的 C++11 相关编译错误

c++ - GCC 的 _Pragma 运算符中的预处理器标记粘贴

c - 为什么 unsigned typeof(var) 不起作用? const typeof(x) 工作得很好,为什么不呢?

c - 字符串附加功能不起作用

c - 在同一个程序中使用 scanf 和 fgets?

c - C 中的段错误导致代码有时运行但有时不运行

c++ - 与动态库链接导致的可执行运行时崩溃

c - mongodb c-api 中的 $exists 查询

c - 通过 token 连接重复调用宏是未指定的行为吗?