Prevent your DLL from being unloaded

30 06 2008

Here’s the scenario, you’ve just found a neat little way to inject your dll into another process but for one reason or another your dll is being unloaded instantly right after DllMain() is called. Damn, you think! It must be checking the dll somehow and calling FreeLibrary() if it doesn’t match specific requirements, how do I bypass this?

I had no idea either until I read this article.

Essentially what you do is call LoadLibrary() again from inside your DllMain() function so the count for your dll is incremented, the host app calls FreeLibrary() and you stay resident (every one is happy).

Here’s the source for you lazy types….


BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch(ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
LockLibraryIntoProcessMem(hModule, &g_Self);
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
int LockLibraryIntoProcessMem(HMODULE DllHandle, HMODULE *LocalDllHandle)
{
if(NULL == LocalDllHandle)
return ERROR_INVALID_PARAMETER;
*LocalDllHandle = NULL;
TCHAR moduleName[1024];
if(0 == GetModuleFileName(DllHandle, moduleName, sizeof(moduleName)/ sizeof(TCHAR)))
return GetLastError();
*LocalDllHandle = LoadLibrary(moduleName);
if(NULL == *LocalDllHandle)
return GetLastError();
return NO_ERROR;
}

Also I apologise for the shitbox code paste, the <code> tags on wordpress seem to go crazy whenever you insert a newline.


Actions

Information

Leave a comment