xref: /linux/tools/testing/selftests/bpf/progs/verifier_const.c (revision ae90f6a6170d7a7a1aa4fddf664fbd093e3023bc)
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2024 Isovalent */
3 
4 #include "vmlinux.h"
5 #include <bpf/bpf_helpers.h>
6 #include <bpf/bpf_tracing.h>
7 #include "bpf_misc.h"
8 
9 const volatile long foo = 42;
10 long bar;
11 long bart = 96;
12 
13 SEC("tc/ingress")
14 __description("rodata/strtol: write rejected")
15 __failure __msg("write into map forbidden")
tcx1(struct __sk_buff * skb)16 int tcx1(struct __sk_buff *skb)
17 {
18 	char buff[] = { '8', '4', '\0' };
19 	bpf_strtol(buff, sizeof(buff), 0, (long *)&foo);
20 	return TCX_PASS;
21 }
22 
23 SEC("tc/ingress")
24 __description("bss/strtol: write accepted")
25 __success
tcx2(struct __sk_buff * skb)26 int tcx2(struct __sk_buff *skb)
27 {
28 	char buff[] = { '8', '4', '\0' };
29 	bpf_strtol(buff, sizeof(buff), 0, &bar);
30 	return TCX_PASS;
31 }
32 
33 SEC("tc/ingress")
34 __description("data/strtol: write accepted")
35 __success
tcx3(struct __sk_buff * skb)36 int tcx3(struct __sk_buff *skb)
37 {
38 	char buff[] = { '8', '4', '\0' };
39 	bpf_strtol(buff, sizeof(buff), 0, &bart);
40 	return TCX_PASS;
41 }
42 
43 SEC("tc/ingress")
44 __description("rodata/mtu: write rejected")
45 __failure __msg("write into map forbidden")
tcx4(struct __sk_buff * skb)46 int tcx4(struct __sk_buff *skb)
47 {
48 	bpf_check_mtu(skb, skb->ifindex, (__u32 *)&foo, 0, 0);
49 	return TCX_PASS;
50 }
51 
52 SEC("tc/ingress")
53 __description("bss/mtu: write accepted")
54 __success
tcx5(struct __sk_buff * skb)55 int tcx5(struct __sk_buff *skb)
56 {
57 	bpf_check_mtu(skb, skb->ifindex, (__u32 *)&bar, 0, 0);
58 	return TCX_PASS;
59 }
60 
61 SEC("tc/ingress")
62 __description("data/mtu: write accepted")
63 __success
tcx6(struct __sk_buff * skb)64 int tcx6(struct __sk_buff *skb)
65 {
66 	bpf_check_mtu(skb, skb->ifindex, (__u32 *)&bart, 0, 0);
67 	return TCX_PASS;
68 }
69 
write_fixed(volatile void * p,__u32 val)70 static inline void write_fixed(volatile void *p, __u32 val)
71 {
72 	*(volatile __u32 *)p = val;
73 }
74 
write_dyn(void * p,void * val,int len)75 static inline void write_dyn(void *p, void *val, int len)
76 {
77 	bpf_copy_from_user(p, len, val);
78 }
79 
80 SEC("tc/ingress")
81 __description("rodata/mark: write with unknown reg rejected")
82 __failure __msg("write into map forbidden")
tcx7(struct __sk_buff * skb)83 int tcx7(struct __sk_buff *skb)
84 {
85 	write_fixed((void *)&foo, skb->mark);
86 	return TCX_PASS;
87 }
88 
89 SEC("lsm.s/bprm_committed_creds")
90 __description("rodata/mark: write with unknown reg rejected")
91 __failure __msg("write into map forbidden")
BPF_PROG(bprm,struct linux_binprm * bprm)92 int BPF_PROG(bprm, struct linux_binprm *bprm)
93 {
94 	write_dyn((void *)&foo, &bart, bpf_get_prandom_u32() & 3);
95 	return 0;
96 }
97 
98 char LICENSE[] SEC("license") = "GPL";
99