Make Your Dynamic Module Unfreeable (Anti-FreeLibrary)1 minute read
Let’s say your product injects a module into a target process, if the target process knows the existence of your module it can call
FreeLibrary function to unload your module (assume that the reference count is one).
One way to stay injected is to hook
FreeLibrary function and check passed arguments every time the target process calls
There is a way to get the same result without hooking.
LdrUnloadDll function, it checks the
ProcessStaticImport field of
LDR_DATA_TABLE_ENTRY structure to check if the module is dynamically loaded or not.
The check happens inside
ProcessStaticImport field is set,
LdrpDecrementNodeLoadCountLockHeld returns without freeing the loaded module
So, if we set the
FreeLibrary will not be able to unload our module:
In this case, the module prints
"Hello" every time it attaches to a process, and
"Bye!" when it detaches.
There is an officially supported way of doing the same thing:
"The module stays loaded until the process is terminated, no matter how many times FreeLibrary is called."