在c中执行字符串的内容

executing the content of a string in c

#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

正如@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