头文件(hookMain.h)内容
#pragma once
#include<Windows.h>DWORD* g_iatAddr = NULL;
DWORD* g_unHookAddr = NULL;BOOL InstallHook(); //安装钩子
BOOL UninstallHook(); //卸载钩子
DWORD* GetIatAddr(const char* dllName, const char* dllFuncName);
源文件(iatHookMain.cpp)内容
#include "hookMain.h"int WINAPI HookMessageBoxW( //必须指定调用约定,否则注入时会弹错误窗口HWND hWnd,LPCWSTR lpText,LPCWSTR lpCaption,UINT uType
)
{int result = MessageBoxA(0, "51hook", "提示", MB_OK);return result;
}BOOL InstallHook() //安装钩子
{DWORD dwOldProtect = 0;VirtualProtect(g_iatAddr, 4, PAGE_EXECUTE_READWRITE, &dwOldProtect);*g_iatAddr = (DWORD)HookMessageBoxW;VirtualProtect(g_iatAddr, 4, dwOldProtect, &dwOldProtect);return TRUE;
}BOOL UninstallHook() //卸载钩子
{DWORD dwOldProtect = 0;VirtualProtect(g_iatAddr, 4, PAGE_EXECUTE_READWRITE, &dwOldProtect);*g_iatAddr = (DWORD)g_unHookAddr;VirtualProtect(g_iatAddr, 4, dwOldProtect, &dwOldProtect);return TRUE;
}DWORD* GetIatAddr(const char* dllName, const char* dllFuncName)
{HMODULE hModule = GetModuleHandleA(0); //获取当前进程exe文件模块句柄DWORD dwhModule = (DWORD)hModule;PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)hModule; //获取dos头PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS)(pDosHeader->e_lfanew + dwhModule); //获取NT头PIMAGE_OPTIONAL_HEADER pOptionHeader = &pNtHeader->OptionalHeader; //获取可选PE头IMAGE_DATA_DIRECTORY dataDirectory = pOptionHeader->DataDirectory[1]; //获取数据目录表PIMAGE_IMPORT_DESCRIPTOR pImageImportTable = (PIMAGE_IMPORT_DESCRIPTOR)(dataDirectory.VirtualAddress + dwhModule); //获取导入表while (pImageImportTable->Name) // 遍历导入表获取符合条件的函数{char* iatDllName = (char*)(pImageImportTable->Name + dwhModule);if (_stricmp(iatDllName, dllName) == 0){PIMAGE_THUNK_DATA pInt = (PIMAGE_THUNK_DATA)(pImageImportTable->OriginalFirstThunk+ dwhModule); //获取导入名称表PIMAGE_THUNK_DATA pIat = (PIMAGE_THUNK_DATA)(pImageImportTable->FirstThunk+ dwhModule); //获取导入地址表while (pInt->u1.Function){if ((pInt->u1.Ordinal & 0x8000000) == 0){PIMAGE_IMPORT_BY_NAME pImportName = (PIMAGE_IMPORT_BY_NAME)(pInt->u1.Function + dwhModule);if (_stricmp(pImportName->Name, dllFuncName) == 0){return (DWORD*)pIat;}}++pInt;}}++pImageImportTable;}return NULL;
}BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD callReason, LPVOID lpReservered)
{if (callReason == DLL_PROCESS_ATTACH){/*** 1 获取iat表* 2 保存要hook的函数地址* 3 安装钩子*/g_iatAddr = GetIatAddr("user32.dll", "MessageBoxW");g_unHookAddr = (DWORD*)* g_iatAddr;InstallHook();}else if (callReason == DLL_PROCESS_DETACH){UninstallHook();}return TRUE;
}