1 /* Copyright 2017 The Chromium OS Authors. All rights reserved.
2  * Use of this source code is governed by a BSD-style license that can be
3  * found in the LICENSE file.
4  */
5 
6 #include "system.h"
7 
8 #include <errno.h>
9 #include <fcntl.h>
10 #include <grp.h>
11 #include <net/if.h>
12 #include <pwd.h>
13 #include <stdbool.h>
14 #include <stdio.h>
15 #include <string.h>
16 #include <sys/ioctl.h>
17 #include <sys/prctl.h>
18 #include <sys/socket.h>
19 #include <sys/stat.h>
20 #include <sys/statvfs.h>
21 #include <unistd.h>
22 
23 #include <linux/securebits.h>
24 
25 #include "syscall_wrapper.h"
26 #include "util.h"
27 
28 /*
29  * SECBIT_NO_CAP_AMBIENT_RAISE was added in kernel 4.3, so fill in the
30  * definition if the securebits header doesn't provide it.
31  */
32 #ifndef SECBIT_NO_CAP_AMBIENT_RAISE
33 #define SECBIT_NO_CAP_AMBIENT_RAISE (issecure_mask(6))
34 #endif
35 
36 #ifndef SECBIT_NO_CAP_AMBIENT_RAISE_LOCKED
37 #define SECBIT_NO_CAP_AMBIENT_RAISE_LOCKED (issecure_mask(7))
38 #endif
39 
40 /*
41  * Assert the value of SECURE_ALL_BITS at compile-time.
42  * Android devices are currently compiled against 4.4 kernel headers. Kernel 4.3
43  * added a new securebit.
44  * When a new securebit is added, the new SECURE_ALL_BITS mask will return EPERM
45  * when used on older kernels. The compile-time assert will catch this situation
46  * at compile time.
47  */
48 #if defined(__ANDROID__)
49 _Static_assert(SECURE_ALL_BITS == 0x55, "SECURE_ALL_BITS == 0x55.");
50 #endif
51 
52 /* Used by lookup_(user|group) functions. */
53 #define MAX_PWENT_SZ (1 << 20)
54 #define MAX_GRENT_SZ (1 << 20)
55 
secure_noroot_set_and_locked(uint64_t mask)56 int secure_noroot_set_and_locked(uint64_t mask)
57 {
58 	return (mask & (SECBIT_NOROOT | SECBIT_NOROOT_LOCKED)) ==
59 	       (SECBIT_NOROOT | SECBIT_NOROOT_LOCKED);
60 }
61 
lock_securebits(uint64_t skip_mask,bool require_keep_caps)62 int lock_securebits(uint64_t skip_mask, bool require_keep_caps)
63 {
64 	/* The general idea is to set all bits, subject to exceptions below. */
65 	unsigned long securebits = SECURE_ALL_BITS | SECURE_ALL_LOCKS;
66 
67 	/*
68 	 * SECBIT_KEEP_CAPS is special in that it is automatically cleared on
69 	 * execve(2). This implies that attempts to set SECBIT_KEEP_CAPS (as is
70 	 * the default) in processes that have it locked already (such as nested
71 	 * minijail usage) would fail. Thus, unless the caller requires it,
72 	 * allow it to remain off if it is already locked.
73 	 */
74 	if (!require_keep_caps) {
75 		int current_securebits = prctl(PR_GET_SECUREBITS);
76 		if (current_securebits < 0) {
77 			pwarn("prctl(PR_GET_SECUREBITS) failed");
78 			return -1;
79 		}
80 
81 		if ((current_securebits & SECBIT_KEEP_CAPS_LOCKED) != 0 &&
82 		    (current_securebits & SECBIT_KEEP_CAPS) == 0) {
83 			securebits &= ~SECBIT_KEEP_CAPS;
84 		}
85 	}
86 
87 	/*
88 	 * Ambient capabilities can only be raised if they're already present
89 	 * in the permitted *and* inheritable set. Therefore, we don't really
90 	 * need to lock the NO_CAP_AMBIENT_RAISE securebit, since we are already
91 	 * configuring the permitted and inheritable set.
92 	 */
93 	securebits &=
94 	    ~(SECBIT_NO_CAP_AMBIENT_RAISE | SECBIT_NO_CAP_AMBIENT_RAISE_LOCKED);
95 
96 	/* Don't set any bits that the user requested not to be touched. */
97 	securebits &= ~skip_mask;
98 
99 	if (!securebits) {
100 		warn("not locking any securebits");
101 		return 0;
102 	}
103 	int securebits_ret = prctl(PR_SET_SECUREBITS, securebits);
104 	if (securebits_ret < 0) {
105 		pwarn("prctl(PR_SET_SECUREBITS) failed");
106 		return -1;
107 	}
108 
109 	return 0;
110 }
111 
write_proc_file(pid_t pid,const char * content,const char * basename)112 int write_proc_file(pid_t pid, const char *content, const char *basename)
113 {
114 	int fd, ret;
115 	size_t sz, len;
116 	ssize_t written;
117 	char filename[32];
118 
119 	sz = sizeof(filename);
120 	ret = snprintf(filename, sz, "/proc/%d/%s", pid, basename);
121 	if (ret < 0 || (size_t)ret >= sz) {
122 		warn("failed to generate %s filename", basename);
123 		return -1;
124 	}
125 
126 	fd = open(filename, O_WRONLY | O_CLOEXEC);
127 	if (fd < 0) {
128 		pwarn("failed to open '%s'", filename);
129 		return -errno;
130 	}
131 
132 	len = strlen(content);
133 	written = write(fd, content, len);
134 	if (written < 0) {
135 		pwarn("failed to write '%s'", filename);
136 		return -errno;
137 	}
138 
139 	if ((size_t)written < len) {
140 		warn("failed to write %zu bytes to '%s'", len, filename);
141 		return -1;
142 	}
143 	close(fd);
144 	return 0;
145 }
146 
147 /*
148  * We specifically do not use cap_valid() as that only tells us the last
149  * valid cap we were *compiled* against (i.e. what the version of kernel
150  * headers says). If we run on a different kernel version, then it's not
151  * uncommon for that to be less (if an older kernel) or more (if a newer
152  * kernel).
153  * Normally, we suck up the answer via /proc. On Android, not all processes are
154  * guaranteed to be able to access '/proc/sys/kernel/cap_last_cap' so we
155  * programmatically find the value by calling prctl(PR_CAPBSET_READ).
156  */
get_last_valid_cap(void)157 unsigned int get_last_valid_cap(void)
158 {
159 	unsigned int last_valid_cap = 0;
160 	if (is_android()) {
161 		for (; prctl(PR_CAPBSET_READ, last_valid_cap, 0, 0, 0) >= 0;
162 		     ++last_valid_cap)
163 			;
164 
165 		/* |last_valid_cap| will be the first failing value. */
166 		if (last_valid_cap > 0) {
167 			last_valid_cap--;
168 		}
169 	} else {
170 		const char cap_file[] = "/proc/sys/kernel/cap_last_cap";
171 		FILE *fp = fopen(cap_file, "re");
172 		if (fscanf(fp, "%u", &last_valid_cap) != 1)
173 			pdie("fscanf(%s)", cap_file);
174 		fclose(fp);
175 	}
176 	return last_valid_cap;
177 }
178 
cap_ambient_supported(void)179 int cap_ambient_supported(void)
180 {
181 	return prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_IS_SET, CAP_CHOWN, 0, 0) >=
182 	       0;
183 }
184 
config_net_loopback(void)185 int config_net_loopback(void)
186 {
187 	const char ifname[] = "lo";
188 	int sock;
189 	struct ifreq ifr;
190 
191 	/* Make sure people don't try to add really long names. */
192 	_Static_assert(sizeof(ifname) <= IFNAMSIZ, "interface name too long");
193 
194 	sock = socket(AF_LOCAL, SOCK_DGRAM | SOCK_CLOEXEC, 0);
195 	if (sock < 0) {
196 		pwarn("socket(AF_LOCAL) failed");
197 		return -1;
198 	}
199 
200 	/*
201 	 * Do the equiv of `ip link set up lo`.  The kernel will assign
202 	 * IPv4 (127.0.0.1) & IPv6 (::1) addresses automatically!
203 	 */
204 	strcpy(ifr.ifr_name, ifname);
205 	if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) {
206 		pwarn("ioctl(SIOCGIFFLAGS) failed");
207 		return -1;
208 	}
209 
210 	/* The kernel preserves ifr.ifr_name for use. */
211 	ifr.ifr_flags |= IFF_UP | IFF_RUNNING;
212 	if (ioctl(sock, SIOCSIFFLAGS, &ifr) < 0) {
213 		pwarn("ioctl(SIOCSIFFLAGS) failed");
214 		return -1;
215 	}
216 
217 	close(sock);
218 	return 0;
219 }
220 
write_pid_to_path(pid_t pid,const char * path)221 int write_pid_to_path(pid_t pid, const char *path)
222 {
223 	FILE *fp = fopen(path, "we");
224 
225 	if (!fp) {
226 		pwarn("failed to open '%s'", path);
227 		return -errno;
228 	}
229 	if (fprintf(fp, "%d\n", (int)pid) < 0) {
230 		/* fprintf(3) does not set errno on failure. */
231 		warn("fprintf(%s) failed", path);
232 		return -1;
233 	}
234 	if (fclose(fp)) {
235 		pwarn("fclose(%s) failed", path);
236 		return -errno;
237 	}
238 
239 	return 0;
240 }
241 
242 /*
243  * Create the |path| directory and its parents (if need be) with |mode|.
244  * If not |isdir|, then |path| is actually a file, so the last component
245  * will not be created.
246  */
mkdir_p(const char * path,mode_t mode,bool isdir)247 int mkdir_p(const char *path, mode_t mode, bool isdir)
248 {
249 	int rc;
250 	char *dir = strdup(path);
251 	if (!dir) {
252 		rc = errno;
253 		pwarn("strdup(%s) failed", path);
254 		return -rc;
255 	}
256 
257 	/* Starting from the root, work our way out to the end. */
258 	char *p = strchr(dir + 1, '/');
259 	while (p) {
260 		*p = '\0';
261 		if (mkdir(dir, mode) && errno != EEXIST) {
262 			rc = errno;
263 			pwarn("mkdir(%s, 0%o) failed", dir, mode);
264 			free(dir);
265 			return -rc;
266 		}
267 		*p = '/';
268 		p = strchr(p + 1, '/');
269 	}
270 
271 	/*
272 	 * Create the last directory.  We still check EEXIST here in case
273 	 * of trailing slashes.
274 	 */
275 	free(dir);
276 	if (isdir && mkdir(path, mode) && errno != EEXIST) {
277 		rc = errno;
278 		pwarn("mkdir(%s, 0%o) failed", path, mode);
279 		return -rc;
280 	}
281 	return 0;
282 }
283 
284 /*
285  * setup_mount_destination: Ensures the mount target exists.
286  * Creates it if needed and possible.
287  */
setup_mount_destination(const char * source,const char * dest,uid_t uid,uid_t gid,bool bind,unsigned long * mnt_flags)288 int setup_mount_destination(const char *source, const char *dest, uid_t uid,
289 			    uid_t gid, bool bind, unsigned long *mnt_flags)
290 {
291 	int rc;
292 	struct stat st_buf;
293 	bool domkdir;
294 
295 	rc = stat(dest, &st_buf);
296 	if (rc == 0) /* destination exists */
297 		return 0;
298 
299 	/*
300 	 * Try to create the destination.
301 	 * Either make a directory or touch a file depending on the source type.
302 	 *
303 	 * If the source isn't an absolute path, assume it is a filesystem type
304 	 * such as "tmpfs" and create a directory to mount it on.  The dest will
305 	 * be something like "none" or "proc" which we shouldn't be checking.
306 	 */
307 	if (source[0] == '/') {
308 		/* The source is an absolute path -- it better exist! */
309 		rc = stat(source, &st_buf);
310 		if (rc) {
311 			rc = errno;
312 			pwarn("stat(%s) failed", source);
313 			return -rc;
314 		}
315 
316 		/*
317 		 * If bind mounting, we only create a directory if the source
318 		 * is a directory, else we always bind mount it as a file to
319 		 * support device nodes, sockets, etc...
320 		 *
321 		 * For all other mounts, we assume a block/char source is
322 		 * going to want a directory to mount to.  If the source is
323 		 * something else (e.g. a fifo or socket), this probably will
324 		 * not do the right thing, but we'll fail later on when we try
325 		 * to mount(), so shouldn't be a big deal.
326 		 */
327 		domkdir = S_ISDIR(st_buf.st_mode) ||
328 			  (!bind && (S_ISBLK(st_buf.st_mode) ||
329 				     S_ISCHR(st_buf.st_mode)));
330 
331 		/* If bind mounting, also grab the mount flags of the source. */
332 		if (bind && mnt_flags) {
333 			struct statvfs stvfs_buf;
334 			rc = statvfs(source, &stvfs_buf);
335 			if (rc) {
336 				rc = errno;
337 				pwarn(
338 				    "failed to look up mount flags: source=%s",
339 				    source);
340 				return -rc;
341 			}
342 			*mnt_flags = stvfs_buf.f_flag;
343 		}
344 	} else {
345 		/* The source is a relative path -- assume it's a pseudo fs. */
346 
347 		/* Disallow relative bind mounts. */
348 		if (bind) {
349 			warn("relative bind-mounts are not allowed: source=%s",
350 			     source);
351 			return -EINVAL;
352 		}
353 
354 		domkdir = true;
355 	}
356 
357 	/*
358 	 * Now that we know what we want to do, do it!
359 	 * We always create the intermediate dirs and the final path with 0755
360 	 * perms and root/root ownership.  This shouldn't be a problem because
361 	 * the actual mount will set those perms/ownership on the mount point
362 	 * which is all people should need to access it.
363 	 */
364 	rc = mkdir_p(dest, 0755, domkdir);
365 	if (rc)
366 		return rc;
367 	if (!domkdir) {
368 		int fd = open(dest, O_RDWR | O_CREAT | O_CLOEXEC, 0700);
369 		if (fd < 0) {
370 			rc = errno;
371 			pwarn("open(%s) failed", dest);
372 			return -rc;
373 		}
374 		close(fd);
375 	}
376 	if (chown(dest, uid, gid)) {
377 		rc = errno;
378 		pwarn("chown(%s, %u, %u) failed", dest, uid, gid);
379 		return -rc;
380 	}
381 	return 0;
382 }
383 
384 /*
385  * lookup_user: Gets the uid/gid for the given username.
386  */
lookup_user(const char * user,uid_t * uid,gid_t * gid)387 int lookup_user(const char *user, uid_t *uid, gid_t *gid)
388 {
389 	char *buf = NULL;
390 	struct passwd pw;
391 	struct passwd *ppw = NULL;
392 	/*
393 	 * sysconf(_SC_GETPW_R_SIZE_MAX), under glibc, is documented to return
394 	 * a suggested starting size for the buffer, so let's try getting this
395 	 * size first, and fallback to a default othersise.
396 	 */
397 	ssize_t sz = sysconf(_SC_GETPW_R_SIZE_MAX);
398 	if (sz == -1)
399 		sz = 65536; /* your guess is as good as mine... */
400 
401 	do {
402 		buf = malloc(sz);
403 		if (!buf)
404 			return -ENOMEM;
405 		int err = getpwnam_r(user, &pw, buf, sz, &ppw);
406 		/*
407 		 * We're safe to free the buffer here. The strings inside |pw|
408 		 * point inside |buf|, but we don't use any of them; this leaves
409 		 * the pointers dangling but it's safe.
410 		 * |ppw| points at |pw| if getpwnam_r(3) succeeded.
411 		 */
412 		free(buf);
413 		if (err == ERANGE) {
414 			/* |buf| was too small, retry with a bigger one. */
415 			sz <<= 1;
416 		} else if (err != 0) {
417 			/* We got an error not related to the size of |buf|. */
418 			return -err;
419 		} else if (!ppw) {
420 			/* Not found. */
421 			return -ENOENT;
422 		} else {
423 			*uid = ppw->pw_uid;
424 			*gid = ppw->pw_gid;
425 			return 0;
426 		}
427 	} while (sz <= MAX_PWENT_SZ);
428 
429 	/* A buffer of size MAX_PWENT_SZ is still too small, return an error. */
430 	return -ERANGE;
431 }
432 
433 /*
434  * lookup_group: Gets the gid for the given group name.
435  */
lookup_group(const char * group,gid_t * gid)436 int lookup_group(const char *group, gid_t *gid)
437 {
438 	char *buf = NULL;
439 	struct group gr;
440 	struct group *pgr = NULL;
441 	/*
442 	 * sysconf(_SC_GETGR_R_SIZE_MAX), under glibc, is documented to return
443 	 * a suggested starting size for the buffer, so let's try getting this
444 	 * size first, and fallback to a default otherwise.
445 	 */
446 	ssize_t sz = sysconf(_SC_GETGR_R_SIZE_MAX);
447 	if (sz == -1)
448 		sz = 65536; /* and mine is as good as yours, really */
449 
450 	do {
451 		buf = malloc(sz);
452 		if (!buf)
453 			return -ENOMEM;
454 		int err = getgrnam_r(group, &gr, buf, sz, &pgr);
455 		/*
456 		 * We're safe to free the buffer here. The strings inside |gr|
457 		 * point inside |buf|, but we don't use any of them; this leaves
458 		 * the pointers dangling but it's safe.
459 		 * |pgr| points at |gr| if getgrnam_r(3) succeeded.
460 		 */
461 		free(buf);
462 		if (err == ERANGE) {
463 			/* |buf| was too small, retry with a bigger one. */
464 			sz <<= 1;
465 		} else if (err != 0) {
466 			/* We got an error not related to the size of |buf|. */
467 			return -err;
468 		} else if (!pgr) {
469 			/* Not found. */
470 			return -ENOENT;
471 		} else {
472 			*gid = pgr->gr_gid;
473 			return 0;
474 		}
475 	} while (sz <= MAX_GRENT_SZ);
476 
477 	/* A buffer of size MAX_GRENT_SZ is still too small, return an error. */
478 	return -ERANGE;
479 }
480 
seccomp_action_is_available(const char * wanted)481 static bool seccomp_action_is_available(const char *wanted)
482 {
483 	if (is_android()) {
484 		/*
485 		 * Accessing |actions_avail| is generating SELinux denials, so
486 		 * skip for now.
487 		 * TODO(crbug.com/978022, jorgelo): Remove once the denial is
488 		 * fixed.
489 		 */
490 		return false;
491 	}
492 	const char actions_avail_path[] =
493 	    "/proc/sys/kernel/seccomp/actions_avail";
494 	FILE *f = fopen(actions_avail_path, "re");
495 
496 	if (!f) {
497 		pwarn("fopen(%s) failed", actions_avail_path);
498 		return false;
499 	}
500 
501 	char *actions_avail = NULL;
502 	size_t buf_size = 0;
503 	if (getline(&actions_avail, &buf_size, f) < 0) {
504 		pwarn("getline() failed");
505 		free(actions_avail);
506 		return false;
507 	}
508 
509 	/*
510 	 * This is just substring search, which means that partial matches will
511 	 * match too (e.g. "action" would match "longaction"). There are no
512 	 * seccomp actions which include other actions though, so we're good for
513 	 * now. Eventually we might want to split the string by spaces.
514 	 */
515 	bool available = strstr(actions_avail, wanted) != NULL;
516 	free(actions_avail);
517 	return available;
518 }
519 
seccomp_ret_log_available(void)520 int seccomp_ret_log_available(void)
521 {
522 	static int ret_log_available = -1;
523 
524 	if (ret_log_available == -1)
525 		ret_log_available = seccomp_action_is_available("log");
526 
527 	return ret_log_available;
528 }
529 
seccomp_ret_kill_process_available(void)530 int seccomp_ret_kill_process_available(void)
531 {
532 	static int ret_kill_process_available = -1;
533 
534 	if (ret_kill_process_available == -1)
535 		ret_kill_process_available =
536 		    seccomp_action_is_available("kill_process");
537 
538 	return ret_kill_process_available;
539 }
540 
seccomp_filter_flags_available(unsigned int flags)541 bool seccomp_filter_flags_available(unsigned int flags)
542 {
543 	return sys_seccomp(SECCOMP_SET_MODE_FILTER, flags, NULL) != -1 ||
544 	       errno != EINVAL;
545 }
546