cant-launch 0.0.20

Sandbox setup (Landlock, seccomp) and exec for Cantainer capsules.
Documentation
//! Sandbox setup and exec for Cantainer.
//!
//! [`plan`] completes a policy with what the executable needs to start (its ELF interpreter,
//! shared libraries and a small runtime base), filters the environment and builds argv.
//! [`exec`] then makes the kernel enforce the plan and replaces the current process with the
//! program:
//!
//! 1. create writable command-line files that do not exist yet (so they have an inode),
//! 2. Landlock: deny by default, allow each grant (also sets `no_new_privs`),
//! 3. seccomp: baseline deny list plus the socket families the policy does not allow,
//! 4. `execve`.
//!
//! There is no supervisor process: exit status, signals and the terminal belong to the
//! program, exactly as if it had been run directly. Restrictions are inherited by everything
//! it starts and cannot be lifted.
//!
//! Linux only. On other systems every entry point returns [`LaunchError::Unsupported`], so the
//! workspace still builds on macOS for editing.

// No unsafe code, except in coverage builds (`cargo llvm-cov` sets `cfg(coverage)`): there,
// `flush_coverage` calls the profiler runtime. Shipped and normal builds forbid unsafe code.
#![cfg_attr(not(coverage), forbid(unsafe_code))]
#![cfg_attr(coverage, deny(unsafe_code))]

use std::ffi::OsString;
use std::path::PathBuf;

use cant_policy::Policy;

#[cfg(target_os = "linux")]
mod linux;

pub mod netns;

#[cfg(target_os = "linux")]
pub use linux::elf::{
    ElfError, Resolved, in_merged_usr, resolve as resolve_libraries,
    resolve_in as resolve_libraries_in,
};
#[cfg(target_os = "linux")]
pub use linux::landlock::MIN_ABI;

/// Name of the environment variable carrying the effective policy into a cant, so that a
/// nested `cant` can explain and pre-check attenuation. It is informational: the kernel
/// enforces the real restrictions, and a forged value cannot widen them.
pub const POLICY_ENV: &str = "CANT_POLICY";

/// Files every program may need to read: the loader cache, locale, time zone, terminfo, the CA
/// trust store and a few devices.
pub const RUNTIME_READ: &[&str] = &[
    "/etc/ld.so.cache",
    "/etc/ld.so.preload",
    "/etc/localtime",
    "/usr/share/zoneinfo",
    "/usr/lib/locale",
    "/usr/share/locale",
    "/etc/locale.alias",
    "/usr/share/terminfo",
    "/usr/lib/terminfo",
    "/lib/terminfo",
    "/etc/terminfo",
    // The host's public CA trust store, for TLS (Debian/Ubuntu, Fedora/RHEL, Alpine, openSUSE).
    // Only these: never `/etc/ssl` or `/etc/pki` as a whole, which hold `private/` key
    // directories. Symlinked entries resolve into the directories listed after them.
    "/etc/ssl/certs",
    "/etc/ssl/cert.pem",
    "/etc/ssl/ca-bundle.pem",
    "/etc/pki/tls/certs",
    "/etc/pki/ca-trust/extracted",
    "/usr/share/ca-certificates",
    "/var/lib/ca-certificates",
    "/dev/zero",
    "/dev/urandom",
    "/dev/random",
];

/// What name resolution reads, granted (read-only) to every cant with `network = true`:
/// without them a program may reach the network but can't look up a host name. They hold no
/// secrets. A symlinked `/etc/resolv.conf` (systemd-resolved) resolves to its target.
pub const NETWORK_READ: &[&str] = &[
    "/etc/resolv.conf",
    "/etc/hosts",
    "/etc/nsswitch.conf",
    "/etc/host.conf",
    "/etc/gai.conf",
];

/// Devices every program may read and write.
pub const RUNTIME_READ_WRITE: &[&str] = &["/dev/null", "/dev/full", "/dev/tty"];

