我正在尝试编写一个简单的钩子类,该钩子类将钩子安装在目标地址处,并绕开流程进入自定义函数。

Main.cpp

#include "SingleHook.h"
#include <iostream>

using namespace std;

void originalFunction()
{
    cout << "originalFunction()" << endl;
}

void fakeFunction()
{
    cout << "fakeFunction()" << endl;
}

void main()
{
    SingleHook sHook((DWORD)originalFunction, (DWORD)fakeFunction);

    originalFunction(); //Should call the original function
    sHook.InstallHook();

    originalFunction(); //Should call the fake function

    sHook.UninstallHook();
    originalFunction(); //Should again call the original function

    cin.get();
}


单钩

#pragma once
#define HLength 6
#include <windows.h>

class SingleHook {
private:
    void* hookTarget;
    byte originalBytes[HLength];
    byte hookBytes[HLength];

public:
    SingleHook(DWORD originalFunction, DWORD targetFunction)
    {
        //backing up original bytes
        ::memcpy(originalBytes, &originalFunction, HLength);

        //generating hook bytes
        hookBytes[0] = 0x68; //push
        hookBytes[1] = ((byte*)targetFunction)[0];
        hookBytes[2] = ((byte*)targetFunction)[1];
        hookBytes[3] = ((byte*)targetFunction)[2];
        hookBytes[4] = ((byte*)targetFunction)[3];
        hookBytes[5] = 0xC3; //retn

        //setting up hook target
        hookTarget = &originalFunction;
    }

    void* InvokeOriginalFunction(...);
    void InstallHook();
    void UninstallHook();
};


SingleHook.cpp

#include "SingleHook.h"

void* SingleHook::InvokeOriginalFunction(...)
{
    UninstallHook();
    //TODO INVOKE ORIGINAL SOMEHOW
    InstallHook();

    return nullptr;
}

void SingleHook::InstallHook()
{
    DWORD oldProt;
    ::VirtualProtect(hookTarget, HLength, PAGE_EXECUTE_READWRITE, &oldProt);
    ::memcpy(hookTarget, hookBytes, HLength);
    ::VirtualProtect(hookTarget, HLength, oldProt, nullptr);
}

void SingleHook::UninstallHook()
{
    DWORD oldProt;
    ::VirtualProtect(hookTarget, HLength, PAGE_EXECUTE_READWRITE, &oldProt);
    ::memcpy(hookTarget, originalBytes, HLength);
    ::VirtualProtect(hookTarget, HLength, oldProt, nullptr);
}


现在的问题是,当我安装挂钩并尝试调用originalFunction()时,它仍然进入原始功能,而未调用fakeFunction() ...我已经仔细检查了代码,一切似乎都很好,但是必须某个地方的陷阱。

最佳答案

看看这里:

SingleHook(DWORD originalFunction, DWORD targetFunction)
{
    //backing up original bytes
    ::memcpy(originalBytes, &originalFunction, HLength);


&originalFunction是堆栈上变量originalFunction的地址。请改用(void*)originalFunction

10-08 11:10