1 // SPDX-License-Identifier: GPL-2.0
2 // Copyright (c) 2020 Facebook
3 
4 #include <linux/bpf.h>
5 #include <bpf/bpf_endian.h>
6 #include <bpf/bpf_helpers.h>
7 
8 #include <linux/if_ether.h>
9 #include <linux/in.h>
10 #include <linux/in6.h>
11 #include <linux/ipv6.h>
12 #include <linux/tcp.h>
13 
14 #include <sys/types.h>
15 #include <sys/socket.h>
16 
17 int _version SEC("version") = 1;
18 char _license[] SEC("license") = "GPL";
19 
20 __u16 g_serv_port = 0;
21 
22 static inline void set_ip(__u32 *dst, const struct in6_addr *src)
23 {
24 	dst[0] = src->in6_u.u6_addr32[0];
25 	dst[1] = src->in6_u.u6_addr32[1];
26 	dst[2] = src->in6_u.u6_addr32[2];
27 	dst[3] = src->in6_u.u6_addr32[3];
28 }
29 
30 static inline void set_tuple(struct bpf_sock_tuple *tuple,
31 			     const struct ipv6hdr *ip6h,
32 			     const struct tcphdr *tcph)
33 {
34 	set_ip(tuple->ipv6.saddr, &ip6h->daddr);
35 	set_ip(tuple->ipv6.daddr, &ip6h->saddr);
36 	tuple->ipv6.sport = tcph->dest;
37 	tuple->ipv6.dport = tcph->source;
38 }
39 
40 static inline int is_allowed_peer_cg(struct __sk_buff *skb,
41 				     const struct ipv6hdr *ip6h,
42 				     const struct tcphdr *tcph)
43 {
44 	__u64 cgid, acgid, peer_cgid, peer_acgid;
45 	struct bpf_sock_tuple tuple;
46 	size_t tuple_len = sizeof(tuple.ipv6);
47 	struct bpf_sock *peer_sk;
48 
49 	set_tuple(&tuple, ip6h, tcph);
50 
51 	peer_sk = bpf_sk_lookup_tcp(skb, &tuple, tuple_len,
52 				    BPF_F_CURRENT_NETNS, 0);
53 	if (!peer_sk)
54 		return 0;
55 
56 	cgid = bpf_skb_cgroup_id(skb);
57 	peer_cgid = bpf_sk_cgroup_id(peer_sk);
58 
59 	acgid = bpf_skb_ancestor_cgroup_id(skb, 2);
60 	peer_acgid = bpf_sk_ancestor_cgroup_id(peer_sk, 2);
61 
62 	bpf_sk_release(peer_sk);
63 
64 	return cgid && cgid == peer_cgid && acgid && acgid == peer_acgid;
65 }
66 
67 SEC("cgroup_skb/ingress")
68 int ingress_lookup(struct __sk_buff *skb)
69 {
70 	__u32 serv_port_key = 0;
71 	struct ipv6hdr ip6h;
72 	struct tcphdr tcph;
73 
74 	if (skb->protocol != bpf_htons(ETH_P_IPV6))
75 		return 1;
76 
77 	/* For SYN packets coming to listening socket skb->remote_port will be
78 	 * zero, so IPv6/TCP headers are loaded to identify remote peer
79 	 * instead.
80 	 */
81 	if (bpf_skb_load_bytes(skb, 0, &ip6h, sizeof(ip6h)))
82 		return 1;
83 
84 	if (ip6h.nexthdr != IPPROTO_TCP)
85 		return 1;
86 
87 	if (bpf_skb_load_bytes(skb, sizeof(ip6h), &tcph, sizeof(tcph)))
88 		return 1;
89 
90 	if (!g_serv_port)
91 		return 0;
92 
93 	if (tcph.dest != g_serv_port)
94 		return 1;
95 
96 	return is_allowed_peer_cg(skb, &ip6h, &tcph);
97 }
98