1// SPDX-License-Identifier: GPL-2.0
2#define _GNU_SOURCE
3
4#include <cap-ng.h>
5#include <linux/capability.h>
6#include <stdbool.h>
7#include <string.h>
8#include <stdio.h>
9#include <fcntl.h>
10#include <errno.h>
11#include <stdarg.h>
12#include <sched.h>
13#include <sys/mount.h>
14#include <limits.h>
15#include <libgen.h>
16#include <malloc.h>
17#include <sys/wait.h>
18#include <sys/prctl.h>
19#include <sys/stat.h>
20
21#include "../kselftest.h"
22
23static int nerrs;
24static pid_t mpid;	/*  main() pid is used to avoid duplicate test counts */
25
26static void vmaybe_write_file(bool enoent_ok, char *filename, char *fmt, va_list ap)
27{
28	char buf[4096];
29	int fd;
30	ssize_t written;
31	int buf_len;
32
33	buf_len = vsnprintf(buf, sizeof(buf), fmt, ap);
34	if (buf_len < 0)
35		ksft_exit_fail_msg("vsnprintf failed - %s\n", strerror(errno));
36
37	if (buf_len >= sizeof(buf))
38		ksft_exit_fail_msg("vsnprintf output truncated\n");
39
40
41	fd = open(filename, O_WRONLY);
42	if (fd < 0) {
43		if ((errno == ENOENT) && enoent_ok)
44			return;
45		ksft_exit_fail_msg("open of %s failed - %s\n",
46					filename, strerror(errno));
47	}
48	written = write(fd, buf, buf_len);
49	if (written != buf_len) {
50		if (written >= 0) {
51			ksft_exit_fail_msg("short write to %s\n", filename);
52		} else {
53			ksft_exit_fail_msg("write to %s failed - %s\n",
54						filename, strerror(errno));
55		}
56	}
57	if (close(fd) != 0) {
58		ksft_exit_fail_msg("close of %s failed - %s\n",
59					filename, strerror(errno));
60	}
61}
62
63static void maybe_write_file(char *filename, char *fmt, ...)
64{
65	va_list ap;
66
67	va_start(ap, fmt);
68	vmaybe_write_file(true, filename, fmt, ap);
69	va_end(ap);
70}
71
72static void write_file(char *filename, char *fmt, ...)
73{
74	va_list ap;
75
76	va_start(ap, fmt);
77	vmaybe_write_file(false, filename, fmt, ap);
78	va_end(ap);
79}
80
81static bool create_and_enter_ns(uid_t inner_uid)
82{
83	uid_t outer_uid;
84	gid_t outer_gid;
85	int i;
86	bool have_outer_privilege;
87
88	outer_uid = getuid();
89	outer_gid = getgid();
90
91	if (outer_uid == 0 && unshare(CLONE_NEWNS) == 0) {
92		ksft_print_msg("[NOTE]\tUsing global UIDs for tests\n");
93		if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0)
94			ksft_exit_fail_msg("PR_SET_KEEPCAPS - %s\n",
95						strerror(errno));
96		if (setresuid(inner_uid, inner_uid, -1) != 0)
97			ksft_exit_fail_msg("setresuid - %s\n", strerror(errno));
98
99		// Re-enable effective caps
100		capng_get_caps_process();
101		for (i = 0; i < CAP_LAST_CAP; i++)
102			if (capng_have_capability(CAPNG_PERMITTED, i))
103				capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, i);
104		if (capng_apply(CAPNG_SELECT_CAPS) != 0)
105			ksft_exit_fail_msg(
106					"capng_apply - %s\n", strerror(errno));
107
108		have_outer_privilege = true;
109	} else if (unshare(CLONE_NEWUSER | CLONE_NEWNS) == 0) {
110		ksft_print_msg("[NOTE]\tUsing a user namespace for tests\n");
111		maybe_write_file("/proc/self/setgroups", "deny");
112		write_file("/proc/self/uid_map", "%d %d 1", inner_uid, outer_uid);
113		write_file("/proc/self/gid_map", "0 %d 1", outer_gid);
114
115		have_outer_privilege = false;
116	} else {
117		ksft_exit_skip("must be root or be able to create a userns\n");
118	}
119
120	if (mount("none", "/", NULL, MS_REC | MS_PRIVATE, NULL) != 0)
121		ksft_exit_fail_msg("remount everything private - %s\n",
122					strerror(errno));
123
124	return have_outer_privilege;
125}
126
127static void chdir_to_tmpfs(void)
128{
129	char cwd[PATH_MAX];
130	if (getcwd(cwd, sizeof(cwd)) != cwd)
131		ksft_exit_fail_msg("getcwd - %s\n", strerror(errno));
132
133	if (mount("private_tmp", ".", "tmpfs", 0, "mode=0777") != 0)
134		ksft_exit_fail_msg("mount private tmpfs - %s\n",
135					strerror(errno));
136
137	if (chdir(cwd) != 0)
138		ksft_exit_fail_msg("chdir to private tmpfs - %s\n",
139					strerror(errno));
140}
141
142static void copy_fromat_to(int fromfd, const char *fromname, const char *toname)
143{
144	int from = openat(fromfd, fromname, O_RDONLY);
145	if (from == -1)
146		ksft_exit_fail_msg("open copy source - %s\n", strerror(errno));
147
148	int to = open(toname, O_CREAT | O_WRONLY | O_EXCL, 0700);
149
150	while (true) {
151		char buf[4096];
152		ssize_t sz = read(from, buf, sizeof(buf));
153		if (sz == 0)
154			break;
155		if (sz < 0)
156			ksft_exit_fail_msg("read - %s\n", strerror(errno));
157
158		if (write(to, buf, sz) != sz)
159			/* no short writes on tmpfs */
160			ksft_exit_fail_msg("write - %s\n", strerror(errno));
161	}
162
163	close(from);
164	close(to);
165}
166
167static bool fork_wait(void)
168{
169	pid_t child = fork();
170	if (child == 0) {
171		nerrs = 0;
172		return true;
173	} else if (child > 0) {
174		int status;
175		if (waitpid(child, &status, 0) != child ||
176		    !WIFEXITED(status)) {
177			ksft_print_msg("Child died\n");
178			nerrs++;
179		} else if (WEXITSTATUS(status) != 0) {
180			ksft_print_msg("Child failed\n");
181			nerrs++;
182		} else {
183			/* don't print this message for mpid */
184			if (getpid() != mpid)
185				ksft_test_result_pass("Passed\n");
186		}
187		return false;
188	} else {
189		ksft_exit_fail_msg("fork - %s\n", strerror(errno));
190		return false;
191	}
192}
193
194static void exec_other_validate_cap(const char *name,
195				    bool eff, bool perm, bool inh, bool ambient)
196{
197	execl(name, name, (eff ? "1" : "0"),
198	      (perm ? "1" : "0"), (inh ? "1" : "0"), (ambient ? "1" : "0"),
199	      NULL);
200	ksft_exit_fail_msg("execl - %s\n", strerror(errno));
201}
202
203static void exec_validate_cap(bool eff, bool perm, bool inh, bool ambient)
204{
205	exec_other_validate_cap("./validate_cap", eff, perm, inh, ambient);
206}
207
208static int do_tests(int uid, const char *our_path)
209{
210	bool have_outer_privilege = create_and_enter_ns(uid);
211
212	int ourpath_fd = open(our_path, O_RDONLY | O_DIRECTORY);
213	if (ourpath_fd == -1)
214		ksft_exit_fail_msg("open '%s' - %s\n",
215					our_path, strerror(errno));
216
217	chdir_to_tmpfs();
218
219	copy_fromat_to(ourpath_fd, "validate_cap", "validate_cap");
220
221	if (have_outer_privilege) {
222		uid_t gid = getegid();
223
224		copy_fromat_to(ourpath_fd, "validate_cap",
225			       "validate_cap_suidroot");
226		if (chown("validate_cap_suidroot", 0, -1) != 0)
227			ksft_exit_fail_msg("chown - %s\n", strerror(errno));
228		if (chmod("validate_cap_suidroot", S_ISUID | 0700) != 0)
229			ksft_exit_fail_msg("chmod - %s\n", strerror(errno));
230
231		copy_fromat_to(ourpath_fd, "validate_cap",
232			       "validate_cap_suidnonroot");
233		if (chown("validate_cap_suidnonroot", uid + 1, -1) != 0)
234			ksft_exit_fail_msg("chown - %s\n", strerror(errno));
235		if (chmod("validate_cap_suidnonroot", S_ISUID | 0700) != 0)
236			ksft_exit_fail_msg("chmod - %s\n", strerror(errno));
237
238		copy_fromat_to(ourpath_fd, "validate_cap",
239			       "validate_cap_sgidroot");
240		if (chown("validate_cap_sgidroot", -1, 0) != 0)
241			ksft_exit_fail_msg("chown - %s\n", strerror(errno));
242		if (chmod("validate_cap_sgidroot", S_ISGID | 0710) != 0)
243			ksft_exit_fail_msg("chmod - %s\n", strerror(errno));
244
245		copy_fromat_to(ourpath_fd, "validate_cap",
246			       "validate_cap_sgidnonroot");
247		if (chown("validate_cap_sgidnonroot", -1, gid + 1) != 0)
248			ksft_exit_fail_msg("chown - %s\n", strerror(errno));
249		if (chmod("validate_cap_sgidnonroot", S_ISGID | 0710) != 0)
250			ksft_exit_fail_msg("chmod - %s\n", strerror(errno));
251	}
252
253	capng_get_caps_process();
254
255	/* Make sure that i starts out clear */
256	capng_update(CAPNG_DROP, CAPNG_INHERITABLE, CAP_NET_BIND_SERVICE);
257	if (capng_apply(CAPNG_SELECT_CAPS) != 0)
258		ksft_exit_fail_msg("capng_apply - %s\n", strerror(errno));
259
260	if (uid == 0) {
261		ksft_print_msg("[RUN]\tRoot => ep\n");
262		if (fork_wait())
263			exec_validate_cap(true, true, false, false);
264	} else {
265		ksft_print_msg("[RUN]\tNon-root => no caps\n");
266		if (fork_wait())
267			exec_validate_cap(false, false, false, false);
268	}
269
270	ksft_print_msg("Check cap_ambient manipulation rules\n");
271
272	/* We should not be able to add ambient caps yet. */
273	if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, CAP_NET_BIND_SERVICE, 0, 0, 0) != -1 || errno != EPERM) {
274		if (errno == EINVAL)
275			ksft_test_result_fail(
276				"PR_CAP_AMBIENT_RAISE isn't supported\n");
277		else
278			ksft_test_result_fail(
279				"PR_CAP_AMBIENT_RAISE should have failed eith EPERM on a non-inheritable cap\n");
280		return 1;
281	}
282	ksft_test_result_pass(
283		"PR_CAP_AMBIENT_RAISE failed on non-inheritable cap\n");
284
285	capng_update(CAPNG_ADD, CAPNG_INHERITABLE, CAP_NET_RAW);
286	capng_update(CAPNG_DROP, CAPNG_PERMITTED, CAP_NET_RAW);
287	capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_NET_RAW);
288	if (capng_apply(CAPNG_SELECT_CAPS) != 0)
289		ksft_exit_fail_msg("capng_apply - %s\n", strerror(errno));
290	if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, CAP_NET_RAW, 0, 0, 0) != -1 || errno != EPERM) {
291		ksft_test_result_fail(
292			"PR_CAP_AMBIENT_RAISE should have failed on a non-permitted cap\n");
293		return 1;
294	}
295	ksft_test_result_pass(
296		"PR_CAP_AMBIENT_RAISE failed on non-permitted cap\n");
297
298	capng_update(CAPNG_ADD, CAPNG_INHERITABLE, CAP_NET_BIND_SERVICE);
299	if (capng_apply(CAPNG_SELECT_CAPS) != 0)
300		ksft_exit_fail_msg("capng_apply - %s\n", strerror(errno));
301	if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, CAP_NET_BIND_SERVICE, 0, 0, 0) != 0) {
302		ksft_test_result_fail(
303			"PR_CAP_AMBIENT_RAISE should have succeeded\n");
304		return 1;
305	}
306	ksft_test_result_pass("PR_CAP_AMBIENT_RAISE worked\n");
307
308	if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_IS_SET, CAP_NET_BIND_SERVICE, 0, 0, 0) != 1) {
309		ksft_test_result_fail("PR_CAP_AMBIENT_IS_SET is broken\n");
310		return 1;
311	}
312
313	if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0, 0) != 0)
314		ksft_exit_fail_msg("PR_CAP_AMBIENT_CLEAR_ALL - %s\n",
315					strerror(errno));
316
317	if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_IS_SET, CAP_NET_BIND_SERVICE, 0, 0, 0) != 0) {
318		ksft_test_result_fail(
319			"PR_CAP_AMBIENT_CLEAR_ALL didn't work\n");
320		return 1;
321	}
322
323	if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, CAP_NET_BIND_SERVICE, 0, 0, 0) != 0)
324		ksft_exit_fail_msg("PR_CAP_AMBIENT_RAISE - %s\n",
325					strerror(errno));
326
327	capng_update(CAPNG_DROP, CAPNG_INHERITABLE, CAP_NET_BIND_SERVICE);
328	if (capng_apply(CAPNG_SELECT_CAPS) != 0)
329		ksft_exit_fail_msg("capng_apply - %s\n", strerror(errno));
330
331	if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_IS_SET, CAP_NET_BIND_SERVICE, 0, 0, 0) != 0) {
332		ksft_test_result_fail("Dropping I should have dropped A\n");
333		return 1;
334	}
335
336	ksft_test_result_pass("Basic manipulation appears to work\n");
337
338	capng_update(CAPNG_ADD, CAPNG_INHERITABLE, CAP_NET_BIND_SERVICE);
339	if (capng_apply(CAPNG_SELECT_CAPS) != 0)
340		ksft_exit_fail_msg("capng_apply - %s\n", strerror(errno));
341	if (uid == 0) {
342		ksft_print_msg("[RUN]\tRoot +i => eip\n");
343		if (fork_wait())
344			exec_validate_cap(true, true, true, false);
345	} else {
346		ksft_print_msg("[RUN]\tNon-root +i => i\n");
347		if (fork_wait())
348			exec_validate_cap(false, false, true, false);
349	}
350
351	if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, CAP_NET_BIND_SERVICE, 0, 0, 0) != 0)
352		ksft_exit_fail_msg("PR_CAP_AMBIENT_RAISE - %s\n",
353					strerror(errno));
354
355	ksft_print_msg("[RUN]\tUID %d +ia => eipa\n", uid);
356	if (fork_wait())
357		exec_validate_cap(true, true, true, true);
358
359	/* The remaining tests need real privilege */
360
361	if (!have_outer_privilege) {
362		ksft_test_result_skip("SUID/SGID tests (needs privilege)\n");
363		goto done;
364	}
365
366	if (uid == 0) {
367		ksft_print_msg("[RUN]\tRoot +ia, suidroot => eipa\n");
368		if (fork_wait())
369			exec_other_validate_cap("./validate_cap_suidroot",
370						true, true, true, true);
371
372		ksft_print_msg("[RUN]\tRoot +ia, suidnonroot => ip\n");
373		if (fork_wait())
374			exec_other_validate_cap("./validate_cap_suidnonroot",
375						false, true, true, false);
376
377		ksft_print_msg("[RUN]\tRoot +ia, sgidroot => eipa\n");
378		if (fork_wait())
379			exec_other_validate_cap("./validate_cap_sgidroot",
380						true, true, true, true);
381
382		if (fork_wait()) {
383			ksft_print_msg(
384				"[RUN]\tRoot, gid != 0, +ia, sgidroot => eip\n");
385			if (setresgid(1, 1, 1) != 0)
386				ksft_exit_fail_msg("setresgid - %s\n",
387							strerror(errno));
388			exec_other_validate_cap("./validate_cap_sgidroot",
389						true, true, true, false);
390		}
391
392		ksft_print_msg("[RUN]\tRoot +ia, sgidnonroot => eip\n");
393		if (fork_wait())
394			exec_other_validate_cap("./validate_cap_sgidnonroot",
395						true, true, true, false);
396	} else {
397		ksft_print_msg("[RUN]\tNon-root +ia, sgidnonroot => i\n");
398		if (fork_wait())
399			exec_other_validate_cap("./validate_cap_sgidnonroot",
400					false, false, true, false);
401
402		if (fork_wait()) {
403			ksft_print_msg("[RUN]\tNon-root +ia, sgidroot => i\n");
404			if (setresgid(1, 1, 1) != 0)
405				ksft_exit_fail_msg("setresgid - %s\n",
406							strerror(errno));
407			exec_other_validate_cap("./validate_cap_sgidroot",
408						false, false, true, false);
409		}
410	}
411
412done:
413	ksft_print_cnts();
414	return nerrs ? 1 : 0;
415}
416
417int main(int argc, char **argv)
418{
419	char *tmp1, *tmp2, *our_path;
420
421	/* Find our path */
422	tmp1 = strdup(argv[0]);
423	if (!tmp1)
424		ksft_exit_fail_msg("strdup - %s\n", strerror(errno));
425	tmp2 = dirname(tmp1);
426	our_path = strdup(tmp2);
427	if (!our_path)
428		ksft_exit_fail_msg("strdup - %s\n", strerror(errno));
429	free(tmp1);
430
431	mpid = getpid();
432
433	if (fork_wait()) {
434		ksft_print_header();
435		ksft_set_plan(12);
436		ksft_print_msg("[RUN]\t+++ Tests with uid == 0 +++\n");
437		return do_tests(0, our_path);
438	}
439
440	ksft_print_msg("==================================================\n");
441
442	if (fork_wait()) {
443		ksft_print_header();
444		ksft_set_plan(9);
445		ksft_print_msg("[RUN]\t+++ Tests with uid != 0 +++\n");
446		return do_tests(1, our_path);
447	}
448
449	return nerrs ? 1 : 0;
450}
451