1 // SPDX-License-Identifier: GPL-2.0
2 
3 /*
4  * Copyright (C) 2020 Google LLC.
5  */
6 
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <unistd.h>
10 #include <sys/wait.h>
11 #include <test_progs.h>
12 #include <linux/ring_buffer.h>
13 
14 #include "ima.skel.h"
15 
16 static int run_measured_process(const char *measured_dir, u32 *monitored_pid)
17 {
18 	int child_pid, child_status;
19 
20 	child_pid = fork();
21 	if (child_pid == 0) {
22 		*monitored_pid = getpid();
23 		execlp("./ima_setup.sh", "./ima_setup.sh", "run", measured_dir,
24 		       NULL);
25 		exit(errno);
26 
27 	} else if (child_pid > 0) {
28 		waitpid(child_pid, &child_status, 0);
29 		return WEXITSTATUS(child_status);
30 	}
31 
32 	return -EINVAL;
33 }
34 
35 static u64 ima_hash_from_bpf;
36 
37 static int process_sample(void *ctx, void *data, size_t len)
38 {
39 	ima_hash_from_bpf = *((u64 *)data);
40 	return 0;
41 }
42 
43 void test_test_ima(void)
44 {
45 	char measured_dir_template[] = "/tmp/ima_measuredXXXXXX";
46 	struct ring_buffer *ringbuf;
47 	const char *measured_dir;
48 	char cmd[256];
49 
50 	int err, duration = 0;
51 	struct ima *skel = NULL;
52 
53 	skel = ima__open_and_load();
54 	if (CHECK(!skel, "skel_load", "skeleton failed\n"))
55 		goto close_prog;
56 
57 	ringbuf = ring_buffer__new(bpf_map__fd(skel->maps.ringbuf),
58 				   process_sample, NULL, NULL);
59 	if (!ASSERT_OK_PTR(ringbuf, "ringbuf"))
60 		goto close_prog;
61 
62 	err = ima__attach(skel);
63 	if (CHECK(err, "attach", "attach failed: %d\n", err))
64 		goto close_prog;
65 
66 	measured_dir = mkdtemp(measured_dir_template);
67 	if (CHECK(measured_dir == NULL, "mkdtemp", "err %d\n", errno))
68 		goto close_prog;
69 
70 	snprintf(cmd, sizeof(cmd), "./ima_setup.sh setup %s", measured_dir);
71 	if (CHECK_FAIL(system(cmd)))
72 		goto close_clean;
73 
74 	err = run_measured_process(measured_dir, &skel->bss->monitored_pid);
75 	if (CHECK(err, "run_measured_process", "err = %d\n", err))
76 		goto close_clean;
77 
78 	err = ring_buffer__consume(ringbuf);
79 	ASSERT_EQ(err, 1, "num_samples_or_err");
80 	ASSERT_NEQ(ima_hash_from_bpf, 0, "ima_hash");
81 
82 close_clean:
83 	snprintf(cmd, sizeof(cmd), "./ima_setup.sh cleanup %s", measured_dir);
84 	CHECK_FAIL(system(cmd));
85 close_prog:
86 	ima__destroy(skel);
87 }
88