kprobes简介
1 | KProbes is a debugging mechanism for the Linux kernel which can also be used for monitoring events inside a production system. You can use it to weed out performance bottlenecks, log specific events, trace problems etc. KProbes was developed by IBM as an underlying mechanism for another higher level tracing tool called DProbes. DProbes adds a number of features, including its own scripting language for the writing of probe handlers. However, only KProbes has been merged into the standard kernel. |
Kprobes是Linux内核的一种调试机制,可以用来在生产环境中监控内核事件,其允许使用者在内核指定位置注册自定义的回调函数,捕捉内核事件、对内核信息进行过滤、分析,达到内核观测的效果。kprobes这种内核追踪机制常用于性能、安全监控领域,最常见的,比如用于hids/cwpp/edr的agent;本质上,他和替换系统调用表这种比较暴力的开膛破腹式的监控手段不同(典型的如yulong),内核机制的支持使其相对比较稳定和优雅(虽然不如ebpf),如果probe点合适(字段不经常变更),且兼容性足够好,那么将kprobes用在agent模块上则会使agent获得性能、安全(绕过相对用户态较难)的双重优势,典型如开源项目agent-smith,目前agent已在字节大量部署,据说部署规模有10w+;不再赘述,记录下核心知识点的学习过程。
kprobes原理
Kprobes
Kporbes系列本质上包含了三种探测手段,即kprobe、kretprobe、jprobe,其分别有不同的应用场景,简单介绍如下:
1 | kprobe:支持使用者在内核任意位置注册回调,但有部分注册点是受限的,如不允许其以本身为probe点进行注册等 |
kprobe
执行流程
1 | How Does a Kprobe Work? |
1 | 1、注册kprobe点时kprobe将备份被探测的指令并将被探测函数的头指令替换成int3,并在notifier_call_chain中注册关联到对应kprobe点的pre_handler异常处理函数 |
Example
贴下linux内核samples目录测试用例源码:
1 |
|
kretprobe
执行流程
1 | Kretprobe entry-handler |
1 | 1、对指定的函数入口进行kprobe插桩 |
Example
贴下linux内核samples目录测试用例源码:
1 |
|
jprobe
执行流程
1 | A JProbe has to transfer control to another function which has the same prototype as the function on which the probe was placed and then give back control to the original function with the same state as there was before the JProbe was executed. A JProbe leverages the mechanism used by a KProbe. Instead of calling a user-defined pre-handler a JProbe specifies its own pre-handler called setjmp_pre_handler() and uses another handler called a break_handler. This is a three-step process. |
1 | 1、对指定函数入口进行kprobe插桩 |
Example
本质上感觉jprobe与kprobe就效果而言其实差不多,不知道是不是因为这个samples中没有给jprobe的用例,网上找了一个:
1 | /*jprobe_test.c */ |
总结
参考agent-smith写了一个小玩具,用kprobe拿了一下内核sys_execve系统调用对应的进程启动事件,kprobe这块的接口都比较简单,不再赘述
参考链接
https://lwn.net/Articles/132196/
https://www.kernel.org/doc/Documentation/kprobes.txt
https://www.cnblogs.com/LittleHann/p/3854977.html
https://www.cnblogs.com/LittleHann/p/3920387.html
https://kernelgo.org/kprobe.html
https://blog.csdn.net/luckyapple1028/article/details/54350410