xref: /linux/tools/testing/selftests/bpf/progs/test_verify_pkcs7_sig.c (revision fd7d598270724cc787982ea48bbe17ad383a8b7f)
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 #define MAX_DATA_SIZE (1024 * 1024)
15 #define MAX_SIG_SIZE 1024
16 
17 extern struct bpf_key *bpf_lookup_user_key(__u32 serial, __u64 flags) __ksym;
18 extern struct bpf_key *bpf_lookup_system_key(__u64 id) __ksym;
19 extern void bpf_key_put(struct bpf_key *key) __ksym;
20 extern int bpf_verify_pkcs7_signature(struct bpf_dynptr *data_ptr,
21 				      struct bpf_dynptr *sig_ptr,
22 				      struct bpf_key *trusted_keyring) __ksym;
23 
24 __u32 monitored_pid;
25 __u32 user_keyring_serial;
26 __u64 system_keyring_id;
27 
28 struct data {
29 	__u8 data[MAX_DATA_SIZE];
30 	__u32 data_len;
31 	__u8 sig[MAX_SIG_SIZE];
32 	__u32 sig_len;
33 };
34 
35 struct {
36 	__uint(type, BPF_MAP_TYPE_ARRAY);
37 	__uint(max_entries, 1);
38 	__type(key, __u32);
39 	__type(value, struct data);
40 } data_input SEC(".maps");
41 
42 char _license[] SEC("license") = "GPL";
43 
44 SEC("lsm.s/bpf")
45 int BPF_PROG(bpf, int cmd, union bpf_attr *attr, unsigned int size)
46 {
47 	struct bpf_dynptr data_ptr, sig_ptr;
48 	struct data *data_val;
49 	struct bpf_key *trusted_keyring;
50 	__u32 pid;
51 	__u64 value;
52 	int ret, zero = 0;
53 
54 	pid = bpf_get_current_pid_tgid() >> 32;
55 	if (pid != monitored_pid)
56 		return 0;
57 
58 	data_val = bpf_map_lookup_elem(&data_input, &zero);
59 	if (!data_val)
60 		return 0;
61 
62 	ret = bpf_probe_read_kernel(&value, sizeof(value), &attr->value);
63 	if (ret)
64 		return ret;
65 
66 	ret = bpf_copy_from_user(data_val, sizeof(struct data),
67 				 (void *)(unsigned long)value);
68 	if (ret)
69 		return ret;
70 
71 	if (data_val->data_len > sizeof(data_val->data))
72 		return -EINVAL;
73 
74 	bpf_dynptr_from_mem(data_val->data, data_val->data_len, 0, &data_ptr);
75 
76 	if (data_val->sig_len > sizeof(data_val->sig))
77 		return -EINVAL;
78 
79 	bpf_dynptr_from_mem(data_val->sig, data_val->sig_len, 0, &sig_ptr);
80 
81 	if (user_keyring_serial)
82 		trusted_keyring = bpf_lookup_user_key(user_keyring_serial, 0);
83 	else
84 		trusted_keyring = bpf_lookup_system_key(system_keyring_id);
85 
86 	if (!trusted_keyring)
87 		return -ENOENT;
88 
89 	ret = bpf_verify_pkcs7_signature(&data_ptr, &sig_ptr, trusted_keyring);
90 
91 	bpf_key_put(trusted_keyring);
92 
93 	return ret;
94 }
95