/// The system's dynamic loaders. A cant that may execute files in a directory (cargo's build
/// scripts in `$CWD`) gets these, because the kernel needs execute access to a program's
/// loader to start it, and `cant` can't know in advance which files will run. Programs whose
/// libraries `cant` resolves get their own loader anyway.
pub const DYNAMIC_LOADERS: &[&str] = &[
    "/lib64/ld-linux-x86-64.so.2",
    "/lib/ld-linux-aarch64.so.1",
    "/lib/ld-linux-riscv64-lp64d.so.1",
    "/lib/ld-musl-x86_64.so.1",
    "/lib/ld-musl-aarch64.so.1",
    "/lib/ld-musl-riscv64.so.1",
];

/// How to start a can's program: through the can's own ELF loader, with the can's own
/// libraries, and nothing resolved from the host.
#[derive(Debug, Clone, Default)]
pub struct CanStart {
    /// The bundled loader (`<root>/lib64/ld-linux-x86-64.so.2`); `None` for a static program.
    pub loader: Option<PathBuf>,
    /// Directories searched for shared libraries, in order.
    pub library_path: Vec<PathBuf>,
}

/// Everything needed to start a cant.
#[derive(Debug, Clone)]
pub struct Plan {
    /// Cant name, for messages.
    pub cant: String,
    /// Canonical path of the executable.
    pub program: PathBuf,
    /// The program the cant is about: `program` itself, except for a can, where `program` is
    /// the can's bundled loader and this is the program it starts.
    pub entrypoint: PathBuf,
    /// `argv[0]` (the program's name as found, e.g. `vim` for `/usr/bin/vim.basic`).
    pub argv0: OsString,
    /// Arguments after `argv[0]`: the manifest's fixed arguments, then the user's.
    pub args: Vec<OsString>,
    /// The complete environment of the program.
    pub env: Vec<(OsString, OsString)>,
    /// The policy to enforce (this cant's own layer).
    pub policy: Policy,
    /// The policy in effect after attenuation by an enclosing cant (equal to `policy` when
    /// `cant` is not itself running inside a cant).
    pub effective: Policy,
    /// Whether an enclosing cant's policy was found.
    pub nested: bool,
    /// Shared libraries that could not be found (the loader will report them if needed).
    pub missing_libs: Vec<String>,
    /// The loopback port of the proxy, when the cant runs in its own network namespace with an
    /// allow list (see [`Plan::use_proxy`]).
    pub netns_proxy: Option<u16>,
}

/// The environment a program behind the namespace's proxy gets, whatever `[env] pass` says
/// (docs/NETWORK-ALLOWLIST.md §10.3: Go and Python read the upper- or lowercase variables;
/// Node's `fetch` needs `NODE_USE_ENV_PROXY`).
pub fn proxy_environment(port: u16) -> Vec<(OsString, OsString)> {
    let url = format!("http://127.0.0.1:{port}");
    let local = "localhost,127.0.0.1,::1";
    [
        ("HTTPS_PROXY", url.as_str()),
        ("https_proxy", url.as_str()),
        ("HTTP_PROXY", url.as_str()),
        ("http_proxy", url.as_str()),
        ("NO_PROXY", local),
        ("no_proxy", local),
        ("NODE_USE_ENV_PROXY", "1"),
    ]
    .into_iter()
    .map(|(k, v)| (k.into(), v.into()))
    .collect()
}

impl Plan {
    /// Runs the program behind the proxy listening on `port` inside its network namespace:
    /// sets [`proxy_environment`] (replacing the user's values), and Landlock will allow TCP
    /// connects to that port only.
    pub fn use_proxy(&mut self, port: u16) {
        let vars = proxy_environment(port);
        self.env
            .retain(|(k, _)| !vars.iter().any(|(name, _)| name == k));
        self.env.extend(vars);
        self.netns_proxy = Some(port);
    }
}

