1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2017 Facebook
3  */
4 #include <stddef.h>
5 #include <string.h>
6 #include <linux/bpf.h>
7 #include <linux/if_ether.h>
8 #include <linux/if_packet.h>
9 #include <linux/ip.h>
10 #include <linux/ipv6.h>
11 #include <linux/in.h>
12 #include <linux/tcp.h>
13 #include <linux/pkt_cls.h>
14 #include "bpf_helpers.h"
15 #include "bpf_endian.h"
16 
17 #define barrier() __asm__ __volatile__("": : :"memory")
18 int _version SEC("version") = 1;
19 
20 /* llvm will optimize both subprograms into exactly the same BPF assembly
21  *
22  * Disassembly of section .text:
23  *
24  * 0000000000000000 test_pkt_access_subprog1:
25  * ; 	return skb->len * 2;
26  *        0:	61 10 00 00 00 00 00 00	r0 = *(u32 *)(r1 + 0)
27  *        1:	64 00 00 00 01 00 00 00	w0 <<= 1
28  *        2:	95 00 00 00 00 00 00 00	exit
29  *
30  * 0000000000000018 test_pkt_access_subprog2:
31  * ; 	return skb->len * val;
32  *        3:	61 10 00 00 00 00 00 00	r0 = *(u32 *)(r1 + 0)
33  *        4:	64 00 00 00 01 00 00 00	w0 <<= 1
34  *        5:	95 00 00 00 00 00 00 00	exit
35  *
36  * Which makes it an interesting test for BTF-enabled verifier.
37  */
38 static __attribute__ ((noinline))
39 int test_pkt_access_subprog1(volatile struct __sk_buff *skb)
40 {
41 	return skb->len * 2;
42 }
43 
44 static __attribute__ ((noinline))
45 int test_pkt_access_subprog2(int val, volatile struct __sk_buff *skb)
46 {
47 	return skb->len * val;
48 }
49 
50 SEC("classifier/test_pkt_access")
51 int test_pkt_access(struct __sk_buff *skb)
52 {
53 	void *data_end = (void *)(long)skb->data_end;
54 	void *data = (void *)(long)skb->data;
55 	struct ethhdr *eth = (struct ethhdr *)(data);
56 	struct tcphdr *tcp = NULL;
57 	__u8 proto = 255;
58 	__u64 ihl_len;
59 
60 	if (eth + 1 > data_end)
61 		return TC_ACT_SHOT;
62 
63 	if (eth->h_proto == bpf_htons(ETH_P_IP)) {
64 		struct iphdr *iph = (struct iphdr *)(eth + 1);
65 
66 		if (iph + 1 > data_end)
67 			return TC_ACT_SHOT;
68 		ihl_len = iph->ihl * 4;
69 		proto = iph->protocol;
70 		tcp = (struct tcphdr *)((void *)(iph) + ihl_len);
71 	} else if (eth->h_proto == bpf_htons(ETH_P_IPV6)) {
72 		struct ipv6hdr *ip6h = (struct ipv6hdr *)(eth + 1);
73 
74 		if (ip6h + 1 > data_end)
75 			return TC_ACT_SHOT;
76 		ihl_len = sizeof(*ip6h);
77 		proto = ip6h->nexthdr;
78 		tcp = (struct tcphdr *)((void *)(ip6h) + ihl_len);
79 	}
80 
81 	if (test_pkt_access_subprog1(skb) != skb->len * 2)
82 		return TC_ACT_SHOT;
83 	if (test_pkt_access_subprog2(2, skb) != skb->len * 2)
84 		return TC_ACT_SHOT;
85 	if (tcp) {
86 		if (((void *)(tcp) + 20) > data_end || proto != 6)
87 			return TC_ACT_SHOT;
88 		barrier(); /* to force ordering of checks */
89 		if (((void *)(tcp) + 18) > data_end)
90 			return TC_ACT_SHOT;
91 		if (tcp->urg_ptr == 123)
92 			return TC_ACT_OK;
93 	}
94 
95 	return TC_ACT_UNSPEC;
96 }
97