merry-process 0.1.2

Sandboxed host-process execution (Landlock/seccomp, Seatbelt, Windows Job Objects) for Merry.
Documentation
use super::SandboxLaunch;
use landlock::{
    ABI, Access, AccessFs, CompatLevel, Compatible, Ruleset, RulesetAttr, RulesetCreatedAttr,
    RulesetStatus, Scope,
};
use seccompiler::{
    SeccompAction, SeccompCmpArgLen, SeccompCmpOp, SeccompCondition, SeccompFilter, SeccompRule,
};
use std::collections::BTreeMap;

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())
}