-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmain.bpf.c
72 lines (58 loc) · 2.07 KB
/
main.bpf.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
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_endian.h>
#include <bpf/bpf_tracing.h>
#include <bpf/bpf_core_read.h>
#include "main.h"
struct {
__uint(type, BPF_MAP_TYPE_PERF_EVENT_ARRAY);
__uint(key_size, sizeof(u32));
__uint(value_size, sizeof(u32));
} events SEC(".maps");
SEC("socket")
int socket_filter_icmp(struct __sk_buff *skb) {
struct event_t event = {};
// 过滤以太网Ethernet II帧的数据类型,只处理 ETH_P_IP 类型
struct ethhdr eth_hdr;
if (bpf_skb_load_bytes(skb, 0, ð_hdr, sizeof(eth_hdr)) < 0)
return 0;
if (bpf_ntohs(eth_hdr.h_proto) != ETH_P_IP)
return 0;
// 从 IP 首部中过滤协议类型,只处理 ICMP 协议
struct iphdr ip_hdr;
if (bpf_skb_load_bytes(skb, ETH_HLEN, &ip_hdr, sizeof(ip_hdr)) < 0)
return 0;
if (ip_hdr.protocol != IPPROTO_ICMP)
return 0;
event.src_addr = ip_hdr.saddr;
event.dst_addr = ip_hdr.daddr;
// 解析 ICMP 消息
struct icmphdr icmp_hdr;
if (bpf_skb_load_bytes(skb, ETH_HLEN + sizeof(struct iphdr), &icmp_hdr, sizeof(icmp_hdr)) < 0)
return 0;
event.type = icmp_hdr.type;
event.code = icmp_hdr.code;
bpf_perf_event_output(skb, &events, BPF_F_CURRENT_CPU, &event, sizeof(event));
return 0;
}
SEC("socket")
int socket_filter_tcp(struct __sk_buff *skb) {
u16 h_proto;
if (bpf_skb_load_bytes(skb, offsetof(struct ethhdr, h_proto), &h_proto,
sizeof(h_proto)) < 0)
return 0;
if (bpf_ntohs(h_proto) != ETH_P_IP) // not ipv4
return 0;
struct iphdr ip_hdr;
if (bpf_skb_load_bytes(skb, ETH_HLEN, &ip_hdr, sizeof(ip_hdr)) < 0)
return 0;
if (ip_hdr.protocol != IPPROTO_TCP) // not tcp
return 0;
struct tcphdr tcp_hdr;
if (bpf_skb_load_bytes(skb, ETH_HLEN + sizeof(struct iphdr), &tcp_hdr,
sizeof(tcp_hdr)) < 0)
return 0;
bpf_printk("saddr: %pI4, daddr: %pI4:%d", &ip_hdr.saddr, &ip_hdr.daddr, bpf_htons(tcp_hdr.dest));
return 0;
}
char _license[] SEC("license") = "GPL";