cant-launch 0.0.18

Sandbox setup (Landlock, seccomp) and exec for Cantainer capsules.
Documentation
//! Can this system make a user + network namespace? (Phase 6.2; docs/NETWORK-ALLOWLIST.md
//! ยง10.) Host allowlists need one: the can gets a network with only `lo`, and a filtering
//! proxy outside is its only way out (Phase 6.4). Until then this only *reports*: `cant check`
//! and `--explain` say whether host enforcement will be possible here, and if not, the step
//! that failed and the fix.
//!
//! [`enter`] changes the calling process for good, so it runs in a short-lived child (`cant
//! __probe-netns`). [`facts`] and [`hint`] are plain functions of what `/proc` says.

use std::fmt;

/// A step of entering the namespace, in order.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Step {
    Unshare,
    Setgroups,
    UidMap,
    GidMap,
}

impl Step {
    /// The short code `cant __probe-netns` prints.
    pub fn code(self) -> &'static str {
        match self {
            Step::Unshare => "unshare",
            Step::Setgroups => "setgroups",
            Step::UidMap => "uid_map",
            Step::GidMap => "gid_map",
        }
    }

    /// The step with this [`Step::code`].
    pub fn from_code(code: &str) -> Option<Step> {
        [Step::Unshare, Step::Setgroups, Step::UidMap, Step::GidMap]
            .into_iter()
            .find(|s| s.code() == code)
    }
}

impl fmt::Display for Step {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Step::Unshare => "unshare(CLONE_NEWUSER|CLONE_NEWNET)",
            Step::Setgroups => "writing /proc/self/setgroups",
            Step::UidMap => "writing /proc/self/uid_map",
            Step::GidMap => "writing /proc/self/gid_map",
        })
    }
}

/// The step that failed, and its errno.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Failure {
    pub step: Step,
    pub errno: i32,
}

impl fmt::Display for Failure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let e = std::io::Error::from_raw_os_error(self.errno);
        write!(f, "{}: {e}", self.step)
    }
}

/// What explains a failure: the sysctls that turn user namespaces off, Ubuntu's AppArmor
/// restriction, and whether this looks like a container.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Facts {
    /// `kernel.apparmor_restrict_unprivileged_userns` (Ubuntu 24.04+).
    pub apparmor_restrict: Option<u32>,
    /// `user.max_user_namespaces`.
    pub max_user_namespaces: Option<u64>,
    /// `kernel.unprivileged_userns_clone` (Debian's patch).
    pub unprivileged_userns_clone: Option<u32>,
    /// `/proc/self/attr/apparmor/current`, e.g. `docker-default (enforce)`.
    pub apparmor_label: Option<String>,
    /// `/.dockerenv`, `/run/.containerenv`, `$container`, or a container AppArmor label.
    pub in_container: bool,
}

/// Reads [`Facts`] from `/proc` and the root directory.
pub fn facts() -> Facts {
    let read = |p: &str| {
        std::fs::read_to_string(p)
            .ok()
            .map(|s| s.trim().to_string())
    };
    let label = read("/proc/self/attr/apparmor/current");
    let in_container = std::path::Path::new("/.dockerenv").exists()
        || std::path::Path::new("/run/.containerenv").exists()
        || std::env::var_os("container").is_some()
        || label.as_deref().is_some_and(|l| {
            l.starts_with("docker-default") || l.starts_with("containers-default")
        });
    Facts {
        apparmor_restrict: read("/proc/sys/kernel/apparmor_restrict_unprivileged_userns")
            .and_then(|s| s.parse().ok()),
        max_user_namespaces: read("/proc/sys/user/max_user_namespaces")
            .and_then(|s| s.parse().ok()),
        unprivileged_userns_clone: read("/proc/sys/kernel/unprivileged_userns_clone")
            .and_then(|s| s.parse().ok()),
        apparmor_label: label,
        in_container,
    }
}

/// Why the namespace can't be made here and what would fix it, in a sentence.
pub fn hint(f: &Failure, facts: &Facts) -> String {
    const EPERM: i32 = 1;
    const EACCES: i32 = 13;
    if facts.max_user_namespaces == Some(0) {
        return "user namespaces are turned off (user.max_user_namespaces = 0)".into();
    }
    if facts.unprivileged_userns_clone == Some(0) {
        return "unprivileged user namespaces are turned off \
                (kernel.unprivileged_userns_clone = 0)"
            .into();
    }
    match (f.step, f.errno) {
        (Step::Unshare, EPERM) if facts.in_container => "this container's seccomp profile \
             refuses user namespaces; start it with `--security-opt \
             seccomp=cant-seccomp.json` (in Cantainer's release files), not with \
             `apparmor=unconfined`, `seccomp=unconfined` or `--privileged`"
            .into(),
        (Step::Setgroups, EACCES) if facts.apparmor_restrict == Some(1) => "Ubuntu's AppArmor \
             restricts user namespaces for programs without a profile \
             (kernel.apparmor_restrict_unprivileged_userns = 1); Cantainer's .deb will \
             install one for /usr/bin/cant"
            .into(),
        _ => "user namespaces aren't available to this user here".into(),
    }
}

