-
Notifications
You must be signed in to change notification settings - Fork 10
/
hook_scanner.cpp
152 lines (119 loc) · 2.53 KB
/
hook_scanner.cpp
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
#include "includes.hpp"
bool HookScanAndPatch(std::vector<HOOK_SCAN_DATA>* hk_vec, HANDLE h_proc)
{
if (!hk_vec || !h_proc)
{
return false;
}
if (!hk_vec->empty())
{
hk_vec->clear();
}
ProcessInfo PI;
if (!PI.SetProcess(h_proc))
{
return false;
}
DWORD modules_count = sizeof(modules) / sizeof(modules[0]);
DWORD funcs_count = sizeof(to_hk_scan) / sizeof(to_hk_scan[0]);
for (DWORD i = 0; i < modules_count; ++i)
{
HMODULE mod = GetModuleHandleW(modules[i]);
HMODULE remote_mod = PI._GetModuleHandle(modules[i]);
if (!mod || !remote_mod)
{
if (!hk_vec->empty())
{
hk_vec->clear();
}
return false;
}
for (DWORD j = 0; j < funcs_count; ++j)
{
DWORD func_addr = (DWORD)GetProcAddress(mod, to_hk_scan[j]);
if (func_addr)
{
HOOK_SCAN_DATA data;
data.func_addr = (void*)(func_addr - (DWORD)mod + (DWORD)remote_mod);
data.func_name = to_hk_scan[j];
memcpy(data.orig_bytes, (void*)func_addr, SCAN_BYTES_COUNT);
if (!ReadProcessMemory(h_proc, data.func_addr, data.remote_bytes, SCAN_BYTES_COUNT, NULL))
{
if (!hk_vec->empty())
{
hk_vec->clear();
}
return false;
}
hk_vec->push_back(data);
}
}
}
if (hk_vec->empty())
{
return false;
}
if (hk_vec->size() != funcs_count)
{
hk_vec->clear();
return false;
}
CompareFuncs(hk_vec);
if (!RestoreHookedFuncs(hk_vec, h_proc, HOOK_RESTORE_MODE::HRM_RESTORE_ORIG))
{
hk_vec->clear();
return false;
}
return true;
}
bool CompareFuncs(std::vector<HOOK_SCAN_DATA>* hk_vec)
{
if (!hk_vec || hk_vec->empty())
{
return false;
}
for (auto& el : *hk_vec)
{
el.hooked = false;
for (DWORD i = 0; i < SCAN_BYTES_COUNT; ++i)
{
if (el.orig_bytes[i] != el.remote_bytes[i])
{
el.hooked = true;
LOG("%s hooked", el.func_name.c_str());
break;
}
}
}
return true;
}
bool RestoreHookedFuncs(std::vector<HOOK_SCAN_DATA>* hk_vec, HANDLE h_proc, HOOK_RESTORE_MODE mode)
{
if (!hk_vec || hk_vec->empty() || !h_proc)
{
return false;
}
for (auto& el : *hk_vec)
{
if (el.hooked)
{
if (mode == HOOK_RESTORE_MODE::HRM_RESTORE_ORIG)
{
if (!WriteProcessMemory(h_proc, el.func_addr, el.orig_bytes, SCAN_BYTES_COUNT, NULL))
{
return false;
}
LOG("%s original bytes restored", el.func_name.c_str());
}
else
{
if (!WriteProcessMemory(h_proc, el.func_addr, el.remote_bytes, SCAN_BYTES_COUNT, NULL))
{
return false;
}
LOG("%s hook bytes restored", el.func_name.c_str());
}
}
}
return true;
}