-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhook_engine.c
354 lines (285 loc) · 10 KB
/
hook_engine.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
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
#define _GNU_SOURCE 1
#ifndef __x86_64__
#error Unsupported ARCH :(
#endif
#include "hook_engine.h"
#include "hde/hde64.h"
#include <sys/types.h>
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <assert.h>
#include <dlfcn.h>
struct Overlay
{
uintptr_t target; // Where in address space this will ultimately end up.
uint8_t *p; // Current output position.
uint8_t code[HOOK_TRAMPOLINE_LEN];
};
static __thread int g_mem_fd = -1;
static __thread char g_errmsg[256];
#define FORMAT_ERRMSG(...) snprintf(g_errmsg, sizeof g_errmsg, __VA_ARGS__)
// Dump as many bytes as fit into buf, but don't cross page boundary.
static
const char *hexdump(const void *mem, char *buf, size_t size)
{
uintptr_t page_mask = sysconf(_SC_PAGESIZE) - 1;
const uint8_t *mem_p = mem;
const uint8_t *mem_end = (const uint8_t *)(((uintptr_t)mem + page_mask) & ~page_mask);
char *buf_p = buf;
char *buf_end = buf + size;
while (mem_p < mem_end && buf_p + 3 < buf_end)
buf_p += sprintf(buf_p, "%02x", *mem_p++);
return buf;
}
static
const char *funcname(void *func)
{
Dl_info info;
if (dladdr(func, &info) == 0 || !info.dli_sname)
return "Unknown";
return info.dli_sname;
}
static inline
void put_uint32(uint8_t *p, uint32_t v)
{
struct u32 { uint32_t u32; } __attribute__((__packed__));
((struct u32*)(p))->u32 = v;
}
static inline
void put_uint64(uint8_t *p, uint64_t v)
{
struct u64 { uint64_t u64; } __attribute__((__packed__));
((struct u64*)(p))->u64 = v;
}
static inline
size_t overlay_size(const struct Overlay *c)
{
return c->p - c->code;
}
static
int install_overlay(const struct Overlay *c)
{
ssize_t c_size = overlay_size(c);
if (g_mem_fd == -1) {
// No /proc/self/mem available, use mprotect.
uintptr_t page_mask = sysconf(_SC_PAGESIZE) - 1;
uintptr_t page_begin = c->target & ~page_mask;
uintptr_t page_end = (c->target + c_size + page_mask) & ~page_mask;
if (mprotect((void*)page_begin, page_end - page_begin, PROT_WRITE|PROT_EXEC) != 0)
goto error;
memcpy((void*)c->target, c->code, c_size);
mprotect((void*)page_begin, page_end - page_begin, PROT_EXEC);
return 0;
}
if (pwrite(g_mem_fd, c->code, c_size, c->target) == c_size) {
return 0;
}
error:
FORMAT_ERRMSG("patching code in memory: %s", strerror(errno));
return -1;
}
static
void write_initial_jmp(struct Overlay *c, uintptr_t target)
{
// movq target, %rax
c->p[0] = 0x48;
c->p[1] = 0xB8;
put_uint64(c->p + 2, target);
// jmp %rax
c->p[10] = 0xFF;
c->p[11] = 0xE0;
c->p += 12;
}
static
void write_jmp(struct Overlay *c, uintptr_t target, uintptr_t **jump_table)
{
// jmp *jump_table(%rip)
c->p[0] = 0xff;
c->p[1] = 0x25;
put_uint32(c->p + 2, (uintptr_t)(*jump_table) - (c->target + overlay_size(c) + 6));
c->p += 6;
(*jump_table)[0] = target;
(*jump_table)++;
}
static
void write_call(struct Overlay *c, uintptr_t target, uintptr_t **jump_table)
{
// call *jump_table(%rip)
write_jmp(c, target, jump_table);
c->p[-5] = 0x15;
}
// used by get_jump_table() for validation
void reference_trampoline(void);
HOOK_DEFINE_TRAMPOLINE(reference_trampoline);
static
uint64_t *get_jump_table(void *trampoline)
{
// validate trampoline - must be in a clean state,
// HOOK_TRAMPOLINE_LEN * (int 3) instructions,
// followed by lea [rip-relative], %rax.
// +3 in memcmp below to check lea instruction (minus offset part).
if (memcmp(trampoline, (void *)reference_trampoline,
HOOK_TRAMPOLINE_LEN + 3) != 0) {
return NULL;
}
// trampoline points to a symbol created with HOOK_DEFINE_TRAMPOLINE
// macro; after TRAMPOLINE_LEN area, there's a code sequence
// returning a pointer to a per-trampoline jump table
return ((uint64_t*(*)(void)) ((uintptr_t)trampoline + HOOK_TRAMPOLINE_LEN)) ();
}
// Patch function @fn, so that every time it is called, control is
// transferred to @replacement.
//
// If @trampoline is provided, instructions destroyed in @fn are
// transferred to @trampoline.
int hook_install(void *fn, void *replacement, void *trampoline)
{
// We render code in two overlays, and later overwrite @fn and
// @trampoline with the overlays' content.
struct Overlay fn_overlay = {(uintptr_t)fn, fn_overlay.code};
struct Overlay t_overlay = {(uintptr_t)trampoline, t_overlay.code};
// Jump table is normally extracted from the trampoline. Provide a
// placeholder if trampoline is NULL
uint64_t jump_table_data[HOOK_JUMP_MAX], *jump_table = jump_table_data;
if (trampoline && !(jump_table = get_jump_table(trampoline))) {
FORMAT_ERRMSG("bad trampoline pointer");
return -1;
}
// Prepare code to overwrite @fn with. This will be JMP @replacement.
write_initial_jmp(&fn_overlay, (uintptr_t)replacement);
// @fn is going to be partially clobbered. Disassemble and evacuate
// some instructions.
uintptr_t rip = (uintptr_t)fn;
const uintptr_t rip_hazzard = rip + overlay_size(&fn_overlay);
while (rip < rip_hazzard) {
hde64s s;
uintptr_t rip_dest = UINTPTR_MAX;
char hexdump_buf[HOOK_CLOBBERED_LEN*2 + 1];
hde64_disasm((const uint8_t *)rip, &s);
if (s.flags & F_ERROR) {
FORMAT_ERRMSG("creating trampoline for %s: unknown instruction at offset %+d (%s)",
funcname(fn),
(int)(rip - (uintptr_t)fn),
hexdump(fn, hexdump_buf, sizeof hexdump_buf));
return -1;
}
rip += s.len;
switch (s.opcode) {
case 0xCC:
FORMAT_ERRMSG("creating trampoline for %s: 'INT 3' instruction, "
"looks like a breakpoint set by debugger (%s)",
funcname(fn),
hexdump(fn, hexdump_buf, sizeof hexdump_buf));
return -1;
case 0xE8:
// relative call, 32 bit immediate offset
assert(s.flags & F_IMM32);
rip_dest = rip + (int32_t)s.imm.imm32;
write_call(&t_overlay, rip_dest, &jump_table);
goto check_rip_dest;
case 0xE9:
// relative jump, 8 bit immediate offset
assert(s.flags & F_IMM8);
rip_dest = rip + (int8_t)s.imm.imm8;
write_jmp(&t_overlay, rip_dest, &jump_table);
goto check_rip_dest;
case 0xEB:
// relative jump, 32 bit immediate offset
assert(s.flags & F_IMM32);
rip_dest = rip + (int32_t)s.imm.imm32;
write_jmp(&t_overlay, rip_dest, &jump_table);
goto check_rip_dest;
case 0xE3:
// jump if %ecx/ %rcx zero
FORMAT_ERRMSG("creating trampoline for %s: 'JCXZ' instruction not supported (%s)",
funcname(fn),
hexdump(fn, hexdump_buf, sizeof hexdump_buf));
return -1;
case 0x70 ... 0x7f:
// Jcc jump, 8 bit immediate offset
assert(s.flags & F_IMM8);
rip_dest = rip + (int8_t)s.imm.imm8;
t_overlay.p[0] = s.opcode ^ 1;
t_overlay.p[1] = 6;
t_overlay.p += 2;
write_jmp(&t_overlay, rip_dest, &jump_table);
goto check_rip_dest;
case 0x0F:
if (s.opcode2 >= 0x80 && s.opcode2 <= 0x8F) {
// Jcc jump, 32 bit immediate offset
assert(s.flags & F_IMM32);
rip_dest = rip + (int32_t)s.imm.imm32;
// Convert to a shorter form
t_overlay.p[0] = (s.opcode2 - 0x10) ^ 1;
t_overlay.p[1] = 6;
t_overlay.p += 2;
write_jmp(&t_overlay, rip_dest, &jump_table);
goto check_rip_dest;
}
break;
}
// RIP-relative addressing
if ((s.flags & F_MODRM) &&
s.modrm_mod == 0 && s.modrm_rm == 0x5) {
// LEA?
if (s.opcode != 0x8D) {
FORMAT_ERRMSG("creating trampoline for %s: %%rip-relative addressing (%s)",
funcname(fn),
hexdump(fn, hexdump_buf, sizeof hexdump_buf));
return -1;
}
// Convert to MOV
t_overlay.p[0] = 0x48 + s.rex_r;
t_overlay.p[1] = 0xB8 + s.modrm_reg;
put_uint64(t_overlay.p + 2, rip + (int32_t)s.disp.disp32);
t_overlay.p += 10;
continue;
}
// Copy instruction
memcpy(t_overlay.p, (const uint8_t *)rip - s.len, s.len);
t_overlay.p += s.len;
continue;
check_rip_dest:
// If we've seen a jump into the range we are about to overwrite,
// this isn't going to work.
if (rip_dest > (uintptr_t)fn && rip_dest < rip_hazzard) {
FORMAT_ERRMSG("creating trampoline for %s: a jump into the "
"clobbered instruction range encountered (%s)",
funcname(fn),
hexdump(fn, hexdump_buf, sizeof hexdump_buf));
return -1;
}
}
// If we've clobbered a *part* of an instruction, we should beter
// int3 the surviving part.
size_t partially_clobbered = rip - rip_hazzard;
memset(fn_overlay.p, 0xcc, partially_clobbered);
fn_overlay.p += partially_clobbered;
// Connect trampoline to the unclobbered part of @fn.
write_jmp(&t_overlay, rip, &jump_table);
// Now actually owerwrite things.
if (trampoline && install_overlay(&t_overlay) != 0)
return -1;
return install_overlay(&fn_overlay);
}
int hook_begin()
{
if (g_mem_fd == -1) {
g_mem_fd = open("/proc/self/mem", O_WRONLY|O_NOCTTY|O_CLOEXEC);
}
return 0;
}
void hook_end()
{
if (g_mem_fd != -1)
close(g_mem_fd);
g_mem_fd = - 1;
}
const char *hook_last_error()
{
return g_errmsg;
}