diff --git a/docs/guide/getting-started.md b/docs/guide/getting-started.md index e102e7b..e48fee8 100644 --- a/docs/guide/getting-started.md +++ b/docs/guide/getting-started.md @@ -92,18 +92,28 @@ The `ctor` crate runs the function at load time, before `main` or the test harness starts. This keeps your test functions clean and avoids repeating the namespace setup in every binary. -### Keeping your own uid - -`init_userns()` maps your user to root (uid 0) inside the namespace. A -process that also talks to the session D-Bus, for example to use a desktop -portal, then fails: D-Bus clients such as `zbus` claim uid 0, and the bus -rejects them. - -In that case call `init_userns_keep_uid()` (or -`init_userns_keep_uid_for_ctor()` from a `#[ctor]`). Your user keeps its -uid. Spawned commands keep `CAP_NET_ADMIN`, `CAP_NET_RAW` and -`CAP_NET_BIND_SERVICE`, so `nft`, `tc`, `ping` and low ports work, but -commands such as `mount` do not. That is why it is not the default. +### Your uid and running as root + +`init_userns()` keeps your uid inside the namespace. Services that check the +caller's uid, such as the session D-Bus or PipeWire portals, keep working. +The patchbay process has all capabilities in the namespace. Spawned commands +keep `CAP_NET_ADMIN`, `CAP_NET_RAW` and `CAP_NET_BIND_SERVICE`, so `nft`, +`tc`, `ping` and low ports work. + +Some commands need root, for example `mount`. Spawn them through `root()`: + +```rust +let child = device.root().spawn_command_sync(std::process::Command::new("mount"))?; +``` + +Root needs a subordinate id range for your user, the same setup rootless +podman uses: `newuidmap` and `newgidmap` on `PATH` and an entry in +`/etc/subuid` and `/etc/subgid`. patchbay maps uid 0 to the first id of +that range. Without it, `root()` returns an error and everything else +works. Root inside the namespace is that subordinate id on the host, so +files a root command creates outside the lab belong to it, and you need +`podman unshare rm` to remove them. Prefer running commands as yourself +where they work. ## Creating a lab diff --git a/patchbay-cli/src/native.rs b/patchbay-cli/src/native.rs index f803cce..ac71c91 100644 --- a/patchbay-cli/src/native.rs +++ b/patchbay-cli/src/native.rs @@ -18,8 +18,8 @@ use serde::{Deserialize, Serialize}; /// where main() is not our code (nextest spawns each test as a process). #[ctor::ctor(unsafe)] fn _init_userns() { - // Safety: called from .init_array before main() and before any threads. - unsafe { patchbay::init_userns_for_ctor() }; + // Runs before main() and before any threads. `init()` reports the result. + let _ = patchbay::init_userns(); } /// Initialize user namespaces (called from main() as well for the CLI binary). diff --git a/patchbay/Cargo.toml b/patchbay/Cargo.toml index 1e518f0..982069b 100644 --- a/patchbay/Cargo.toml +++ b/patchbay/Cargo.toml @@ -24,7 +24,7 @@ libc = "0.2" netlink-packet-core = "0.9" netlink-packet-route = "0.33" netlink-proto = "0.13" -rustix = { version = "1.1", default-features = false, features = ["std", "thread", "process"] } +rustix = { version = "1.1", default-features = false, features = ["std", "thread", "process", "pipe"] } serde = { version = "1", features = ["derive"] } serde_json = "1" strum = { version = "0.28", features = ["derive"] } diff --git a/patchbay/src/device.rs b/patchbay/src/device.rs index d685abb..c8b6e5c 100644 --- a/patchbay/src/device.rs +++ b/patchbay/src/device.rs @@ -364,6 +364,14 @@ impl Device { self.lab.netns.spawn_thread_in(&self.ns, f) } + /// Returns a handle that spawns commands as root in this device's namespace. + /// + /// See [`AsRoot`](crate::AsRoot) for when root is available and what it + /// means for files on the host. + pub fn root(&self) -> crate::AsRoot<'_> { + crate::AsRoot::new(&self.lab, &self.ns) + } + /// Spawns a [`tokio::process::Command`] in this device's network namespace. /// /// The child is registered with the namespace's tokio reactor so that diff --git a/patchbay/src/lib.rs b/patchbay/src/lib.rs index 2c7eb89..a261b30 100644 --- a/patchbay/src/lib.rs +++ b/patchbay/src/lib.rs @@ -193,9 +193,9 @@ //! //! Linux with unprivileged user namespaces enabled, plus `nft` and `tc` in //! PATH. No root needed. Call [`init_userns`] before spawning any threads -//! to enter the user namespace. Use [`init_userns_keep_uid`] instead if the -//! process also talks to services that check its uid, such as the session -//! D-Bus. +//! to enter the user namespace. The process keeps its uid. Commands can run +//! as root on request with [`Device::root`] if the host has a subordinate id +//! range for the user. use anyhow::{anyhow, bail, Context, Result}; @@ -256,9 +256,7 @@ pub use crate::dns_server::DnsServer; pub use crate::{ core::{NodeId, ReflectorGuard}, event::{IfaceCounters, IfaceSnapshot, LabEvent, LabEventKind, LabState}, - userns::{ - init_userns, init_userns_for_ctor, init_userns_keep_uid, init_userns_keep_uid_for_ctor, - }, + userns::{init_userns, AsRoot}, }; /// Verifies the process has enough privileges to manage namespaces, routes, and raw sockets. diff --git a/patchbay/src/router.rs b/patchbay/src/router.rs index 045c3f9..3e8eca1 100644 --- a/patchbay/src/router.rs +++ b/patchbay/src/router.rs @@ -598,6 +598,14 @@ impl Router { self.lab.netns.spawn_thread_in(&self.ns, f) } + /// Returns a handle that spawns commands as root in this router's namespace. + /// + /// See [`AsRoot`](crate::AsRoot) for when root is available and what it + /// means for files on the host. + pub fn root(&self) -> crate::AsRoot<'_> { + crate::AsRoot::new(&self.lab, &self.ns) + } + /// Spawns a [`tokio::process::Command`] in this router's network namespace. /// /// The child is registered with the namespace's tokio reactor. diff --git a/patchbay/src/userns.rs b/patchbay/src/userns.rs index f1dbd5e..36e5c69 100644 --- a/patchbay/src/userns.rs +++ b/patchbay/src/userns.rs @@ -1,20 +1,17 @@ -//! User-namespace bootstrap helpers. +//! User-namespace bootstrap. //! -//! The ctor entrypoints are intentionally libc-only so they can run from ELF -//! `.init_array` before Rust stdlib/TLS initialization. +//! [`init_userns`] moves the process into a new user namespace in which it +//! keeps its own uid and gid. If the host has a subordinate id range for the +//! user (`/etc/subuid`, `/etc/subgid`, and the `newuidmap`/`newgidmap` +//! helpers), the namespace also maps uid and gid 0 to the first subordinate +//! id, so commands can run as root on request (see [`Device::root`]), and the +//! rest of the range to itself. +//! +//! [`Device::root`]: crate::Device::root use std::sync::OnceLock; -/// How the calling user is mapped into the new user namespace. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Mapping { - /// Map the calling user and group to 0 (root) inside the namespace. - Root, - /// Map the calling user and group to their own ids inside the namespace. - KeepUid, -} - -/// Capabilities that child processes keep in [`Mapping::KeepUid`] mode. +/// Capabilities that child processes keep. /// /// A process that is not uid 0 keeps only its ambient capabilities across /// `execve`. These keep `nft`, `tc`, `conntrack` and `ping` working. @@ -25,142 +22,274 @@ const AMBIENT_CAPS: [u32; 3] = [ 13, // CAP_NET_RAW ]; -/// The mapping and result of the first bootstrap in this process. -static STATE: OnceLock<(Mapping, Result<(), String>)> = OnceLock::new(); - /// Idempotent user-namespace bootstrap. /// -/// Call at the start of `main()` (before Tokio creates threads) when running as -/// a non-root user. Uses an internal `OnceLock` so it is safe to call multiple -/// times; subsequent calls are instant no-ops. -/// -/// Maps the calling user to root (uid 0) inside the namespace. See -/// [`init_userns_keep_uid`] to keep the user's own uid. -pub fn init_userns() -> anyhow::Result<()> { - init(Mapping::Root) -} - -/// Idempotent user-namespace bootstrap that keeps the caller's uid and gid. -/// -/// Use this when the process also talks to a service that checks its uid, -/// such as the session D-Bus: under [`init_userns`] a client like `zbus` -/// claims uid 0, and the bus rejects it. +/// Call at the start of `main()`, or from a `#[ctor::ctor]` function, before +/// any threads exist. Uses an internal `OnceLock`, so it is safe to call more +/// than once. Later calls return the first result. /// -/// The process itself keeps all capabilities in the namespace. Child -/// processes are not root and keep only `CAP_NET_ADMIN`, `CAP_NET_RAW` and -/// `CAP_NET_BIND_SERVICE`. That covers `nft`, `tc`, `ping` and low ports, -/// but not commands such as `mount` or ones that check for uid 0. +/// The process keeps its uid and gid inside the namespace, so services that +/// check the caller's uid, such as the session D-Bus or PipeWire portals, keep +/// working. The process itself has all capabilities in the namespace. Child +/// processes keep `CAP_NET_ADMIN`, `CAP_NET_RAW` and `CAP_NET_BIND_SERVICE`, +/// which covers `nft`, `tc`, `ping` and low ports. /// -/// Fails if [`init_userns`] already ran in this process. -pub fn init_userns_keep_uid() -> anyhow::Result<()> { - init(Mapping::KeepUid) -} - -fn init(mapping: Mapping) -> anyhow::Result<()> { - let (done, result) = - STATE.get_or_init(|| (mapping, do_bootstrap(mapping).map_err(|e| e.to_string()))); - if *done != mapping { - anyhow::bail!("user namespace already initialized with mapping {done:?}, not {mapping:?}"); - } - result +/// If `newuidmap` and `newgidmap` are on `PATH` and `/etc/subuid` and +/// `/etc/subgid` have an entry for the user, uid and gid 0 map to the first +/// subordinate id and the rest of the range maps to itself. Commands can then +/// run as root with [`Device::root`](crate::Device::root) and +/// [`Router::root`](crate::Router::root). If the helpers are missing or fail, +/// only the user's own ids are mapped and root is not available. +pub fn init_userns() -> anyhow::Result<()> { + static RESULT: OnceLock> = OnceLock::new(); + RESULT + .get_or_init(|| do_bootstrap().map_err(|e| format!("{e:#}"))) .as_ref() .map(|_| ()) .map_err(|e| anyhow::anyhow!("{e}")) } -/// Raw libc-only variant safe for ELF `.init_array` / pre-TLS contexts. -/// -/// # Safety -/// -/// Must only be called from a single-threaded ELF init context (e.g. a -/// `#[ctor::ctor]` function) before the Rust standard library has been -/// initialized. After that point use [`init_userns`] instead. -pub unsafe fn init_userns_for_ctor() { - #[cfg(target_os = "linux")] - unsafe { - userns_bootstrap_libc(Mapping::Root); - } +/// Returns whether uid and gid 0 are mapped in the current user namespace, +/// so that a child process can switch to root. +pub(crate) fn root_is_mapped() -> bool { + let has_zero = |path: &str| { + std::fs::read_to_string(path).is_ok_and(|map| { + map.lines() + .any(|line| line.split_whitespace().next() == Some("0")) + }) + }; + has_zero("/proc/self/uid_map") && has_zero("/proc/self/gid_map") } -/// Libc-only variant of [`init_userns_keep_uid`] for ELF `.init_array` contexts. -/// -/// # Safety -/// -/// Must only be called from a single-threaded ELF init context (e.g. a -/// `#[ctor::ctor]` function) before the Rust standard library has been -/// initialized. After that point use [`init_userns_keep_uid`] instead. -pub unsafe fn init_userns_keep_uid_for_ctor() { - #[cfg(target_os = "linux")] - unsafe { - userns_bootstrap_libc(Mapping::KeepUid); +#[cfg(target_os = "linux")] +fn do_bootstrap() -> anyhow::Result<()> { + use anyhow::Context; + let uid = rustix::process::getuid().as_raw(); + let gid = rustix::process::getgid().as_raw(); + match RangeParams::detect(uid, gid) { + Some(range) => range_bootstrap(uid, gid, &range).context("range userns bootstrap")?, + None => single_id_bootstrap(uid, gid).context("single-id userns bootstrap")?, + } + if rustix::process::geteuid().as_raw() != uid { + anyhow::bail!("userns bootstrap finished without UID {uid} mapping"); } + // SAFETY: only makes system calls with pointers to local buffers. + if unsafe { raise_ambient_caps() } != 0 { + return Err(std::io::Error::last_os_error()).context("raise ambient capabilities"); + } + Ok(()) } +#[cfg(not(target_os = "linux"))] +fn do_bootstrap() -> anyhow::Result<()> { + Ok(()) +} + +/// Maps only the current uid and gid, each to itself. Needs no host setup. #[cfg(target_os = "linux")] -fn do_bootstrap(mapping: Mapping) -> anyhow::Result<()> { +fn single_id_bootstrap(uid: u32, gid: u32) -> anyhow::Result<()> { use anyhow::Context; use rustix::thread::UnshareFlags; - let uid = rustix::process::getuid().as_raw(); - let gid = rustix::process::getgid().as_raw(); - let (inner_uid, inner_gid) = match mapping { - Mapping::Root => (0, 0), - Mapping::KeepUid => (uid, gid), - }; crate::netns::unshare_namespaces(UnshareFlags::NEWUSER) .context("unshare(CLONE_NEWUSER) failed")?; - std::fs::write("/proc/self/setgroups", "deny\n").context("write setgroups")?; - std::fs::write("/proc/self/uid_map", format!("{inner_uid} {uid} 1\n")) - .context("write uid_map")?; - std::fs::write("/proc/self/gid_map", format!("{inner_gid} {gid} 1\n")) - .context("write gid_map")?; - match mapping { - Mapping::Root if !rustix::process::geteuid().is_root() => { - anyhow::bail!("userns bootstrap finished without UID 0 mapping") - } - Mapping::Root => Ok(()), - Mapping::KeepUid => { - if rustix::process::geteuid().as_raw() != uid { - anyhow::bail!("userns bootstrap finished without UID {uid} mapping"); - } - // SAFETY: only makes system calls with pointers to local buffers. - if unsafe { raise_ambient_caps() } != 0 { - return Err(std::io::Error::last_os_error()).context("raise ambient capabilities"); - } - Ok(()) - } - } + write_single_id_maps(uid, gid) } -#[cfg(not(target_os = "linux"))] -fn do_bootstrap(_mapping: Mapping) -> anyhow::Result<()> { +/// Writes single-entry uid and gid maps of the current user namespace. +/// +/// Skips a map that is already written, so this also completes a range map +/// that the helpers wrote only in part. +#[cfg(target_os = "linux")] +fn write_single_id_maps(uid: u32, gid: u32) -> anyhow::Result<()> { + use anyhow::Context; + let is_empty = |path: &str| std::fs::read_to_string(path).is_ok_and(|map| map.is_empty()); + if is_empty("/proc/self/uid_map") { + std::fs::write("/proc/self/uid_map", format!("{uid} {uid} 1\n")) + .context("write uid_map")?; + } + if is_empty("/proc/self/gid_map") { + std::fs::write("/proc/self/setgroups", "deny\n").context("write setgroups")?; + std::fs::write("/proc/self/gid_map", format!("{gid} {gid} 1\n")) + .context("write gid_map")?; + } Ok(()) } +/// Sub-id ranges and helper paths for a range map. +#[cfg(target_os = "linux")] +struct RangeParams { + newuidmap: std::path::PathBuf, + newgidmap: std::path::PathBuf, + sub_uid_start: u32, + sub_uid_count: u32, + sub_gid_start: u32, + sub_gid_count: u32, +} + +#[cfg(target_os = "linux")] +impl RangeParams { + /// Detects whether a range map is possible for the current user. + /// + /// Requires `newuidmap` and `newgidmap` on `PATH` and an `/etc/subuid` and + /// `/etc/subgid` entry for the user. Returns `None` (use the single-id + /// map) if anything is missing. + fn detect(uid: u32, gid: u32) -> Option { + let newuidmap = find_in_path("newuidmap")?; + let newgidmap = find_in_path("newgidmap")?; + let user = user_name(uid)?; + let (sub_uid_start, sub_uid_count) = parse_subid("/etc/subuid", &user, uid)?; + let (sub_gid_start, sub_gid_count) = parse_subid("/etc/subgid", &user, gid)?; + Some(Self { + newuidmap, + newgidmap, + sub_uid_start, + sub_uid_count, + sub_gid_start, + sub_gid_count, + }) + } +} + +/// Returns the login name of `uid` from the passwd database. #[cfg(target_os = "linux")] -unsafe fn userns_bootstrap_libc(mapping: Mapping) { - let uid = unsafe { libc::getuid() }; - let gid = unsafe { libc::getgid() }; - let (inner_uid, inner_gid) = match mapping { - Mapping::Root => (0, 0), - Mapping::KeepUid => (uid, gid), +fn user_name(uid: u32) -> Option { + let mut pwd = std::mem::MaybeUninit::::uninit(); + let mut buf = vec![0 as libc::c_char; 4096]; + let mut result = std::ptr::null_mut(); + // SAFETY: `pwd`, `buf` and `result` are valid for the call. On success + // `result` points to `pwd`, whose string fields point into `buf`. + let rc = unsafe { + libc::getpwuid_r( + uid, + pwd.as_mut_ptr(), + buf.as_mut_ptr(), + buf.len(), + &mut result, + ) }; - if unsafe { libc::unshare(libc::CLONE_NEWUSER) } != 0 { - return; + if rc != 0 || result.is_null() { + return None; } + // SAFETY: `getpwuid_r` succeeded, so `pw_name` is a NUL-terminated string in `buf`. + let name = unsafe { std::ffi::CStr::from_ptr((*result).pw_name) }; + name.to_str().ok().map(str::to_owned) +} - unsafe { proc_write(c"/proc/self/setgroups".as_ptr(), b"deny\n") }; +/// Maps the current uid and gid plus their subordinate ranges, using the +/// setuid `newuidmap`/`newgidmap` helpers. +/// +/// The current process enters the new user namespace, then a short-lived child +/// (still in the parent namespace, where the setuid helpers have authority) +/// writes the range maps against the parent's pid. If the helpers fail, for +/// example because they lack their setuid bit, this falls back to the +/// single-id map, so a broken helper costs the range but not the namespace. +#[cfg(target_os = "linux")] +fn range_bootstrap(uid: u32, gid: u32, range: &RangeParams) -> anyhow::Result<()> { + use anyhow::Context; + use rustix::{ + io::{read, write}, + pipe::pipe, + process::{getpid, waitpid, Pid, WaitOptions}, + thread::UnshareFlags, + }; - let mut uid_buf = [0u8; 32]; - let uid_line = format_map_line(&mut uid_buf, inner_uid, uid); - unsafe { proc_write(c"/proc/self/uid_map".as_ptr(), uid_line) }; + let uid_lines = id_map_lines(uid, range.sub_uid_start, range.sub_uid_count); + let gid_lines = id_map_lines(gid, range.sub_gid_start, range.sub_gid_count); - let mut gid_buf = [0u8; 32]; - let gid_line = format_map_line(&mut gid_buf, inner_gid, gid); - unsafe { proc_write(c"/proc/self/gid_map".as_ptr(), gid_line) }; + // p2c signals the child once the parent has unshared (and carries the + // parent pid). c2p carries the child's success byte back. + let (p2c_r, p2c_w) = pipe().context("pipe")?; + let (c2p_r, c2p_w) = pipe().context("pipe")?; - if mapping == Mapping::KeepUid { - let _ = unsafe { raise_ambient_caps() }; + // SAFETY: called single-threaded during bootstrap (before Tokio starts). + // The child only reads a pid, runs the setuid helpers, and `_exit`s. + let child = unsafe { libc::fork() }; + if child < 0 { + return Err(std::io::Error::last_os_error()).context("fork"); + } + if child == 0 { + drop(p2c_w); + drop(c2p_r); + let mut pid_buf = [0u8; 4]; + let ok = read(&p2c_r, &mut pid_buf).is_ok_and(|n| n == 4) && { + let target = u32::from_ne_bytes(pid_buf).to_string(); + run_idmap(&range.newuidmap, &target, &uid_lines) + && run_idmap(&range.newgidmap, &target, &gid_lines) + }; + let _ = write(&c2p_w, &[u8::from(ok)]); + // SAFETY: exit without running atexit handlers in the forked child. + unsafe { libc::_exit(0) }; } + + drop(p2c_r); + drop(c2p_w); + let mapped = (|| -> anyhow::Result { + crate::netns::unshare_namespaces(UnshareFlags::NEWUSER) + .context("unshare(CLONE_NEWUSER) failed")?; + let pid = getpid().as_raw_nonzero().get() as u32; + write(&p2c_w, &pid.to_ne_bytes()).context("signal child")?; + let mut status = [0u8; 1]; + let got = read(&c2p_r, &mut status).context("await child")?; + Ok(got == 1 && status[0] == 1) + })(); + // Closing the pipe unblocks a child that still waits for the pid. + drop(p2c_w); + let _ = waitpid(Pid::from_raw(child), WaitOptions::empty()); + if !mapped? { + tracing::warn!("newuidmap/newgidmap failed, falling back to a single-id user namespace"); + write_single_id_maps(uid, gid).context("fall back to single-id maps")?; + } + Ok(()) +} + +/// Returns the `inner outer count` triples for one id and its subordinate +/// range: the id to itself, 0 to the first subordinate id, and the rest of the +/// range to itself. +#[cfg(target_os = "linux")] +fn id_map_lines(id: u32, sub_start: u32, sub_count: u32) -> Vec<[u32; 3]> { + let mut lines = vec![[id, id, 1], [0, sub_start, 1]]; + if sub_count > 1 { + lines.push([sub_start + 1, sub_start + 1, sub_count - 1]); + } + lines +} + +/// Runs `helper ...` with the given map lines. +#[cfg(target_os = "linux")] +fn run_idmap(helper: &std::path::Path, pid: &str, lines: &[[u32; 3]]) -> bool { + std::process::Command::new(helper) + .arg(pid) + .args(lines.iter().flatten().map(u32::to_string)) + .status() + .is_ok_and(|status| status.success()) +} + +/// Finds an executable by name on `PATH`. +#[cfg(target_os = "linux")] +fn find_in_path(name: &str) -> Option { + let path = std::env::var_os("PATH")?; + std::env::split_paths(&path) + .map(|dir| dir.join(name)) + .find(|candidate| candidate.is_file()) +} + +/// Parses an `/etc/subuid`-style file for the `login:start:count` entry that +/// matches the user by name or numeric id. +#[cfg(target_os = "linux")] +fn parse_subid(path: &str, name: &str, id: u32) -> Option<(u32, u32)> { + let contents = std::fs::read_to_string(path).ok()?; + let id_str = id.to_string(); + for line in contents.lines() { + let mut fields = line.split(':'); + let login = fields.next()?; + if login != name && login != id_str { + continue; + } + let start = fields.next()?.parse().ok()?; + let count = fields.next()?.parse().ok()?; + return Some((start, count)); + } + None } /// Adds [`AMBIENT_CAPS`] to the inheritable and ambient sets. @@ -169,7 +298,7 @@ unsafe fn userns_bootstrap_libc(mapping: Mapping) { /// /// # Safety /// -/// libc-only; safe to call before the Rust standard library is initialized. +/// Only makes system calls with pointers to local buffers. #[cfg(target_os = "linux")] unsafe fn raise_ambient_caps() -> libc::c_long { /// `_LINUX_CAPABILITY_VERSION_3`, which takes two data words. @@ -220,64 +349,95 @@ unsafe fn raise_ambient_caps() -> libc::c_long { 0 } -#[cfg(target_os = "linux")] -unsafe fn proc_write(path: *const libc::c_char, data: &[u8]) { - let fd = unsafe { libc::open(path, libc::O_WRONLY) }; - if fd < 0 { - return; - } - let _ = unsafe { libc::write(fd, data.as_ptr().cast::(), data.len()) }; - let _ = unsafe { libc::close(fd) }; +/// Spawns commands as root (uid 0) in one node's namespace. +/// +/// Returned by [`Device::root`](crate::Device::root) and +/// [`Router::root`](crate::Router::root). The patchbay process keeps the +/// user's uid, and its own code already has all capabilities in the +/// namespace. Child processes normally run as the user too, with only the +/// network capabilities. Use this for commands that need more, or that check +/// for uid 0, such as `mount`. +/// +/// Root inside the namespace is the user's first subordinate id outside it. +/// Files that a root command creates on the host file system are therefore +/// owned by that id, and the user cannot remove them directly (use +/// `podman unshare rm`). Prefer running commands as the user where they work. +/// +/// Spawning fails if the host has no subordinate id range for the user, see +/// [`init_userns`]. +pub struct AsRoot<'a> { + lab: &'a crate::lab::LabInner, + ns: &'a str, } -/// Formats an id map line `" 1\n"` into `buf`. -#[cfg(target_os = "linux")] -fn format_map_line(buf: &mut [u8; 32], inner: u32, outer: u32) -> &[u8] { - let mut pos = 0usize; - pos = write_decimal(buf, pos, inner); - buf[pos] = b' '; - pos += 1; - pos = write_decimal(buf, pos, outer); - buf[pos..pos + 3].copy_from_slice(b" 1\n"); - pos += 3; - &buf[..pos] -} +impl<'a> AsRoot<'a> { + pub(crate) fn new(lab: &'a crate::lab::LabInner, ns: &'a str) -> Self { + Self { lab, ns } + } -/// Writes `n` in decimal at `buf[pos..]` and returns the new position. -#[cfg(target_os = "linux")] -fn write_decimal(buf: &mut [u8; 32], mut pos: usize, n: u32) -> usize { - if n == 0 { - buf[pos] = b'0'; - return pos + 1; + /// Spawns a [`tokio::process::Command`] as root in the node's namespace. + /// + /// Works like [`Device::spawn_command`](crate::Device::spawn_command) + /// otherwise. + pub fn spawn_command( + &self, + mut cmd: tokio::process::Command, + ) -> anyhow::Result { + use anyhow::Context; + ensure_root_mapped()?; + cmd.uid(0).gid(0); + let rt = self.lab.rt_handle_for(self.ns)?; + self.lab.netns.run_closure_in(self.ns, move || { + let _guard = rt.enter(); + cmd.spawn() + .context("spawn async command as root in namespace") + }) } - let mut n = n; - let mut rev = [0u8; 10]; - let mut len = 0usize; - while n > 0 { - rev[len] = b'0' + (n % 10) as u8; - n /= 10; - len += 1; + + /// Spawns a [`std::process::Command`] as root in the node's namespace. + /// + /// Works like [`Device::spawn_command_sync`](crate::Device::spawn_command_sync) + /// otherwise. + pub fn spawn_command_sync( + &self, + mut cmd: std::process::Command, + ) -> anyhow::Result { + use std::os::unix::process::CommandExt; + + use anyhow::Context; + ensure_root_mapped()?; + cmd.uid(0).gid(0); + self.lab.netns.run_closure_in(self.ns, move || { + cmd.spawn().context("spawn command as root in namespace") + }) } - while len > 0 { - len -= 1; - buf[pos] = rev[len]; - pos += 1; +} + +/// Fails with an explanation if uid or gid 0 is not mapped. +fn ensure_root_mapped() -> anyhow::Result<()> { + if root_is_mapped() { + return Ok(()); } - pos + anyhow::bail!( + "root is not mapped in patchbay's user namespace. Running commands as root \ + needs newuidmap/newgidmap on PATH and an /etc/subuid and /etc/subgid entry \ + for the user" + ) } #[cfg(all(test, target_os = "linux"))] mod tests { - use super::format_map_line; + use super::id_map_lines; #[test] - fn map_line_formats_ids() { - let mut buf = [0u8; 32]; - assert_eq!(format_map_line(&mut buf, 0, 1000), b"0 1000 1\n"); - assert_eq!(format_map_line(&mut buf, 1000, 1000), b"1000 1000 1\n"); + fn map_lines_keep_the_id_and_put_root_on_the_range() { + assert_eq!( + id_map_lines(1000, 100000, 65536), + [[1000, 1000, 1], [0, 100000, 1], [100001, 100001, 65535]] + ); assert_eq!( - format_map_line(&mut buf, u32::MAX, u32::MAX), - b"4294967295 4294967295 1\n" + id_map_lines(1000, 100000, 1), + [[1000, 1000, 1], [0, 100000, 1]] ); } } diff --git a/patchbay/tests/userns.rs b/patchbay/tests/userns.rs new file mode 100644 index 0000000..f48c428 --- /dev/null +++ b/patchbay/tests/userns.rs @@ -0,0 +1,154 @@ +//! Tests the user namespace from [`patchbay::init_userns`]. + +use std::net::{IpAddr, SocketAddr}; + +use anyhow::{ensure, Context, Result}; +use patchbay::{IfaceConfig, Lab, LinkCondition, LinkDirection, Nat}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; + +#[ctor::ctor(unsafe)] +fn init() { + patchbay::init_userns().expect("user namespace"); +} + +/// Parses `/proc/self/uid_map` into `[inner, outer, count]` lines. +fn uid_map() -> Result> { + let map = std::fs::read_to_string("/proc/self/uid_map")?; + map.lines() + .map(|line| { + let fields: Vec = line + .split_whitespace() + .map(str::parse) + .collect::>()?; + let [inner, outer, count] = fields[..] else { + anyhow::bail!("unexpected uid_map line: {line:?}"); + }; + Ok([inner, outer, count]) + }) + .collect() +} + +/// Whether the host gave the user a subordinate range, so root is mapped. +fn has_range() -> Result { + Ok(uid_map()?.len() > 1) +} + +/// The process keeps its uid. With a subordinate range, 0 maps to the first +/// subordinate id and the rest of the range to itself. +#[test] +fn uid_maps_to_itself() -> Result<()> { + let map = uid_map()?; + // SAFETY: getuid has no preconditions. + let uid = unsafe { libc::getuid() }; + ensure!(map[0] == [uid, uid, 1], "uid not mapped to itself: {map:?}"); + if let [_, [0, root, 1], rest @ ..] = &map[..] { + for &[inner, outer, _] in rest { + ensure!(inner == outer, "range not mapped to itself: {map:?}"); + ensure!(inner == root + 1, "range does not follow root: {map:?}"); + } + } else { + ensure!(map.len() == 1, "unexpected uid_map: {map:?}"); + } + Ok(()) +} + +/// `root()` spawns commands as uid 0 with all capabilities; plain spawns run +/// as the user. +#[tokio::test(flavor = "current_thread")] +async fn root_command_runs_as_uid_zero() -> Result<()> { + patchbay::check_caps()?; + let lab = Lab::new().await?; + let dc = lab.add_router("dc").build().await?; + let dev = lab.add_device("dev").uplink(dc.id()).build().await?; + + let id = |root: bool| -> Result { + let mut cmd = std::process::Command::new("sh"); + cmd.args(["-c", "id -u; grep CapEff /proc/self/status"]) + .stdout(std::process::Stdio::piped()); + let child = if root { + dev.root().spawn_command_sync(cmd)? + } else { + dev.spawn_command_sync(cmd)? + }; + let output = child.wait_with_output()?; + ensure!(output.status.success(), "command failed: {output:?}"); + Ok(String::from_utf8(output.stdout)?) + }; + + // SAFETY: getuid has no preconditions. + let uid = unsafe { libc::getuid() }; + let as_user = id(false)?; + ensure!( + as_user.starts_with(&format!("{uid}\n")), + "unexpected: {as_user:?}" + ); + + if !has_range()? { + let err = dev + .root() + .spawn_command_sync(std::process::Command::new("true")); + ensure!(err.is_err(), "root spawn without a range should fail"); + return Ok(()); + } + let as_root = id(true)?; + ensure!(as_root.starts_with("0\n"), "unexpected: {as_root:?}"); + ensure!( + as_root.contains("CapEff:\t000001ffffffffff"), + "root lacks capabilities: {as_root:?}" + ); + Ok(()) +} + +/// NAT, link conditions, low ports and a spawned `ping` work without uid 0. +#[tokio::test(flavor = "current_thread")] +async fn lab_works_without_root() -> Result<()> { + patchbay::check_caps()?; + let lab = Lab::new().await?; + let dc = lab.add_router("dc").build().await?; + let home = lab.add_router("home").nat(Nat::Moderate).build().await?; + let server = lab + .add_device("server") + .iface("eth0", dc.id()) + .build() + .await?; + let client = lab + .add_device("client") + .iface( + "eth0", + IfaceConfig::routed(home.id()) + .condition(LinkCondition::mobile_4g(), LinkDirection::Egress), + ) + .build() + .await?; + + let server_ip = server.ip().context("no server ip")?; + // A port below 1024 needs CAP_NET_BIND_SERVICE in the namespace. + let addr = SocketAddr::new(IpAddr::V4(server_ip), 80); + let listener = server + .spawn(move |_| async move { tokio::net::TcpListener::bind(addr).await })? + .await??; + server.spawn(move |_| async move { + let (mut stream, _) = listener.accept().await?; + let mut buf = vec![0u8; 64]; + let n = stream.read(&mut buf).await?; + stream.write_all(&buf[..n]).await?; + anyhow::Ok(()) + })?; + let echoed = client + .spawn(move |_| async move { + let mut stream = tokio::net::TcpStream::connect(addr).await?; + stream.write_all(b"hello").await?; + let mut buf = vec![0u8; 64]; + let n = stream.read(&mut buf).await?; + anyhow::Ok(buf[..n].to_vec()) + })? + .await??; + ensure!(echoed == b"hello", "unexpected echo: {echoed:?}"); + + // `ping` runs as a child process, which keeps only the ambient capabilities. + let mut cmd = tokio::process::Command::new("ping"); + cmd.args(["-c", "1", "-W", "2", &server_ip.to_string()]); + let status = client.spawn_command(cmd)?.wait().await?; + ensure!(status.success(), "ping failed: {status}"); + Ok(()) +} diff --git a/patchbay/tests/userns_fallback.rs b/patchbay/tests/userns_fallback.rs new file mode 100644 index 0000000..a4cbdeb --- /dev/null +++ b/patchbay/tests/userns_fallback.rs @@ -0,0 +1,100 @@ +//! The user-namespace bootstrap falls back to a single-id map when the +//! `newuidmap`/`newgidmap` helpers fail. +//! +//! The test runs its own binary again with broken helpers first on `PATH`. The +//! child bootstraps from a ctor, before the test harness starts threads. + +use std::sync::OnceLock; + +use anyhow::{ensure, Context, Result}; + +/// Set in the child process. +const CHILD_ENV: &str = "PATCHBAY_TEST_FALLBACK_CHILD"; + +static CHILD_RESULT: OnceLock> = OnceLock::new(); + +#[ctor::ctor(unsafe)] +fn init() { + if std::env::var_os(CHILD_ENV).is_some() { + let result = patchbay::init_userns().map_err(|e| format!("{e:#}")); + let _ = CHILD_RESULT.set(result); + } +} + +/// A failing `newuidmap` costs the subordinate range, not the namespace. +#[tokio::test(flavor = "current_thread")] +async fn broken_newuidmap_falls_back_to_single_id_map() -> Result<()> { + if std::env::var_os(CHILD_ENV).is_some() { + return child().await; + } + if !has_subuid_entry() { + eprintln!("skipping: no /etc/subuid entry, so the helpers never run"); + return Ok(()); + } + + let dir = testdir::testdir!(); + for helper in ["newuidmap", "newgidmap"] { + let path = dir.join(helper); + std::fs::write(&path, "#!/bin/sh\nexit 1\n")?; + std::fs::set_permissions(&path, std::os::unix::fs::PermissionsExt::from_mode(0o755))?; + } + let path = format!("{}:{}", dir.display(), std::env::var("PATH")?); + let output = std::process::Command::new(std::env::current_exe()?) + .args([ + "--exact", + "broken_newuidmap_falls_back_to_single_id_map", + "--nocapture", + ]) + .env(CHILD_ENV, "1") + .env("PATH", path) + .output() + .context("run child")?; + ensure!( + output.status.success(), + "child failed:\n{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + Ok(()) +} + +/// Checks the bootstrap result and that a lab works in the child. +async fn child() -> Result<()> { + CHILD_RESULT + .get() + .context("bootstrap did not run")? + .clone() + .map_err(anyhow::Error::msg)?; + let map = std::fs::read_to_string("/proc/self/uid_map")?; + ensure!( + map.lines().count() == 1, + "expected a single-id map: {map:?}" + ); + // SAFETY: getuid has no preconditions. + let uid = unsafe { libc::getuid() }; + ensure!( + map.split_whitespace() + .take(2) + .all(|id| id == uid.to_string()), + "uid not mapped to itself: {map:?}" + ); + patchbay::check_caps()?; + let lab = patchbay::Lab::new().await?; + let dc = lab.add_router("dc").build().await?; + let dev = lab.add_device("dev").uplink(dc.id()).build().await?; + ensure!(dev.ip().is_some(), "device has no ip"); + Ok(()) +} + +/// Returns whether `/etc/subuid` has an entry for the current user. +fn has_subuid_entry() -> bool { + // SAFETY: getuid has no preconditions. + let uid = unsafe { libc::getuid() }.to_string(); + let user = std::env::var("USER").unwrap_or_default(); + std::fs::read_to_string("/etc/subuid").is_ok_and(|subuid| { + subuid.lines().any(|line| { + let login = line.split(':').next().unwrap_or_default(); + login == uid || (!user.is_empty() && login == user) + }) + }) +} diff --git a/patchbay/tests/userns_keep_uid.rs b/patchbay/tests/userns_keep_uid.rs deleted file mode 100644 index 8c13c24..0000000 --- a/patchbay/tests/userns_keep_uid.rs +++ /dev/null @@ -1,79 +0,0 @@ -//! Tests a lab after [`patchbay::init_userns_keep_uid`]. - -use std::net::{IpAddr, SocketAddr}; - -use anyhow::{ensure, Context, Result}; -use patchbay::{IfaceConfig, Lab, LinkCondition, LinkDirection, Nat}; -use tokio::io::{AsyncReadExt, AsyncWriteExt}; - -#[ctor::ctor(unsafe)] -fn init() { - patchbay::init_userns_keep_uid().expect("user namespace"); -} - -/// The uid inside the namespace is the uid outside it. -#[test] -fn uid_maps_to_itself() -> Result<()> { - let map = std::fs::read_to_string("/proc/self/uid_map")?; - let fields: Vec<&str> = map.split_whitespace().collect(); - ensure!(fields.len() == 3, "unexpected uid_map: {map:?}"); - ensure!(fields[0] == fields[1], "uid not mapped to itself: {map:?}"); - // SAFETY: getuid has no preconditions. - let uid = unsafe { libc::getuid() }; - ensure!(fields[0] == uid.to_string(), "getuid {uid} != {map:?}"); - Ok(()) -} - -/// NAT, link conditions, low ports and a spawned `ping` work without uid 0. -#[tokio::test(flavor = "current_thread")] -async fn lab_works_without_root() -> Result<()> { - patchbay::check_caps()?; - let lab = Lab::new().await?; - let dc = lab.add_router("dc").build().await?; - let home = lab.add_router("home").nat(Nat::Moderate).build().await?; - let server = lab - .add_device("server") - .iface("eth0", dc.id()) - .build() - .await?; - let client = lab - .add_device("client") - .iface( - "eth0", - IfaceConfig::routed(home.id()) - .condition(LinkCondition::mobile_4g(), LinkDirection::Egress), - ) - .build() - .await?; - - let server_ip = server.ip().context("no server ip")?; - // A port below 1024 needs CAP_NET_BIND_SERVICE in the namespace. - let addr = SocketAddr::new(IpAddr::V4(server_ip), 80); - let listener = server - .spawn(move |_| async move { tokio::net::TcpListener::bind(addr).await })? - .await??; - server.spawn(move |_| async move { - let (mut stream, _) = listener.accept().await?; - let mut buf = vec![0u8; 64]; - let n = stream.read(&mut buf).await?; - stream.write_all(&buf[..n]).await?; - anyhow::Ok(()) - })?; - let echoed = client - .spawn(move |_| async move { - let mut stream = tokio::net::TcpStream::connect(addr).await?; - stream.write_all(b"hello").await?; - let mut buf = vec![0u8; 64]; - let n = stream.read(&mut buf).await?; - anyhow::Ok(buf[..n].to_vec()) - })? - .await??; - ensure!(echoed == b"hello", "unexpected echo: {echoed:?}"); - - // `ping` runs as a child process, which keeps only the ambient capabilities. - let mut cmd = tokio::process::Command::new("ping"); - cmd.args(["-c", "1", "-W", "2", &server_ip.to_string()]); - let status = client.spawn_command(cmd)?.wait().await?; - ensure!(status.success(), "ping failed: {status}"); - Ok(()) -}