【原创】简单通用的Inline Hook代码

前不久给羽毛写一个Hook时弄的,当时用的VirtualAlloc,今天发现可以创建可执行的堆,那么为了节省空间就改成HeapAlloc了。

适用于已经确定要Hook位置和需要取下的代码长度的inline hook,hook为相对地址jmp,占用5字节。不适用于要hook的地址已经有jmp类指令,比如已经被别的程序装了钩子,那样的话需要单独处理,即将原来的钩子移走的同时修改原来钩子的相对跳转值,一般情况用不上,不符合“简单”的要求。

下面贴代码:

HANDLE hHookHeap = NULL;
 
PVOID InstallHook(PVOID CodeAddr, LONG CodeLen, PVOID HookProc)    //ret: StubProc
{
    if (hHookHeap == NULL) hHookHeap = HeapCreate(HEAP_CREATE_ENABLE_EXECUTE, 0, 0);
    DWORD oldProtect;
    VirtualProtect(CodeAddr, CodeLen, PAGE_EXECUTE_READWRITE, &oldProtect);
    PVOID StubProc = HeapAlloc(hHookHeap, 0, CodeLen + 5);
    memcpy(StubProc, (PVOID)CodeAddr, CodeLen);
    *((PBYTE)StubProc + CodeLen) = '\xE9';
    *(PDWORD)((PBYTE)StubProc + CodeLen + 1) = (DWORD)CodeAddr + CodeLen - ((DWORD)StubProc + CodeLen + 5);
    *((PBYTE)CodeAddr) = '\xE9';
    *(PDWORD)((PBYTE)CodeAddr + 1) = (DWORD)HookProc - ((DWORD)CodeAddr + 5);
    VirtualProtect(CodeAddr, CodeLen, oldProtect, &oldProtect);
    return StubProc;
}

VOID UninstallHook(LPVOID CodeAddr, LONG CodeLen, LPVOID StubProc)
{
    DWORD oldProtect;
    VirtualProtect(CodeAddr, CodeLen, PAGE_EXECUTE_READWRITE, &oldProtect);
    memcpy(CodeAddr, StubProc, CodeLen);
    HeapFree(hHookHeap, 0, StubProc);
    VirtualProtect(CodeAddr, CodeLen, oldProtect, &oldProtect);
}

One thought on “【原创】简单通用的Inline Hook代码

  1. Yo

    vb基本解决,目前还处于跪求嵌入汇编模式开发。天煞、有人用vb去开发sys,居然没人深入对嵌入汇编的开发。

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Using REAL email address will help you receive reply notifications.

Current ye@r *