merry-process 0.1.3

Sandboxed host-process execution (Landlock/seccomp, Seatbelt, Windows Job Objects) for Merry.
Documentation
use super::{SandboxLaunch, required_permission_review_paths};
use crate::process_runner::WorkspaceProcessEnvironment;
use crate::resolve_host_path;
use landlock::{
    ABI, Access, AccessFs, CompatLevel, Compatible, Ruleset, RulesetAttr, RulesetCreatedAttr,
    RulesetStatus, Scope,
};
use merry_runtime::{PathAccess, PathAccessRule, PathAccessRuleSource, ProcessRunnerError};
use seccompiler::{
    SeccompAction, SeccompCmpArgLen, SeccompCmpOp, SeccompCondition, SeccompFilter, SeccompRule,
};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

pub(super) fn ensure_required_paths_exist(
    cwd_root: &Path,
    environment: &WorkspaceProcessEnvironment,
    path_rules: &[PathAccessRule],
    required_rules: &[PathAccessRule],
    read_only: &[PathBuf],
    read_write: &[PathBuf],
) -> Result<(), ProcessRunnerError> {
    if required_rules.is_empty() || !cwd_root.exists() {
        return Ok(());
    }
    let required_paths = required_permission_review_paths(required_rules, read_only, read_write);
    for path in required_paths {
        if path.exists() {
            continue;
        }
        let requested_write = required_rules.iter().any(|rule| {
            rule.access() == PathAccess::ReadWrite && resolve_host_path(rule.path()) == path
        });
        let suggested_parent =
            safe_existing_parent_for_landlock(&path, environment, path_rules, requested_write);
        let message = match suggested_parent {
            Some(parent) => format!(
                "Linux Landlock cannot grant access to non-existent path `{}`; request access to its existing parent directory `{}` instead, or create the target first",
                path.display(),
                parent.display()
            ),
            None => format!(
                "Linux Landlock cannot grant access to non-existent path `{}` (grant a specific existing parent directory if safe, create the target first, or toggle Sandbox off in TUI Settings)",
                path.display()
            ),
        };
        return Err(ProcessRunnerError::infrastructure(message));
    }
    Ok(())
}

fn safe_existing_parent_for_landlock(
    target: &Path,
    environment: &WorkspaceProcessEnvironment,
    path_rules: &[PathAccessRule],
    requested_write: bool,
) -> Option<PathBuf> {
    let existing_parent = target
        .ancestors()
        .skip(1)
        .find(|ancestor| ancestor.is_dir())?;
    let resolved_parent = resolve_host_path(existing_parent);
    if is_overly_broad_landlock_parent(&resolved_parent, environment.home_path()) {
        return None;
    }
    let conflicts_with_policy = path_rules.iter().any(|rule| {
        let rule_path = resolve_host_path(rule.path());
        let is_protected = rule.access() == PathAccess::Deny
            || (requested_write
                && rule.access() == PathAccess::ReadOnly
                && matches!(
                    rule.source(),
                    PathAccessRuleSource::ProductReadOnly
                        | PathAccessRuleSource::TrustedGlobalConfig
                ));
        if !is_protected {
            return false;
        }
        resolved_parent == rule_path
            || resolved_parent.starts_with(&rule_path)
            || rule_path.starts_with(&resolved_parent)
    });
    (!conflicts_with_policy).then_some(resolved_parent)
}

fn is_overly_broad_landlock_parent(candidate: &Path, home: &Path) -> bool {
    if candidate == Path::new("/") {
        return true;
    }
    let resolved_home = resolve_host_path(home);
    let broad_roots = [
        resolved_home.clone(),
        resolved_home.join(".config"),
        resolved_home.join(".local"),
        resolved_home.join(".local/share"),
        resolved_home.join(".local/state"),
        resolved_home.join(".cache"),
    ];
    if broad_roots.iter().any(|root| candidate == root) {
        return true;
    }
    for var in [
        "XDG_CONFIG_HOME",
        "XDG_DATA_HOME",
        "XDG_STATE_HOME",
        "XDG_CACHE_HOME",
    ] {
        if let Some(value) = std::env::var_os(var)
            .map(PathBuf::from)
            .filter(|p| p.is_absolute())
            && candidate == resolve_host_path(&value)
        {
            return true;
        }
    }
    false
}

