xref: /linux/tools/testing/selftests/bpf/progs/test_kfunc_dynptr_param.c (revision c16ce856e422e73a54c41131e0332de1afe09b8b)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 /*
4  * Copyright (C) 2022 Huawei Technologies Duesseldorf GmbH
5  *
6  * Author: Roberto Sassu <roberto.sassu@huawei.com>
7  */
8 
9 #include "vmlinux.h"
10 #include <errno.h>
11 #include <bpf/bpf_helpers.h>
12 #include <bpf/bpf_tracing.h>
13 #include "bpf_misc.h"
14 #include "bpf_kfuncs.h"
15 
16 struct {
17 	__uint(type, BPF_MAP_TYPE_RINGBUF);
18 	__uint(max_entries, 4096);
19 } ringbuf SEC(".maps");
20 
21 struct {
22 	__uint(type, BPF_MAP_TYPE_ARRAY);
23 	__uint(max_entries, 1);
24 	__type(key, __u32);
25 	__type(value, __u32);
26 } array_map SEC(".maps");
27 
28 int err, pid;
29 
30 char _license[] SEC("license") = "GPL";
31 
32 SEC("?lsm.s/bpf")
33 __failure __msg("cannot pass in dynptr at an offset=-8")
34 int BPF_PROG(not_valid_dynptr, int cmd, union bpf_attr *attr, unsigned int size, bool kernel)
35 {
36 	unsigned long val = 0;
37 
38 	return bpf_verify_pkcs7_signature((struct bpf_dynptr *)&val,
39 					  (struct bpf_dynptr *)&val, NULL);
40 }
41 
42 SEC("?lsm.s/bpf")
43 __failure __msg("R1 expected pointer to stack or const struct bpf_dynptr")
44 int BPF_PROG(not_ptr_to_stack, int cmd, union bpf_attr *attr, unsigned int size, bool kernel)
45 {
46 	static struct bpf_dynptr val;
47 
48 	return bpf_verify_pkcs7_signature(&val, &val, NULL);
49 }
50 
51 SEC("lsm.s/bpf")
52 int BPF_PROG(dynptr_data_null, int cmd, union bpf_attr *attr, unsigned int size, bool kernel)
53 {
54 	struct bpf_key *trusted_keyring;
55 	struct bpf_dynptr ptr;
56 	__u32 *value;
57 	int ret, zero = 0;
58 
59 	if (bpf_get_current_pid_tgid() >> 32 != pid)
60 		return 0;
61 
62 	value = bpf_map_lookup_elem(&array_map, &zero);
63 	if (!value)
64 		return 0;
65 
66 	/* Pass invalid flags. */
67 	ret = bpf_dynptr_from_mem(value, sizeof(*value), ((__u64)~0ULL), &ptr);
68 	if (ret != -EINVAL)
69 		return 0;
70 
71 	trusted_keyring = bpf_lookup_system_key(0);
72 	if (!trusted_keyring)
73 		return 0;
74 
75 	err = bpf_verify_pkcs7_signature(&ptr, &ptr, trusted_keyring);
76 
77 	bpf_key_put(trusted_keyring);
78 
79 	return 0;
80 }
81