Detours 3.0 Hook崩溃MessageBoxA

时间:2014-01-15 03:03:32

标签: c++ winapi hook detours

我正在尝试将MessageBoxA函数与MS Detours 3.0挂钩但是当我尝试它时我的程序崩溃了。我不确定导致程序崩溃的原因。当我运行测试程序并点击shift时,会出现消息框,但是当我注入dll并命中shift时,我的程序崩溃了。

测试计划

#include <Windows.h>

int main()
{
    for(;;)
    {
        if(GetAsyncKeyState(VK_SHIFT))
        {
            MessageBoxA(0,"NOT HOOKED","HOOK STATUS",0);
        }
    }
}

HOOK DLL

#include <Windows.h>
#include <detours.h>
#pragma comment(lib,"detours.lib")

BOOL (WINAPI* oMessageBoxA)(HWND,LPCTSTR,LPCTSTR,UINT);

BOOL WINAPI hMessageBoxA( HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption,UINT uType) 
{ 
        return oMessageBoxA(hWnd,"HOOKED",lpCaption,uType);
} 

void patch()
{
    HMODULE user32 = GetModuleHandle("user32.dll");
    if(user32 != NULL)
    {
        DWORD MessageBoxAddress = (DWORD)GetProcAddress(user32,"MessageBoxA");
        oMessageBoxA = (BOOL (WINAPI*)(HWND, LPCTSTR, LPCTSTR, UINT))MessageBoxAddress;
        DetourTransactionBegin();
        DetourUpdateThread(GetCurrentThread());
        DetourAttach(&(PVOID&)oMessageBoxA, hMessageBoxA);
        DetourTransactionCommit();
    }
}

BOOL WINAPI DllMain(HINSTANCE hinstDLL,DWORD fdwReason,LPVOID lpvReserved)
{
    if(fdwReason==DLL_PROCESS_ATTACH)
    {
        patch();
    }
}

1 个答案:

答案 0 :(得分:2)

您已经错误地声明了MessageBoxA()的签名,并且使用DWORD MessageBoxAddress将无法在64位DLL中使用。

请尝试使用此DLL代码:

#include <Windows.h>
#include <detours.h>
#pragma comment(lib,"detours.lib")

typedef int (WINAPI* LPFN_MBA)(HWND, LPCSTR, LPCSTR, UINT);
LPFN_MBA oMessageBoxA = NULL;

int WINAPI hMessageBoxA( HWND hWnd, LPCSTR lpText, LPCSTR lpCaption,UINT uType) 
{ 
    return oMessageBoxA(hWnd,"HOOKED",lpCaption,uType);
} 

void patch()
{
    HMODULE user32 = GetModuleHandle(TEXT("user32.dll"));
    if (user32 != NULL)
    {
        oMessageBoxA = (LPFN_MBA) GetProcAddress(user32, "MessageBoxA");
        if (oMessageBoxA != NULL)
        { 
            DetourTransactionBegin();
            DetourUpdateThread(GetCurrentThread());
            DetourAttach((PVOID*)&oMessageBoxA, hMessageBoxA);
            DetourTransactionCommit();
        } 
    }
}

void unpatch()
{
    if (oMessageBoxA != NULL)
    {
        DetourTransactionBegin();
        DetourUpdateThread(GetCurrentThread());
        DetourDetach((PVOID*)&oMessageBoxA, hMessageBoxA);
        DetourTransactionCommit();
    }
}


BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
    if (fdwReason == DLL_PROCESS_ATTACH)
    {
        DisableThreadLibraryCalls(hinstDLL);
        patch();
    }
    else if (fdwReason == DLL_PROCESS_DETACH)
    {
        unpatch();
    }
}

阅读以下内容以获取更多详细信息:

API Hooking with MS Detours