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 
14 extern struct bpf_key *bpf_lookup_system_key(__u64 id) __ksym;
15 extern void bpf_key_put(struct bpf_key *key) __ksym;
16 extern int bpf_verify_pkcs7_signature(struct bpf_dynptr *data_ptr,
17 				      struct bpf_dynptr *sig_ptr,
18 				      struct bpf_key *trusted_keyring) __ksym;
19 
20 struct {
21 	__uint(type, BPF_MAP_TYPE_RINGBUF);
22 } ringbuf SEC(".maps");
23 
24 struct {
25 	__uint(type, BPF_MAP_TYPE_ARRAY);
26 	__uint(max_entries, 1);
27 	__type(key, __u32);
28 	__type(value, __u32);
29 } array_map SEC(".maps");
30 
31 int err, pid;
32 
33 char _license[] SEC("license") = "GPL";
34 
35 SEC("?lsm.s/bpf")
36 int BPF_PROG(dynptr_type_not_supp, int cmd, union bpf_attr *attr,
37 	     unsigned int size)
38 {
39 	char write_data[64] = "hello there, world!!";
40 	struct bpf_dynptr ptr;
41 
42 	bpf_ringbuf_reserve_dynptr(&ringbuf, sizeof(write_data), 0, &ptr);
43 
44 	return bpf_verify_pkcs7_signature(&ptr, &ptr, NULL);
45 }
46 
47 SEC("?lsm.s/bpf")
48 int BPF_PROG(not_valid_dynptr, int cmd, union bpf_attr *attr, unsigned int size)
49 {
50 	unsigned long val;
51 
52 	return bpf_verify_pkcs7_signature((struct bpf_dynptr *)&val,
53 					  (struct bpf_dynptr *)&val, NULL);
54 }
55 
56 SEC("?lsm.s/bpf")
57 int BPF_PROG(not_ptr_to_stack, int cmd, union bpf_attr *attr, unsigned int size)
58 {
59 	unsigned long val;
60 
61 	return bpf_verify_pkcs7_signature((struct bpf_dynptr *)val,
62 					  (struct bpf_dynptr *)val, NULL);
63 }
64 
65 SEC("lsm.s/bpf")
66 int BPF_PROG(dynptr_data_null, int cmd, union bpf_attr *attr, unsigned int size)
67 {
68 	struct bpf_key *trusted_keyring;
69 	struct bpf_dynptr ptr;
70 	__u32 *value;
71 	int ret, zero = 0;
72 
73 	if (bpf_get_current_pid_tgid() >> 32 != pid)
74 		return 0;
75 
76 	value = bpf_map_lookup_elem(&array_map, &zero);
77 	if (!value)
78 		return 0;
79 
80 	/* Pass invalid flags. */
81 	ret = bpf_dynptr_from_mem(value, sizeof(*value), ((__u64)~0ULL), &ptr);
82 	if (ret != -EINVAL)
83 		return 0;
84 
85 	trusted_keyring = bpf_lookup_system_key(0);
86 	if (!trusted_keyring)
87 		return 0;
88 
89 	err = bpf_verify_pkcs7_signature(&ptr, &ptr, trusted_keyring);
90 
91 	bpf_key_put(trusted_keyring);
92 
93 	return 0;
94 }
95