C++跳跃钩子 [Windows]

3

我想学习有关钩子的知识,但网络上找到的教程似乎无法运行。

我想做的是C++中的跳转钩子。

下面是代码:

void DoHook(DWORD* Address, DWORD* Hook, DWORD pid){   

    HANDLE Server = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ , false, pid );
    Address = (DWORD*)Address + 0x18;
    DWORD OldProt;     
    DWORD HookOffset = (DWORD*)Hook-(DWORD*)Address-5;
    std::wcout << "Hook on address" << std::hex << Address<< std::endl;
    std::wcout << "Hook offset is " << std::hex << HookOffset << std::endl;

    if ( ! VirtualProtectEx(Server, (LPVOID) Address, 40,PAGE_EXECUTE_READWRITE, &OldProt) ) {
        ErrorExit(L"VirtualProtectEx");
    };

    char* CharPointer = (char*) Address;
    BYTE newdata[5]={0xE9}; 
    BYTE x;
    int i = 1;
    while ( HookOffset > 0 ) {
        x = HookOffset & 0xff;
        newdata[5-i] = x;
        i++;
        HookOffset >>= 8;
    }
    std::wcout << "Bytes " <<newdata[0] << " " << newdata[1] << " " << newdata[2] << " " << newdata[3] << " " << newdata[4] << std::endl;

    DWORD newdatasize = sizeof(newdata);
    if ( ! WriteProcessMemory(Server,Address,(LPCVOID*)newdata,newdatasize,NULL) ) {
        ErrorExit(L"WriteProcessMemory");
    }

//  VirtualProtect((void*) Address, 40, 0x40, &OldProt);

    return;
}

这是一些输出文本:

Process ID is 2764 // PID of the app that's being hooked
Function address is 00A81190 // this is the function i'm doing the jump to
Entry point is 00080000 // for the app that's being hooked
Hook on address 00080060 // for the app that's being hooked
Hook offset is 28048e // HookAddress - FunctionAddress - 5
Bytes e9 0 28 4 8e // this is the jump i'm planning to do
Press any key to continue . . .

然而,该应用程序未更新。

3
用这种方式无法写入其他进程的内存。请结合提升的用户权限(管理员)使用 WriteProcessMemory 函数。 - bkausbk
我会使用WriteProcessMemory,但是我似乎无法通过VirtualProtectEx触发的错误。VirtualProtectEx出现错误87:参数不正确。 - your_average_programmer
你为什么需要这样的钩子? - Walter
篡改应用程序以进行一些额外的检查,以防止某些漏洞。 - your_average_programmer
1
你没有检查OpenProcess的返回值。此外,你的地址计算是错误的。通过调试器逐步执行代码将揭示这两个问题。 - Raymond Chen
显示剩余5条评论
1个回答

0

您必须以管理员身份运行程序,才能拥有正确的权限来写入进程内存。这是我测试和使用过多次的x86跳转函数。

bool Detour32(char* src, char* dst, const intptr_t len)
{
    if (len < 5) return false;

    DWORD  curProtection;
    VirtualProtect(src, len, PAGE_EXECUTE_READWRITE, &curProtection);

    intptr_t  relativeAddress = (intptr_t)(dst - (intptr_t)src) - 5;

    *src = (char)'\xE9';
    *(intptr_t*)((intptr_t)src + 1) = relativeAddress;

    VirtualProtect(src, len, curProtection, &curProtection);
    return true;
}

src 是你想要放置钩子的地址,dst 是你想要跳转到的地址。len 是你将使用 jmp 销毁的字节数。jmp 是 5 字节,所以如果你要销毁超过 5 字节的指令,你需要将更多的“被窃取的字节”复制到目标中,以确保它们被执行。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接