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