cant-launch 0.0.21

Sandbox setup (Landlock, seccomp) and exec for Cantainer capsules.
Documentation
//! Mounting package-manager trees read-only in the cant's own mount namespace (see
//! [`crate::readonly`]). Runs before Landlock and seccomp: a Landlock-restricted process may not
//! change its mounts, and the seccomp filter keeps the program from undoing them.

use std::path::{Path, PathBuf};

use rustix::fs::StatVfsMountFlags;
use rustix::mount::{MountFlags, MountPropagationFlags};

use crate::netns::{Failure, Step};
use crate::readonly::WRITABLE_CACHES;

fn failed(step: Step) -> impl Fn(rustix::io::Errno) -> Failure {
    move |e| Failure {
        step,
        errno: e.raw_os_error(),
    }
}

/// Enters a mount namespace (a new user namespace too, unless `in_userns`: the allow-list
/// child is already in its own), keeps its mounts from propagating back, and mounts each of
/// `trees` read-only, with its writable caches on top. Changes the calling process for good;
/// with `!in_userns` it must still have a single thread.
pub fn lock(trees: &[PathBuf], in_userns: bool) -> Result<(), Failure> {
    if in_userns {
        // Already privileged in its own user namespace; a mount namespace alone.
        #[allow(deprecated)] // single-threaded here, see netns::enter
        rustix::thread::unshare(rustix::thread::UnshareFlags::NEWNS)
            .map_err(failed(Step::Unshare))?;
    } else {
        crate::netns::enter_for_mounts()?;
    }
    rustix::mount::mount_change(
        "/",
        MountPropagationFlags::PRIVATE | MountPropagationFlags::REC,
    )
    .map_err(failed(Step::Mount))?;
    for tree in trees {
        read_only(tree)?;
    }
    Ok(())
}

/// `tree` read-only (a bind mount of itself, remounted), keeping the flags its mount already
/// has: inside a user namespace, `nosuid`, `nodev`, `noexec` and the atime flags of the mount
/// it came from are locked and a remount that drops them is refused.
fn read_only(tree: &Path) -> Result<(), Failure> {
    let caches: Vec<PathBuf> = if tree.file_name().is_some_and(|n| n == "node_modules") {
        // `.cache` is created first, while the tree can still be written.
        let _ = std::fs::create_dir(tree.join(".cache"));
        WRITABLE_CACHES
            .iter()
            .map(|c| tree.join(c))
            .filter(|c| std::fs::symlink_metadata(c).is_ok_and(|m| m.is_dir()))
            .collect()
    } else {
        Vec::new()
    };
    let kept = rustix::fs::statvfs(tree)
        .map_err(failed(Step::Mount))?
        .f_flag;
    rustix::mount::mount_bind(tree, tree).map_err(failed(Step::Mount))?;
    // The caches get mounts of their own before the tree's turns read-only: a bind mount copies
    // the flags of the mount its source is on, and read-only is a property of the mount.
    for c in caches {
        rustix::mount::mount_bind(&c, &c).map_err(failed(Step::Mount))?;
    }
    rustix::mount::mount_remount(
        tree,
        MountFlags::BIND | MountFlags::RDONLY | locked(kept),
        "",
    )
    .map_err(failed(Step::Mount))?;
    Ok(())
}

/// The mount flags of `f` that a remount must keep. A remount that names no atime flag means
/// `relatime`, so a `strictatime` mount (neither `noatime` nor `relatime`) says so.
fn locked(f: StatVfsMountFlags) -> MountFlags {
    let atime = if f.intersects(StatVfsMountFlags::NOATIME | StatVfsMountFlags::RELATIME) {
        MountFlags::empty()
    } else {
        MountFlags::STRICTATIME
    };
    atime
        | [
            (StatVfsMountFlags::NOSUID, MountFlags::NOSUID),
            (StatVfsMountFlags::NODEV, MountFlags::NODEV),
            (StatVfsMountFlags::NOEXEC, MountFlags::NOEXEC),
            (StatVfsMountFlags::NOATIME, MountFlags::NOATIME),
            (StatVfsMountFlags::NODIRATIME, MountFlags::NODIRATIME),
            (StatVfsMountFlags::RELATIME, MountFlags::RELATIME),
        ]
        .into_iter()
        .filter(|(s, _)| f.contains(*s))
        .fold(MountFlags::empty(), |acc, (_, m)| acc | m)
}

/// Whether [`lock`] works here: enters the namespaces and mounts a directory read-only. Changes
/// the calling process, so it runs in a short-lived child (`cant __probe-readonly`).
pub fn probe() -> Result<(), Failure> {
    let dir = std::env::temp_dir();
    lock(&[], false)?;
    read_only(&dir)
}

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

    #[test]
    fn a_missing_tree_fails_before_any_mount() {
        let e = read_only(Path::new("/nonexistent/node_modules")).expect_err("no such tree");
        assert_eq!(e.step, Step::Mount);
        assert_eq!(e.errno, rustix::io::Errno::NOENT.raw_os_error());
    }

    #[test]
    fn remounts_keep_the_locked_flags() {
        assert_eq!(locked(StatVfsMountFlags::empty()), MountFlags::STRICTATIME);
        assert_eq!(
            locked(
                StatVfsMountFlags::NOSUID
                    | StatVfsMountFlags::NODEV
                    | StatVfsMountFlags::RELATIME
                    | StatVfsMountFlags::RDONLY
            ),
            MountFlags::NOSUID | MountFlags::NODEV | MountFlags::RELATIME
        );
        assert_eq!(
            locked(
                StatVfsMountFlags::NOEXEC
                    | StatVfsMountFlags::NOATIME
                    | StatVfsMountFlags::NODIRATIME
            ),
            MountFlags::NOEXEC | MountFlags::NOATIME | MountFlags::NODIRATIME
        );
    }
}