如何在运行时挂钩函数

How to hook a function at runtime

提问人:houxinlin 提问时间:11/3/2023 最后编辑:273Khouxinlin 更新时间:11/3/2023 访问量:45

问:

我有以下代码,这段代码来自“https://blog.securehat.co.uk/process-injection/manually-implementing-inline-function-hooking”,我修改了一个挂接自己的函数,但是运行时出错。

#include <Windows.h>

#include <stdio.h>

typedef int(__stdcall* tdOrigFunction)(int name);
tdOrigFunction testFunctionATrampoline;

int __stdcall HookedTestFunction(int name)
{
    printf("HookedMessageBox\n");
    testFunctionATrampoline(name);
    return 2;
}

int Error(const char* msg) {
    printf("%s (%u)", msg, GetLastError());
    return 1;
}
int testFunction(int name) {
    printf("testFunction");
    printf("testFunction");
    printf("testFunction");
    printf("testFunction");
    printf("testFunction");
    printf("testFunction%d",name);
    return 1;
}

int main()
{
    BYTE* origFunctionAddress = NULL;
    BYTE* trampolineAddress = NULL;



    origFunctionAddress = testFunction;
    HANDLE hProcess = GetCurrentProcess();

    BYTE buffer[128] = { 0 };

    SIZE_T nSize = sizeof(buffer);
    SIZE_T bytesRead; 
    BOOL result = ReadProcessMemory(hProcess, origFunctionAddress, buffer, nSize, &bytesRead);

    int offset = 0;
    for (int i = 0; i < 4; i++) {
        offset |= (buffer[1 + i] << (i * 8));
    }
    origFunctionAddress = origFunctionAddress + offset + 5;

    trampolineAddress = (BYTE*)VirtualAlloc(NULL, 20, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
    if (trampolineAddress == NULL) {
        Error("Failed to allocate memory for trampoline");
    }

    int numOfBytesToCopy = 5;
    char trampoline[10] = { 0 };

    memcpy_s(trampoline, numOfBytesToCopy, origFunctionAddress, 5);


    *(DWORD*)(trampoline + numOfBytesToCopy) = 0xE9;


    uintptr_t jumpAddress = (BYTE*)origFunctionAddress - trampolineAddress - numOfBytesToCopy;


    *(uintptr_t*)((uintptr_t)trampoline + numOfBytesToCopy + 1) = jumpAddress;

    if (!WriteProcessMemory(GetCurrentProcess(), trampolineAddress, trampoline, sizeof(trampoline), NULL)) {
        return Error("Error while writing process memory to trampoline");
    }


    DWORD oldProtectVal;
    VirtualProtect(origFunctionAddress, 6, PAGE_EXECUTE_READWRITE, &oldProtectVal);

    *(BYTE*)origFunctionAddress = 0xE9;


    intptr_t hookAddress = (intptr_t)((CHAR*)HookedTestFunction - (intptr_t)origFunctionAddress) - 5;


    *(intptr_t*)((intptr_t)origFunctionAddress + 1) = hookAddress;


    VirtualProtect(origFunctionAddress, 6, oldProtectVal, &oldProtectVal);


    testFunctionATrampoline = (tdOrigFunction)trampolineAddress;

    testFunction(1);

    return 0;
}

我找不到任何相关的钩子方法,其中大多数是针对DLL的,而不是我的要求

c 视窗 NASM

评论

0赞 Cem Polat 11/3/2023
计算应相对于 HookedTestFunction 的地址,而不是 origFunctionAddress 的地址。您应该计算 HookedTestFunction 和 origFunctionAddress 之间的偏移量,并使用它来设置跳转地址。
0赞 houxinlin 11/4/2023
我不太懂组装。您能花几分钟时间帮助我进行必要的修改吗?谢谢。

答: 暂无答案