xref: /openbmc/linux/tools/testing/selftests/bpf/progs/ima.c (revision 91e8fa254dbd0890c34286acdc12e96412305840)
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 
2127a77d0dSRoberto Sassu bool use_ima_file_hash;
22*91e8fa25SRoberto Sassu bool enable_bprm_creds_for_exec;
2327a77d0dSRoberto Sassu 
242746de3cSRoberto Sassu static void ima_test_common(struct file *file)
2534b82d3aSKP Singh {
26f446b570SKP Singh 	u64 ima_hash = 0;
27f446b570SKP Singh 	u64 *sample;
28f446b570SKP Singh 	int ret;
29f446b570SKP Singh 	u32 pid;
3034b82d3aSKP Singh 
31f446b570SKP Singh 	pid = bpf_get_current_pid_tgid() >> 32;
32f446b570SKP Singh 	if (pid == monitored_pid) {
3327a77d0dSRoberto Sassu 		if (!use_ima_file_hash)
342746de3cSRoberto Sassu 			ret = bpf_ima_inode_hash(file->f_inode, &ima_hash,
35f446b570SKP Singh 						 sizeof(ima_hash));
3627a77d0dSRoberto Sassu 		else
3727a77d0dSRoberto Sassu 			ret = bpf_ima_file_hash(file, &ima_hash,
3827a77d0dSRoberto Sassu 						sizeof(ima_hash));
39f446b570SKP Singh 		if (ret < 0 || ima_hash == 0)
40f446b570SKP Singh 			return;
4134b82d3aSKP Singh 
42f446b570SKP Singh 		sample = bpf_ringbuf_reserve(&ringbuf, sizeof(u64), 0);
43f446b570SKP Singh 		if (!sample)
44f446b570SKP Singh 			return;
45f446b570SKP Singh 
46f446b570SKP Singh 		*sample = ima_hash;
47f446b570SKP Singh 		bpf_ringbuf_submit(sample, 0);
48f446b570SKP Singh 	}
49f446b570SKP Singh 
50f446b570SKP Singh 	return;
5134b82d3aSKP Singh }
522746de3cSRoberto Sassu 
532746de3cSRoberto Sassu SEC("lsm.s/bprm_committed_creds")
542746de3cSRoberto Sassu void BPF_PROG(bprm_committed_creds, struct linux_binprm *bprm)
552746de3cSRoberto Sassu {
562746de3cSRoberto Sassu 	ima_test_common(bprm->file);
572746de3cSRoberto Sassu }
58*91e8fa25SRoberto Sassu 
59*91e8fa25SRoberto Sassu SEC("lsm.s/bprm_creds_for_exec")
60*91e8fa25SRoberto Sassu int BPF_PROG(bprm_creds_for_exec, struct linux_binprm *bprm)
61*91e8fa25SRoberto Sassu {
62*91e8fa25SRoberto Sassu 	if (!enable_bprm_creds_for_exec)
63*91e8fa25SRoberto Sassu 		return 0;
64*91e8fa25SRoberto Sassu 
65*91e8fa25SRoberto Sassu 	ima_test_common(bprm->file);
66*91e8fa25SRoberto Sassu 	return 0;
67*91e8fa25SRoberto Sassu }
68