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