1 // SPDX-License-Identifier: GPL-2.0
2 
3 /*
4  * Copyright (C) 2020 Google LLC.
5  */
6 
7 #include <test_progs.h>
8 #include <sys/mman.h>
9 #include <sys/wait.h>
10 #include <unistd.h>
11 #include <malloc.h>
12 #include <stdlib.h>
13 #include <unistd.h>
14 
15 #include "lsm.skel.h"
16 
17 char *CMD_ARGS[] = {"true", NULL};
18 
19 #define GET_PAGE_ADDR(ADDR, PAGE_SIZE)					\
20 	(char *)(((unsigned long) (ADDR + PAGE_SIZE)) & ~(PAGE_SIZE-1))
21 
stack_mprotect(void)22 int stack_mprotect(void)
23 {
24 	void *buf;
25 	long sz;
26 	int ret;
27 
28 	sz = sysconf(_SC_PAGESIZE);
29 	if (sz < 0)
30 		return sz;
31 
32 	buf = alloca(sz * 3);
33 	ret = mprotect(GET_PAGE_ADDR(buf, sz), sz,
34 		       PROT_READ | PROT_WRITE | PROT_EXEC);
35 	return ret;
36 }
37 
exec_cmd(int * monitored_pid)38 int exec_cmd(int *monitored_pid)
39 {
40 	int child_pid, child_status;
41 
42 	child_pid = fork();
43 	if (child_pid == 0) {
44 		*monitored_pid = getpid();
45 		execvp(CMD_ARGS[0], CMD_ARGS);
46 		return -EINVAL;
47 	} else if (child_pid > 0) {
48 		waitpid(child_pid, &child_status, 0);
49 		return child_status;
50 	}
51 
52 	return -EINVAL;
53 }
54 
test_test_lsm(void)55 void test_test_lsm(void)
56 {
57 	struct lsm *skel = NULL;
58 	int err, duration = 0;
59 	int buf = 1234;
60 
61 	skel = lsm__open_and_load();
62 	if (CHECK(!skel, "skel_load", "lsm skeleton failed\n"))
63 		goto close_prog;
64 
65 	err = lsm__attach(skel);
66 	if (CHECK(err, "attach", "lsm attach failed: %d\n", err))
67 		goto close_prog;
68 
69 	err = exec_cmd(&skel->bss->monitored_pid);
70 	if (CHECK(err < 0, "exec_cmd", "err %d errno %d\n", err, errno))
71 		goto close_prog;
72 
73 	CHECK(skel->bss->bprm_count != 1, "bprm_count", "bprm_count = %d\n",
74 	      skel->bss->bprm_count);
75 
76 	skel->bss->monitored_pid = getpid();
77 
78 	err = stack_mprotect();
79 	if (CHECK(errno != EPERM, "stack_mprotect", "want err=EPERM, got %d\n",
80 		  errno))
81 		goto close_prog;
82 
83 	CHECK(skel->bss->mprotect_count != 1, "mprotect_count",
84 	      "mprotect_count = %d\n", skel->bss->mprotect_count);
85 
86 	syscall(__NR_setdomainname, &buf, -2L);
87 	syscall(__NR_setdomainname, 0, -3L);
88 	syscall(__NR_setdomainname, ~0L, -4L);
89 
90 	CHECK(skel->bss->copy_test != 3, "copy_test",
91 	      "copy_test = %d\n", skel->bss->copy_test);
92 
93 close_prog:
94 	lsm__destroy(skel);
95 }
96