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 	bpf_probe_read(&value, sizeof(value), &attr->value);
63 
64 	bpf_copy_from_user(data_val, sizeof(struct data),
65 			   (void *)(unsigned long)value);
66 
67 	if (data_val->data_len > sizeof(data_val->data))
68 		return -EINVAL;
69 
70 	bpf_dynptr_from_mem(data_val->data, data_val->data_len, 0, &data_ptr);
71 
72 	if (data_val->sig_len > sizeof(data_val->sig))
73 		return -EINVAL;
74 
75 	bpf_dynptr_from_mem(data_val->sig, data_val->sig_len, 0, &sig_ptr);
76 
77 	if (user_keyring_serial)
78 		trusted_keyring = bpf_lookup_user_key(user_keyring_serial, 0);
79 	else
80 		trusted_keyring = bpf_lookup_system_key(system_keyring_id);
81 
82 	if (!trusted_keyring)
83 		return -ENOENT;
84 
85 	ret = bpf_verify_pkcs7_signature(&data_ptr, &sig_ptr, trusted_keyring);
86 
87 	bpf_key_put(trusted_keyring);
88 
89 	return ret;
90 }
91