Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 // Copyright (c) 2020 Facebook
0003 
0004 #include <linux/bpf.h>
0005 #include <bpf/bpf_endian.h>
0006 #include <bpf/bpf_helpers.h>
0007 
0008 #include <linux/if_ether.h>
0009 #include <linux/in.h>
0010 #include <linux/in6.h>
0011 #include <linux/ipv6.h>
0012 #include <linux/tcp.h>
0013 
0014 #include <sys/types.h>
0015 #include <sys/socket.h>
0016 
0017 char _license[] SEC("license") = "GPL";
0018 
0019 __u16 g_serv_port = 0;
0020 
0021 static inline void set_ip(__u32 *dst, const struct in6_addr *src)
0022 {
0023     dst[0] = src->in6_u.u6_addr32[0];
0024     dst[1] = src->in6_u.u6_addr32[1];
0025     dst[2] = src->in6_u.u6_addr32[2];
0026     dst[3] = src->in6_u.u6_addr32[3];
0027 }
0028 
0029 static inline void set_tuple(struct bpf_sock_tuple *tuple,
0030                  const struct ipv6hdr *ip6h,
0031                  const struct tcphdr *tcph)
0032 {
0033     set_ip(tuple->ipv6.saddr, &ip6h->daddr);
0034     set_ip(tuple->ipv6.daddr, &ip6h->saddr);
0035     tuple->ipv6.sport = tcph->dest;
0036     tuple->ipv6.dport = tcph->source;
0037 }
0038 
0039 static inline int is_allowed_peer_cg(struct __sk_buff *skb,
0040                      const struct ipv6hdr *ip6h,
0041                      const struct tcphdr *tcph)
0042 {
0043     __u64 cgid, acgid, peer_cgid, peer_acgid;
0044     struct bpf_sock_tuple tuple;
0045     size_t tuple_len = sizeof(tuple.ipv6);
0046     struct bpf_sock *peer_sk;
0047 
0048     set_tuple(&tuple, ip6h, tcph);
0049 
0050     peer_sk = bpf_sk_lookup_tcp(skb, &tuple, tuple_len,
0051                     BPF_F_CURRENT_NETNS, 0);
0052     if (!peer_sk)
0053         return 0;
0054 
0055     cgid = bpf_skb_cgroup_id(skb);
0056     peer_cgid = bpf_sk_cgroup_id(peer_sk);
0057 
0058     acgid = bpf_skb_ancestor_cgroup_id(skb, 2);
0059     peer_acgid = bpf_sk_ancestor_cgroup_id(peer_sk, 2);
0060 
0061     bpf_sk_release(peer_sk);
0062 
0063     return cgid && cgid == peer_cgid && acgid && acgid == peer_acgid;
0064 }
0065 
0066 SEC("cgroup_skb/ingress")
0067 int ingress_lookup(struct __sk_buff *skb)
0068 {
0069     __u32 serv_port_key = 0;
0070     struct ipv6hdr ip6h;
0071     struct tcphdr tcph;
0072 
0073     if (skb->protocol != bpf_htons(ETH_P_IPV6))
0074         return 1;
0075 
0076     /* For SYN packets coming to listening socket skb->remote_port will be
0077      * zero, so IPv6/TCP headers are loaded to identify remote peer
0078      * instead.
0079      */
0080     if (bpf_skb_load_bytes(skb, 0, &ip6h, sizeof(ip6h)))
0081         return 1;
0082 
0083     if (ip6h.nexthdr != IPPROTO_TCP)
0084         return 1;
0085 
0086     if (bpf_skb_load_bytes(skb, sizeof(ip6h), &tcph, sizeof(tcph)))
0087         return 1;
0088 
0089     if (!g_serv_port)
0090         return 0;
0091 
0092     if (tcph.dest != g_serv_port)
0093         return 1;
0094 
0095     return is_allowed_peer_cg(skb, &ip6h, &tcph);
0096 }