Skip to content

Get a better story around the build server running as root #326

Open

Description

@luser

Currently the build server needs to be run as root because it creates an overlay filesystem to mount in the bubblewrap sandbox. Some people are understandably unnerved by running a network daemon as root, so it would be good if we had a better story here. It may not be technically possible to do what we need to do without root, but we could at least have the daemon fork on startup and then have one process drop privileges and run the bulk of the code unprivileged (all the networking etc) with a little bit of IPC to the privileged process to do the things that need privileges.

Activity

  1. jrmuizel commented on Nov 6, 2018

    @jrmuizel
    Contributor

    Is it necessary to use overlayfs?

  2. jrmuizel commented on Nov 13, 2018

    @jrmuizel
    Contributor
  3. jrmuizel commented on Oct 22, 2019

    @jrmuizel
    Contributor

    @chmanchester is it necessary to use overlayfs?

  4. chmanchester commented on Oct 22, 2019

    @chmanchester
    Contributor

    @jrmuizel A builder that uses docker instead was also implemented but is known to be a lot slower and has seen less testing (I haven't tried it).

  5. jrmuizel commented on Oct 22, 2019

    @jrmuizel
    Contributor

    @chmanchester sorry, what I meant was what is being overlayed? i.e. what is overlayfs being used? Is there a something that's shared between jobs?

  6. luser commented on Oct 23, 2019

    @luser
    ContributorAuthor

    The build server mounts a few things in the overlay filesystem:

    fn perform_build(bubblewrap: &Path, compile_command: CompileCommand, inputs_rdr: InputsReader, output_paths: Vec<String>, overlay: &OverlaySpec) -> Result<BuildResult> {
    trace!("Compile environment: {:?}", compile_command.env_vars);
    trace!("Compile command: {:?} {:?}", compile_command.executable, compile_command.arguments);
    crossbeam_utils::thread::scope(|scope| { scope.spawn(|| {
    // Now mounted filesystems will be automatically unmounted when this thread dies
    // (and tmpfs filesystems will be completely destroyed)
    nix::sched::unshare(nix::sched::CloneFlags::CLONE_NEWNS)
    .chain_err(|| "Failed to enter a new Linux namespace")?;
    // Make sure that all future mount changes are private to this namespace
    // TODO: shouldn't need to add these annotations
    let source: Option<&str> = None;
    let fstype: Option<&str> = None;
    let data: Option<&str> = None;
    // Turn / into a 'slave', so it receives mounts from real root, but doesn't propogate back
    nix::mount::mount(source, "/", fstype, nix::mount::MsFlags::MS_REC | nix::mount::MsFlags::MS_PRIVATE, data)
    .chain_err(|| "Failed to turn / into a slave")?;
    let work_dir = overlay.build_dir.join("work");
    let upper_dir = overlay.build_dir.join("upper");
    let target_dir = overlay.build_dir.join("target");
    fs::create_dir(&work_dir).chain_err(|| "Failed to create overlay work directory")?;
    fs::create_dir(&upper_dir).chain_err(|| "Failed to create overlay upper directory")?;
    fs::create_dir(&target_dir).chain_err(|| "Failed to create overlay target directory")?;
    let () = Overlay::writable(
    iter::once(overlay.toolchain_dir.as_path()),
    upper_dir,
    work_dir,
    &target_dir,
    // This error is unfortunately not Send
    ).mount().map_err(|e| Error::from(e.to_string())).chain_err(|| "Failed to mount overlay FS")?;
    trace!("copying in inputs");
    // Note that we don't unpack directly into the upperdir since there overlayfs has some
    // special marker files that we don't want to create by accident (or malicious intent)
    tar::Archive::new(inputs_rdr).unpack(&target_dir).chain_err(|| "Failed to unpack inputs to overlay")?;
    let CompileCommand { executable, arguments, env_vars, cwd } = compile_command;
    let cwd = Path::new(&cwd);
    trace!("creating output directories");
    fs::create_dir_all(join_suffix(&target_dir, cwd)).chain_err(|| "Failed to create cwd")?;
    for path in output_paths.iter() {
    // If it doesn't have a parent, nothing needs creating
    let output_parent = if let Some(p) = Path::new(path).parent() { p } else { continue };
    fs::create_dir_all(join_suffix(&target_dir, cwd.join(output_parent)))
    .chain_err(|| "Failed to create an output directory")?;
    }
    trace!("performing compile");
    // Bubblewrap notes:
    // - We're running as uid 0 (to do the mounts above), and so bubblewrap is run as uid 0
    // - There's special handling in bubblewrap to compare uid and euid - of interest to us,
    // if uid == euid == 0, bubblewrap preserves capabilities (not good!) so we explicitly
    // drop all capabilities
    // - By entering a new user namespace means any set of capabilities do not apply to any
    // other user namespace, i.e. you lose privileges. This is not strictly necessary because
    // we're dropping caps anyway so it's irrelevant which namespace we're in, but it doesn't
    // hurt.
    // - --unshare-all is not ideal as it happily continues if it fails to unshare either
    // the user or cgroups namespace, so we list everything explicitly
    // - The order of bind vs proc + dev is important - the new root must be put in place
    // first, otherwise proc and dev get hidden
    let mut cmd = Command::new(bubblewrap);
    cmd
    .arg("--die-with-parent")
    .args(&["--cap-drop", "ALL"])
    .args(&[
    "--unshare-user", "--unshare-cgroup", "--unshare-ipc",
    "--unshare-pid", "--unshare-net", "--unshare-uts",
    ])
    .arg("--bind").arg(&target_dir).arg("/")
    .args(&["--proc", "/proc"])
    .args(&["--dev", "/dev"])
    .arg("--chdir").arg(cwd);
    for (k, v) in env_vars {
    if k.contains("=") {
    warn!("Skipping environment variable: {:?}", k);
    continue
    }
    cmd.arg("--setenv").arg(k).arg(v);
    }
    cmd.arg("--");
    cmd.arg(executable);
    cmd.args(arguments);
    let compile_output = cmd.output().chain_err(|| "Failed to retrieve output from compile")?;
    trace!("compile_output: {:?}", compile_output);
    let mut outputs = vec![];
    trace!("retrieving {:?}", output_paths);
    for path in output_paths {
    let abspath = join_suffix(&target_dir, cwd.join(&path)); // Resolve in case it's relative since we copy it from the root level
    match fs::File::open(abspath) {
    Ok(file) => {
    let output = OutputData::try_from_reader(file)
    .chain_err(|| "Failed to read output file")?;
    outputs.push((path, output))
    },
    Err(e) => {
    if e.kind() == io::ErrorKind::NotFound {
    debug!("Missing output path {:?}", path)
    } else {
    return Err(Error::from(e).chain_err(|| "Failed to open output file"))
    }
    },
    }
    }
    let compile_output = ProcessOutput::try_from(compile_output)
    .chain_err(|| "Failed to convert compilation exit status")?;
    Ok(BuildResult { output: compile_output, outputs })
    // Bizarrely there's no way to actually get any information from a thread::Result::Err
    }).join().unwrap_or_else(|_e| Err(Error::from("Build thread exited unsuccessfully"))) })
    }

    1. The toolchain (this can be shared across builds)
    2. Any input files required by the compilation. For C/C++ this is just the preprocessed source, but for Rust it includes all of the rlibs that the compile depends on.
    3. Any output directories required by the compilation. These obviously need to be writable.

    It seems like it might be feasible to just figure out the full set of directories needed and explicitly pass them all to bwrap? You'd probably wind up read-only mounting a bunch of top-level directories from the toolchain package, you could write out all the input files somewhere like the code currently does and then mount those directories (you might need to do some work to figure out common path prefixes there) and mount any output directories if they're different.

  7. yuanfang-chen commented on Aug 31, 2023

    @yuanfang-chen
    Contributor

    Hello @luser, thanks a lot for the suggested approach. I'm very interested in this. Was there any change in the status?

  8. added a commit that references this issue on Jun 9, 2026
    03b3fcf
  9. added a commit that references this issue on Jul 24, 2026
    3cfbf80
  10. added 3 commits that reference this issue on Jul 30, 2026
    d90f112
    05bb9da
    f68f114
  11. added a commit that references this issue on Aug 21, 2026
    e246288
  12. added a commit that references this issue on Sep 15, 2026
    63dbffe
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions