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 SEC("test1")
21 int process(struct __sk_buff *skb)
22 {
23 	void *data_end = (void *)(long)skb->data_end;
24 	void *data = (void *)(long)skb->data;
25 	struct ethhdr *eth = (struct ethhdr *)(data);
26 	struct tcphdr *tcp = NULL;
27 	__u8 proto = 255;
28 	__u64 ihl_len;
29 
30 	if (eth + 1 > data_end)
31 		return TC_ACT_SHOT;
32 
33 	if (eth->h_proto == bpf_htons(ETH_P_IP)) {
34 		struct iphdr *iph = (struct iphdr *)(eth + 1);
35 
36 		if (iph + 1 > data_end)
37 			return TC_ACT_SHOT;
38 		ihl_len = iph->ihl * 4;
39 		proto = iph->protocol;
40 		tcp = (struct tcphdr *)((void *)(iph) + ihl_len);
41 	} else if (eth->h_proto == bpf_htons(ETH_P_IPV6)) {
42 		struct ipv6hdr *ip6h = (struct ipv6hdr *)(eth + 1);
43 
44 		if (ip6h + 1 > data_end)
45 			return TC_ACT_SHOT;
46 		ihl_len = sizeof(*ip6h);
47 		proto = ip6h->nexthdr;
48 		tcp = (struct tcphdr *)((void *)(ip6h) + ihl_len);
49 	}
50 
51 	if (tcp) {
52 		if (((void *)(tcp) + 20) > data_end || proto != 6)
53 			return TC_ACT_SHOT;
54 		barrier(); /* to force ordering of checks */
55 		if (((void *)(tcp) + 18) > data_end)
56 			return TC_ACT_SHOT;
57 		if (tcp->urg_ptr == 123)
58 			return TC_ACT_OK;
59 	}
60 
61 	return TC_ACT_UNSPEC;
62 }
63