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