Is it possible to load a binary file into memory and execute it in windows

人走茶凉 提交于 2020-01-01 19:31:15

问题


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



来源:https://stackoverflow.com/questions/31639006/is-it-possible-to-load-a-binary-file-into-memory-and-execute-it-in-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!