xref: /openbmc/linux/tools/testing/selftests/bpf/progs/ima.c (revision 27a77d0d460cdeec57fda2bb6c4f8820ab6e8b38)
134b82d3aSKP Singh // SPDX-License-Identifier: GPL-2.0
234b82d3aSKP Singh 
334b82d3aSKP Singh /*
434b82d3aSKP Singh  * Copyright 2020 Google LLC.
534b82d3aSKP Singh  */
634b82d3aSKP Singh 
734b82d3aSKP Singh #include "vmlinux.h"
834b82d3aSKP Singh #include <errno.h>
934b82d3aSKP Singh #include <bpf/bpf_helpers.h>
1034b82d3aSKP Singh #include <bpf/bpf_tracing.h>
1134b82d3aSKP Singh 
1234b82d3aSKP Singh u32 monitored_pid = 0;
1334b82d3aSKP Singh 
14f446b570SKP Singh struct {
15f446b570SKP Singh 	__uint(type, BPF_MAP_TYPE_RINGBUF);
16f446b570SKP Singh 	__uint(max_entries, 1 << 12);
17f446b570SKP Singh } ringbuf SEC(".maps");
18f446b570SKP Singh 
1934b82d3aSKP Singh char _license[] SEC("license") = "GPL";
2034b82d3aSKP Singh 
21*27a77d0dSRoberto Sassu bool use_ima_file_hash;
22*27a77d0dSRoberto Sassu 
232746de3cSRoberto Sassu static void ima_test_common(struct file *file)
2434b82d3aSKP Singh {
25f446b570SKP Singh 	u64 ima_hash = 0;
26f446b570SKP Singh 	u64 *sample;
27f446b570SKP Singh 	int ret;
28f446b570SKP Singh 	u32 pid;
2934b82d3aSKP Singh 
30f446b570SKP Singh 	pid = bpf_get_current_pid_tgid() >> 32;
31f446b570SKP Singh 	if (pid == monitored_pid) {
32*27a77d0dSRoberto Sassu 		if (!use_ima_file_hash)
332746de3cSRoberto Sassu 			ret = bpf_ima_inode_hash(file->f_inode, &ima_hash,
34f446b570SKP Singh 						 sizeof(ima_hash));
35*27a77d0dSRoberto Sassu 		else
36*27a77d0dSRoberto Sassu 			ret = bpf_ima_file_hash(file, &ima_hash,
37*27a77d0dSRoberto Sassu 						sizeof(ima_hash));
38f446b570SKP Singh 		if (ret < 0 || ima_hash == 0)
39f446b570SKP Singh 			return;
4034b82d3aSKP Singh 
41f446b570SKP Singh 		sample = bpf_ringbuf_reserve(&ringbuf, sizeof(u64), 0);
42f446b570SKP Singh 		if (!sample)
43f446b570SKP Singh 			return;
44f446b570SKP Singh 
45f446b570SKP Singh 		*sample = ima_hash;
46f446b570SKP Singh 		bpf_ringbuf_submit(sample, 0);
47f446b570SKP Singh 	}
48f446b570SKP Singh 
49f446b570SKP Singh 	return;
5034b82d3aSKP Singh }
512746de3cSRoberto Sassu 
522746de3cSRoberto Sassu SEC("lsm.s/bprm_committed_creds")
532746de3cSRoberto Sassu void BPF_PROG(bprm_committed_creds, struct linux_binprm *bprm)
542746de3cSRoberto Sassu {
552746de3cSRoberto Sassu 	ima_test_common(bprm->file);
562746de3cSRoberto Sassu }
57