diff --git a/crates/forge-runner/src/cli.rs b/crates/forge-runner/src/cli.rs index e2d93f8..6fea8f3 100644 --- a/crates/forge-runner/src/cli.rs +++ b/crates/forge-runner/src/cli.rs @@ -137,7 +137,7 @@ where } /// Whether this process was started as a hidden sandbox helper: argv[1] is `__sandbox`, -/// `__sandbox-rm` or `__sandbox-unpack`. Callers that have their own runtime or subscriber check +/// `__sandbox-rm`, `__sandbox-map` or `__sandbox-unpack`. Callers that have their own runtime or subscriber check /// this first, and then call [`hidden_main`]. pub fn is_sandbox_invocation() -> bool { std::env::args_os() @@ -161,6 +161,7 @@ fn hidden_dispatch(args: &[OsString]) -> i32 { match args.first().map(|arg| arg.as_encoded_bytes()) { Some(b"__sandbox") => crate::sandbox::helper_main(), Some(b"__sandbox-rm") => crate::sandbox::idmap::rm_helper_main(&args[1..]), + Some(b"__sandbox-map") => crate::sandbox::idmap::map_helper_main(&args[1..]), Some(b"__sandbox-unpack") => crate::oci::unpack_helper_main(), _ => { eprintln!("forge-sandbox: unknown helper command"); diff --git a/crates/forge-runner/src/sandbox/idmap.rs b/crates/forge-runner/src/sandbox/idmap.rs index ebb89ad..5b1d6f5 100644 --- a/crates/forge-runner/src/sandbox/idmap.rs +++ b/crates/forge-runner/src/sandbox/idmap.rs @@ -8,22 +8,21 @@ //! setuid helpers `newuidmap` and `newgidmap` from shadow-utils, so that is what the helper //! runs. //! -//! The namespace entry functions ([`enter_mapped_userns`]) must run in a single-threaded process. -//! The sandbox helpers are single-threaded, and [`enter_mapped_userns`] forks in subuid mode. +//! The namespace entry functions ([`enter_mapped_userns`]) must run in a single-threaded process, +//! because `unshare(CLONE_NEWUSER)` fails in a multi-threaded one. The sandbox helpers are +//! single-threaded. Subuid mode never forks: it starts a `__sandbox-map` helper of this same +//! binary with `std::process::Command`, and that helper writes the maps. use std::ffi::OsString; -use std::fs::{self, File}; +use std::fs; use std::io::{self, Read, Write}; use std::os::unix::fs::PermissionsExt; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; -use nix::errno::Errno; -use nix::fcntl::OFlag; use nix::mount::{MsFlags, mount}; use nix::sched::{CloneFlags, unshare}; -use nix::sys::wait::{WaitStatus, waitpid}; -use nix::unistd::{ForkResult, Pid, Uid, User, fork, getgid, getpid, getuid, pipe2}; +use nix::unistd::{Uid, User, getgid, getuid}; use serde::{Deserialize, Serialize}; /// The most ids a subordinate range may contribute. This is the usual size of a range. @@ -32,6 +31,8 @@ const MAX_SUBID_COUNT: u32 = 65536; const MIN_SUBID_COUNT: u32 = 1000; /// Where the setuid mapping tools are looked for, in order. const TOOL_DIRS: [&str; 4] = ["/usr/bin", "/bin", "/usr/sbin", "/sbin"]; +/// The hidden subcommand, dispatched from the runner binary, that writes the maps in subuid mode. +pub const MAP_HELPER_CMD: &str = "__sandbox-map"; /// How the sandbox maps ids. Set by `[sandbox] userns` in the runner config. #[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] @@ -231,8 +232,8 @@ fn find_tool(name: &str) -> Option { /// Enters a new user and mount namespace whose ids are mapped as `map` says. The process is root /// inside it, and its mounts are private, so they don't propagate to the host. /// -/// Must be called from a single-threaded process, because subuid mode forks. The caller is the -/// sandbox helper, which has no other threads. +/// Must be called from a single-threaded process, because the unshare needs one. The caller is +/// the sandbox helper, which has no other threads. pub fn enter_mapped_userns(map: &IdMap) -> Result<(), IdMapError> { match (map.sub_uid, map.sub_gid) { (Some((uid_start, count_uid)), Some((gid_start, count_gid))) => { @@ -263,9 +264,12 @@ fn enter_single(map: &IdMap) -> Result<(), IdMapError> { .map_err(|e| IdMapError::Map(format!("cannot write uid_map: {e}"))) } -/// What the forked child needs to write the maps. +/// The arguments of the hidden `__sandbox-map` helper. It writes the maps for a process that has +/// just entered a new user namespace. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] struct MapJob { - parent: i32, + /// The pid of the process whose new namespace gets the maps. + parent: u32, uid: u32, gid: u32, uid_start: u32, @@ -273,95 +277,135 @@ struct MapJob { count: u32, } -/// Subuid mode. The parent unshares, and a forked child writes the maps with `newuidmap` and -/// `newgidmap`. The child can't do this itself, because the maps belong to the parent's new -/// namespace. +impl MapJob { + const USAGE: &'static str = + "usage: __sandbox-map "; + + fn to_args(self) -> Vec { + [ + self.parent, + self.uid, + self.gid, + self.uid_start, + self.gid_start, + self.count, + ] + .iter() + .map(|n| OsString::from(n.to_string())) + .collect() + } + + fn from_args(args: &[OsString]) -> Result { + let [parent, uid, gid, uid_start, gid_start, count] = args else { + return Err(Self::USAGE.into()); + }; + let job = Self { + parent: parse_arg(parent)?, + uid: parse_arg(uid)?, + gid: parse_arg(gid)?, + uid_start: parse_arg(uid_start)?, + gid_start: parse_arg(gid_start)?, + count: parse_arg(count)?, + }; + if job.parent == 0 || job.count == 0 { + return Err(format!( + "parent and count must be positive\n{}", + Self::USAGE + )); + } + Ok(job) + } +} + +fn parse_arg(arg: &OsString) -> Result { + arg.to_str() + .and_then(|s| s.parse().ok()) + .ok_or_else(|| format!("not a number: {}", arg.to_string_lossy())) +} + +/// Subuid mode. A helper process is started before the namespace exists. The parent then unshares +/// and tells the helper to go ahead. The helper runs `newuidmap` and `newgidmap` against the +/// parent's pid, because the maps belong to the parent's new namespace, and this process can't +/// write them itself. /// -/// The child waits on a pipe until the parent has unshared. The parent then writes one byte, and -/// the child runs the two tools. The child reports its failure through a second pipe, which the -/// parent reads to EOF before it reaps the child. +/// The helper blocks on its stdin until the parent writes one byte and closes it. The helper +/// reports failures on stderr, which the parent reads once the helper has exited. fn enter_subuid(map: &IdMap, uid_start: u32, gid_start: u32, count: u32) -> Result<(), IdMapError> { - let pipe_err = |e: Errno| IdMapError::Map(format!("cannot create pipe: {e}")); - let (go_r, go_w) = pipe2(OFlag::O_CLOEXEC).map_err(pipe_err)?; - let (err_r, err_w) = pipe2(OFlag::O_CLOEXEC).map_err(pipe_err)?; let job = MapJob { - parent: getpid().as_raw(), + parent: std::process::id(), uid: map.uid, gid: map.gid, uid_start, gid_start, count, }; + let exe = std::env::current_exe() + .map_err(|e| IdMapError::Map(format!("cannot find the runner binary: {e}")))?; + let mut child = Command::new(exe) + .arg(MAP_HELPER_CMD) + .args(job.to_args()) + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|e| IdMapError::Map(format!("cannot start the mapping helper: {e}")))?; + let Some(mut go) = child.stdin.take() else { + stop_child(&mut child); + return Err(IdMapError::Map("no stdin for the mapping helper".into())); + }; - // SAFETY: the helper is single-threaded (see the module docs), so the child is a copy of a - // process with one thread, and no lock held by another thread can block it. The child only - // reads a pipe, runs std::process::Command, and exits. - match unsafe { fork() }.map_err(|e| IdMapError::Map(format!("cannot fork: {e}")))? { - ForkResult::Child => { - drop(go_w); - drop(err_r); - let mut go = File::from(go_r); - let mut err = File::from(err_w); - let code = match write_maps_in_child(&mut go, &job) { - Ok(()) => 0, - Err(message) => { - let _ = err.write_all(message.as_bytes()); - 1 - } - }; - std::process::exit(code) - } - ForkResult::Parent { child } => { - drop(go_r); - drop(err_w); - let mut go_w = File::from(go_w); - let mut err_r = File::from(err_r); - let signalled = unshare(CloneFlags::CLONE_NEWUSER | CloneFlags::CLONE_NEWNS) - .map_err(|e| IdMapError::Namespace(e.to_string())) - .and_then(|()| { - go_w.write_all(b"1").map_err(|e| { - IdMapError::Map(format!("cannot signal the mapping helper: {e}")) - }) - }); - // Closing the pipe tells the child to exit if it is still waiting. - drop(go_w); - let mut message = Vec::new(); - let _ = err_r.read_to_end(&mut message); - let status = wait_for_child(child); - signalled?; - match status { - Ok(WaitStatus::Exited(_, 0)) => {} - Ok(_) => { - return Err(IdMapError::Map(format!( - "cannot map user ids: {}", - String::from_utf8_lossy(&message).trim() - ))); - } - Err(e) => { - return Err(IdMapError::Map(format!( - "waiting for the mapping helper: {e}" - ))); - } - } - // newgidmap leaves setgroups allowed. Drop the supplementary groups the process had - // before the namespace existed. - nix::unistd::setgroups(&[]) - .map_err(|e| IdMapError::Map(format!("cannot clear groups: {e}"))) - } + let signalled = unshare(CloneFlags::CLONE_NEWUSER | CloneFlags::CLONE_NEWNS) + .map_err(|e| IdMapError::Namespace(e.to_string())) + .and_then(|()| { + go.write_all(b"1") + .map_err(|e| IdMapError::Map(format!("cannot signal the mapping helper: {e}"))) + }); + // Closing stdin ends the helper's wait, so it exits instead of blocking if the signal + // never landed. + drop(go); + if let Err(e) = signalled { + stop_child(&mut child); + return Err(e); } + + let output = child + .wait_with_output() + .map_err(|e| IdMapError::Map(format!("waiting for the mapping helper: {e}")))?; + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + let detail = match stderr.trim() { + "" => output.status.to_string(), + text => text.to_owned(), + }; + return Err(IdMapError::Map(format!("cannot map user ids: {detail}"))); + } + // newgidmap leaves setgroups allowed. Drop the supplementary groups the process had before + // the namespace existed. + nix::unistd::setgroups(&[]).map_err(|e| IdMapError::Map(format!("cannot clear groups: {e}"))) } -/// Runs in the forked child. It waits for the parent's byte, then maps the uids and gids. -fn write_maps_in_child(go: &mut File, job: &MapJob) -> Result<(), String> { - let mut byte = [0u8; 1]; - loop { - match go.read(&mut byte) { - Ok(1) => break, - Ok(_) => return Err("user namespace setup was cancelled".into()), - Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, - Err(e) => return Err(format!("cannot read from the parent: {e}")), +/// Kills a helper that will not be used, and reaps it so nothing is left behind. +fn stop_child(child: &mut std::process::Child) { + let _ = child.kill(); + let _ = child.wait(); +} + +/// ` __sandbox-map `, with the gate byte +/// on stdin. Waits for the byte, then writes the uid and gid maps of `parent`. Exit 0 on success, +/// or 125 with a `forge-sandbox:` line on stderr. +pub fn map_helper_main(args: &[OsString]) -> i32 { + match map_helper(args) { + Ok(()) => 0, + Err(message) => { + eprintln!("forge-sandbox: {message}"); + 125 } } +} + +fn map_helper(args: &[OsString]) -> Result<(), String> { + let job = MapJob::from_args(args)?; + wait_for_go(&mut io::stdin().lock())?; let parent = job.parent.to_string(); let count = job.count.to_string(); let uid_start = job.uid_start.to_string(); @@ -378,6 +422,19 @@ fn write_maps_in_child(go: &mut File, job: &MapJob) -> Result<(), String> { ) } +/// Blocks until the parent writes its byte. EOF before the byte means the parent gave up. +fn wait_for_go(go: &mut impl Read) -> Result<(), String> { + let mut byte = [0u8; 1]; + loop { + match go.read(&mut byte) { + Ok(1) => return Ok(()), + Ok(_) => return Err("user namespace setup was cancelled".into()), + Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, + Err(e) => return Err(format!("cannot read from the parent: {e}")), + } + } +} + fn run_map_tool(tool: &str, args: &[&str]) -> Result<(), String> { let path = find_tool(tool).ok_or_else(|| format!("{tool} is not installed"))?; let output = Command::new(&path) @@ -396,15 +453,6 @@ fn run_map_tool(tool: &str, args: &[&str]) -> Result<(), String> { } } -fn wait_for_child(child: Pid) -> Result { - loop { - match waitpid(child, None) { - Err(Errno::EINTR) => continue, - other => return other, - } - } -} - /// ` __sandbox-rm `, with the [`IdMap`] JSON on stdin. Enters the namespace, makes the /// directories under `path` writable, and removes it. Exit 0 on success, or 125 with a /// `forge-sandbox:` line on stderr. @@ -590,6 +638,45 @@ mod tests { assert_eq!(uneven.size(), 11); } + fn os(args: &[&str]) -> Vec { + args.iter().map(OsString::from).collect() + } + + #[test] + fn map_job_args_round_trip() { + let job = MapJob { + parent: 4242, + uid: 1000, + gid: 1001, + uid_start: 524288, + gid_start: 589824, + count: 65536, + }; + let args = job.to_args(); + assert_eq!( + args, + os(&["4242", "1000", "1001", "524288", "589824", "65536"]) + ); + assert_eq!(MapJob::from_args(&args), Ok(job)); + } + + #[test] + fn map_job_args_reject_bad_input() { + let good = ["4242", "1000", "1001", "524288", "589824", "65536"]; + assert!(MapJob::from_args(&os(&good[..5])).is_err(), "too few"); + let mut extra = good.to_vec(); + extra.push("1"); + assert!(MapJob::from_args(&os(&extra)).is_err(), "too many"); + for (index, bad) in [(0, "0"), (1, "-1"), (2, "x"), (3, ""), (5, "0")] { + let mut args = good.to_vec(); + args[index] = bad; + assert!( + MapJob::from_args(&os(&args)).is_err(), + "argument {index} = {bad:?} should be rejected" + ); + } + } + #[test] fn default_is_single() { let map = IdMap::default();