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 void *buf, *faulty_buf, *null_buf;
26
27 static struct tst_cap cap_req = TST_CAP(TST_CAP_REQ, CAP_SYS_MODULE);
28 static struct tst_cap cap_drop = TST_CAP(TST_CAP_DROP, CAP_SYS_MODULE);
29
30 static struct tcase {
31 const char *name;
32 void **buf;
33 unsigned long *size;
34 const char *param;
35 int cap;
36 int exp_errno;
37 } tcases[] = {
38 {"NULL-buffer", &null_buf, &size, "", 0, EFAULT},
39 {"faulty-buffer", &faulty_buf, &size, "", 0, EFAULT},
40 {"null-param", &buf, &size, NULL, 0, EFAULT},
41 {"zero-size", &buf, &zero_size, "", 0, ENOEXEC},
42 {"invalid_param", &buf, &size, "status=invalid", 0, EINVAL},
43 {"no-perm", &buf, &size, "", 1, EPERM},
44 {"module-exists", &buf, &size, "", 0, EEXIST},
45 };
46
setup(void)47 static void setup(void)
48 {
49 struct stat sb;
50 int fd;
51
52 tst_module_exists(MODULE_NAME, NULL);
53
54 fd = SAFE_OPEN(MODULE_NAME, O_RDONLY|O_CLOEXEC);
55 SAFE_FSTAT(fd, &sb);
56 size = sb.st_size;
57 buf = SAFE_MMAP(0, size, PROT_READ|PROT_EXEC, MAP_PRIVATE, fd, 0);
58 SAFE_CLOSE(fd);
59
60 faulty_buf = tst_get_bad_addr(NULL);
61 }
62
run(unsigned int n)63 static void run(unsigned int n)
64 {
65 struct tcase *tc = &tcases[n];
66
67 if (tc->cap)
68 tst_cap_action(&cap_drop);
69
70 /* Insert module twice */
71 if (tc->exp_errno == EEXIST)
72 tst_module_load(MODULE_NAME, NULL);
73
74 TST_EXP_FAIL(init_module(*tc->buf, *tc->size, tc->param), tc->exp_errno,
75 "TestName: %s", tc->name);
76
77 if (tc->exp_errno == EEXIST)
78 tst_module_unload(MODULE_NAME);
79
80 if (!TST_PASS && !TST_RET)
81 tst_module_unload(MODULE_NAME);
82
83 if (tc->cap)
84 tst_cap_action(&cap_req);
85 }
86
cleanup(void)87 static void cleanup(void)
88 {
89 munmap(buf, size);
90 }
91
92 static struct tst_test test = {
93 .test = run,
94 .tcnt = ARRAY_SIZE(tcases),
95 .setup = setup,
96 .cleanup = cleanup,
97 .needs_root = 1,
98 };
99