Read and Execute Shellcode from a .txt File

2019-02-20 04:59发布

问题:

Testing Shellcode From C Bus Error 10

Above was my previous question which involved excuting shellcode from within a c program, when the shell code is inside the source. It was solved by Carl Norum and was due to memory protection. I have a different problem but is similar. Instead of having the shell code in the same file, I want to read the shell code from a .txt file and execute it. Below I tried marking a section of memory as PROT_EXEC and read the contents of the .txt file into it and execute. But it won't work, I'm getting the same error, KERN_PROTECTION_FAILURE, I tried using mprotect and mmap to mark a section of memory as 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;
}

This is the text.txt file I'm reading in, its the same hello world code, from my previous question:

\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

Since I'm copying the contents of the txt file into PROC_EXEC memory, I don't understand why I'm getting KERN_PROTECTION_FAILURE.

回答1:

Building on my answer to your previous question, here's a solution:

#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;
}

The only real thing that had to change from your program is the loop to convert the ASCII text into binary data. I used fscanf for expediency, but that's pretty fragile.