pub(super) fn probe() -> Result<(), String> {
    let ruleset = Ruleset::default()
        .handle_access(AccessFs::from_all(ABI::V1))
        .map_err(|error| error.to_string())?
        .create()
        .map_err(|error| error.to_string())?;
    drop(ruleset);
    Ok(())
}

pub(super) fn apply(launch: &SandboxLaunch) -> Result<(), String> {
    apply_landlock(launch)?;
    if !launch.network() {
        apply_network_seccomp()?;
    }
    Ok(())
}

fn apply_landlock(launch: &SandboxLaunch) -> Result<(), String> {
    for path in &launch.required_paths {
        if !std::path::Path::new(path).exists() {
            return Err(format!(
                "Linux Landlock cannot grant access to non-existent path `{path}` (grant an existing parent directory if safe, create the target first, or toggle Sandbox off in TUI Settings)"
            ));
        }
    }
    // Use ABI::V6 with BestEffort compatibility: kernels < 6.12 gracefully mask
    // down to their supported filesystem ABI, while 6.12+ also scopes out
    // cross-domain abstract Unix sockets (e.g. X11) and host signals.
    let abi = ABI::V6;
    let ruleset = Ruleset::default()
        .set_compatibility(CompatLevel::BestEffort)
        .handle_access(AccessFs::from_all(abi))
        .map_err(|error| error.to_string())?
        .scope(Scope::from_all(abi))
        .map_err(|error| error.to_string())?
        .create()
        .map_err(|error| error.to_string())?;
    // Do NOT add `launch.traverse` with `AccessFs::Execute`: Landlock never
    // requires ancestor rules for directory traversal, and granting
    // `AccessFs::Execute` on `/` would recursively allow `execve` on ELF
    // binaries anywhere on the host, including ungranted or denied directories.
    let ruleset = add_paths(ruleset, &launch.read_only, AccessFs::from_read(abi))?;
    let ruleset = add_paths(ruleset, &launch.read_write, AccessFs::from_all(abi))?;
    let status = ruleset
        .restrict_self()
        .map_err(|error| format!("Landlock restriction failed: {error}"))?;
    if status.ruleset == RulesetStatus::NotEnforced {
        return Err(
            "Landlock could not enforce the workspace sandbox. Pass --sandbox off to run without it."
                .to_owned(),
        );
    }
    Ok(())
}

fn add_paths(
    ruleset: landlock::RulesetCreated,
    paths: &[String],
    access: landlock::BitFlags<AccessFs>,
) -> Result<landlock::RulesetCreated, String> {
    ruleset
        .add_rules(landlock::path_beneath_rules(paths, access))
        .map_err(|error| format!("failed to add Landlock rules: {error}"))
}

fn apply_network_seccomp() -> Result<(), String> {
    let deny = |domain| -> Result<SeccompRule, String> {
        SeccompRule::new(vec![
            SeccompCondition::new(0, SeccompCmpArgLen::Dword, SeccompCmpOp::Eq, domain)
                .map_err(|error| error.to_string())?,
        ])
        .map_err(|error| error.to_string())
    };
    let mut rules = BTreeMap::new();
    rules.insert(
        libc::SYS_socket,
        vec![
            deny(libc::AF_INET as u64)?,
            deny(libc::AF_INET6 as u64)?,
            deny(libc::AF_PACKET as u64)?,
            deny(libc::AF_VSOCK as u64)?,
        ],
    );
    // Block `io_uring_setup` when network is denied: Linux 5.19+ supports
    // `IORING_OP_SOCKET`, which creates IP sockets inside the kernel without
    // going through `SYS_socket`.
    rules.insert(libc::SYS_io_uring_setup, vec![]);
    let arch = seccompiler::TargetArch::try_from(std::env::consts::ARCH)
        .map_err(|error| error.to_string())?;
    let filter = SeccompFilter::new(
        rules,
        SeccompAction::Allow,
        SeccompAction::Errno(libc::EPERM as u32),
        arch,
    )
    .map_err(|error| error.to_string())?;
    let program = seccompiler::BpfProgram::try_from(filter)
        .map_err(|error: seccompiler::BackendError| error.to_string())?;
    seccompiler::apply_filter(&program).map_err(|error| error.to_string())
}