1 // SPDX-License-Identifier: GPL-2.0 2 3 /* 4 * Copyright 2020 Google LLC. 5 */ 6 7 #include "vmlinux.h" 8 #include <errno.h> 9 #include <bpf/bpf_helpers.h> 10 #include <bpf/bpf_tracing.h> 11 12 u32 monitored_pid = 0; 13 14 struct { 15 __uint(type, BPF_MAP_TYPE_RINGBUF); 16 __uint(max_entries, 1 << 12); 17 } ringbuf SEC(".maps"); 18 19 char _license[] SEC("license") = "GPL"; 20 21 bool use_ima_file_hash; 22 bool enable_bprm_creds_for_exec; 23 bool enable_kernel_read_file; 24 25 static void ima_test_common(struct file *file) 26 { 27 u64 ima_hash = 0; 28 u64 *sample; 29 int ret; 30 u32 pid; 31 32 pid = bpf_get_current_pid_tgid() >> 32; 33 if (pid == monitored_pid) { 34 if (!use_ima_file_hash) 35 ret = bpf_ima_inode_hash(file->f_inode, &ima_hash, 36 sizeof(ima_hash)); 37 else 38 ret = bpf_ima_file_hash(file, &ima_hash, 39 sizeof(ima_hash)); 40 if (ret < 0 || ima_hash == 0) 41 return; 42 43 sample = bpf_ringbuf_reserve(&ringbuf, sizeof(u64), 0); 44 if (!sample) 45 return; 46 47 *sample = ima_hash; 48 bpf_ringbuf_submit(sample, 0); 49 } 50 51 return; 52 } 53 54 SEC("lsm.s/bprm_committed_creds") 55 void BPF_PROG(bprm_committed_creds, struct linux_binprm *bprm) 56 { 57 ima_test_common(bprm->file); 58 } 59 60 SEC("lsm.s/bprm_creds_for_exec") 61 int BPF_PROG(bprm_creds_for_exec, struct linux_binprm *bprm) 62 { 63 if (!enable_bprm_creds_for_exec) 64 return 0; 65 66 ima_test_common(bprm->file); 67 return 0; 68 } 69 70 SEC("lsm.s/kernel_read_file") 71 int BPF_PROG(kernel_read_file, struct file *file, enum kernel_read_file_id id, 72 bool contents) 73 { 74 if (!enable_kernel_read_file) 75 return 0; 76 77 if (!contents) 78 return 0; 79 80 if (id != READING_POLICY) 81 return 0; 82 83 ima_test_common(file); 84 return 0; 85 } 86