Skip to content

Commit 0c34970

Browse files
feat: add event tracking
1 parent ce9e3e5 commit 0c34970

File tree

1 file changed

+28
-5
lines changed

1 file changed

+28
-5
lines changed

bpf-prog/block-iptables/bpf/src/block_iptables.bpf.c

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,20 @@
66
#define sk_family __sk_common.skc_family
77
#define EPERM 1
88
#define IPT_SO_SET_REPLACE 64
9-
char LICENSE[] SEC("license") = "GPL";
10-
11-
volatile const __u32 host_netns_inode = 4026531840; // Initialized by userspace
129
#define TASK_COMM_LEN 16
1310
#define COMM_COUNT 3
11+
12+
char LICENSE[] SEC("license") = "GPL";
13+
volatile const __u32 host_netns_inode = 4026531840; // Initialized by userspace
14+
15+
struct {
16+
__uint(type, BPF_MAP_TYPE_ARRAY);
17+
__uint(max_entries, 1);
18+
__type(key, u32);
19+
__type(value, u64);
20+
__uint(pinning, LIBBPF_PIN_BY_NAME);
21+
} event_counter SEC(".maps");
22+
1423
int is_allowed_parent ()
1524
{
1625
struct task_struct *task = (struct task_struct *)bpf_get_current_task();
@@ -72,17 +81,30 @@ int is_host_ns() {
7281
return 1;
7382
}
7483

84+
void increment_event_counter() {
85+
u32 key = 0;
86+
u64 *value;
87+
88+
value = bpf_map_lookup_elem(&event_counter, &key);
89+
if (value) {
90+
__sync_fetch_and_add(value, 1);
91+
} else {
92+
u64 initial_value = 1;
93+
bpf_map_update_elem(&event_counter, &key, &initial_value, BPF_ANY);
94+
}
95+
}
96+
7597
SEC("lsm/socket_setsockopt")
7698
int BPF_PROG(iptables_legacy_block, struct socket *sock, int level, int optname)
7799
{
78100
if (sock == NULL) {
79101
return 0;
80102
}
81103

82-
// bpf_printk("setsockopt called %d %d\n", level, optname);
83104
if (level == 0 /*IPPROTO_IP*/ || level == 41 /*IPPROTO_IP6*/) {
84105
if (optname == IPT_SO_SET_REPLACE) {
85106
if (is_host_ns() && !is_allowed_parent()) {
107+
increment_event_counter();
86108
return -EPERM;
87109
}
88110
}
@@ -141,7 +163,8 @@ int BPF_PROG(iptables_nftables_block, struct sock *sk, struct sk_buff *skb) {
141163
if(is_allowed_parent()) {
142164
return 0;
143165
} else {
144-
return -EPERM;
166+
increment_event_counter();
167+
return -EPERM;
145168
}
146169
}
147170

0 commit comments

Comments
 (0)