【问题标题】:Read and Execute Shellcode from a .txt File从 .txt 文件读取并执行 Shellcode
【发布时间】:2013-07-24 18:52:31
【问题描述】:

Testing Shellcode From C Bus Error 10

以上是我之前的问题,当 shell 代码在源代码中时,它涉及从 c 程序中执行 shellcode。它由 Carl Norum 解决,是由于内存保护。我有一个不同的问题,但相似。我不想将 shell 代码放在同一个文件中,而是想从 .txt 文件中读取 shell 代码并执行它。下面我尝试将一段内存标记为 PROT_EXEC 并将 .txt 文件的内容读入其中并执行。但它不起作用,我遇到了同样的错误,KERN_PROTECTION_FAILURE,我尝试使用 mprotect 和 mmap 将一段内存标记为 PROT_EXEC。

#include <stdio.h>
#include <sys/mman.h>
#include <string.h>
#include <stdlib.h>

int (*ret)();

unsigned char* buf;

int main()
{
    FILE* file;
    file = fopen("text.txt", "rb");

    fseek(file, 0, SEEK_END);
    unsigned int len = ftell(file);
    fseek(file, 0, SEEK_SET);

    buf = valloc(len);
    fread(buf, 1, len, file);

    fclose(file);

    mprotect(buf, len, PROT_EXEC);

   // I also tried mmap, but same error.
   /* void *ptr = mmap(0, 1024, PROT_EXEC, MAP_ANON | MAP_PRIVATE, -1, 0);

    if (ptr == MAP_FAILED)
    {
        perror("mmap");
        exit(-1);
    }

    memcpy(ptr, buf, 1024);*/

    ret = buf;

    ret();

    return 0;
}

这是我正在阅读的 text.txt 文件,它与我之前的问题中的 hello world 代码相同:

\x55\x48\x89\xe5\xeb\x33\x48\x31\xff\x66\xbf\x01\x00\x5e\x48\x31\xd2\xb2\x0e\x41\xb0\x02\x49\xc1\xe0\x18\x49\x83\xc8\x04\x4c\x89\xc0\x0f\x05\x31\xff\x41\xb0\x02\x49\xc1\xe0\x18\x49\x83\xc8\x01\x4c\x89\xc0\x0f\x05\x48\x89\xec\x5d\xe8\xc8\xff\xff\xff\x48\x65\x6c\x6c\x6f\x2c\x20\x57\x6f\x72\x6c\x64\x21\x0a

由于我将 txt 文件的内容复制到 PROC_EXEC 内存中,我不明白为什么会收到 KERN_PROTECTION_FAILURE。

【问题讨论】:

    标签: c macos shellcode


    【解决方案1】:

    根据我对您之前问题的回答,这里有一个解决方案:

    #include <stdio.h>
    #include <sys/mman.h>
    #include <sys/stat.h>
    #include <stdlib.h>
    
    int main(void)
    {
        FILE *file = fopen("text.txt", "r");
        unsigned char *buf;
        int length = 0;
        struct stat st;
        int v;
    
        // get file size and allocate. We're going to convert to bytes 
        // from text, so this allocation will be safely large enough
        fstat(fileno(file), &st);
        buf = valloc(st.st_size);
        while (fscanf(file, "\\x%02x", &v) == 1)
        {
            buf[length++] = v;
        }
    
        fclose(file);
    
        mprotect(buf, length, PROT_EXEC);
    
        int (*ret)() = (int (*)())buf;
        ret();
    
        return 0;
    }
    

    你的程序唯一需要改变的是循环将 ASCII 文本转换为二进制数据。为了方便起见,我使用了fscanf,但这很脆弱。

    【讨论】:

    • 以下问题:我用 C 语言编写了一个简单的“hello world”程序,在编译后的二进制文件上运行 otool -t,用 otool 的输出替换 text.txt 代码(在同一个 \x (...) 格式),并尝试运行。段故障 11,但不知道为什么。如何生成自己的“shellcode”?
    • @Charybdis,很难说没有看到更多的代码和/或二进制文件。如果你用 C 编写它,你可能会为你的操作系统链接 C 库和运行时的东西,后者你当然不希望包含在内。尝试制作一个非常简单的主例程并仅提取该代码。
    猜你喜欢
    • 1970-01-01
    • 2023-01-26
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    • 2017-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多