#include <windows.h>
#include "APIHook.h"
#include <stdio.h>
/*
APIHook Class x64
Author:201724
*/
//生成内存返回地址长度
#define MAKEALLOCSIZE(dwSaveSize) ((dwSaveSize+12)*2)
/*
[x64 jmp指令替代]
mov rax,目标地址
push rax
ret
*/
APIHook::APIHook(LPCSTR pszModule,LPCSTR pszApiName,PVOID pnewFunction,DWORD dwSaveSize)
{
size_t tSize;
DWORD dwOldProtect;
DWORD_PTR dwOrigin;
byte szOpcode[] = {0x48,0xB8,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x50,0xC3};
IsSuccess = FALSE;
HMODULE hApiModule = GetModuleHandle(pszModule);
if(!hApiModule)
return;
pApiFunctions = GetProcAddress(hApiModule,pszApiName); //获取函数地址
if(!pApiFunctions)
return;
dwhookSaveSize = dwSaveSize; //保存hook的目标长度
tSize = (size_t)dwSaveSize; //保存长度到内存
pHookEntry = VirtualAlloc(0,MAKEALLOCSIZE(dwSaveSize),MEM_COMMIT,PAGE_EXECUTE_READWRITE); //申请一块内存
if(VirtualProtect(pApiFunctions,tSize,PAGE_EXECUTE_READWRITE,&dwOldProtect))
{
memcpy(pHookEntry,pApiFunctions,dwSaveSize); //复制内存..
memcpy((void *)((DWORD_PTR)&szOpcode + 2),&pnewFunction,8); //复制内存地址到opcode中
memcpy(pApiFunctions,&szOpcode,sizeof(szOpcode)); //挂钩
dwOrigin = (DWORD_PTR)pApiFunctions;
dwOrigin += (DWORD_PTR)dwSaveSize;
memcpy((void *)((DWORD_PTR)&szOpcode + 2),&dwOrigin,8); //复制内存地址到opcode中
memcpy((void *)((DWORD_PTR)pHookEntry+(DWORD_PTR)dwSaveSize),&szOpcode,sizeof(szOpcode)); //设置Origin地址
IsSuccess = TRUE;
}else
{
VirtualFree(pHookEntry,MAKEALLOCSIZE(dwSaveSize),MEM_DECOMMIT);
}
}
FARPROC APIHook::GetOrigin()
{
return (FARPROC)pHookEntry;
}
APIHook::~APIHook(void)
{
memcpy(pApiFunctions,pHookEntry,dwhookSaveSize); //解除API 挂钩
VirtualFree(pHookEntry,MAKEALLOCSIZE(dwhookSaveSize),MEM_DECOMMIT);//释放内存
}