/// Errors from planning or launching.
#[derive(Debug, thiserror::Error)]
pub enum LaunchError {
    /// Not running on Linux.
    #[error("cants run on Linux only (this is {})", std::env::consts::OS)]
    Unsupported,
    /// The CPU architecture has no seccomp support in this build.
    #[error("unsupported CPU architecture {0}")]
    UnsupportedArch(&'static str),
    /// The executable could not be analysed.
    #[cfg(target_os = "linux")]
    #[error(transparent)]
    Elf(#[from] ElfError),
    /// A can's library directories can't be passed to its loader.
    #[error("the can's library directories can't be passed to its loader: {0}")]
    CanLibraryPath(String),
    /// Landlock is not available.
    #[error(
        "Landlock is not available on this kernel, so cants cannot be sandboxed; refusing to run (see `cant check`)"
    )]
    LandlockUnavailable,
    /// Landlock is too old to enforce the policy faithfully.
    #[error(
        "this kernel's Landlock ABI is {abi}; at least 3 (Linux 6.2) is required; refusing to run"
    )]
    LandlockTooOld {
        /// The kernel's ABI.
        abi: i32,
    },
    /// Building or applying the Landlock ruleset failed.
    #[error("Landlock setup failed: {0}")]
    Landlock(String),
    /// Building or applying a seccomp filter failed.
    #[error("seccomp setup failed: {0}")]
    Seccomp(String),
    /// A writable command-line file could not be created.
    #[error("cannot create {path}: {source}")]
    Create {
        /// The file.
        path: PathBuf,
        /// Cause.
        source: std::io::Error,
    },
    /// Running inside another cant that may not run this cant's program.
    #[error(
        "{cant} isn't available here: the enclosing cant may not run {shown} \
         (list `{cant}` in its capabilities.cants)"
    )]
    ParentCannotRun {
        /// Cant name.
        cant: String,
        /// The program, for display.
        shown: String,
    },
    /// The enclosing cant does not allow a file named on the command line.
    #[error("{cant} can't {verb} {shown} (not granted by the enclosing cant)")]
    ParentDenies {
        /// Cant name.
        cant: String,
        /// "read", "write" or "execute".
        verb: &'static str,
        /// The path, for display.
        shown: String,
    },
    /// The enclosing cant's policy (in `CANT_POLICY`) is malformed.
    #[error("malformed {POLICY_ENV}: {0}")]
    ParentPolicy(String),
    /// `execve` failed.
    #[error("cannot execute {program}: {source}")]
    Exec {
        /// The program.
        program: PathBuf,
        /// Cause.
        source: std::io::Error,
    },
}

/// Facts about the running kernel, for `cant check`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KernelSupport {
    /// Landlock ABI, if Landlock is available.
    pub landlock_abi: Option<i32>,
    /// Whether this build can install seccomp filters on this architecture.
    pub seccomp_arch: bool,
}

/// Completes `built` into a launch plan.
///
/// `parent` is the policy of an enclosing cant (from [`POLICY_ENV`]), if any.
#[cfg(target_os = "linux")]
pub fn plan(
    manifest: &cant_manifest::Manifest,
    built: cant_policy::Built,
    user_args: &[OsString],
    parent: Option<&Policy>,
    home: &std::path::Path,
    can: Option<&CanStart>,
) -> Result<Plan, LaunchError> {
    linux::plan(manifest, built, user_args, parent, home, can)
}

/// Completes `built` into a launch plan (unsupported on this OS).
#[cfg(not(target_os = "linux"))]
pub fn plan(
    _manifest: &cant_manifest::Manifest,
    _built: cant_policy::Built,
    _user_args: &[OsString],
    _parent: Option<&Policy>,
    _home: &std::path::Path,
    _can: Option<&CanStart>,
) -> Result<Plan, LaunchError> {
    Err(LaunchError::Unsupported)
}

/// Enforces `plan` and replaces the current process with the program.
/// Returns only on failure. `warn` receives non-fatal notices (printed by the CLI).
#[cfg(target_os = "linux")]
pub fn exec(plan: Plan, warn: &mut dyn FnMut(&str)) -> LaunchError {
    linux::exec(plan, warn)
}

