-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathinline_hook.cpp
409 lines (327 loc) · 13.2 KB
/
inline_hook.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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
#include <iterator>
#include <Windows.h>
#if __has_include(<Zydis/Zydis.h>)
#include <Zydis/Zydis.h>
#elif __has_include(<Zydis.h>)
#include <Zydis.h>
#else
#error "Zydis not found"
#endif
#include <safetyhook/allocator.hpp>
#include <safetyhook/thread_freezer.hpp>
#include <safetyhook/utility.hpp>
#include <safetyhook/inline_hook.hpp>
namespace safetyhook {
class UnprotectMemory {
public:
UnprotectMemory(uint8_t* address, size_t size) : m_address{address}, m_size{size} {
VirtualProtect(m_address, m_size, PAGE_EXECUTE_READWRITE, &m_protect);
}
~UnprotectMemory() { VirtualProtect(m_address, m_size, m_protect, &m_protect); }
private:
uint8_t* m_address{};
size_t m_size{};
DWORD m_protect{};
};
#pragma pack(push, 1)
struct JmpE9 {
uint8_t opcode{0xE9};
uint32_t offset{0};
};
#if defined(_M_X64)
struct JmpFF {
uint8_t opcode0{0xFF};
uint8_t opcode1{0x25};
uint32_t offset{0};
};
struct TrampolineEpilogueE9 {
JmpE9 jmp_to_original{};
JmpFF jmp_to_destination{};
uint64_t destination_address{};
};
struct TrampolineEpilogueFF {
JmpFF jmp_to_original{};
uint64_t original_address{};
};
#elif defined(_M_IX86)
struct TrampolineEpilogueE9 {
JmpE9 jmp_to_original{};
JmpE9 jmp_to_destination{};
};
#endif
#pragma pack(pop)
#ifdef _M_X64
static auto make_jmp_ff(uint8_t* src, uint8_t* dst, uint8_t* data) {
JmpFF jmp{};
jmp.offset = static_cast<uint32_t>(data - src - sizeof(jmp));
store(data, dst);
return jmp;
}
static void emit_jmp_ff(uint8_t* src, uint8_t* dst, uint8_t* data, size_t size = sizeof(JmpFF)) {
if (size < sizeof(JmpFF)) {
return;
}
UnprotectMemory unprotect{src, size};
if (size > sizeof(JmpFF)) {
std::fill_n(src, size, static_cast<uint8_t>(0x90));
}
store(src, make_jmp_ff(src, dst, data));
}
#endif
constexpr auto make_jmp_e9(uint8_t* src, uint8_t* dst) {
JmpE9 jmp{};
jmp.offset = static_cast<uint32_t>(dst - src - sizeof(jmp));
return jmp;
}
static void emit_jmp_e9(uint8_t* src, uint8_t* dst, size_t size = sizeof(JmpE9)) {
if (size < sizeof(JmpE9)) {
return;
}
UnprotectMemory unprotect{src, size};
if (size > sizeof(JmpE9)) {
std::fill_n(src, size, static_cast<uint8_t>(0x90));
}
store(src, make_jmp_e9(src, dst));
}
static bool decode(ZydisDecodedInstruction* ix, uint8_t* ip) {
ZydisDecoder decoder{};
ZyanStatus status;
#if defined(_M_X64)
status = ZydisDecoderInit(&decoder, ZYDIS_MACHINE_MODE_LONG_64, ZYDIS_STACK_WIDTH_64);
#elif defined(_M_IX86)
status = ZydisDecoderInit(&decoder, ZYDIS_MACHINE_MODE_LEGACY_32, ZYDIS_STACK_WIDTH_32);
#else
#error "Unsupported architecture"
#endif
if (!ZYAN_SUCCESS(status)) {
return false;
}
return ZYAN_SUCCESS(ZydisDecoderDecodeInstruction(&decoder, nullptr, ip, 15, ix));
}
std::expected<InlineHook, InlineHook::Error> InlineHook::create(void* target, void* destination) {
return create(Allocator::global(), target, destination);
}
std::expected<InlineHook, InlineHook::Error> InlineHook::create(
const std::shared_ptr<Allocator>& allocator, void* target, void* destination) {
InlineHook hook{};
if (const auto setup_result =
hook.setup(allocator, reinterpret_cast<uint8_t*>(target), reinterpret_cast<uint8_t*>(destination));
!setup_result) {
return std::unexpected{setup_result.error()};
}
return hook;
}
InlineHook::InlineHook(InlineHook&& other) noexcept {
*this = std::move(other);
}
InlineHook& InlineHook::operator=(InlineHook&& other) noexcept {
if (this != &other) {
destroy();
std::scoped_lock lock{m_mutex, other.m_mutex};
m_target = other.m_target;
m_destination = other.m_destination;
m_trampoline = std::move(other.m_trampoline);
m_trampoline_size = other.m_trampoline_size;
m_original_bytes = std::move(other.m_original_bytes);
other.m_target = 0;
other.m_destination = 0;
other.m_trampoline_size = 0;
}
return *this;
}
InlineHook::~InlineHook() {
destroy();
}
void InlineHook::reset() {
*this = {};
}
std::expected<void, InlineHook::Error> InlineHook::setup(
const std::shared_ptr<Allocator>& allocator, uint8_t* target, uint8_t* destination) {
m_target = target;
m_destination = destination;
if (auto e9_result = e9_hook(allocator); !e9_result) {
#ifdef _M_X64
if (auto ff_result = ff_hook(allocator); !ff_result) {
return ff_result;
}
#else
return e9_result;
#endif
}
return {};
}
std::expected<void, InlineHook::Error> InlineHook::e9_hook(const std::shared_ptr<Allocator>& allocator) {
m_original_bytes.clear();
m_trampoline_size = sizeof(TrampolineEpilogueE9);
std::vector<uint8_t*> desired_addresses{m_target};
ZydisDecodedInstruction ix{};
for (auto ip = m_target; ip < m_target + sizeof(JmpE9); ip += ix.length) {
if (!decode(&ix, ip)) {
return std::unexpected{Error::failed_to_decode_instruction(ip)};
}
m_trampoline_size += ix.length;
m_original_bytes.insert(m_original_bytes.end(), ip, ip + ix.length);
const auto is_relative = (ix.attributes & ZYDIS_ATTRIB_IS_RELATIVE) != 0;
if (is_relative) {
if (ix.raw.disp.size == 32) {
const auto target_address = ip + ix.length + static_cast<int32_t>(ix.raw.disp.value);
desired_addresses.emplace_back(target_address);
} else if (ix.raw.imm[0].size == 32) {
const auto target_address = ip + ix.length + static_cast<int32_t>(ix.raw.imm[0].value.s);
desired_addresses.emplace_back(target_address);
} else if (ix.meta.category == ZYDIS_CATEGORY_COND_BR && ix.meta.branch_type == ZYDIS_BRANCH_TYPE_SHORT) {
const auto target_address = ip + ix.length + static_cast<int32_t>(ix.raw.imm[0].value.s);
desired_addresses.emplace_back(target_address);
m_trampoline_size += 4; // near conditional branches are 4 bytes larger.
} else if (ix.meta.category == ZYDIS_CATEGORY_UNCOND_BR && ix.meta.branch_type == ZYDIS_BRANCH_TYPE_SHORT) {
const auto target_address = ip + ix.length + static_cast<int32_t>(ix.raw.imm[0].value.s);
desired_addresses.emplace_back(target_address);
m_trampoline_size += 3; // near unconditional branches are 3 bytes larger.
} else {
return std::unexpected{Error::unsupported_instruction_in_trampoline(ip)};
}
}
}
auto trampoline_allocation = allocator->allocate_near(desired_addresses, m_trampoline_size);
if (!trampoline_allocation) {
return std::unexpected{Error::bad_allocation(trampoline_allocation.error())};
}
m_trampoline = std::move(*trampoline_allocation);
for (auto ip = m_target, tramp_ip = m_trampoline.data(); ip < m_target + m_original_bytes.size(); ip += ix.length) {
if (!decode(&ix, ip)) {
m_trampoline.free();
return std::unexpected{Error::failed_to_decode_instruction(ip)};
}
const auto is_relative = (ix.attributes & ZYDIS_ATTRIB_IS_RELATIVE) != 0;
if (is_relative && ix.raw.disp.size == 32) {
std::copy_n(ip, ix.length, tramp_ip);
const auto target_address = ip + ix.length + ix.raw.disp.value;
const auto new_disp = target_address - (tramp_ip + ix.length);
store(tramp_ip + ix.raw.disp.offset, static_cast<int32_t>(new_disp));
tramp_ip += ix.length;
} else if (is_relative && ix.raw.imm[0].size == 32) {
std::copy_n(ip, ix.length, tramp_ip);
const auto target_address = ip + ix.length + ix.raw.imm[0].value.s;
const auto new_disp = target_address - (tramp_ip + ix.length);
store(tramp_ip + ix.raw.imm[0].offset, static_cast<int32_t>(new_disp));
tramp_ip += ix.length;
} else if (ix.meta.category == ZYDIS_CATEGORY_COND_BR && ix.meta.branch_type == ZYDIS_BRANCH_TYPE_SHORT) {
const auto target_address = ip + ix.length + ix.raw.imm[0].value.s;
auto new_disp = target_address - (tramp_ip + 6);
// Handle the case where the target is now in the trampoline.
if (target_address < m_target + m_original_bytes.size()) {
new_disp = static_cast<ptrdiff_t>(ix.raw.imm[0].value.s);
}
*tramp_ip = 0x0F;
*(tramp_ip + 1) = 0x10 + ix.opcode;
store(tramp_ip + 2, static_cast<int32_t>(new_disp));
tramp_ip += 6;
} else if (ix.meta.category == ZYDIS_CATEGORY_UNCOND_BR && ix.meta.branch_type == ZYDIS_BRANCH_TYPE_SHORT) {
const auto target_address = ip + ix.length + ix.raw.imm[0].value.s;
auto new_disp = target_address - (tramp_ip + 5);
// Handle the case where the target is now in the trampoline.
if (target_address < m_target + m_original_bytes.size()) {
new_disp = static_cast<ptrdiff_t>(ix.raw.imm[0].value.s);
}
*tramp_ip = 0xE9;
store(tramp_ip + 1, static_cast<int32_t>(new_disp));
tramp_ip += 5;
} else {
std::copy_n(ip, ix.length, tramp_ip);
tramp_ip += ix.length;
}
}
auto trampoline_epilogue = reinterpret_cast<TrampolineEpilogueE9*>(
m_trampoline.address() + m_trampoline_size - sizeof(TrampolineEpilogueE9));
// jmp from trampoline to original.
auto src = reinterpret_cast<uint8_t*>(&trampoline_epilogue->jmp_to_original);
auto dst = m_target + m_original_bytes.size();
emit_jmp_e9(src, dst);
// jmp from trampoline to destination.
src = reinterpret_cast<uint8_t*>(&trampoline_epilogue->jmp_to_destination);
dst = m_destination;
#ifdef _M_X64
auto data = reinterpret_cast<uint8_t*>(&trampoline_epilogue->destination_address);
emit_jmp_ff(src, dst, data);
#else
emit_jmp_e9(src, dst);
#endif
// jmp from original to trampoline.
execute_while_frozen(
[this, &trampoline_epilogue] {
const auto src = m_target;
const auto dst = reinterpret_cast<uint8_t*>(&trampoline_epilogue->jmp_to_destination);
emit_jmp_e9(src, dst, m_original_bytes.size());
},
[this](uint32_t, HANDLE, CONTEXT& ctx) {
for (size_t i = 0; i < m_original_bytes.size(); ++i) {
fix_ip(ctx, m_target + i, m_trampoline.data() + i);
}
});
return {};
}
#ifdef _M_X64
std::expected<void, InlineHook::Error> InlineHook::ff_hook(const std::shared_ptr<Allocator>& allocator) {
m_original_bytes.clear();
m_trampoline_size = sizeof(TrampolineEpilogueFF);
ZydisDecodedInstruction ix{};
for (auto ip = m_target; ip < m_target + sizeof(JmpFF) + sizeof(uintptr_t); ip += ix.length) {
if (!decode(&ix, ip)) {
return std::unexpected{Error::failed_to_decode_instruction(ip)};
}
// We can't support any instruction that is IP relative here because
// ff_hook should only be called if e9_hook failed indicating that
// we're likely outside the +- 2GB range.
if (ix.attributes & ZYDIS_ATTRIB_IS_RELATIVE) {
return std::unexpected{Error::ip_relative_instruction_out_of_range(ip)};
}
m_original_bytes.insert(m_original_bytes.end(), ip, ip + ix.length);
m_trampoline_size += ix.length;
}
auto trampoline_allocation = allocator->allocate(m_trampoline_size);
if (!trampoline_allocation) {
return std::unexpected{Error::bad_allocation(trampoline_allocation.error())};
}
m_trampoline = std::move(*trampoline_allocation);
std::copy(m_original_bytes.begin(), m_original_bytes.end(), m_trampoline.data());
const auto trampoline_epilogue =
reinterpret_cast<TrampolineEpilogueFF*>(m_trampoline.data() + m_trampoline_size - sizeof(TrampolineEpilogueFF));
// jmp from trampoline to original.
auto src = reinterpret_cast<uint8_t*>(&trampoline_epilogue->jmp_to_original);
auto dst = m_target + m_original_bytes.size();
auto data = reinterpret_cast<uint8_t*>(&trampoline_epilogue->original_address);
emit_jmp_ff(src, dst, data);
// jmp from original to trampoline.
execute_while_frozen(
[this] {
const auto src = m_target;
const auto dst = m_destination;
const auto data = src + sizeof(JmpFF);
emit_jmp_ff(src, dst, data, m_original_bytes.size());
},
[this](uint32_t, HANDLE, CONTEXT& ctx) {
for (size_t i = 0; i < m_original_bytes.size(); ++i) {
fix_ip(ctx, m_target + i, m_trampoline.data() + i);
}
});
return {};
}
#endif
void InlineHook::destroy() {
std::scoped_lock lock{m_mutex};
if (!m_trampoline) {
return;
}
execute_while_frozen(
[this] {
UnprotectMemory unprotect{m_target, m_original_bytes.size()};
std::copy(m_original_bytes.begin(), m_original_bytes.end(), m_target);
},
[this](uint32_t, HANDLE, CONTEXT& ctx) {
for (size_t i = 0; i < m_original_bytes.size(); ++i) {
fix_ip(ctx, m_trampoline.data() + i, m_target + i);
}
});
m_trampoline.free();
}
} // namespace safetyhook