/// Enters a new user + network namespace and maps this user to itself: the steps that fail
/// where namespaces are restricted. Changes the calling process for good, and must run while
/// it has a single thread (`cant __probe-netns` calls it first thing).
#[cfg(target_os = "linux")]
pub fn enter() -> Result<(), Failure> {
    use rustix::thread::UnshareFlags;
    let uid = rustix::process::getuid().as_raw();
    let gid = rustix::process::getgid().as_raw();
    let fail = |step| {
        move |e: std::io::Error| Failure {
            step,
            errno: e.raw_os_error().unwrap_or(0),
        }
    };
    // rustix deprecates the safe `unshare` in favour of an `unsafe` one, because unsharing in a
    // process with several threads leaves them in different namespaces. This process has one
    // thread, and the crates forbid `unsafe`.
    #[allow(deprecated)]
    rustix::thread::unshare(UnshareFlags::NEWUSER | UnshareFlags::NEWNET)
        .map_err(std::io::Error::from)
        .map_err(fail(Step::Unshare))?;
    std::fs::write("/proc/self/setgroups", "deny").map_err(fail(Step::Setgroups))?;
    std::fs::write("/proc/self/uid_map", format!("{uid} {uid} 1")).map_err(fail(Step::UidMap))?;
    std::fs::write("/proc/self/gid_map", format!("{gid} {gid} 1")).map_err(fail(Step::GidMap))?;
    Ok(())
}

/// Not Linux: no namespaces.
#[cfg(not(target_os = "linux"))]
pub fn enter() -> Result<(), Failure> {
    Err(Failure {
        step: Step::Unshare,
        errno: 38, // ENOSYS
    })
}

/// The line `cant __probe-netns` prints for a result.
pub fn report(result: &Result<(), Failure>) -> String {
    match result {
        Ok(()) => "ok".into(),
        Err(f) => format!("failed {} {}", f.step.code(), f.errno),
    }
}

/// Reads a [`report`] line back; anything else is `None`.
pub fn parse_report(line: &str) -> Option<Result<(), Failure>> {
    let line = line.trim();
    if line == "ok" {
        return Some(Ok(()));
    }
    let mut w = line.strip_prefix("failed ")?.split(' ');
    let step = Step::from_code(w.next()?)?;
    let errno = w.next()?.parse().ok()?;
    w.next().is_none().then_some(Err(Failure { step, errno }))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn reports_round_trip() {
        for r in [
            Ok(()),
            Err(Failure {
                step: Step::Unshare,
                errno: 1,
            }),
            Err(Failure {
                step: Step::Setgroups,
                errno: 13,
            }),
            Err(Failure {
                step: Step::UidMap,
                errno: 1,
            }),
            Err(Failure {
                step: Step::GidMap,
                errno: 22,
            }),
        ] {
            assert_eq!(parse_report(&report(&r)), Some(r));
        }
        for junk in [
            "",
            "OK",
            "failed",
            "failed unshare",
            "failed mount 1",
            "failed unshare x",
            "failed unshare 1 2",
        ] {
            assert_eq!(parse_report(junk), None, "{junk}");
        }
        assert_eq!(Step::from_code("nope"), None);
    }

    #[test]
    fn hints_name_the_cause_and_the_fix() {
        let f = |step, errno| Failure { step, errno };
        let ubuntu = Facts {
            apparmor_restrict: Some(1),
            max_user_namespaces: Some(64279),
            apparmor_label: Some("unconfined".into()),
            ..Facts::default()
        };
        assert!(hint(&f(Step::Setgroups, 13), &ubuntu).contains("Ubuntu's AppArmor"));
        let docker = Facts {
            apparmor_label: Some("docker-default (enforce)".into()),
            in_container: true,
            ..Facts::default()
        };
        let h = hint(&f(Step::Unshare, 1), &docker);
        assert!(
            h.contains("seccomp=cant-seccomp.json") && h.contains("not with"),
            "{h}"
        );
        let off = Facts {
            max_user_namespaces: Some(0),
            ..Facts::default()
        };
        assert!(hint(&f(Step::Unshare, 28), &off).contains("max_user_namespaces = 0"));
        let debian = Facts {
            unprivileged_userns_clone: Some(0),
            ..Facts::default()
        };
        assert!(hint(&f(Step::Unshare, 1), &debian).contains("unprivileged_userns_clone = 0"));
        // The same errno without the explaining fact: the plain sentence.
        assert!(hint(&f(Step::Setgroups, 13), &Facts::default()).contains("aren't available"));
        assert!(hint(&f(Step::Unshare, 1), &Facts::default()).contains("aren't available"));
        assert_eq!(
            f(Step::Setgroups, 13).to_string(),
            format!(
                "writing /proc/self/setgroups: {}",
                std::io::Error::from_raw_os_error(13)
            )
        );
        for s in [Step::Unshare, Step::UidMap, Step::GidMap] {
            assert!(!s.to_string().is_empty());
        }
    }

    #[test]
    fn facts_read_without_failing() {
        let f = facts();
        // Whatever this machine is, the label (when there is one) has no newline.
        assert!(
            f.apparmor_label
                .as_deref()
                .is_none_or(|l| !l.contains('\n'))
        );
    }
}