My goal is hook all LoadLibrary calls from particular dll and its dependencies (which may be delayed importable). Here is how I'm trying to solve this task:
Load this dll using
DONT_RESOLVE_DLL_REFERENCES
flag.1.1. Apply this algorithm to dll's submodules recursively.
- Fill the Import Table of this dll manually.
- Hook all
LoadLibraryA
,LoadLibraryW
etc. functions just patching Import Table. - Call
DllMain
of this dll manually withDLL_PROCESS_ATTACH
flag.
And I had a problem with the last step. If I call DllMain
manually then all inner LoadLibrary
calls will be executed from my module's address space (not from dll's one) and all my hooks from step3 is not calling.
And I don't want to hook LoadLibrary
calls in my main module because there is other code which calls LoadLibrary
and I don't wont such side-effects.
So my question is how should I call DllMain in order to force it not using LoadLibrary
from my main module? Is it because of the delayed-import? Or is it just because as I call DllMain
? Or maybe there are better solution of this task?
Here is how I run dll:
void PEUtility::runDllMain(HMODULE module)
{
typedef BOOL(WINAPI *DllMainFunPtr)(HMODULE, DWORD, LPVOID);
auto header = ImageNtHeader(module);
auto dllMain = (DllMainFunPtr)(header->OptionalHeader.AddressOfEntryPoint + (DWORD_PTR)module);
dllMain(module, DLL_PROCESS_ATTACH, NULL);
}
Here is how I fill Import Table: my question about how I'm filling import table
LoadLibrary
hooking is similar to Import Table filling.
UPDATE
I've added a couple of screenshots from ApiMonitor to demonstrate that LoadLibrary("...mso20win32client.dll")
was called from different modules for the case then I load parent library olmapi32.dll
(which depends on mso20win32client.dll
) using all this stuff described above and for the case then I just call LoadLibrary
:
When I use my method described above (using DONT_RESOLVE_DLL_REFERENCES
, DllMain
etc.) (NOTE LAST LINE: mso20win32client.dll
was loaded from mapi32ex64.dll
- my main module):
When I just call LoadLibrary("OLMAPI32.dll")
(NOTE LAST LINE: mso20win32client.dll
was loaded from olmapi32.dll
- dll that I want do load using my method):