# eBPF start! ## 安裝套件 ``` # sudo apt install clang llvm # sudo apt install libbpf-dev # sudo apt install iproute2 # sudo apt install linux-tools-common # uname -r # 5.4.0-42-generic # this is an exmaple # sudo apt install linux-tools-5.4.0-42-generic ``` ## 撰寫 ICMP 封包側錄的 eBPF 程式 ```c= #include <linux/bpf.h> #include <linux/if_ether.h> #include <linux/ip.h> #include <linux/in.h> #include <linux/icmp.h> #include <bpf/bpf_helpers.h> SEC("socket") int icmp_filter(struct __sk_buff *skb) { void *data = (void *)(long)skb->data; void *data_end = (void *)(long)skb->data_end; struct ethhdr *eth = data; struct iphdr *ip = data + sizeof(*eth); if ((void *)ip + sizeof(*ip) > data_end) return 0; if (ip->protocol == IPPROTO_ICMP) { bpf_printk("ICMP packet captured!\n"); } return 0; } char _license[] SEC("license") = "GPL"; ``` 編譯: ``` clang -O2 -target bpf -c ping_capture.c -o ping_capture.o ``` 加載: ``` sudo tc qdisc add dev eth0 clsact sudo tc filter add dev eth0 ingress bpf da obj ping_capture.o sec socket ``` 測試: ``` ping localhost -c 4 ``` 查看訊息: ``` sudo dmesg ``` 訊息也有可能在: ``` sudo cat /sys/kernel/debug/tracing/trace_pipe ``` ![image](https://hackmd.io/_uploads/SyZ2XZYtp.png) 我們可以透過以下指令查看我們有哪些 eBPF programs 被加載: ``` sudo bpftool map list ``` ![image](https://hackmd.io/_uploads/ByFkNbYFp.png)