/* * nova-nix-sandbox's Linux backend (backend.h): runs the builder in fresh * user, mount, PID, IPC and UTS namespaces, and a network namespace unless * the build may reach the host's network, with a chroot that holds the * build's inputs. * * The setup runs here, in C between the namespaces' creation and the * builder's exec, because nova-nix itself can run nothing there: the * process library it spawns builders with gives no hook between fork and * exec, and a child forked from the threaded GHC runtime may make only * async-signal-safe calls before it execs. * * The status channel is the pipe the helper gets as standard output. It * moves to a close-on-exec descriptor and standard output becomes the * log, so a builder that starts closes it, and the reader sees end of * file with nothing written. The builder is PID 1 of its PID namespace, * which ends with it. * * The probe checks that this system lets an unprivileged process make the * namespaces, as upstream's userNamespacesSupported and * mountAndPidNamespacesSupported do (namespaces.cc at Nix 2.24.9, * linux-namespaces.cc at 2.36.0). * * The steps follow upstream's LocalDerivationGoal::startBuilder and * runChild (local-derivation-goal.cc at 2.24.9, which this file calls LDG; * chroot-derivation-builder.cc and linux-derivation-builder.cc at 2.36.0). */#define _GNU_SOURCE#include <errno.h>#include <fcntl.h>#include <grp.h>#include <limits.h>#include <linux/keyctl.h>#include <net/if.h>#include <netinet/in.h>#include <poll.h>#include <sched.h>#include <signal.h>#include <stdint.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/ioctl.h>#include <sys/mount.h>#include <sys/prctl.h>#include <sys/resource.h>#include <sys/signalfd.h>#include <sys/socket.h>#include <sys/stat.h>#include <sys/statvfs.h>#include <sys/syscall.h>#include <sys/types.h>#include <sys/wait.h>#include <unistd.h>#include "backend.h"#include "mountinfo.h"#include "plan.h"#include "posix.h"/* mount_setattr and what it takes, from the kernel's UAPI at Linux 5.12 * (include/uapi/linux/mount.h, include/uapi/linux/fcntl.h and the syscall * tables). They are spelled out here because a C library before glibc * 2.36 declares none of them, and <linux/mount.h> conflicts with * <sys/mount.h> there. The number is 442 in the asm-generic table and * x86's; an architecture this file does not know uses the mountinfo walk * alone. */#if defined(SYS_mount_setattr)#define MOUNT_SETATTR_SYSCALL SYS_mount_setattr#elif defined(__x86_64__) || defined(__i386__) || defined(__aarch64__) || defined(__arm__) || defined(__riscv)#define MOUNT_SETATTR_SYSCALL 442#endif#define MOUNT_SETATTR_READ_ONLY ((uint64_t)0x00000001)#define MOUNT_SETATTR_RECURSIVE 0x8000struct mount_setattr_attributes { uint64_t attr_set; uint64_t attr_clr; uint64_t propagation; uint64_t userns_fd;};/* The byte the helper sends the child once its ids are mapped. */#define RELEASE_BYTE '1'/* Exit statuses of the probe's mount check, read back by the probe. */#define PROBE_PRIVATE_FAILED 1#define PROBE_PROC_FAILED 2/* The hostname and domain name a build sees (runChild in LDG). Upstream * passes sizeof, so the kernel holds the terminating NUL too. */static const char sandbox_hostname[] = "localhost";static const char sandbox_domainname[] = "(none)";/* What a devpts instance of the sandbox's own is mounted with (runChild in * LDG). */static const char devpts_options[] = "newinstance,mode=0620";/* The mount table of the process reading it. */static const char mountinfo_path[] = "/proc/self/mountinfo";/* The open descriptors of the process reading it. */static const char descriptor_listing[] = "/proc/self/fd";/* What the read of a file with no size, such as one in /proc, starts with. */#define PROC_READ_START_BYTES ((size_t)16 * 1024)/* What the cloned child needs: the plan, the program, the sync pipe and * the signal mask to restore before it execs. */struct child_context { const struct plan *plan; char **argv; int sync_read; int sync_write; sigset_t original_mask;};/* The backend this file is. */const enum plan_backend backend_plan = PLAN_LINUX;/* ------------------------------------------------------------------------ * Paths * ------------------------------------------------------------------------ *//* PREFIX followed by PATH, or NULL with errno set. */static char *joined(const char *prefix, const char *path){ size_t prefix_length = strlen(prefix); size_t path_length = strlen(path); char *result = malloc(prefix_length + path_length + 1); if (result == NULL) { errno = ENOMEM; return NULL; } memcpy(result, prefix, prefix_length); memcpy(result + prefix_length, path, path_length + 1); return result;}static int path_exists(const char *path){ struct stat st; return lstat(path, &st) == 0;}/* Create PATH and every missing directory above it, as upstream's * createDirs does. Answers 0, or -1 with errno set. */static int create_dirs(const char *path){ char *copy = joined("", path); char *slash; if (copy == NULL) return -1; for (slash = strchr(copy + 1, '/'); ; slash = strchr(slash + 1, '/')) { if (slash != NULL) *slash = '\0'; if (mkdir(copy, 0777) < 0 && errno != EEXIST) { int error = errno; free(copy); errno = error; return -1; } if (slash == NULL) break; *slash = '/'; } free(copy); return 0;}/* ------------------------------------------------------------------------ * Mounts * ------------------------------------------------------------------------ *//* The flags a read-only remount of a bind must keep: in a user namespace * the kernel refuses to clear those the source mount locked. */static unsigned long locked_flags(const char *path, int *error){ struct statvfs fs; unsigned long flags = 0; if (statvfs(path, &fs) < 0) { *error = errno; return 0; } if (fs.f_flag & ST_NOSUID) flags |= MS_NOSUID; if (fs.f_flag & ST_NODEV) flags |= MS_NODEV; if (fs.f_flag & ST_NOEXEC) flags |= MS_NOEXEC; if (fs.f_flag & ST_NOATIME) flags |= MS_NOATIME; if (fs.f_flag & ST_NODIRATIME) flags |= MS_NODIRATIME; if (fs.f_flag & ST_RELATIME) flags |= MS_RELATIME; *error = 0; return flags;}/* Read the whole of a file that reports no size, such as one in /proc, * into a buffer of its own. Answers the buffer, or NULL with errno set. */static char *read_whole(const char *path, size_t *length){ size_t capacity = PROC_READ_START_BYTES; size_t used = 0; char *bytes = malloc(capacity); int fd = open(path, O_RDONLY | O_CLOEXEC); int error = 0; if (bytes == NULL || fd < 0) { error = bytes == NULL ? ENOMEM : errno; goto failed; } for (;;) { ssize_t got; if (used == capacity) { char *larger = realloc(bytes, capacity * 2); if (larger == NULL) { error = ENOMEM; goto failed; } bytes = larger; capacity *= 2; } got = read(fd, bytes + used, capacity - used); if (got < 0) { if (errno == EINTR) continue; error = errno; goto failed; } if (got == 0) break; used += (size_t)got; } close(fd); *length = used; return bytes;failed: if (fd >= 0) close(fd); free(bytes); errno = error; return NULL;}/* The /proc entry for a descriptor, through which a path-taking call acts * on what the descriptor opened. */static void descriptor_path(char *path, size_t capacity, int fd){ snprintf(path, capacity, "/proc/self/fd/%d", fd);}/* Open what is at RELATIVE beneath the directory or mount TOP names, one * component at a time without following a link, so the walk stays beneath * TOP whatever another user does to a path meanwhile; each step crosses * into a mount on the component it reaches. Answers a descriptor, or -1 * with errno set. */static int open_beneath(int top, char *relative){ char *cursor = relative; int at = fcntl(top, F_DUPFD_CLOEXEC, 0); while (at >= 0) { char *slash; int next; int error; while (*cursor == '/') cursor++; if (*cursor == '\0') break; slash = strchr(cursor, '/'); if (slash != NULL) *slash = '\0'; next = openat(at, cursor, O_PATH | O_NOFOLLOW | O_CLOEXEC); error = errno; close(at); errno = error; at = next; if (slash == NULL) break; cursor = slash + 1; } return at;}/* Remount the mount a descriptor names read-only, keeping the flags it * locked. Answers 0, or an errno value. */static int remount_read_only_at(int mounted){ char path[64]; int error = 0; unsigned long keep; descriptor_path(path, sizeof path, mounted); keep = locked_flags(path, &error); if (error != 0) return error; return mount(NULL, path, NULL, MS_BIND | MS_REMOUNT | MS_RDONLY | keep, NULL) < 0 ? errno : 0;}/* Remount the mount MOUNTED names read-only, and each mount beneath it, * as the process's mountinfo lists them, each reached from MOUNTED by * open_beneath, not by its path. The mount namespace is the child's own * and private, and nothing else mounts in it, so the list does not * change under the walk. Answers 0, or an errno value. */static int remount_tree_read_only(int mounted){ char link[64]; char top[PATH_MAX]; char point[PATH_MAX]; size_t point_length = 0; size_t length = 0; struct mountinfo_cursor cursor; enum mountinfo_read found; int error = 0; ssize_t top_length; char *mountinfo; descriptor_path(link, sizeof link, mounted); top_length = readlink(link, top, sizeof top - 1); if (top_length < 0) return errno; top[top_length] = '\0'; mountinfo = read_whole(mountinfo_path, &length); if (mountinfo == NULL) return errno; cursor.next = mountinfo; cursor.end = mountinfo + length; while ((found = mountinfo_next_within(&cursor, top, (size_t)top_length, point, sizeof point - 1, &point_length)) == MOUNTINFO_FOUND) { int beneath; point[point_length] = '\0'; if (strlen(point) != point_length) { error = EINVAL; break; } beneath = open_beneath(mounted, point + top_length); if (beneath < 0) { error = errno; break; } error = remount_read_only_at(beneath); close(beneath); if (error != 0) break; } if (error == 0 && found == MOUNTINFO_TOO_LONG) error = ENAMETOOLONG; free(mountinfo); return error;}/* Make the mount a descriptor names read-only, and every mount beneath * it, which a recursive bind brought along, so no part of a host path a * build sees stays writable. mount_setattr does it in one step, setting * the flag without touching the others, so a locked one stays as it is. * A kernel before Linux 5.12 has no mount_setattr; there each mount is * remounted read-only in turn. Answers 0, or an errno value. */static int make_read_only(int mounted){#if defined(MOUNT_SETATTR_SYSCALL) struct mount_setattr_attributes attributes; memset(&attributes, 0, sizeof attributes); attributes.attr_set = MOUNT_SETATTR_READ_ONLY; if (syscall(MOUNT_SETATTR_SYSCALL, mounted, "", AT_EMPTY_PATH | MOUNT_SETATTR_RECURSIVE, &attributes, sizeof attributes) == 0) return 0; if (errno != ENOSYS) return errno;#endif return remount_tree_read_only(mounted);}/* What make_point answers for a symlink source, copied rather than * bound. */#define TARGET_IS_COPIED_LINK (-2)/* How a directory on the way to a target is opened: as a path alone, * which takes search on it and not read, as a directory a bind may have * brought in at 0711 allows, and serves to open, make and link beneath * it and to mount on. */#define WALK_FLAGS (O_PATH | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)/* Open the directory NAME in PARENT, making it where it is missing, without * following a link. Answers a descriptor, or -1 with errno set, ELOOP for * a link. */static int enter_directory(int parent, const char *name){ struct stat st; int below = openat(parent, name, WALK_FLAGS); if (below < 0 && errno == ENOENT) { if (mkdirat(parent, name, 0777) < 0 && errno != EEXIST) return -1; below = openat(parent, name, WALK_FLAGS); } /* A link opened with O_DIRECTORY fails as no directory first. */ if (below < 0 && errno == ENOTDIR && fstatat(parent, name, &st, AT_SYMLINK_NOFOLLOW) == 0 && S_ISLNK(st.st_mode)) errno = ELOOP; return below;}/* Open the directory that holds TARGET beneath the chroot's ROOT, making * each directory on the way where it is missing. Each component is opened * without following a link, so a target whose path crosses one, such as * the skeleton's /dev/fd or a link an earlier entry copied in, fails with * ELOOP where joining it to the root and following what is there would * lead out of the chroot; upstream joins and follows (doBind in LDG). * Answers the directory's descriptor and points *NAME at the target's last * component, in *COMPONENTS, which the caller frees, or at nothing when * TARGET is the root itself; or -1 with errno set. */static int walk_to_parent(const char *root, const char *target, char **components, const char **name){ char *cursor; int directory; *name = NULL; *components = joined("", target); if (*components == NULL) return -1; directory = open(root, WALK_FLAGS); cursor = *components; while (directory >= 0) { char *slash; while (*cursor == '/') cursor++; if (*cursor == '\0') break; slash = strchr(cursor, '/'); if (slash != NULL) *slash = '\0'; if (*name != NULL) { int below = enter_directory(directory, *name); int error = errno; close(directory); errno = error; directory = below; if (directory < 0) break; } *name = cursor; if (slash == NULL) break; cursor = slash + 1; } if (directory < 0) { int error = errno; free(*components); *components = NULL; errno = error; } return directory;}/* Make, in PARENT at NAME, the place for a bind of SOURCE, whose lstat is * ST: a directory or an empty file to mount on, opened without following * a link, or for a symlink source a copy of the link, which cannot be * bound (doBind in LDG). NAME is nothing for the root itself, which only a * directory binds. Answers a descriptor of what to mount on, * TARGET_IS_COPIED_LINK, or -1 with errno set. */static int make_point(int parent, const char *name, const struct stat *st, const char *source){ if (S_ISLNK(st->st_mode)) { char contents[PATH_MAX]; ssize_t length = readlink(source, contents, sizeof contents - 1); if (length < 0) return -1; if (name == NULL) { errno = EEXIST; return -1; } contents[length] = '\0'; return symlinkat(contents, parent, name) < 0 ? -1 : TARGET_IS_COPIED_LINK; } if (name == NULL) { if (S_ISDIR(st->st_mode)) return fcntl(parent, F_DUPFD_CLOEXEC, 0); errno = EISDIR; return -1; } if (S_ISDIR(st->st_mode)) return enter_directory(parent, name); return openat(parent, name, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW | O_CLOEXEC, 0666);}/* Open the bind just made at NAME in PARENT, or on the root ROOT itself, * reached through the directory the walk found, not by a path joined * again; the lookup crosses into the new mount. Answers a descriptor, or * -1 with errno set. */static int open_bind(const char *root, int parent, const char *name){ if (name == NULL) return open(root, WALK_FLAGS); return openat(parent, name, O_PATH | O_NOFOLLOW | O_CLOEXEC);}/* Bind SOURCE onto the mount point a descriptor names, through the * descriptor's /proc entry, so the path the walk found is the one bound * onto. Answers 0, or an errno value. */static int bind_onto(const char *source, int mount_point){ char path[64]; snprintf(path, sizeof path, "/proc/self/fd/%d", mount_point); return mount(source, path, "", MS_BIND | MS_REC, NULL) < 0 ? errno : 0;}/* Bind one plan entry into the chroot, as upstream's doBind (in LDG), * and make it read-only when the plan says so. Fails the process. */static void bind_entry(const struct plan *plan, size_t index){ const struct bind *bind = &plan->binds[index]; const char *source = bind->source; char *resolved = NULL; char *components; const char *name; struct stat st; long at = (long)index; int parent; int mount_point; int error; if (bind->canonical) { resolved = realpath(source, NULL); if (resolved == NULL) { if (bind->optional && errno == ENOENT) return; status_fail("bind-source", errno, at); } source = resolved; } /* Upstream leaves /proc to the procfs it mounts (runChild in LDG). */ if (strcmp(source, "/proc") == 0) { free(resolved); return; } if (lstat(source, &st) < 0) { if (bind->optional && errno == ENOENT) { free(resolved); return; } status_fail("bind-source", errno, at); } parent = walk_to_parent(plan->root, bind->target, &components, &name); if (parent < 0) status_fail("bind-target", errno, at); mount_point = make_point(parent, name, &st, source); if (mount_point == -1) status_fail("bind-target", errno, at); if (mount_point != TARGET_IS_COPIED_LINK) { error = bind_onto(source, mount_point); close(mount_point); if (error != 0) status_fail("bind", error, at); if (bind->read_only) { int mounted = open_bind(plan->root, parent, name); error = mounted < 0 ? errno : make_read_only(mounted); if (mounted >= 0) close(mounted); if (error != 0) status_fail("remount", error, at); } } close(parent); free(components); free(resolved);}/* Whether the plan binds anything at TARGET in the chroot. */static int plan_binds(const struct plan *plan, const char *target){ size_t i; for (i = 0; i < plan->bind_count; i++) if (strcmp(plan->binds[i].target, target) == 0) return 1; return 0;}/* Bind a host device directory or node the devpts fallback needs, as * upstream binds it: writable, as the sandbox binds only these and the * build directory, since a terminal is written through it, and only where * the kernel will not mount a devpts of the sandbox's own. */static void bind_host(const struct plan *plan, const char *source, const char *stage){ struct stat st; char *components; const char *name; int parent; int mount_point; int error = 0; if (lstat(source, &st) < 0) status_fail(stage, errno, NO_INDEX); parent = walk_to_parent(plan->root, source, &components, &name); if (parent < 0) status_fail(stage, errno, NO_INDEX); mount_point = make_point(parent, name, &st, source); if (mount_point == -1) status_fail(stage, errno, NO_INDEX); /* A host node that is a link is copied, as upstream's doBind copies * one (in LDG), and nothing is left to bind. */ if (mount_point != TARGET_IS_COPIED_LINK) { error = bind_onto(source, mount_point); close(mount_point); } close(parent); free(components); if (error != 0) status_fail(stage, error, NO_INDEX);}/* /proc, /dev/shm and /dev/pts of the sandbox's own (runChild in LDG). */static void mount_filesystems(const struct plan *plan){ char *proc = joined(plan->root, "/proc"); char *shm = joined(plan->root, "/dev/shm"); char *pts = joined(plan->root, "/dev/pts"); char *ptmx = joined(plan->root, "/dev/ptmx"); char *pts_ptmx = joined(plan->root, "/dev/pts/ptmx"); if (proc == NULL || shm == NULL || pts == NULL || ptmx == NULL || pts_ptmx == NULL) status_fail("proc", ENOMEM, NO_INDEX); if (create_dirs(proc) < 0 || mount("none", proc, "proc", 0, NULL) < 0) status_fail("proc", errno, NO_INDEX); if (path_exists("/dev/shm")) { char *options = joined("size=", plan->dev_shm_size); if (options == NULL || mount("none", shm, "tmpfs", 0, options) < 0) status_fail("dev-shm", errno, NO_INDEX); free(options); } if (path_exists("/dev/pts/ptmx") && !path_exists(ptmx) && !plan_binds(plan, "/dev/pts")) { if (mount("none", pts, "devpts", 0, devpts_options) == 0) { if (symlink("/dev/pts/ptmx", ptmx) < 0) status_fail("devpts", errno, NO_INDEX); /* With some kernels ptmx is created with mode 0 (runChild in * LDG). */ if (chmod(pts_ptmx, 0666) < 0) status_fail("devpts", errno, NO_INDEX); } else { if (errno != EINVAL) status_fail("devpts", errno, NO_INDEX); bind_host(plan, "/dev/pts", "devpts"); bind_host(plan, "/dev/ptmx", "devpts"); } } free(proc); free(shm); free(pts); free(ptmx); free(pts_ptmx);}/* ------------------------------------------------------------------------ * The child: PID 1 of the new namespaces * ------------------------------------------------------------------------ *//* Bring the private network's loopback interface up (runChild in LDG). */static void loopback_up(void){ struct ifreq request; int fd = socket(PF_INET, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_IP); if (fd < 0) status_fail("loopback-socket", errno, NO_INDEX); memset(&request, 0, sizeof request); memcpy(request.ifr_name, "lo", sizeof "lo"); request.ifr_flags = IFF_UP | IFF_LOOPBACK | IFF_RUNNING; if (ioctl(fd, SIOCSIFFLAGS, &request) < 0) status_fail("loopback", errno, NO_INDEX); close(fd);}/* Die with the helper, as upstream's child dies with its parent * (startProcess in processes.cc). A credential change can clear the * setting, so it is made again once the ids are final. */static void die_with_helper(void){ if (prctl(PR_SET_PDEATHSIG, SIGKILL) < 0) status_fail("pdeathsig", errno, NO_INDEX);}/* clone(2) as fork makes a child, with no stack of its own: without * CLONE_VM the child runs on its copy of this process's stack. Upstream * clones onto a stack it maps (startProcess in processes.cc), a switch the * address sanitizer cannot follow (google/sanitizers issue 189), so its * reports from such a child may be false; on its copy of a stack the * sanitizer knows, the child's are true. The raw system call, as * bubblewrap makes it, since glibc's clone takes a stack; the arguments * after the stack are read only for flags this file does not pass. The * child gets 0, and runs single-threaded, as this process does. */static pid_t raw_clone(int flags){#if defined(__s390__) || defined(__CRIS__) return (pid_t)syscall(SYS_clone, (void *)NULL, (unsigned long)flags);#else return (pid_t)syscall(SYS_clone, (unsigned long)flags, (void *)NULL);#endif}static int child_main(const struct child_context *context){ const struct plan *plan = context->plan; char release = '\0'; ssize_t got; size_t i; char *etc; struct rlimit core; /* Before the release, so a helper that has already died is seen as the * end of the sync pipe, and one that dies later kills this process. */ die_with_helper(); /* Wait until the helper has mapped this namespace's ids; end of file * means it failed and has reported why (runChild in LDG). */ close(context->sync_write); do { got = read(context->sync_read, &release, 1); } while (got < 0 && errno == EINTR); if (got != 1 || release != RELEASE_BYTE) _exit(EXIT_FAILURE); close(context->sync_read); /* No controlling terminal, and no terminal signals (commonChildInit in * child.cc). */ if (setsid() < 0) status_fail("setsid", errno, NO_INDEX); if (plan->private_network) loopback_up(); if (sethostname(sandbox_hostname, sizeof sandbox_hostname) < 0) status_fail("hostname", errno, NO_INDEX); if (setdomainname(sandbox_domainname, sizeof sandbox_domainname) < 0) status_fail("domainname", errno, NO_INDEX); /* Mounts made below must not propagate out (runChild in LDG). */ if (mount(NULL, "/", NULL, MS_PRIVATE | MS_REC, NULL) < 0) status_fail("private", errno, NO_INDEX); /* pivot_root needs the new root to be a mount of its own (runChild in * LDG). */ if (mount(plan->root, plan->root, NULL, MS_BIND, NULL) < 0) status_fail("bind-root", errno, NO_INDEX); for (i = 0; i < plan->bind_count; i++) bind_entry(plan, i); mount_filesystems(plan); /* Upstream's mode for /etc once its files are in place (runChild in LDG). * /etc belongs to the user who made the chroot. That is root for a * build as a build user, as upstream's /etc is; for a build as the * invoking user it is that user, as whom the builder runs, so the * builder can make it writable again. It is the build's own copy, * removed with the chroot, and its host files are read-only binds. */ etc = joined(plan->root, "/etc"); if (etc == NULL || chmod(etc, 0555) < 0) status_fail("etc", errno, NO_INDEX); free(etc); /* Make the chroot the root and detach the old one (runChild in LDG). */ if (chdir(plan->root) < 0) status_fail("chdir-root", errno, NO_INDEX); if (mkdir("real-root", 0) < 0) status_fail("real-root", errno, NO_INDEX); if (syscall(SYS_pivot_root, ".", "real-root") < 0) status_fail("pivot", errno, NO_INDEX); if (chroot(".") < 0) status_fail("chroot", errno, NO_INDEX); if (umount2("real-root", MNT_DETACH) < 0) status_fail("umount", errno, NO_INDEX); if (rmdir("real-root") < 0) status_fail("rmdir", errno, NO_INDEX); /* The sandbox's ids, which map to the plan's host ids (runChild in * LDG). */ if (setgid((gid_t)plan->sandbox_gid) < 0) status_fail("setgid", errno, NO_INDEX); if (setuid((uid_t)plan->sandbox_uid) < 0) status_fail("setuid", errno, NO_INDEX); die_with_helper(); if (chdir(plan->build_dir) < 0) status_fail("chdir", errno, NO_INDEX); /* Every descriptor but the status pipe, which closes when the builder * starts (runChild's closeExtraFDs). */ posix_close_descriptors(descriptor_listing, posix_status_fd()); /* A session keyring of the builder's own, anonymous and empty, which * upstream does not make: its builder runs as a build user, with no * keys of the invoking user's. A builder run as the invoking user * would otherwise inherit the user's session keyring through the * namespaces, and with it possession of every key linked from it, and * one run as a build user loses nothing by the join. The join stops * that inheritance and nothing more (security/keys at * Linux 6.8): /proc/keys lists the keys of every uid the namespace * maps, the builder's own among them (key_serial_next in proc.c); the * user keyring gives its owner's uid every permission * (look_up_user_keyrings in process_keys.c); and a key's owner gets those * permissions whatever namespace asks (key_task_permission in * permission.c). So the builder can link the user keyring into its own * (keyctl_keyring_link in keyctl.c), possess it, and read what it holds. * Only a filter refusing keyctl, add_key and request_key closes that. A * kernel without keyrings has none to inherit, and a filter that refuses * the join refuses the builder's keyctl too. */ if (syscall(SYS_keyctl, KEYCTL_JOIN_SESSION_KEYRING, (char *)NULL) < 0 && errno != ENOSYS && errno != EPERM) status_fail("keyring", errno, NO_INDEX); /* No privileges gained through the exec, from a setuid program or file * capabilities a sandbox-paths entry makes reachable, as upstream's * builder gains none unless allow-new-privileges is set * (allowNewPrivileges in globals.hh and setupSeccomp in * local-derivation-goal.cc at 2.24.9, local-settings.hh and * linux-derivation-builder.cc at 2.36.0). */ if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) status_fail("no-new-privs", errno, NO_INDEX); /* No core dumps (runChild in LDG). Upstream also raises the hard limit * to infinity, which an unprivileged process may not; the hard limit is * left as it is. */ if (getrlimit(RLIMIT_CORE, &core) == 0) { core.rlim_cur = 0; setrlimit(RLIMIT_CORE, &core); } sigprocmask(SIG_SETMASK, &context->original_mask, NULL); execve(context->argv[0], context->argv, plan->environment); status_fail("exec", errno, NO_INDEX); return EXIT_FAILURE;}/* ------------------------------------------------------------------------ * The helper: outside the new namespaces * ------------------------------------------------------------------------ *//* Write a namespace's id map from outside it (startBuilder in LDG). Answers * 0, or an errno value. */static int write_proc_file(pid_t pid, const char *name, const char *contents){ char path[64]; int fd; size_t length = strlen(contents); ssize_t written; snprintf(path, sizeof path, "/proc/%ld/%s", (long)pid, name); fd = open(path, O_WRONLY | O_CLOEXEC); if (fd < 0) return errno; written = write(fd, contents, length); if (written < 0 || (size_t)written != length) { int error = written < 0 ? errno : EIO; close(fd); return error; } close(fd); return 0;}/* Report a failure of the helper's own, after the child is made. The * child's PID namespace ends with it. */static void fail_after_clone(pid_t child, const char *stage, int error){ int wait_status; kill(child, SIGKILL); while (waitpid(child, &wait_status, 0) < 0 && errno == EINTR) ; status_fail(stage, error, (long)child);}/* Wait for the builder, killing it on a terminating signal or when the * lifeline closes. Answers 0 with how it ended in *WAIT_STATUS, or the * errno of a wait that failed, which ends the build: the builder is * killed, and how it ended cannot be known. The kernel ends the builder's * PID namespace with the builder, PID 1 there, so once it is reaped no * process of the build is left. */static int wait_for_builder(pid_t child, int signals_fd, int lifeline_fd, int *wait_status){ for (;;) { struct pollfd watched[2]; pid_t reaped; watched[0].fd = signals_fd; watched[0].events = POLLIN; watched[0].revents = 0; watched[1].fd = lifeline_fd; watched[1].events = POLLIN; watched[1].revents = 0; if (poll(watched, 2, -1) < 0) { if (errno == EINTR) continue; /* With nothing left to watch, the builder is ended and reaped. */ kill(child, SIGKILL); return posix_reap(child, wait_status); } if (watched[1].revents != 0) { char discard[64]; ssize_t got = read(lifeline_fd, discard, sizeof discard); if (got <= 0 && !(got < 0 && errno == EINTR)) { kill(child, SIGKILL); close(lifeline_fd); lifeline_fd = -1; } } if (watched[0].revents & POLLIN) { struct signalfd_siginfo info; ssize_t got = read(signals_fd, &info, sizeof info); if (got == (ssize_t)sizeof info && info.ssi_signo != SIGCHLD) kill(child, SIGKILL); } reaped = waitpid(child, wait_status, WNOHANG); if (reaped == child) return 0; if (reaped < 0 && errno != EINTR) { int error = errno; kill(child, SIGKILL); return error; } }}int backend_run(const struct plan *plan, char **argv){ struct child_context context; int lifeline_fd; int signals_fd; int null_fd; int sync_pipe[2]; int error; int flags; pid_t child; char map[64]; sigset_t handled; int wait_status = 0; /* Standard input, past the plan, is the lifeline; the builder reads * /dev/null (commonChildInit in child.cc). */ lifeline_fd = fcntl(STDIN_FILENO, F_DUPFD_CLOEXEC, 3); null_fd = open("/dev/null", O_RDWR | O_CLOEXEC); if (lifeline_fd < 0 || null_fd < 0 || dup2(null_fd, STDIN_FILENO) < 0) status_fail("stdin", errno, NO_INDEX); close(null_fd); /* Supplementary groups cannot be dropped inside the new user namespace * (startBuilder in LDG). */ if (setgroups(0, NULL) < 0) { if (errno != EPERM || plan->require_drop_groups) status_fail("setgroups", errno, NO_INDEX); } if (pipe2(sync_pipe, O_CLOEXEC) < 0) status_fail("sync", errno, NO_INDEX); /* The signals the helper answers are blocked from before the builder * exists, and read through a descriptor once it does, so none is lost * and none interrupts the setup; the builder unblocks them before it * execs. */ sigemptyset(&handled); sigaddset(&handled, SIGTERM); sigaddset(&handled, SIGINT); sigaddset(&handled, SIGHUP); sigaddset(&handled, SIGCHLD); if (sigprocmask(SIG_BLOCK, &handled, &context.original_mask) < 0) status_fail("signals", errno, NO_INDEX); context.plan = plan; context.argv = argv; context.sync_read = sync_pipe[0]; context.sync_write = sync_pipe[1]; /* No CLONE_PARENT, so the builder stays this process's child and its * exit is this process's to relay (startProcess in processes.cc, and * LocalDerivationGoal::startBuilder in local-derivation-goal.cc at * 2.24.9, ChrootLinuxDerivationBuilder::startChild in * linux-derivation-builder.cc at 2.36.0). */ flags = CLONE_NEWUSER | CLONE_NEWPID | CLONE_NEWNS | CLONE_NEWIPC | CLONE_NEWUTS | SIGCHLD; if (plan->private_network) flags |= CLONE_NEWNET; child = raw_clone(flags); if (child < 0) status_fail("clone", errno, NO_INDEX); if (child == 0) _exit(child_main(&context)); close(sync_pipe[0]); signals_fd = signalfd(-1, &handled, SFD_CLOEXEC); if (signals_fd < 0) fail_after_clone(child, "signals", errno); /* The sandbox's ids map to the host ids the plan names: a build user's, * which only root may map to, or the invoking user's (startBuilder in * LDG). */ snprintf(map, sizeof map, "%lu %lu 1", plan->sandbox_uid, plan->host_uid); if ((error = write_proc_file(child, "uid_map", map)) != 0) fail_after_clone(child, "uid-map", error); if ((error = write_proc_file(child, "setgroups", "deny")) != 0) fail_after_clone(child, "setgroups-deny", error); snprintf(map, sizeof map, "%lu %lu 1", plan->sandbox_gid, plan->host_gid); if ((error = write_proc_file(child, "gid_map", map)) != 0) fail_after_clone(child, "gid-map", error); { char release = RELEASE_BYTE; ssize_t written; do { written = write(sync_pipe[1], &release, 1); } while (written < 0 && errno == EINTR); if (written != 1) fail_after_clone(child, "release", written < 0 ? errno : EIO); } close(sync_pipe[1]); posix_close_status(); error = wait_for_builder(child, signals_fd, lifeline_fd, &wait_status); close(signals_fd); if (error != 0) { /* The status pipe is closed, so the reason goes to the build log, * in upstream's words for a wait that fails (Pid::wait in * processes.cc). */ fprintf(stderr, "nova-nix-sandbox: cannot get exit status of PID %ld: %s\n", (long)child, strerror(error)); return EXIT_FAILURE; } return posix_relay(wait_status);}/* ------------------------------------------------------------------------ * The probe * ------------------------------------------------------------------------ *//* Compare a sysctl's contents, its trailing newlines and spaces trimmed as * upstream trims them (userNamespacesSupported in namespaces.cc at 2.24.9, * linux-namespaces.cc at 2.36.0), with EXPECTED: 1 when they match, 0 when * they do not, and -1 when the file cannot be read. */static int sysctl_is(const char *path, const char *expected){ char contents[32]; ssize_t length; int fd = open(path, O_RDONLY | O_CLOEXEC); if (fd < 0) return -1; length = read(fd, contents, sizeof contents - 1); close(fd); if (length < 0) return -1; while (length > 0 && (contents[length - 1] == '\n' || contents[length - 1] == ' ')) length--; contents[length] = '\0'; return strcmp(contents, expected) == 0;}static int probe_exit(void){ return EXIT_SUCCESS;}static int probe_mounts(void){ /* So the remount below does not touch the parent's /proc. */ if (mount(NULL, "/", NULL, MS_PRIVATE | MS_REC, NULL) < 0) return PROBE_PRIVATE_FAILED; if (mount("none", "/proc", "proc", 0, NULL) < 0) return PROBE_PROC_FAILED; return EXIT_SUCCESS;}/* Clone a child into the namespaces and wait for it. Answers the child's * exit status, or -1 with errno set when it could not be made. */static int probe_child(int (*entry)(void), int flags){ int wait_status; pid_t child = raw_clone(flags | SIGCHLD); if (child < 0) return -1; if (child == 0) _exit(entry()); while (waitpid(child, &wait_status, 0) < 0) if (errno != EINTR) return -1; return WIFEXITED(wait_status) ? WEXITSTATUS(wait_status) : EXIT_FAILURE;}/* The namespace checks. Answers the stage of the check that failed and * its errno, or NULL when none did. */static const char *probe_namespaces(int *error){ int outcome = probe_child(probe_exit, CLONE_NEWUSER); *error = 0; if (outcome != 0) { *error = outcome < 0 ? errno : 0; return "userns"; } outcome = probe_child(probe_mounts, CLONE_NEWNS | CLONE_NEWPID | CLONE_NEWUSER); if (outcome < 0) { *error = errno; return "mountns"; } if (outcome != 0) { /* Ubuntu's AppArmor lets an unprivileged process make a user * namespace but denies it capabilities there, so the mounts fail; * naming the restriction says what to change. */ if (sysctl_is("/proc/sys/kernel/apparmor_restrict_unprivileged_userns", "1") == 1) return "apparmor"; return outcome == PROBE_PROC_FAILED ? "proc-remount" : "mountns"; } return NULL;}const char *backend_probe(int *error){ if ((*error = posix_reset_sigchld()) != 0) return "sigchld"; if (!path_exists("/proc/self/ns/user")) return "userns-missing"; if (sysctl_is("/proc/sys/user/max_user_namespaces", "0") != 0) return "userns-max"; if (sysctl_is("/proc/sys/kernel/unprivileged_userns_clone", "0") == 1) return "userns-clone"; return probe_namespaces(error);}