Pregunta

I detoured LoadLibraryA, in order to block the function from being called into my app. It is meant to block'dll injection'. Please refer to the well-known CDetour library if you've never seen these.

It hooks the load library function and even returns sucessfully, also blocking unknown dll's from being loaded into the memory. Any tips?

bool ( __stdcall* LoadLibraryA ) ( LPCSTR );

bool LoadLibraryADetoured( LPCSTR szMsg )
{
    if( strcmp( szMsg, "MyAllowedDll.dll" ) )
        return TRUE;

    return FALSE;
}

INT APIENTRY DllMain( HMODULE hModule, DWORD dwReason, LPVOID Reserved )
{
    switch( dwReason )
    {
        case DLL_PROCESS_ATTACH:
            {
                DWORD dwRetAddress = (DWORD)GetProcAddress( GetModuleHandleA( "kernel32.dll" ), "LoadLibraryA" );
                ZChatInput = ( bool ( __stdcall* ) ( ) )LoadLibraryA( ( PBYTE )dwRetAddress, ( PBYTE )LoadLibraryADetoured );
                DisableThreadLibraryCalls( hModule );
                break;
            }
        case DLL_THREAD_ATTACH:
        case DLL_PROCESS_DETACH:
            DetourRemove( ( PBYTE )dwRetAddress, ( PBYTE )LoadLibraryADetoured );
        case DLL_THREAD_DETACH:
            break;
    }
    return TRUE;
}
¿Fue útil?

Solución

According to MSDN, there are severe limitations of what you can safely do in DllMain(). LoadLibrary() is not safe there for sure.

From http://msdn.microsoft.com/en-us/library/windows/desktop/ms682583%28v=vs.85%29.aspx:

Because Kernel32.dll is guaranteed to be loaded in the process address space when the entry-point function is called, calling functions in Kernel32.dll does not result in the DLL being used before its initialization code has been executed. Therefore, the entry-point function can call functions in Kernel32.dll that do not load other DLLs. For example, DllMain can create synchronization objects such as critical sections and mutexes, and use TLS. Unfortunately, there is not a comprehensive list of safe functions in Kernel32.dll.

(Bold emphasis is mine)

Otros consejos

Your detour needs to use the same calling convention as the function being detoured. LoadLibraryA() uses __stdcall but your detour uses the compiler default, which is usually __cdecl instead.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top