c语言钩取函数 并奉上使用实例 2021-04-08 110
运行环境: Windows 7 32位 Visual Studio 2010
/**
名称:getAPIAddress
功能: 根据模块名称和函数名称获取函数地址
参数: TCHAR * moduleName 模块名称 TCHAR * funcName 函数名称
返回值:return 1 represent moduleName is wrong
return 0 represent funcName is wrong
**/
FARPROC getAPIAddress(TCHAR * moduleName,TCHAR * wFuncName){
char funcName[MAX_PATH] = {0,};
WideCharToMultiByte(CP_ACP, NULL,(LPCWSTR)wFuncName,-1,funcName,MAX_PATH,0,0);
HMODULE hKer;
hKer = GetModuleHandle(moduleName);
if(!hKer)
return (FARPROC)-1;
return GetProcAddress(hKer,funcName);
}
/**
名称:hookByCode
功能: 在某个API下钩子
参数:TCHAR * moduleName 模块名 TCHAR * funcName 函数名 PVOID hookProc 钩子函数
返回值:PBYTE 返回被下钩子的API的前5个字节 用于脱钩
**/
PBYTE hookByCode(TCHAR * moduleName,TCHAR * funcName,PVOID hookProc){
//获取API函数地址
PVOID APIAddr = getAPIAddress(moduleName,funcName);
//保存API前五个字节
BYTE pBuf[5] = {0,};
memcpy(pBuf,APIAddr,5);
//计算跳转距离
//目标位置
DWORD desPos = (DWORD)hookProc;
//源位置
DWORD srcPos = (DWORD)APIAddr+5;
DWORD jmpDistance = desPos-srcPos;
//取得可写权限
DWORD lpflOldProtect;
VirtualProtect(APIAddr,5,PAGE_READWRITE,&lpflOldProtect);
//设置跳转语句
memcpy((byte *)APIAddr+1,&jmpDistance,4);
*(BYTE *)APIAddr = 0xE9;
VirtualProtect(APIAddr,5,lpflOldProtect,&lpflOldProtect);
return pBuf;
}
HMODULE myload(LPCSTR lpLibFileName){
printf("惊喜吗!!!");
return 0;
}
void main(){
hookByCode(L"kernel32.dll",L"LoadLibraryA",myload); //让LoadLibray被myload函数取代
HMODULE load = LoadLibraryW(L"kernel32.dll");
HMODULE (*loadW)(LPCSTR);
loadW = (HMODULE (*)(LPCSTR))GetProcAddress(load,"LoadLibraryA");
loadW("d");
}
结果图: