xref: /linux/tools/testing/selftests/bpf/progs/test_tc_peer.c (revision 6beeaf48db6c548fcfc2ad32739d33af2fef3a5b)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <stdint.h>
3 #include <stdbool.h>
4 
5 #include <linux/bpf.h>
6 #include <linux/stddef.h>
7 #include <linux/pkt_cls.h>
8 #include <linux/if_ether.h>
9 #include <linux/ip.h>
10 
11 #include <bpf/bpf_helpers.h>
12 
13 volatile const __u32 IFINDEX_SRC;
14 volatile const __u32 IFINDEX_DST;
15 
16 static const __u8 src_mac[] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55};
17 static const __u8 dst_mac[] = {0x00, 0x22, 0x33, 0x44, 0x55, 0x66};
18 
19 SEC("classifier/chk_egress")
20 int tc_chk(struct __sk_buff *skb)
21 {
22 	return TC_ACT_SHOT;
23 }
24 
25 SEC("classifier/dst_ingress")
26 int tc_dst(struct __sk_buff *skb)
27 {
28 	return bpf_redirect_peer(IFINDEX_SRC, 0);
29 }
30 
31 SEC("classifier/src_ingress")
32 int tc_src(struct __sk_buff *skb)
33 {
34 	return bpf_redirect_peer(IFINDEX_DST, 0);
35 }
36 
37 SEC("classifier/dst_ingress_l3")
38 int tc_dst_l3(struct __sk_buff *skb)
39 {
40 	return bpf_redirect(IFINDEX_SRC, 0);
41 }
42 
43 SEC("classifier/src_ingress_l3")
44 int tc_src_l3(struct __sk_buff *skb)
45 {
46 	__u16 proto = skb->protocol;
47 
48 	if (bpf_skb_change_head(skb, ETH_HLEN, 0) != 0)
49 		return TC_ACT_SHOT;
50 
51 	if (bpf_skb_store_bytes(skb, 0, &src_mac, ETH_ALEN, 0) != 0)
52 		return TC_ACT_SHOT;
53 
54 	if (bpf_skb_store_bytes(skb, ETH_ALEN, &dst_mac, ETH_ALEN, 0) != 0)
55 		return TC_ACT_SHOT;
56 
57 	if (bpf_skb_store_bytes(skb, ETH_ALEN + ETH_ALEN, &proto, sizeof(__u16), 0) != 0)
58 		return TC_ACT_SHOT;
59 
60 	return bpf_redirect_peer(IFINDEX_DST, 0);
61 }
62 
63 char __license[] SEC("license") = "GPL";
64