0
votes

I have recently been attempting to hook MessageBox as part of a learning course and during this I have developed a hook-callback which is:

int WINAPI MessageBoxCallback(HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType)
{
    DWORD dwAddr = (DWORD)GetProcAddress(GetModuleHandle("User32.dll"), "MessageBoxA"); //Grab address of MessageBoxA
    __asm
    {

    add dwAddr, 0x5            //Before we continue on-wards we add 5 bytes to the current address to avoid the infinite loop
        jmp dwAddr          //Then finally jump to (MessageBoxA + 0x5)
     }

}

This is very simple to think about it as we are simply jumping back into MessageBoxA + 0x5 this so I believe has no mistake on its own, I have in-fact even checked if I have forgot to missing bytes but the prologue of the callback is:

mov edi, edi

push ebp

mov ebp esp

That said, I am sure that I have not any mistake for giving back the bytes. If so yet it crashes the program however it shows a message box then crashes after the hook was placed.

I have further checked if the hook was properly placed and it seem perfect I have done all the breakpointing and debugging yet it fails.

1

1 Answers

1
votes

MessageBoxA(), depending on the Windows version, does not create a stack frame. So it doesn't restore the ESP register in its epilogue. But your function does, required to store the dwAddr local variable. So the stack pointer doesn't get restored and the RET instruction in MessageBoxA() pops the wrong return address. Kaboom.

You'd have to tinker with __declspec(naked) to get your function's prologue to match MessageBoxA's epilogue. This works on my machine:

__declspec(naked)
int WINAPI MessageBoxCallback(HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType) {
    __asm {
        push ebp
    }
    static DWORD dwAddr = (DWORD)GetProcAddress(GetModuleHandle("User32.dll"), "MessageBoxA"); //Grab address of MessageBoxA
    __asm
    {
        add dwAddr, 0x5 
        jmp dwAddr
    }
}