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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With