【问题标题】:executing the content of a string in c [duplicate]在c中执行字符串的内容[重复]
【发布时间】:2021-01-22 15:21:16
【问题描述】:
#include<stdio.h>
#include<stdlib.h>

char code[] ="\x52\x56\x57\x50\xB8\x41\x00\x00\x00\x50\xB8\x01\x00\x00\x00\xBF\x01\x00\x00\x00\x48\x89\xE6\xBA\x01\x00\x00\x00\x0F\x05\x58\x58\x5F\x5E\x5A\xC3";

int main(){
    void(*func)() = (void (*)())code;
    (*func)();
    return 0 ;
    
}

我这里有一个字符串,它存储一个二进制代码来打印一个字符('A'),我将它作为一个函数指针传递给 func ,而不是我尝试执行它。 输出:

$ ./test
Segmentation fault (core dumped)

这是汇编代码:

0:  52                      push   rdx
1:  56                      push   rsi
2:  57                      push   rdi
3:  50                      push   rax
4:  b8 41 00 00 00          mov    eax,0x41
9:  50                      push   rax
a:  b8 01 00 00 00          mov    eax,0x1
f:  bf 01 00 00 00          mov    edi,0x1
14: 48 89 e6                mov    rsi,rsp
17: ba 01 00 00 00          mov    edx,0x1
1c: 0f 05                   syscall
1e: 58                      pop    rax
1f: 58                      pop    rax
20: 5f                      pop    rdi
21: 5e                      pop    rsi
22: 5a                      pop    rdx
23: c3                      ret

【问题讨论】:

标签: c linux string assembly segmentation-fault


【解决方案1】:

正如@WeatherVane 所指出的,您需要获得执行数据段的权限,mprotect 可以提供帮助:

#include <stdio.h>
#include <sys/mman.h>
#include <stdint.h>

static char code[] = "\x52\x56\x57\x50\xB8\x41\x00\x00\x00\x50\xB8\x01\x00\x00"
                     "\x00\xBF\x01\x00\x00\x00\x48\x89\xE6\xBA\x01\x00\x00\x00"
                     "\x0F\x05\x58\x58\x5F\x5E\x5A\xC3";
                                 
int main(void)
{
    uintptr_t page = (uintptr_t)code & -4095ULL;

    mprotect((void *)page, 4096, PROT_READ | PROT_EXEC | PROT_WRITE);

    void (*func)(void) = (void (*)(void))code;

    func();
    return 0;
}

你可以在godbolt看到结果(A

【讨论】:

    猜你喜欢
    • 2011-05-17
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    • 2013-10-05
    • 2020-02-14
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    相关资源
    最近更新 更多