Created
July 12, 2017 13:08
-
-
Save lxfly2000/32f084ead834fb9fb8e71539bacca73c to your computer and use it in GitHub Desktop.
替换函数地址实现Hook。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//参考:http://blog.csdn.net/friendan/article/details/12222651 | |
//目前只能对自身进程Hook。 | |
#ifndef WIN32 | |
#error 该程序目前只能在 x86 平台中使用。 | |
#endif | |
#include<Windows.h> | |
using FUNCTYPE = decltype(MessageBox); | |
FUNCTYPE *funcOriginal = nullptr; | |
DWORD protectOriginal; | |
bool hookOn = false; | |
char apientry[5]; | |
DWORD hHookPid; | |
HANDLE hHookProcess; | |
void StartHook(); | |
void StopHook(); | |
int WINAPI RedirectFunction(HWND hWindow, LPCWSTR msg, LPCWSTR title, UINT type) | |
{ | |
OutputDebugString(msg); | |
OutputDebugString(TEXT(" ...Hook成功\n")); | |
StopHook();//注意此时函数被Hook,应先临时关闭Hook才可调用原函数 | |
int r = MessageBox(hWindow, TEXT("你成功实现了Hook。"), title, type); | |
StartHook(); | |
return r; | |
} | |
void StartHook() | |
{ | |
hHookProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, hHookPid); | |
funcOriginal = (FUNCTYPE*)GetProcAddress(LoadLibrary(TEXT("user32.dll")), "MessageBoxW"); | |
memcpy(apientry, funcOriginal, 5); | |
DWORD entryaddr = reinterpret_cast<DWORD>(RedirectFunction) - reinterpret_cast<DWORD>(funcOriginal) - 5; | |
char asmcode[5] = { '\xe9' };//JMP | |
memcpy(asmcode + 1, &entryaddr, 4); | |
VirtualProtectEx(hHookProcess, funcOriginal, 5, PAGE_EXECUTE_READWRITE, &protectOriginal); | |
WriteProcessMemory(hHookProcess, funcOriginal, asmcode, 5, NULL); | |
VirtualProtectEx(hHookProcess, funcOriginal, 5, protectOriginal, &protectOriginal); | |
hookOn = true; | |
} | |
void StopHook() | |
{ | |
VirtualProtectEx(hHookProcess, funcOriginal, 5, PAGE_EXECUTE_READWRITE, &protectOriginal); | |
WriteProcessMemory(hHookProcess, funcOriginal, apientry, 5, NULL); | |
VirtualProtectEx(hHookProcess, funcOriginal, 5, protectOriginal, &protectOriginal); | |
CloseHandle(hHookProcess); | |
hookOn = false; | |
} | |
int WINAPI wWinMain(HINSTANCE, HINSTANCE, LPWSTR, int) | |
{ | |
int action = 0; | |
hHookPid = GetCurrentProcessId();//获取进程ID | |
if (__argc == 2)hHookPid = _wtoi(__wargv[1]); | |
do { | |
action = MessageBox(NULL, TEXT("是:启动钩子,否:停止钩子"), hookOn ? L"On" : L"Off", MB_YESNOCANCEL); | |
if (action == IDYES)StartHook(); | |
else if (action == IDNO)StopHook(); | |
} while (action != IDCANCEL); | |
if (hookOn)StopHook(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment