//
//本程序是用寻找并修改(Improt Address Table)的方法来实现HOOK一个API函数
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#define UNICODE
#define _UNICODE
PIMAGE_DOS_HEADER pDosHeader;
PIMAGE_NT_HEADERS pNTHeaders;
PIMAGE_OPTIONAL_HEADER pOptHeader;
PIMAGE_IMPORT_DESCRIPTOR pImportDescriptor;
PIMAGE_THUNK_DATA pThunkData;
PIMAGE_IMPORT_BY_NAME pImportByName;
HMODULE hMod;
int * addr = (int *)MessageBoxA; //保存函数的入口地址
// 定义MessageBoxA函数原型
typedef int (WINAPI *PFNMESSAGEBOX)(HWND, LPCSTR, LPCSTR, UINT uType);
int WINAPI MessageBoxProxy(IN HWND hWnd, IN LPCSTR lpText, IN LPCSTR lpCaption, IN UINT uType);
int * myaddr = (int *)MessageBoxProxy;
int main()
{
//OutputDebugString(_T("start !"));
MessageBoxA(NULL, "原函数", "09HookDemo", 0);
//-------------HOOK部分
hMod = GetModuleHandle(NULL);
pDosHeader = (PIMAGE_DOS_HEADER)hMod;
pNTHeaders = (PIMAGE_NT_HEADERS)((BYTE *)hMod + pDosHeader->e_lfanew);
pOptHeader = (PIMAGE_OPTIONAL_HEADER)&(pNTHeaders->OptionalHeader);
pImportDescriptor = (PIMAGE_IMPORT_DESCRIPTOR)((BYTE *)hMod + pOptHeader->DataDirectory[1].VirtualAddress);
while(pImportDescriptor->FirstThunk)
{
char * dllname = (char *)((BYTE *)hMod + pImportDescriptor->Name);
//printf("函数模块:%s\n",dllname);
pThunkData = (PIMAGE_THUNK_DATA)((BYTE *)hMod + pImportDescriptor->OriginalFirstThunk);
int no = 1;
while(pThunkData->u1.Function)
{
char * funname = (char *)((BYTE *)hMod + (DWORD)pThunkData->u1.AddressOfData + 2);
PDWORD lpAddr = (DWORD *)((BYTE *)hMod + (DWORD)pImportDescriptor->FirstThunk) +(no-1);
//printf("%4d: ",no);
//printf("%30s",funname);
//printf("%8x\n",lpAddr);
//printf("%8x\n",*lpAddr);
//修改内存的部分
if((*lpAddr) == (int)addr)
{
//修改内存页的属性
DWORD dwOLD;
MEMORY_BASIC_INFORMATION mbi;
VirtualQuery(lpAddr,&mbi,sizeof(mbi));
VirtualProtect(lpAddr,sizeof(DWORD),PAGE_READWRITE,&dwOLD);
//写内存
WriteProcessMemory(GetCurrentProcess(),
lpAddr, &myaddr, sizeof(DWORD), NULL);
//恢复内存页的属性
VirtualProtect(lpAddr,sizeof(DWORD),dwOLD,0);
}
//---------
no++;
pThunkData++;
}
pImportDescriptor++;
}
//用于测试的API函数
MessageBoxA(NULL, "原函数", "09HookDemo", 0);
getchar();
return 0;
}
int WINAPI MessageBoxProxy(IN HWND hWnd, IN LPCSTR lpText, IN LPCSTR lpCaption, IN UINT uType)
{
return ((PFNMESSAGEBOX)addr)(NULL, "Gxter", "Gxter", 0);
//用地址调用一个API函数
}
[培训]内核驱动高级班,冲击BAT一流互联网大厂工作,每周日13:00-18:00直播授课