xref: /DragonOS/kernel/crates/rbpf/examples/load_elf__block_a_port.c (revision 7b0ef10895108a0de5ff5ef3d2f93f40cf2e33a5)
1 // SPDX-License-Identifier: (APACHE-2.0 OR MIT)
2 // Copyright 2016 6WIND S.A. <quentin.monnet@6wind.com>
3 
4 // Block TCP packets on source or destination port 0x9999.
5 
6 #include <linux/ip.h>
7 #include <linux/in.h>
8 #include <linux/tcp.h>
9 #include <linux/bpf.h>
10 
11 #define ETH_ALEN 6
12 #define ETH_P_IP 0x0008 /* htons(0x0800) */
13 #define TCP_HDR_LEN 20
14 
15 #define BLOCKED_TCP_PORT 0x9999
16 
17 struct eth_hdr {
18     unsigned char   h_dest[ETH_ALEN];
19     unsigned char   h_source[ETH_ALEN];
20     unsigned short  h_proto;
21 };
22 
23 #define SEC(NAME) __attribute__((section(NAME), used))
24 SEC(".classifier")
25 int handle_ingress(struct __sk_buff *skb)
26 {
27     void *data = (void *)(long)skb->data;
28     void *data_end = (void *)(long)skb->data_end;
29     struct eth_hdr *eth = data;
30     struct iphdr *iph = data + sizeof(*eth);
31     struct tcphdr *tcp = data + sizeof(*eth) + sizeof(*iph);
32 
33     /* single length check */
34     if (data + sizeof(*eth) + sizeof(*iph) + sizeof(*tcp) > data_end)
35         return 0;
36     if (eth->h_proto != ETH_P_IP)
37         return 0;
38     if (iph->protocol != IPPROTO_TCP)
39         return 0;
40     if (tcp->source == BLOCKED_TCP_PORT || tcp->dest == BLOCKED_TCP_PORT)
41         return -1;
42     return 0;
43 }
44