Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hooks: why do we need to VirtualProtect() again to restore permissions?

Tags:

c++

x86

winapi

hook

Here is some standard piece of code where we install the hook rewriting some bytes at the beginning of the function of our interest. My question is: why do we need to reprotect a piece of rewrited memory? Can't we just leave it with PAGE_EXECUTE_READWRITE permissions? We assume here that we need constantly restore original bytes and rehook again.

if (VirtualProtect(funcPtr, 6, PAGE_EXECUTE_READWRITE, &dwProtect)) // make memory writable
{
    ReadProcessMemory(GetCurrentProcess(), (LPVOID)funcPtr, Hook::origData, 6, 0); // save old data
    DWORD offset = ((DWORD)hook - (DWORD)funcPtr - 5);  //((to)-(from)-5)
    memcpy(&jmp[1], &offset, 4); // write address into jmp
    memcpy(Hook::hookData, jmp, 6); // save hook data
    WriteProcessMemory(GetCurrentProcess(), (LPVOID)funcPtr, jmp, 6, 0); // write jmp
    VirtualProtect(funcPtr, 6, dwProtect, NULL); // reprotect
}
like image 953
withkittens Avatar asked Nov 19 '12 20:11

withkittens


1 Answers

Once the door is open, anyone can walk through. If you've removed write-protection from a memory range, any code can update that memory - not just your code. The memory has no way of knowing that your (legitimate) code is the one updating it versus some possible malware or even just plain buggy DLL that is also loaded into the process space. Reprotecting it helps guard against not-your-code updating the memory locations you want to change.

like image 199
prprcupofcoffee Avatar answered Nov 06 '22 23:11

prprcupofcoffee