xref: /linux/tools/testing/selftests/bpf/progs/test_tc_peer.c (revision 5a8cd539ac19f7a68e68e1d25ef9ca2ff55b8500)
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("tc")
tc_chk(struct __sk_buff * skb)20 int tc_chk(struct __sk_buff *skb)
21 {
22 	return TC_ACT_SHOT;
23 }
24 
25 SEC("tc")
tc_dst(struct __sk_buff * skb)26 int tc_dst(struct __sk_buff *skb)
27 {
28 	return bpf_redirect_peer(IFINDEX_SRC, 0);
29 }
30 
31 SEC("tc")
tc_src(struct __sk_buff * skb)32 int tc_src(struct __sk_buff *skb)
33 {
34 	return bpf_redirect_peer(IFINDEX_DST, 0);
35 }
36 
37 SEC("tc")
tc_dst_ing(struct __sk_buff * skb)38 int tc_dst_ing(struct __sk_buff *skb)
39 {
40 	if (!skb->mark) {
41 		skb->mark = 0x1;
42 		return bpf_redirect_peer(IFINDEX_SRC, BPF_F_EGRESS);
43 	}
44 
45 	return bpf_redirect(IFINDEX_DST, 0);
46 }
47 
48 SEC("tc")
tc_src_ing(struct __sk_buff * skb)49 int tc_src_ing(struct __sk_buff *skb)
50 {
51 	if (!skb->mark) {
52 		skb->mark = 0x1;
53 		return bpf_redirect_peer(IFINDEX_DST, BPF_F_EGRESS);
54 	}
55 
56 	return bpf_redirect(IFINDEX_SRC, 0);
57 }
58 
59 SEC("tc")
tc_dst_l3(struct __sk_buff * skb)60 int tc_dst_l3(struct __sk_buff *skb)
61 {
62 	return bpf_redirect(IFINDEX_SRC, 0);
63 }
64 
65 SEC("tc")
tc_src_l3(struct __sk_buff * skb)66 int tc_src_l3(struct __sk_buff *skb)
67 {
68 	__u16 proto = skb->protocol;
69 
70 	if (bpf_skb_change_head(skb, ETH_HLEN, 0) != 0)
71 		return TC_ACT_SHOT;
72 
73 	if (bpf_skb_store_bytes(skb, 0, &src_mac, ETH_ALEN, 0) != 0)
74 		return TC_ACT_SHOT;
75 
76 	if (bpf_skb_store_bytes(skb, ETH_ALEN, &dst_mac, ETH_ALEN, 0) != 0)
77 		return TC_ACT_SHOT;
78 
79 	if (bpf_skb_store_bytes(skb, ETH_ALEN + ETH_ALEN, &proto, sizeof(__u16), 0) != 0)
80 		return TC_ACT_SHOT;
81 
82 	return bpf_redirect_peer(IFINDEX_DST, 0);
83 }
84 
85 char __license[] SEC("license") = "GPL";
86