How to make a Hook and Trampoline function in one for WinAPI hooking

只愿长相守 提交于 2019-12-06 07:26:59

If I understood the question correctly, you want to avoid "hard-coding" the trampoline function in assembly, presumably so you could have multiple trampolines in use at the same time without duplicating the code. You can achieve this using VirtualAlloc (malloc won't work since the returned memory won't be executable).

I wrote this from memory without access to a compiler so it might have some minor bugs, but the general idea is here. Normally you would also use VirtualProtect to change the page permissions to r-x instead of rwx once you're done modifying it, but I've left that out for the sake of simplicity:

void *CreateTrampoline(void *originalFunc)
{
    /* Allocate the trampoline function */
    uint8_t *trampoline = VirtualAlloc(
        NULL,
        5 + 5, /* 5 for the prologue, 5 for the JMP */
        MEM_COMMIT | MEM_RESERVE,
        PAGE_EXECUTE_READWRITE); /* Make trampoline executable */

    /* Copy the original function's prologue */
    memcpy(trampoline, originalFunc, 5);

    /* JMP rel/32 opcode */
    trampoline[5] = 0xE9;

    /* JMP rel/32 operand */
    uint32_t jmpDest = (uint32_t)originalFunc + 5; /* Skip original prologue */
    uint32_t jmpSrc = (uint32_t)trampoline + 10; /* Starting after the JMP */
    uint32_t delta = jmpDest - jmpSrc;
    memcpy(trampoline + 6, &delta, 4);

    return trampoline;
}

Your InstallHook function would then just call CreateTrampoline to create a trampoline, then patch the first 5 bytes of the original function with a JMP rel/32 to your hook.

Be warned, this only works on WinAPI functions, because Microsoft requires that they have a 5-byte prologue to enable hot-patching (which is what you're doing here). Normal functions do not have this requirement -- usually they only start with push ebp; mov ebp, esp which is only 3 bytes (and sometimes not even that, if the compiler decides to optimize it out).

Edit: here's how the math works:

                          _______________delta______________
                         |                                  |
trampoline               |                  originalFunc    |
    |                    |                        |         |
    v                    |                        v         v
    [prologue][jmp delta]                         [prologue][rest of func]
    |________||_________|                         |________|
         5    +    5                                   5
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!