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