-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHookDLL.c
95 lines (71 loc) · 2.31 KB
/
HookDLL.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#define DEF_USER32 "user32.dll"
#define DEF_MSGBOXW "MessageBoxW"
typedef int(WINAPI* PFMessageBoxW)(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType);
BYTE g_OrgByte[5] = { 0, };
BOOL Hook_Code(LPCSTR szDllName, LPCSTR szFuncName, PROC pfNew) {
FARPROC pfOrg;
DWORD dwOldProtect, dwAddress;
BYTE pBuf[5] = { 0xE9, 0, }; //jmp 0x00000000
PBYTE pByte;
//Get The Target API Address
pfOrg = (FARPROC)GetProcAddress(GetModuleHandleA(szDllName), szFuncName);
pByte = (PBYTE)pfOrg;
//Already Hooked
if (pByte[0] == 0xE9) {
return FALSE;
}
//Add WRITE Attribute To Patch 5 Byte
VirtualProtect((LPVOID)pfOrg, 5, PAGE_EXECUTE_READWRITE, &dwOldProtect);
//Back up Original 5 Byte
memcpy(g_OrgByte, pfOrg, 5);
//JMP ???? (E9 XXXX)
//XXXX => pfNew - pfOrg - 5
dwAddress = (DWORD)pfNew - (DWORD)pfOrg - 5;
memcpy(&pBuf[1], &dwAddress, 4);
//Patch 5 Byte
memcpy(pfOrg, pBuf, 5);
VirtualProtect((LPVOID)pfOrg, 5, dwOldProtect, &dwOldProtect);
return TRUE;
}
BOOL UnHook_Code(LPCSTR szDllName, LPCSTR szFuncName) {
FARPROC pFunc;
DWORD dwOldProtect;
PBYTE pByte;
pFunc = GetProcAddress(GetModuleHandleA(szDllName), szFuncName);
pByte = (PBYTE)pFunc;
if (pByte[0] != 0xE9) {
return FALSE;
}
VirtualProtect((LPVOID)pFunc, 5, PAGE_EXECUTE_READWRITE, &dwOldProtect);
memcpy(pFunc, g_OrgByte, 5);
VirtualProtect((LPVOID)pFunc, 5, dwOldProtect, &dwOldProtect);
return TRUE;
}
int WINAPI NewMessageBoxW(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType) {
FARPROC pf_msgboxw;
int return_val;
UnHook_Code(DEF_USER32, DEF_MSGBOXW);
pf_msgboxw = GetProcAddress(GetModuleHandleA(DEF_USER32), DEF_MSGBOXW);
return_val = ((PFMessageBoxW)pf_msgboxw)(hWnd, L"Hooked Message!", lpCaption, uType);
Hook_Code(DEF_USER32, DEF_MSGBOXW, (PROC)NewMessageBoxW);
return return_val;
}
BOOL WINAPI DllMain(HMODULE hModule,
DWORD fdwReason,
LPVOID lpReserved
)
{
switch (fdwReason)
{
case DLL_PROCESS_ATTACH:
Hook_Code(DEF_USER32, DEF_MSGBOXW, (PROC)NewMessageBoxW);
break;
case DLL_PROCESS_DETACH:
UnHook_Code(DEF_USER32, DEF_MSGBOXW);
break;
}
return TRUE;
}