C. Raluca
C. Raluca

Reputation: 75

C++ VirtualProtect PAGE_NOACCESS causes crash

Good day, I am trying to somehow prevent "dll injection" into my program. Here is what I have so far, but it crashes my .exe for some reason.. I am loading this code, with a .dll attached to my program.

declaration:

LPBYTE _LdrLoadDll = (LPBYTE)GetProcAddress(GetModuleHandle("ntdll.dll"), "LdrLoadDll");

function:

   void HookNoAccess(LPVOID Offset, int size)
    {
        HMODULE hand = GetModuleHandle("MYPROGRAM.exe");
        DWORD OldProtect;
        VirtualProtect(Offset, size, PAGE_NOACCESS, &OldProtect);
        VirtualProtect((LPVOID)((DWORD)hand + (DWORD)0x12d1), 6, PAGE_NOACCESS, &OldProtect);
    }

calling it:

HookNoAccess(_LdrLoadDll, 2); // tried any size...

It should stop access to that current procccess, but why is it crashing...

Can someone help me please?

Upvotes: 2

Views: 1649

Answers (1)

Cody Gray
Cody Gray

Reputation: 244843

Given that LdrLoadDll is an undocumented function, I don't know for sure what it does, how it works, or where it is used internally, but I doubt that you would enjoy much success if you were able to completely block it, since it is probably what Windows itself uses to load DLLs into your process…

Beyond that, VirtualProtect affects all pages that contain one or more bytes of the specified range. In other words, the granularity of protection that it offers is that of pages. If you aren't careful to avoid other memory blocks being located on the same page, you will crash when trying to access them.

Finally, that second call to VirtualProtect is extremely suspect. What is that value you're hard-coding as the address offset? And the same problem as mentioned above: the granularity of protection offered by VirtualProtect is that of pages. A page is 4k bytes (generally speaking), so even if you only specify a size of 6 bytes, you are setting PAGE_NOACCESS for an entire 4k page that contains at least part of your application's executable code.

Really, you should only be using VirtualProtect on memory blocks that you have allocated yourself with either VirtualAlloc or VirtualAllocEx. Anything else, changing the protection level of memory blocks outside of your control, is just asking for trouble.

Upvotes: 1

Related Questions