Injecting code into executable at runtime

Deadly 提交于 2019-11-30 04:01:54

This is essentially how executable loaders do things; in their case they perform a mmap of a file, not an anonymous mapping, but apart from that it's essentially the same.

Note that it's a good idea not to have both write and execute access at the same time, as it makes certain types of security exploits easier. You can use mprotect to adjust the protection flags after the initial mapping.

Thomas Pornin

Your solution is mostly what should be done: have the OS consider the pages as executable. However, some operating systems will enforce the so-called W^X policy, in which a page can be either writable or executable, but not both simultaneously. For such systems (namely OpenBSD, but there are modified Linux versions which do it too), your mmap() above will fail. So the complete solution would entail first allocating some pages with mmap() and PROT_READ | PROT_WRITE, then use mprotect() to switch the pages to PROT_READ | PROT_EXEC when the code has been generated.

Even if the OS does not enforce W^X, a call to mprotect() is highly recommended because of cache effects (data access and execution are quite separate from each other in the CPU; you want to be sure that the CPU will use your newly written opcodes and not what was in RAM immediately before; mprotect() contains the necessary magic for that).

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