Is it possible to load a binary file into memory a

2020-07-30 07:13发布

问题:

I am trying to write a program to read a binary file from memory execute it and exit but the OS doesn't seem to let me execute it from memory, the entire point of this exercise is to load a binary file with no header into memory.

This is my code for the binary file:

push eax

mov eax,3
mov edi,eax
sub eax,edi


pop eax
leave
ret

And my loader is as follows:

int main(int argc, char **argv){
    void (*ptr)(void);
    FILE *fo = fopen(argv[1],"r");
    int l = fseek(fo,0,SEEK_END);
    fread((void*)ptr,l*sizeof(char),1,fo);
    ptr();
    return 0;
}

I know I am probably going about this the wrong way.

回答1:

While the code you showed is location independent, so can execute anywhere, it is not the case of memory allocated for data. Actual versions of OS's enforces the memory access protection explicitly denying execution on data memory. But first of all there is a big error in your program, you have not defined any memory for the code you want load:

void (*ptr)(void);  //This allocates only space for a function pointer, but no memory

When reading data from disk it will be write somewhere in memory triggering a memory access fault. To get executable memory from OS you can use functions as VirtualAlloc, and then make the allocated memory executable using other functions as VirtualProtect. Then you must assign to your function pointer the address of executable memory and only at that time read code from disk. This process is often used for malware or code injection, and can work for local or remote processes, that's why I'll not give better explanation. Curiosity is good, but... ;-)



回答2:

Is it possible? Yes. But as people have commented, there's much more to it than what you're currently going on (even ignoring the pending seg fault in your code). Among other things you should realize that Visual Studio (at least) build programs that by default are explicitly prevented from executing 'data'. See documentation for the /NXCOMPAT flag and Data Execution Prevention