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 
13 #include "ima.skel.h"
14 
15 static int run_measured_process(const char *measured_dir, u32 *monitored_pid)
16 {
17 	int child_pid, child_status;
18 
19 	child_pid = fork();
20 	if (child_pid == 0) {
21 		*monitored_pid = getpid();
22 		execlp("./ima_setup.sh", "./ima_setup.sh", "run", measured_dir,
23 		       NULL);
24 		exit(errno);
25 
26 	} else if (child_pid > 0) {
27 		waitpid(child_pid, &child_status, 0);
28 		return WEXITSTATUS(child_status);
29 	}
30 
31 	return -EINVAL;
32 }
33 
34 void test_test_ima(void)
35 {
36 	char measured_dir_template[] = "/tmp/ima_measuredXXXXXX";
37 	const char *measured_dir;
38 	char cmd[256];
39 
40 	int err, duration = 0;
41 	struct ima *skel = NULL;
42 
43 	skel = ima__open_and_load();
44 	if (CHECK(!skel, "skel_load", "skeleton failed\n"))
45 		goto close_prog;
46 
47 	err = ima__attach(skel);
48 	if (CHECK(err, "attach", "attach failed: %d\n", err))
49 		goto close_prog;
50 
51 	measured_dir = mkdtemp(measured_dir_template);
52 	if (CHECK(measured_dir == NULL, "mkdtemp", "err %d\n", errno))
53 		goto close_prog;
54 
55 	snprintf(cmd, sizeof(cmd), "./ima_setup.sh setup %s", measured_dir);
56 	if (CHECK_FAIL(system(cmd)))
57 		goto close_clean;
58 
59 	err = run_measured_process(measured_dir, &skel->bss->monitored_pid);
60 	if (CHECK(err, "run_measured_process", "err = %d\n", err))
61 		goto close_clean;
62 
63 	CHECK(skel->data->ima_hash_ret < 0, "ima_hash_ret",
64 	      "ima_hash_ret = %ld\n", skel->data->ima_hash_ret);
65 
66 	CHECK(skel->bss->ima_hash == 0, "ima_hash",
67 	      "ima_hash = %lu\n", skel->bss->ima_hash);
68 
69 close_clean:
70 	snprintf(cmd, sizeof(cmd), "./ima_setup.sh cleanup %s", measured_dir);
71 	CHECK_FAIL(system(cmd));
72 close_prog:
73 	ima__destroy(skel);
74 }
75