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
run_measured_process(const char * measured_dir,u32 * monitored_pid)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
process_sample(void * ctx,void * data,size_t len)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
test_test_ima(void)43 void test_test_ima(void)
44 {
45 char measured_dir_template[] = "/tmp/ima_measuredXXXXXX";
46 struct ring_buffer *ringbuf = NULL;
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 err = system(cmd);
72 if (CHECK(err, "failed to run command", "%s, errno = %d\n", cmd, errno))
73 goto close_clean;
74
75 err = run_measured_process(measured_dir, &skel->bss->monitored_pid);
76 if (CHECK(err, "run_measured_process", "err = %d\n", err))
77 goto close_clean;
78
79 err = ring_buffer__consume(ringbuf);
80 ASSERT_EQ(err, 1, "num_samples_or_err");
81 ASSERT_NEQ(ima_hash_from_bpf, 0, "ima_hash");
82
83 close_clean:
84 snprintf(cmd, sizeof(cmd), "./ima_setup.sh cleanup %s", measured_dir);
85 err = system(cmd);
86 CHECK(err, "failed to run command", "%s, errno = %d\n", cmd, errno);
87 close_prog:
88 ring_buffer__free(ringbuf);
89 ima__destroy(skel);
90 }
91