1 // SPDX-License-Identifier: GPL-2.0
2
3 #include "vmlinux.h"
4
5 #include <bpf/bpf_helpers.h>
6
7 #define AF_INET6 10
8
9 struct {
10 __uint(type, BPF_MAP_TYPE_SK_STORAGE);
11 __uint(map_flags, BPF_F_NO_PREALLOC);
12 __type(key, int);
13 __type(value, int);
14 } sockops_netns_cookies SEC(".maps");
15
16 struct {
17 __uint(type, BPF_MAP_TYPE_SK_STORAGE);
18 __uint(map_flags, BPF_F_NO_PREALLOC);
19 __type(key, int);
20 __type(value, int);
21 } sk_msg_netns_cookies SEC(".maps");
22
23 struct {
24 __uint(type, BPF_MAP_TYPE_SOCKMAP);
25 __uint(max_entries, 2);
26 __type(key, __u32);
27 __type(value, __u64);
28 } sock_map SEC(".maps");
29
30 int tcx_init_netns_cookie, tcx_netns_cookie;
31 int cgroup_skb_init_netns_cookie, cgroup_skb_netns_cookie;
32
33 SEC("sockops")
get_netns_cookie_sockops(struct bpf_sock_ops * ctx)34 int get_netns_cookie_sockops(struct bpf_sock_ops *ctx)
35 {
36 struct bpf_sock *sk = ctx->sk;
37 int *cookie;
38 __u32 key = 0;
39
40 if (ctx->family != AF_INET6)
41 return 1;
42
43 if (!sk)
44 return 1;
45
46 switch (ctx->op) {
47 case BPF_SOCK_OPS_TCP_CONNECT_CB:
48 cookie = bpf_sk_storage_get(&sockops_netns_cookies, sk, 0,
49 BPF_SK_STORAGE_GET_F_CREATE);
50 if (!cookie)
51 return 1;
52
53 *cookie = bpf_get_netns_cookie(ctx);
54 break;
55 case BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB:
56 bpf_sock_map_update(ctx, &sock_map, &key, BPF_NOEXIST);
57 break;
58 default:
59 break;
60 }
61
62 return 1;
63 }
64
65 SEC("sk_msg")
get_netns_cookie_sk_msg(struct sk_msg_md * msg)66 int get_netns_cookie_sk_msg(struct sk_msg_md *msg)
67 {
68 struct bpf_sock *sk = msg->sk;
69 int *cookie;
70
71 if (msg->family != AF_INET6)
72 return 1;
73
74 if (!sk)
75 return 1;
76
77 cookie = bpf_sk_storage_get(&sk_msg_netns_cookies, sk, 0,
78 BPF_SK_STORAGE_GET_F_CREATE);
79 if (!cookie)
80 return 1;
81
82 *cookie = bpf_get_netns_cookie(msg);
83
84 return 1;
85 }
86
87 SEC("tcx/ingress")
get_netns_cookie_tcx(struct __sk_buff * skb)88 int get_netns_cookie_tcx(struct __sk_buff *skb)
89 {
90 tcx_init_netns_cookie = bpf_get_netns_cookie(NULL);
91 tcx_netns_cookie = bpf_get_netns_cookie(skb);
92 return TCX_PASS;
93 }
94
95 SEC("cgroup_skb/ingress")
get_netns_cookie_cgroup_skb(struct __sk_buff * skb)96 int get_netns_cookie_cgroup_skb(struct __sk_buff *skb)
97 {
98 cgroup_skb_init_netns_cookie = bpf_get_netns_cookie(NULL);
99 cgroup_skb_netns_cookie = bpf_get_netns_cookie(skb);
100 return SK_PASS;
101 }
102
103 char _license[] SEC("license") = "GPL";
104