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;
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();
57 fd = SAFE_OPEN(MODULE_NAME, O_RDONLY|O_CLOEXEC);
58 SAFE_FSTAT(fd, &sb);
59 size = sb.st_size;
60 buf = SAFE_MMAP(0, size, PROT_READ|PROT_EXEC, MAP_PRIVATE, fd, 0);
61 SAFE_CLOSE(fd);
62
63 faulty_buf = tst_get_bad_addr(NULL);
64 }
65
run(unsigned int n)66 static void run(unsigned int n)
67 {
68 struct tcase *tc = &tcases[n];
69
70 if (tc->skip_in_lockdown && kernel_lockdown) {
71 tst_res(TCONF, "Kernel is locked down, skipping %s", tc->name);
72 return;
73 }
74
75 if (tc->cap)
76 tst_cap_action(&cap_drop);
77
78 /* Insert module twice */
79 if (tc->exp_errno == EEXIST)
80 tst_module_load(MODULE_NAME, NULL);
81
82 TST_EXP_FAIL(init_module(*tc->buf, *tc->size, tc->param),
83 tc->exp_errno, "TestName: %s", tc->name);
84
85 if (tc->exp_errno == EEXIST)
86 tst_module_unload(MODULE_NAME);
87
88 if (!TST_PASS && !TST_RET)
89 tst_module_unload(MODULE_NAME);
90
91 if (tc->cap)
92 tst_cap_action(&cap_req);
93 }
94
cleanup(void)95 static void cleanup(void)
96 {
97 munmap(buf, size);
98 }
99
100 static struct tst_test test = {
101 .test = run,
102 .tcnt = ARRAY_SIZE(tcases),
103 .setup = setup,
104 .cleanup = cleanup,
105 .needs_root = 1,
106 };
107