/// Enforces `plan` and replaces the current process (unsupported on this OS).
#[cfg(not(target_os = "linux"))]
pub fn exec(_plan: Plan, _warn: &mut dyn FnMut(&str)) -> LaunchError {
    LaunchError::Unsupported
}

/// Probes kernel support. On Linux this applies a no-op Landlock ruleset to the calling
/// process (the only way to learn the ABI through the `landlock` crate), so call it only
/// from a process that is about to exit, such as `cant check`.
#[cfg(target_os = "linux")]
pub fn probe_kernel() -> KernelSupport {
    KernelSupport {
        landlock_abi: linux::landlock::probe_abi(),
        seccomp_arch: cfg!(any(
            target_arch = "x86_64",
            target_arch = "aarch64",
            target_arch = "riscv64"
        )),
    }
}

/// Probes kernel support (nothing is supported on this OS).
#[cfg(not(target_os = "linux"))]
pub fn probe_kernel() -> KernelSupport {
    KernelSupport {
        landlock_abi: None,
        seccomp_arch: false,
    }
}

/// Writes this process's coverage profile now. Only in coverage builds (`cargo llvm-cov`);
/// elsewhere it does nothing. Called right before `exec` (which replaces the process without
/// running the profiler's exit handler, so every successful `cant run` would otherwise leave no
/// coverage) and before the supervisor dies from a signal. Never compiled into shipped binaries.
#[cfg(coverage)]
#[allow(unsafe_code)]
pub fn flush_coverage() {
    unsafe extern "C" {
        fn __llvm_profile_write_file() -> i32;
    }
    // SAFETY: the profiler runtime that every coverage build links defines this function; it
    // takes no arguments and only writes the profile file named by LLVM_PROFILE_FILE.
    let _ = unsafe { __llvm_profile_write_file() };
}

/// Does nothing outside coverage builds.
#[cfg(not(coverage))]
pub fn flush_coverage() {}

/// The directory the coverage profile is written to (coverage builds only): the sandbox lets
/// `cant` write there, so that [`flush_coverage`] still works after Landlock is applied.
#[cfg(coverage)]
pub(crate) fn coverage_dir() -> Option<PathBuf> {
    let file = PathBuf::from(std::env::var_os("LLVM_PROFILE_FILE")?);
    file.parent().map(std::path::Path::to_path_buf)
}

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

    #[test]
    fn the_proxy_environment_replaces_the_users() {
        let mut plan = Plan {
            cant: "x".into(),
            program: PathBuf::from("/bin/x"),
            entrypoint: PathBuf::from("/bin/x"),
            argv0: "x".into(),
            args: Vec::new(),
            env: vec![
                ("HTTPS_PROXY".into(), "http://corp:3128".into()),
                ("LANG".into(), "C".into()),
            ],
            policy: Policy::default(),
            effective: Policy::default(),
            nested: false,
            missing_libs: Vec::new(),
            netns_proxy: None,
        };
        plan.use_proxy(41000);
        assert_eq!(plan.netns_proxy, Some(41000));
        let get = |k: &str| {
            plan.env
                .iter()
                .filter(|(n, _)| n == k)
                .map(|(_, v)| v.to_string_lossy().into_owned())
                .collect::<Vec<_>>()
        };
        assert_eq!(
            get("HTTPS_PROXY"),
            ["http://127.0.0.1:41000"],
            "replaced, once"
        );
        assert_eq!(get("http_proxy"), ["http://127.0.0.1:41000"]);
        assert_eq!(get("no_proxy"), ["localhost,127.0.0.1,::1"]);
        assert_eq!(get("NODE_USE_ENV_PROXY"), ["1"]);
        assert_eq!(get("LANG"), ["C"], "the rest stays");
        assert_eq!(proxy_environment(1).len(), 7);
    }
}