1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) 2020 Viresh Kumar <viresh.kumar@linaro.org>
4  */
5 
6 /*\
7  * [Description]
8  *
9  * Basic init_module() failure tests.
10  *
11  * [Algorithm]
12  *
13  * Tests various failure scenarios for init_module().
14  */
15 
16 #include <linux/capability.h>
17 #include <errno.h>
18 #include "lapi/init_module.h"
19 #include "tst_module.h"
20 #include "tst_capability.h"
21 
22 #define MODULE_NAME	"init_module.ko"
23 
24 static unsigned long size, zero_size;
25 static int kernel_lockdown, secure_boot;
26 static void *buf, *faulty_buf, *null_buf;
27 
28 static struct tst_cap cap_req = TST_CAP(TST_CAP_REQ, CAP_SYS_MODULE);
29 static struct tst_cap cap_drop = TST_CAP(TST_CAP_DROP, CAP_SYS_MODULE);
30 
31 static struct tcase {
32 	const char *name;
33 	void **buf;
34 	unsigned long *size;
35 	const char *param;
36 	int cap;
37 	int skip_in_lockdown;
38 	int exp_errno;
39 } tcases[] = {
40 	{"NULL-buffer", &null_buf, &size, "", 0, 0, EFAULT},
41 	{"faulty-buffer", &faulty_buf, &size, "", 0, 0, EFAULT},
42 	{"null-param", &buf, &size, NULL, 0, 1, EFAULT},
43 	{"zero-size", &buf, &zero_size, "", 0, 0, ENOEXEC},
44 	{"invalid_param", &buf, &size, "status=invalid", 0, 1, EINVAL},
45 	{"no-perm", &buf, &size, "", 1, 0, EPERM},
46 	{"module-exists", &buf, &size, "", 0, 1, EEXIST},
47 };
48 
setup(void)49 static void setup(void)
50 {
51 	struct stat sb;
52 	int fd;
53 
54 	tst_module_exists(MODULE_NAME, NULL);
55 
56 	kernel_lockdown = tst_lockdown_enabled() > 0;
57 	secure_boot = tst_secureboot_enabled() > 0;
58 	fd = SAFE_OPEN(MODULE_NAME, O_RDONLY|O_CLOEXEC);
59 	SAFE_FSTAT(fd, &sb);
60 	size = sb.st_size;
61 	buf = SAFE_MMAP(0, size, PROT_READ|PROT_EXEC, MAP_PRIVATE, fd, 0);
62 	SAFE_CLOSE(fd);
63 
64 	faulty_buf = tst_get_bad_addr(NULL);
65 }
66 
run(unsigned int n)67 static void run(unsigned int n)
68 {
69 	struct tcase *tc = &tcases[n];
70 
71 	if (tc->skip_in_lockdown && (kernel_lockdown || secure_boot)) {
72 		tst_res(TCONF, "Cannot load unsigned modules, skipping %s", tc->name);
73 		return;
74 	}
75 
76 	if (tc->cap)
77 		tst_cap_action(&cap_drop);
78 
79 	/* Insert module twice */
80 	if (tc->exp_errno == EEXIST)
81 		tst_module_load(MODULE_NAME, NULL);
82 
83 	TST_EXP_FAIL(init_module(*tc->buf, *tc->size, tc->param),
84 		tc->exp_errno, "TestName: %s", tc->name);
85 
86 	if (tc->exp_errno == EEXIST)
87 		tst_module_unload(MODULE_NAME);
88 
89 	if (!TST_PASS && !TST_RET)
90 		tst_module_unload(MODULE_NAME);
91 
92 	if (tc->cap)
93 		tst_cap_action(&cap_req);
94 }
95 
cleanup(void)96 static void cleanup(void)
97 {
98 	munmap(buf, size);
99 }
100 
101 static struct tst_test test = {
102 	.test = run,
103 	.tcnt = ARRAY_SIZE(tcases),
104 	.setup = setup,
105 	.cleanup = cleanup,
106 	.needs_root = 1,
107 };
108