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