运行环境: Windows 7 32位 Visual Studio 2010
/**
名称: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");
}
结果图: