Liang Jinrong: tracking Linux kernel with ebpf

Song Baohua 2021-05-04 02:36:31
liang jinrong tracking linux kernel


Original Liang Jinrong Linux Journey to the core Yesterday

1. Preface

We can use BPF Yes Linux Kernel tracking , Collect the kernel data we want , Thus to Linux Program analysis and debugging . Compared with other tracking technologies , Use BPF The main advantage of is that it's almost accessible Linux Any information about the kernel and the application , meanwhile ,BPF Little impact on system performance , It's very efficient , And developers don't need to modify programs to collect data .

This article will introduce assurance BPF Security of program BPF Validator , And then to BPF The toolset of the program BCC For example , Share kprobes and tracepoints Type of BPF The use of programs and programming examples .

2. BPF Validator

BPF With the help of tracking probe, information is collected, debugged and analyzed , Compared to other tools that rely on recompiling the kernel ,BPF Programs are more secure . Recompile the way the kernel introduces external modules , System crash may occur due to program errors .BPF The verifier of the program will be in BPF Analyze the program before loading it into the kernel , Eliminate this risk .

BPF The first check performed by the verifier is to BPF Static analysis of the code loaded by the virtual machine , The goal is to make sure that the process ends as expected . What the verifier does in the first check is :

  • The program does not contain control loops ;

  • The program will not execute more than the maximum number of instructions allowed by the kernel ;

  • The program does not contain any unreachable instructions ;

  • The program doesn't go beyond the boundaries of the program .

BPF The second check performed by the verifier is for BPF Pre run the program , The work done is :

  • analysis BPF Every instruction executed by a program , Ensure that invalid instructions are not executed ;

  • Check that all memory pointers are properly accessed and referenced ;

  • The pre run notifies the verifier of the execution result of the program control flow , Make sure BPF The program will eventually execute BPF_EXIT Instructions .

3. The core probe kprobes

Kernel probes can track most kernel functions , And the system loss is the minimum . When the traced kernel function is called , Attached to the probe BPF Code will be executed , After that, the kernel will return to normal mode .

3.1 kprobes class BPF The advantages and disadvantages of the program

  • advantage Dynamic tracking kernel , There are many kernel functions that can be traced , Can extract most of the kernel information .

  • shortcoming There is no stable application binary interface , It may change as the kernel version evolves .

3.2 kprobes

kprobe Programs allow you to insert... Before executing kernel functions BPF Program . When the kernel executes to kprobe When the kernel function is mounted , First run BPF Program ,BPF After program running , Return to continue executing kernel functions . Here is a use kprobe Of bcc Program example , The function is to monitor kernel functions kfree_skb function , When this function is triggered , Record the process that triggered it pid, Process name and trigger times , And print out the process that triggered this function pid, Process name and trigger times :

#!/usr/bin/python3
# coding=utf-8
from __future__ import print_function
from bcc import BPF
from time import sleep
# define BPF program
bpf_program = """
#include <uapi/linux/ptrace.h>
struct key_t{
u64 pid;
};
BPF_HASH(counts, struct key_t);
int trace_kfree_skb(struct pt_regs *ctx) {
u64 zero = 0, *val, pid;
pid = bpf_get_current_pid_tgid() >> 32;
struct key_t key = {};
key.pid = pid;
val = counts.lookup_or_try_init(&key, &zero);
if (val) {
(*val)++;
}
return 0;
}
"""
def pid_to_comm(pid):
try:
comm = open("/proc/%s/comm" % pid, "r").read().rstrip()
return comm
except IOError:
return str(pid)
# load BPF
b = BPF(text=bpf_program)
b.attach_kprobe(event="kfree_skb", fn_name="trace_kfree_skb")
# header
print("Tracing kfree_skb... Ctrl-C to end.")
print("%-10s %-12s %-10s" % ("PID", "COMM", "DROP_COUNTS"))
while 1:
sleep(1)
for k, v in sorted(b["counts"].items(),key = lambda counts: counts[1].value):
print("%-10d %-12s %-10d" % (k.pid, pid_to_comm(k.pid), v.value))

The bcc The program consists of two parts , Part of it is python Language , Part of it is c Language .python Part of the main work is BPF Program loading and operation BPF programmatic map, And data processing .c Part of it will be llvm The compiler is compiled as BPF Bytecode , after BPF After the verifier verifies the security , Load into the kernel to execute .python and c You can check the following two manuals for unfamiliar functions in , No more details here :

python For some unfamiliar functions, please refer to this manual :  Click here to jump

c You can refer to this manual for the unfamiliar functions encountered in section :  Click here to jump

It should be noted that , The BPF The program type is kprobe, It defines the program type here :

b.attach_kprobe(event="kfree_skb", fn_name="trace_kfree_skb")
  • b.attach_kprobe() It's time to BPF The program type is kprobe;

  • event="kfree_skb" It specifies kprobe The kernel function mounted is kfree_skb;

  • fn_name="trace_kfree_skb" Specifies that when kernel functions are detected kfree_skb when , Carry out the trace_kfree_skb function ;

BPF The first parameter of the program is always ctx, This parameter is called context , Provides access to information being processed by the kernel , Depending on the running BPF The type of program .CPU Save different information about the kernel's tasks in registers , These registers can be accessed with the help of the macro provided by the kernel , Such as PT_REGS_RC.

The program runs as follows :

3.3 kretprobes

Compared to the core probe kprobe Program ,kretprobe The program is inserted when the kernel function has a return value BPF Program . When the kernel executes to kretprobe When the kernel function is mounted , Execute the kernel function first , Execute when kernel function returns BPF Program , Return after operation .

On the surface of the above BPF Program, for example , If you want to use kretprobe, You can modify :

b.attach_kretprobe(event="kfree_skb", fn_name="trace_kfree_skb")
  • b.attach_kretprobe() It's time to BPF The program type is kretprobe,kretprobe Type of BPF The program will be executed when the kernel function tracked has a return value BPF Program ;

  • event="kfree_skb" It specifies kretprobe The kernel function mounted is kfree_skb;

  • fn_name="trace_kfree_skb" Specified when kernel functions kfree_skb When there is a return value , Carry out the trace_kfree_skb function ;

4. Kernel static trace points tracepoint

tracepoint Is the kernel static trace point , It is associated with kprobe The main difference between class programs is tracepoint Written and modified in the kernel by kernel developers .

4.1 tracepoint The advantages and disadvantages of the program

  • advantage The tracking point is static ,ABI A more stable , It doesn't change with the kernel version .

  • shortcoming Tracepoints are added by kernel staff , It won't cover all the subsystems of the kernel .

4.2 tracepoint Available tracking points

All tracking points in the system are defined in /sys/kernel/debug/traceing/events Directory :

Use command perf list  You can also list the available tracepoint spot :

about bcc Procedure , To monitor kfree_skb For example ,tracepoint The program can be written like this :

b.attach_tracepoint(tp="skb:kfree_skb", fn_name="trace_kfree_skb")

bcc follow tracepoint Naming conventions , The first is to specify the subsystem to track , Here is “skb:”, And then there are tracking points in the subsystem “kfree_skb”:

5. summary

This paper mainly introduces the guarantee BPF Security of program BPF Validator , And then to BPF The toolset of the program BCC For example , Shared kprobes and tracepoints Type of BPF The use of programs and programming examples . This article is about kernel tracking , So how should user space programs track , This will be shared step by step in later articles , Thank you for reading .

Reference material :

  • If not installed bcc, Please refer to the website below for installation ;

    https://github.com/iovisor/bcc/blob/master/INSTALL.md

  • bcc Programming instruction manual

    https://github.com/iovisor/bcc/blob/master/docs/reference_guide.md

  • Reference books 《Linux Kernel observation technology BPF》

版权声明
本文为[Song Baohua]所创,转载请带上原文链接,感谢
https://javamana.com/2021/05/20210504022910871t.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云