VirtualProtect raises an exception "Access violation reading location 0x00000000" when restoring old protection

-1

Let say I have an executable file called A.exe, it has a DIALOG resource with id = 101. And I also have a dll file called ResHack.dll, it has a DIALOG resource with id also = 101. I have successfully injected this DLL into A.exe process.

My purpose is when A.exe runs, it should load my DIALOG resource in ResHack.dll instead of its' original DIALOG resource, so I done something like this in my ResHack.dll:

// dll HMODULE, assuming that I got this from DllMain
HMODULE g_hModule;
// get current process (A.exe) HMODULE
HMODULE pidh = GetModuleHandleW(NULL);

int id = 101;
// get the entry of the original resource in A.exe
auto dllResEntry = (IMAGE_RESOURCE_DATA_ENTRY*)FindResourceW(g_hModule, MAKEINTRESOURCE(id), RT_DIALOG);
// get the entry of my resource in ResHack.exe
auto exeResEntry = (IMAGE_RESOURCE_DATA_ENTRY*)FindResourceW(NULL, MAKEINTRESOURCE(id), RT_DIALOG);

DWORD dwOldProtection = 0;
// change exe resource entry protection to READWRITE
VirtualProtect(exeResEntry, sizeof(*exeResEntry), PAGE_READWRITE, &dwOldProtection);

// replace offset so that it will point to my resource
exeResEntry->Size = dllResEntry->Size;
exeResEntry->OffsetToData = dllResEntry->OffsetToData + (DWORD)g_hModule - (DWORD)pidh;

// restore the old protection
VirtualProtect(exeResEntry, sizeof(*exeResEntry), dwOldProtection, NULL); // this is where the exception raises

When I run it, it raises an unexplainable exception at the second VirtualProtect call: Exception thrown at 0x590D612D in A.exe: 0xC0000005: Access violation reading location 0x00000000. (dllResEntry and exeResEntry are not null in this case).

Also I don't know if this is the right way to change exe resource on-the-fly, because if I remove the second VirtualProtect call, then this code runs, but then A.exe process fails to display any dialog.

Thanks for any help.

c++
winapi
exe
code-injection
asked on Stack Overflow Aug 29, 2018 by Meigyoku Thmn • edited Aug 29, 2018 by Meigyoku Thmn

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0