forked from ilammy/ftrace-hook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathftrace_hook.c
676 lines (570 loc) · 15.5 KB
/
ftrace_hook.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
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
//go build: ignore
/*
* Hooking kernel functions using ftrace framework
*
* Copyright (c) 2018 ilammy
*/
#define pr_fmt(fmt) "ftrace_hook: " fmt
#include <linux/ftrace.h>
#include <linux/kallsyms.h>
#include <linux/kernel.h>
#include <linux/linkage.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <linux/version.h>
#include <linux/kprobes.h>
#include <linux/fs.h>
#include <linux/namei.h>
#include <linux/init.h>
#include <linux/types.h>
#include <net/sock.h>
#include <net/netlink.h>
#include <linux/completion.h>
#include <linux/mutex.h>
MODULE_DESCRIPTION("Example module hooking clone() and execve() via ftrace");
MODULE_AUTHOR("ilammy <[email protected]> wangzhen <wanglian.163.com>");
MODULE_LICENSE("GPL");
#define NETLINK_TEST 25
#define MAX_MSGSIZE 1024
int stringlength(char *s);
static DECLARE_COMPLETION(msg_received);
static uint32_t msg_seq = 0;
static uint32_t ENABLE = 0;
static struct sock *nl_sk = NULL;
/**
* sec 3
*/
#define MAX_MSGS 10240
static DEFINE_MUTEX(my_mutex);
struct msg_info {
int seqid;
char *payload;
struct completion comp;
};
static struct msg_info msg_buffer[MAX_MSGS];
//向用户态进程回发消息
static int sendnlmsg(char *message, int pid)
{
static int timeout_count;
struct sk_buff *skb_1;
struct nlmsghdr *nlh;
int len = NLMSG_SPACE(MAX_MSGSIZE);
int slen = 0;
int sqid, head;
if(!message || !nl_sk)
{
return -1;
}
skb_1 = alloc_skb(len,GFP_KERNEL);
if(!skb_1)
{
printk(KERN_ERR "my_net_link:alloc_skb error\n");
}
slen = stringlength(message);
nlh = nlmsg_put(skb_1,0,0,NLMSG_DONE,MAX_MSGSIZE,0);
NETLINK_CB(skb_1).portid = 0;
NETLINK_CB(skb_1).dst_group = 0;
message[slen]= '\0';
// 设置唯一的seqid
msg_seq++;
nlh->nlmsg_seq = msg_seq;
sqid = msg_seq;
memcpy(NLMSG_DATA(nlh),message,slen+1);
printk("my_net_link:send message '%s' %d.\n",(char *)NLMSG_DATA(nlh), sqid);
// 发送消息
netlink_unicast(nl_sk,skb_1,pid,MSG_DONTWAIT);
// 如何检测程序准备就绪,才开始等待用户态的响应
if (ENABLE) {
head = sqid % MAX_MSGS;
if (!wait_for_completion_interruptible_timeout(&msg_buffer[head].comp, msecs_to_jiffies(200))) {
// 5次超时就关闭
timeout_count++;
if (timeout_count > 5) {
mutex_lock(&my_mutex);
ENABLE = 0;
timeout_count = 0;
mutex_unlock(&my_mutex);
pr_info("wait timeout 5 times, disabled");
}
return 0;
}
mutex_lock(&my_mutex);
// 从缓冲区读取接收到的seqid
if (msg_buffer[head].seqid != sqid) {
pr_info("head is:%d seqid not equal: %d!=%d\n", head,msg_buffer[head].seqid,sqid);
mutex_unlock(&my_mutex);
return 0;
}
if (strcmp(msg_buffer[head].payload, "0") == 0 && msg_buffer[head].seqid == sqid) {
mutex_unlock(&my_mutex);
return 1;
}
mutex_unlock(&my_mutex);
}
return 0;
}
int stringlength(char *s)
{
int slen = 0;
for(; *s; s++)
{
slen++;
}
return slen;
}
//接收用户态发来的消息
static void nl_data_ready(struct sk_buff *__skb)
{
struct sk_buff *skb;
struct nlmsghdr *nlh;
char str[10];
skb = skb_get(__skb);
if(skb->len >= NLMSG_SPACE(0))
{
nlh = nlmsg_hdr(skb);
memcpy(str, NLMSG_DATA(nlh), sizeof(str));
//启用
if (strcmp(str, "2") == 0) {
ENABLE = 1;
return;
}
//退出
if (strcmp(str, "3") == 0) {
ENABLE = 0;
return;
}
printk("Message received:%d,%s\n",nlh->nlmsg_seq, str) ;
if (ENABLE) {
mutex_lock(&my_mutex);
msg_buffer[(nlh->nlmsg_seq % MAX_MSGS)].seqid = nlh->nlmsg_seq;
memcpy(msg_buffer[(nlh->nlmsg_seq % MAX_MSGS)].payload, str, 8);
pr_info("set seq status:%d,%s\n", msg_buffer[(nlh->nlmsg_seq % MAX_MSGS)].seqid, msg_buffer[(nlh->nlmsg_seq % MAX_MSGS)].payload);
complete(&msg_buffer[(nlh->nlmsg_seq % MAX_MSGS)].comp);
mutex_unlock(&my_mutex);
}
kfree_skb(skb);
}
}
#if LINUX_VERSION_CODE >= KERNEL_VERSION(5,7,0)
static unsigned long lookup_name(const char *name)
{
struct kprobe kp = {
.symbol_name = name
};
unsigned long retval;
if (register_kprobe(&kp) < 0) return 0;
retval = (unsigned long) kp.addr;
unregister_kprobe(&kp);
return retval;
}
#else
static unsigned long lookup_name(const char *name)
{
return kallsyms_lookup_name(name);
}
#endif
#if LINUX_VERSION_CODE < KERNEL_VERSION(5,11,0)
#define FTRACE_OPS_FL_RECURSION FTRACE_OPS_FL_RECURSION_SAFE
#endif
#if LINUX_VERSION_CODE < KERNEL_VERSION(5,11,0)
#define ftrace_regs pt_regs
static __always_inline struct pt_regs *ftrace_get_regs(struct ftrace_regs *fregs)
{
return fregs;
}
#endif
/*
* There are two ways of preventing vicious recursive loops when hooking:
* - detect recusion using function return address (USE_FENTRY_OFFSET = 0)
* - avoid recusion by jumping over the ftrace call (USE_FENTRY_OFFSET = 1)
*/
#define USE_FENTRY_OFFSET 0
/**
* struct ftrace_hook - describes a single hook to install
*
* @name: name of the function to hook
*
* @function: pointer to the function to execute instead
*
* @original: pointer to the location where to save a pointer
* to the original function
*
* @address: kernel address of the function entry
*
* @ops: ftrace_ops state for this function hook
*
* The user should fill in only &name, &hook, &orig fields.
* Other fields are considered implementation details.
*/
struct ftrace_hook {
const char *name;
void *function;
void *original;
unsigned long address;
struct ftrace_ops ops;
};
static int fh_resolve_hook_address(struct ftrace_hook *hook)
{
hook->address = lookup_name(hook->name);
if (!hook->address) {
pr_debug("unresolved symbol: %s\n", hook->name);
return -ENOENT;
}
#if USE_FENTRY_OFFSET
*((unsigned long*) hook->original) = hook->address + MCOUNT_INSN_SIZE;
#else
*((unsigned long*) hook->original) = hook->address;
#endif
return 0;
}
/**
* centos7 need declate this function with manual
*/
#if LINUX_VERSION_CODE < KERNEL_VERSION(3,16,0)
static inline bool within_module(unsigned long addr, const struct module *mod)
{
return within_module_init(addr, mod) || within_module_core(addr, mod);
}
#endif
static void notrace fh_ftrace_thunk(unsigned long ip, unsigned long parent_ip,
struct ftrace_ops *ops, struct ftrace_regs *fregs)
{
struct pt_regs *regs = ftrace_get_regs(fregs);
struct ftrace_hook *hook = container_of(ops, struct ftrace_hook, ops);
#if USE_FENTRY_OFFSET
regs->ip = (unsigned long)hook->function;
#else
if (!within_module(parent_ip, THIS_MODULE))
regs->ip = (unsigned long)hook->function;
#endif
}
/**
* fh_install_hooks() - register and enable a single hook
* @hook: a hook to install
*
* Returns: zero on success, negative error code otherwise.
*/
static int fh_install_hook(struct ftrace_hook *hook)
{
int err;
err = fh_resolve_hook_address(hook);
if (err)
return err;
/*
* We're going to modify %rip register so we'll need IPMODIFY flag
* and SAVE_REGS as its prerequisite. ftrace's anti-recursion guard
* is useless if we change %rip so disable it with RECURSION.
* We'll perform our own checks for trace function reentry.
*/
hook->ops.func = fh_ftrace_thunk;
hook->ops.flags = FTRACE_OPS_FL_SAVE_REGS
| FTRACE_OPS_FL_RECURSION
| FTRACE_OPS_FL_IPMODIFY;
err = ftrace_set_filter_ip(&hook->ops, hook->address, 0, 0);
if (err) {
pr_debug("ftrace_set_filter_ip() failed: %d\n", err);
return err;
}
err = register_ftrace_function(&hook->ops);
if (err) {
pr_debug("register_ftrace_function() failed: %d\n", err);
ftrace_set_filter_ip(&hook->ops, hook->address, 1, 0);
return err;
}
return 0;
}
/**
* fh_remove_hooks() - disable and unregister a single hook
* @hook: a hook to remove
*/
static void fh_remove_hook(struct ftrace_hook *hook)
{
int err;
err = unregister_ftrace_function(&hook->ops);
if (err) {
pr_debug("unregister_ftrace_function() failed: %d\n", err);
}
err = ftrace_set_filter_ip(&hook->ops, hook->address, 1, 0);
if (err) {
pr_debug("ftrace_set_filter_ip() failed: %d\n", err);
}
}
/**
* fh_install_hooks() - register and enable multiple hooks
* @hooks: array of hooks to install
* @count: number of hooks to install
*
* If some hooks fail to install then all hooks will be removed.
*
* Returns: zero on success, negative error code otherwise.
*/
static int fh_install_hooks(struct ftrace_hook *hooks, size_t count)
{
int err;
size_t i;
for (i = 0; i < count; i++) {
err = fh_install_hook(&hooks[i]);
if (err)
goto error;
}
return 0;
error:
while (i != 0) {
fh_remove_hook(&hooks[--i]);
}
return err;
}
/**
* fh_remove_hooks() - disable and unregister multiple hooks
* @hooks: array of hooks to remove
* @count: number of hooks to remove
*/
static void fh_remove_hooks(struct ftrace_hook *hooks, size_t count)
{
size_t i;
for (i = 0; i < count; i++)
fh_remove_hook(&hooks[i]);
}
#ifndef CONFIG_X86_64
#error Currently only x86_64 architecture is supported
#endif
#if defined(CONFIG_X86_64) && (LINUX_VERSION_CODE >= KERNEL_VERSION(4,17,0))
#define PTREGS_SYSCALL_STUBS 1
#endif
/*
* Tail call optimization can interfere with recursion detection based on
* return address on the stack. Disable it to avoid machine hangups.
*/
#if !USE_FENTRY_OFFSET
#pragma GCC optimize("-fno-optimize-sibling-calls")
#endif
#ifdef PTREGS_SYSCALL_STUBS
static asmlinkage long (*real_sys_clone)(struct pt_regs *regs);
static asmlinkage long fh_sys_clone(struct pt_regs *regs)
{
long ret;
pr_info("clone() before\n");
ret = real_sys_clone(regs);
pr_info("clone() after: %ld\n", ret);
return ret;
}
#else
static asmlinkage long (*real_sys_clone)(unsigned long clone_flags,
unsigned long newsp, int __user *parent_tidptr,
int __user *child_tidptr, unsigned long tls);
static asmlinkage long fh_sys_clone(unsigned long clone_flags,
unsigned long newsp, int __user *parent_tidptr,
int __user *child_tidptr, unsigned long tls)
{
long ret;
pr_info("clone() before\n");
ret = real_sys_clone(clone_flags, newsp, parent_tidptr,
child_tidptr, tls);
pr_info("clone() after: %ld\n", ret);
return ret;
}
#endif
static char *duplicate_filename(const char __user *filename)
{
char *kernel_filename;
kernel_filename = kmalloc(4096, GFP_KERNEL);
if (!kernel_filename)
return NULL;
if (strncpy_from_user(kernel_filename, filename, 4096) < 0) {
kfree(kernel_filename);
return NULL;
}
return kernel_filename;
}
#ifdef PTREGS_SYSCALL_STUBS
static asmlinkage long (*real_sys_execve)(struct pt_regs *regs);
static asmlinkage long fh_sys_execve(struct pt_regs *regs)
{
long ret;
char *kernel_filename;
struct path path;
char *buf;
char *absolute_path;
int buflen = 512;
kernel_filename = duplicate_filename((void*) regs->di);
pr_info("execve() before: %s\n", kernel_filename);
// 将文件名转换为路径
ret = kern_path(kernel_filename, LOOKUP_FOLLOW, &path);
if (ret)
{
pr_err("kern_path failed\n");
kfree(kernel_filename);
return ret;
}
// 分配一个缓冲区来存储绝对路径
buf = kmalloc(buflen, GFP_KERNEL);
if (!buf)
{
pr_err("kmalloc for buf failed\n");
path_put(&path);
kfree(kernel_filename);
return -ENOMEM;
}
// 获取绝对路径
absolute_path = d_path(&path, buf, buflen);
if (IS_ERR(absolute_path))
{
pr_err("d_path failed\n");
kfree(buf);
path_put(&path);
kfree(kernel_filename);
return PTR_ERR(absolute_path);
}
// 打印绝对路径
pr_info("execve() absolute path: %s\n", absolute_path);
/**
* check md5, if ok; goto real_sys_execve else return
*/
ret = sendnlmsg(absolute_path, 100);
if (ret) {
pr_err("Failed to get response from user space\n");
pr_info("execve() hooked: %ld\n", ret);
kfree(buf);
path_put(&path);
kfree(kernel_filename);
return -ret;
}
// 清理工作
kfree(buf);
path_put(&path);
kfree(kernel_filename);
ret = real_sys_execve(regs);
pr_info("execve() after: %ld\n", ret);
return ret;
}
#else
static asmlinkage long (*real_sys_execve)(const char __user *filename,
const char __user *const __user *argv,
const char __user *const __user *envp);
static asmlinkage long fh_sys_execve(const char __user *filename,
const char __user *const __user *argv,
const char __user *const __user *envp)
{
long ret;
char *kernel_filename;
struct path path;
char *buf;
char *absolute_path;
int buflen = 512;
// Duplicate the filename from userspace to kernel space
kernel_filename = duplicate_filename(filename);
if (!kernel_filename)
return -ENOMEM;
pr_info("execve() before: %s\n", kernel_filename);
// Convert the filename to a path
ret = kern_path(kernel_filename, LOOKUP_FOLLOW, &path);
if (ret)
{
pr_err("kern_path failed\n");
kfree(kernel_filename);
return ret;
}
// Allocate a buffer to store the absolute path
buf = kmalloc(buflen, GFP_KERNEL);
if (!buf)
{
pr_err("kmalloc for buf failed\n");
path_put(&path);
kfree(kernel_filename);
return -ENOMEM;
}
// Get the absolute path
absolute_path = d_path(&path, buf, buflen);
if (IS_ERR(absolute_path))
{
pr_err("d_path failed\n");
kfree(buf);
path_put(&path);
kfree(kernel_filename);
return PTR_ERR(absolute_path);
}
// Print the absolute path
pr_info("execve() absolute path: %s\n", absolute_path);
/**
* check md5, if ok; goto real_sys_execve else return
*/
// netlink
ret = sendnlmsg(absolute_path, 100);
if (ret) {
pr_err("Failed to get response from user space\n");
pr_info("execve() hooked: %ld\n", ret);
kfree(buf);
path_put(&path);
kfree(kernel_filename);
return -ret;
}
// Clean up
kfree(buf);
path_put(&path);
kfree(kernel_filename);
ret = real_sys_execve(filename, argv, envp);
pr_info("execve() after: %ld\n", ret);
return ret;
}
#endif
/*
* x86_64 kernels have a special naming convention for syscall entry points in newer kernels.
* That's what you end up with if an architecture has 3 (three) ABIs for system calls.
*/
#ifdef PTREGS_SYSCALL_STUBS
#define SYSCALL_NAME(name) ("__x64_" name)
#else
#define SYSCALL_NAME(name) (name)
#endif
#define HOOK(_name, _function, _original) \
{ \
.name = SYSCALL_NAME(_name), \
.function = (_function), \
.original = (_original), \
}
static struct ftrace_hook demo_hooks[] = {
//HOOK("sys_clone", fh_sys_clone, &real_sys_clone),
HOOK("sys_execve", fh_sys_execve, &real_sys_execve),
};
static int fh_init(void)
{
int err;
int i =0;
struct netlink_kernel_cfg cfg = {
.input = nl_data_ready,
};
err = fh_install_hooks(demo_hooks, ARRAY_SIZE(demo_hooks));
if (err)
return err;
pr_info("module loaded\n");
// 手动初始化 msg_buffer
for (; i < MAX_MSGS; i++) {
msg_buffer[i].seqid = i;
//memset(msg_buffer[i].payload, 0, sizeof(msg_buffer[i].payload));
msg_buffer[i].payload = kmalloc(8, GFP_KERNEL);
init_completion(&msg_buffer[i].comp);
}
nl_sk = netlink_kernel_create(&init_net, NETLINK_TEST, &cfg);
if(!nl_sk){
printk(KERN_ERR "my_net_link: create netlink socket error.\n");
return 1;
}
printk("my_net_link_4: create netlink socket ok.\n");
return 0;
}
module_init(fh_init);
static void fh_exit(void)
{
int i;
fh_remove_hooks(demo_hooks, ARRAY_SIZE(demo_hooks));
pr_info("module unloaded\n");
if (nl_sk) {
netlink_kernel_release(nl_sk);
}
for (i = 0; i < MAX_MSGS; i++) {
kfree(msg_buffer[i].payload);
}
printk("my_net_link: self module exited\n");
}
module_exit(fh_exit);