typedef
int
(WINAPI
*
lpMessageBoxA)(HWND, LPCSTR, LPCSTR, UINT);
BYTE olddata32[
5
]
=
{
0
};
void hook();
void Unhook();
/
/
回调函数 当调用hook时,hook执行完成后调用该函数后再进入main函数
int
WINAPI MyMessageboxA(HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType)
{
Unhook();
lpMessageBoxA messagebox
=
(lpMessageBoxA)GetProcAddress(GetModuleHandleA(
"user32.dll"
),
"MessageBoxA"
);
int
ret
=
messagebox(
0
,
"inlinehook"
,
"tip3"
,
0
);
hook();
/
/
函数释放前再次HOOK,为了拦截下次调用
return
ret;
}
void hook()
{
/
/
获取messagebox的基地址
DWORD messagebox
=
(DWORD)GetProcAddress(GetModuleHandleA(
"user32.dll"
),
"MessageBoxA"
);
BYTE data[
5
]
=
{
0xe9
, };
DWORD offset
=
(DWORD)MyMessageboxA
-
messagebox
-
5
;
/
/
计算jmp跳转的偏移量
/
/
保存前五个字节的数据
memcpy(olddata32, (const void
*
)messagebox,
5
);
/
/
把偏移量与JMP指令拼接
memcpy(&data[
1
], &offset,
4
);
DWORD oldProtect
=
0
;
/
/
更改页面属性 将内存改为可读可写可执行
VirtualProtect((LPVOID)messagebox,
5
, PAGE_EXECUTE_READWRITE, &oldProtect);
memcpy((void
*
)messagebox, data,
5
);
/
/
还原属性
VirtualProtect((LPVOID)messagebox,
5
, oldProtect, &oldProtect);
}
void Unhook()
{
DWORD messagebox
=
(DWORD)GetProcAddress(GetModuleHandleA(
"user32.dll"
),
"MessageBoxA"
);
DWORD oldProtect
=
0
;
VirtualProtect((LPVOID)messagebox,
5
, PAGE_EXECUTE_READWRITE, &oldProtect);
memcpy((void
*
)messagebox, olddata32, sizeof(olddata32));
VirtualProtect((LPVOID)messagebox,
5
, oldProtect, &oldProtect);
}
void main()
{
MessageBoxA(
0
,
"hello"
,
"tip1"
,
0
);
hook();
MessageBoxA(
0
,
"hello"
,
"tip2"
,
0
);
}