#include "Hook.h"
void CHook::OnHook()
{
VirtualProtectEx(hProcess, pHook->FunAddr, 5, PAGE_READWRITE, &dwPID);
WriteProcessMemory((HANDLE)-1, pHook->FunAddr, pHook->NewCode, 5, 0); //替换函数地址
VirtualProtectEx(hProcess, pHook->FunAddr, 5, dwPID, &dwPID);
}
void CHook::UnHook()
{
VirtualProtectEx(hProcess, pHook->FunAddr, 5, PAGE_READWRITE, &dwPID);
WriteProcessMemory((HANDLE)-1, pHook->FunAddr, pHook->OldCode, 5, 0); // 还原函数地址
VirtualProtectEx(hProcess, pHook->FunAddr, 5, dwPID, &dwPID);
}
CHook::CHook(HMODULE hModule, LPCTSTR lpszFunName, FARPROC* dwOldFunc, FARPROC* dwNewFunc)
{
pHook = new HOOKSTRUCT;
// 记录函数地址
pHook->FunAddr = GetProcAddress(hModule, lpszFunName);
if (pHook->FunAddr){
*dwOldFunc = pHook->FunAddr;
dwPID = GetCurrentProcessId();
hProcess = OpenProcess(PROCESS_ALL_ACCESS, 0, dwPID);
// 备份原函数的前5个字节, 一般以 __stdcall 声明的 API 理论上都可以这样 HOOK
memcpy(pHook->OldCode, pHook->FunAddr, 5);
pHook->NewCode[0] = 0xE9; // 构造JMP
DWORD dwJmpAddr = (DWORD)dwNewFunc - (DWORD)pHook->FunAddr - 5; // 计算JMP地址
memcpy(&pHook->NewCode[1], &dwJmpAddr, 4);
//开始进行HOOK
OnHook();
}
}
CHook::CHook(HMODULE hModule, LPCTSTR lpszFunName, FARPROC* dwOldFunc)
{
pHook = new HOOKSTRUCT;
// 记录函数地址
pHook->FunAddr = GetProcAddress(hModule, lpszFunName);
if (pHook->FunAddr){
*dwOldFunc = pHook->FunAddr;
}
}
CHook::~CHook()
{
UnHook();
}
API Hook 已不是秘密,只是折腾出了一个Class方便使用而已
也是修改IAT,但纠结的是需要不断的WriteMemory临界区,
调用一次写两次,一次Hook,一次还原......
看了一下Detours的代码,好像在执行Hook函数时不时从开头的几个字节执行的...好像jmp一下跳过了一段代码再执行的...求高人给点意见,我想完善一下这个Class
每回执行函数前都要Hook,执行完还要Unhook,好环燥嘞~~
[招生]科锐逆向工程师培训(2024年11月15日实地,远程教学同时开班, 第51期)