cosca 0.7.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
//! Test groups: one declaration each (`docs/principles.md` ยง10).
//!
//! A group is a skuld fixture carrying three things: `requires` (the off-switch: `Err` only for
//! `<env>=0`, so an opted-out test is ignored, at list time too), a setup that fails the test
//! unless `<env>_CONSENT` is exactly `1` (system-affecting groups only), and the group's label
//! (lane selection, `SKULD_LABELS=<label>`).

/// Proof that the group is enabled (and consented to, where asked).
///
/// The `cgroup` group also carries a [`StrayLeaves`] check that runs when the test ends.
pub(crate) struct Group {
    #[allow(dead_code, reason = "held only for its Drop")]
    stray_leaves: Option<StrayLeaves>,
}

impl Group {
    pub(crate) fn plain() -> Group {
        Group { stray_leaves: None }
    }

    /// This group, plus a check at the end of the test that it left no cosca cgroup leaf behind.
    #[allow(dead_code, reason = "a root that includes this file may have no test in the group")]
    pub(crate) fn watching_leaves(self) -> Group {
        Group {
            stray_leaves: Some(StrayLeaves::new()),
        }
    }
}

/// Fails the test with `message`, or only prints it while the test is already failing: a second panic during unwinding
/// aborts the test binary.
#[allow(
    dead_code,
    reason = "the lib uses it on Linux only; every integration root includes it"
)]
pub fn fail_unless_panicking(message: String) {
    if std::thread::panicking() {
        eprintln!("{message}");
    } else {
        panic!("{message}");
    }
}

/// Removes the cosca cgroup leaves a test made and did not remove, then fails the test. A leaf is named
/// `cosca-<pid>-<n>-<random>` in this process's own cgroup, and a test process is one test (nextest), so at the end
/// of the test every leaf of this pid is that test's. Each is killed, drained and removed with its child cgroups
/// ([`cgroup_leaf::remove_tree`]). While the test is already panicking it only prints them.
///
/// It never disables itself: a cgroup that cannot be determined or listed fails the test.
pub(crate) struct StrayLeaves {
    #[cfg_attr(not(target_os = "linux"), allow(dead_code, reason = "only the Linux drop reads it"))]
    pub(crate) own_cgroup: std::path::PathBuf,
}

impl StrayLeaves {
    #[cfg(target_os = "linux")]
    fn new() -> StrayLeaves {
        StrayLeaves::of(cgroup_leaf::own_cgroup())
    }

    /// The check for `own_cgroup`; its absence is a failure, not a reason to watch nothing.
    #[cfg(target_os = "linux")]
    pub(crate) fn of(own_cgroup: Result<std::path::PathBuf, String>) -> StrayLeaves {
        match own_cgroup {
            Ok(own_cgroup) => StrayLeaves { own_cgroup },
            Err(why) => panic!("the cgroup group needs cgroup v2, and {why}"),
        }
    }

    #[cfg(not(target_os = "linux"))]
    fn new() -> StrayLeaves {
        panic!("the cgroup group is Linux-only: there are no cgroup leaves to watch here");
    }
}

#[cfg(target_os = "linux")]
impl Drop for StrayLeaves {
    fn drop(&mut self) {
        let dir = &self.own_cgroup;
        let prefix = format!("cosca-{}-", std::process::id());
        let entries = match std::fs::read_dir(dir) {
            Ok(entries) => entries,
            Err(e) => return fail_unless_panicking(format!("cannot list the own cgroup {}: {e}", dir.display())),
        };
        let mut left = Vec::new();
        let mut failures = Vec::new();
        for entry in entries {
            match entry {
                Ok(entry) if entry.file_name().to_string_lossy().starts_with(&prefix) => left.push(entry.path()),
                Ok(_) => {}
                Err(e) => failures.push(format!("list {}: {e}", dir.display())),
            }
        }
        for leaf in &left {
            if let Err(why) = cgroup_leaf::remove_tree(leaf) {
                failures.push(format!("remove {}: {why}", leaf.display()));
            }
        }
        if left.is_empty() && failures.is_empty() {
            return;
        }
        let test = std::thread::current().name().unwrap_or("?").to_owned();
        let mut message = format!("{test} left cgroup leaves behind in {}: {left:?}", dir.display());
        if !failures.is_empty() {
            message.push_str(&format!("; could not clean up: {failures:?}"));
        }
        fail_unless_panicking(message);
    }
}

// The cgroup helpers shared with the integration tests and the lib's tokio front tests, compiled from their real source.
#[cfg(target_os = "linux")]
#[path = "../tests/common/cgroup.rs"]
#[allow(dead_code, reason = "each root that includes this file uses a subset of the helpers")]
pub mod cgroup_leaf;

/// The rule behind every group: `Ok(false)` for `enabled_var=0`; `Err` naming the consent
/// variable for an enabled group without exactly `<enabled_var>_CONSENT=1`.
pub(crate) fn check_group(enabled_var: &str, var: impl Fn(&str) -> Option<String>) -> Result<bool, String> {
    let consent = format!("{enabled_var}_CONSENT");
    if require_enabled(enabled_var, &var).is_err() {
        return Ok(false);
    }
    if var(&consent).as_deref() != Some("1") {
        return Err(format!(
            "tests under {enabled_var} touch real system state and run only in a sandbox (a container, VM or \
             CI); set {consent}=1 there to consent, or {enabled_var}=0 to turn the group off"
        ));
    }
    Ok(true)
}

/// A group's `requires`: `Err` only when `enabled_var` is `0`.
pub(crate) fn require_enabled(enabled_var: &str, var: impl Fn(&str) -> Option<String>) -> Result<(), String> {
    if var(enabled_var).as_deref() == Some("0") {
        return Err(format!("{enabled_var}=0"));
    }
    Ok(())
}

/// A consent-asking group's setup: [`check_group`]'s rule, where `what` says what the group does.
pub(crate) fn require_consent(
    enabled_var: &str,
    what: &str,
    var: impl Fn(&str) -> Option<String>,
) -> Result<Group, String> {
    match check_group(enabled_var, var) {
        Ok(true) => Ok(Group::plain()),
        // skuld runs the body of a test whose `requires` failed when ignored tests are included
        // (`--run-ignored only`), so a group that is off refuses here as well.
        Ok(false) => Err(format!("{enabled_var}=0")),
        Err(why) => Err(format!("the group {what}: {why}")),
    }
}

/// Declares a test group: the fixture `$fixture`, labelled `$label` (declared in
/// `test_harness.rs`), switched off by `env = "<NAME>"` set to `0`. With `consent = "<what the
/// group does>"` its setup also fails the test unless `<NAME>_CONSENT` is exactly `1`. With
/// `precondition = <fn>` it fails the test with the `Err` of `<fn>(<NAME>)`, which names what the
/// host lacks and the opt-out.
///
/// A test file brings the fixture into scope with `use crate::test_groups::{$fixture, Group};`.
macro_rules! test_group {
    ($label:ident => $fixture:ident, env = $env:literal, consent = $what:literal, watching_leaves) => {
        test_group!(@declare $label, $fixture, $env,
            require_consent($env, $what, |name| std::env::var(name).ok()).map(Group::watching_leaves));
    };
    ($label:ident => $fixture:ident, env = $env:literal, consent = $what:literal) => {
        test_group!(@declare $label, $fixture, $env, require_consent($env, $what, |name| std::env::var(name).ok()));
    };
    ($label:ident => $fixture:ident, env = $env:literal, precondition = $check:path) => {
        test_group!(@declare $label, $fixture, $env,
            require_enabled($env, |name| std::env::var(name).ok()).and_then(|()| $check($env)).map(|()| Group::plain()));
    };
    ($label:ident => $fixture:ident, env = $env:literal) => {
        test_group!(@declare $label, $fixture, $env, require_enabled($env, |name| std::env::var(name).ok()).map(|()| Group::plain()));
    };
    (@declare $label:ident, $fixture:ident, $env:literal, $setup:expr) => {
        mod $fixture {
            #[allow(dead_code, reason = "a root that includes this file may have no test in the group")]
            pub(super) fn enabled() -> Result<(), String> {
                super::require_enabled($env, |name| std::env::var(name).ok())
            }
        }

        #[allow(dead_code, reason = "a root that includes this file may have no test in the group")]
        #[skuld::fixture(requires = [$fixture::enabled], labels = [crate::test_harness::$label])]
        pub(crate) fn $fixture() -> Result<Group, String> {
            $setup
        }
    };
}

test_group!(ROOT => root, env = "COSCA_TEST_ROOT", consent = "runs as root, for a DAC bypass");
test_group!(NAMESPACES => namespaces, env = "COSCA_TEST_NAMESPACES", consent = "unshares namespaces and mounts");
test_group!(DRIVE_MAPPING => drive_mapping, env = "COSCA_TEST_DRIVE_MAPPING", consent = "maps a drive letter for the whole logon session");
test_group!(SETUID => setuid, env = "COSCA_TEST_SETUID", consent = "runs a setuid-root copy of cosca_testbin");
test_group!(PATH_PROBES => path_probes, env = "COSCA_TEST_PATH_PROBES", consent = "launches copies of cosca_testbin_image, creates a suspended process, makes a directory of its own under the Microsoft folder in %LOCALAPPDATA% and plants a file symlink in it, makes symlinks, junctions and app execution aliases and directory trees whose paths run past MAX_PATH, to over 300 characters, in its temp directory, runs whoami and find from System32 and winget --version, and reaches its temp directory through the administrative share of localhost");
test_group!(SHELL_EXECUTE => shell_execute, env = "COSCA_TEST_SHELL_EXECUTE", consent = "elevates through ShellExecuteEx and registers volatile App Paths keys");
test_group!(SHELL_PROBES => shell_probes, env = "COSCA_TEST_SHELL_PROBES", consent = "plants and executes batch files through ShellExecuteEx and launches copies of cosca_testbin_image");
test_group!(ELEVATION_ROUTES => elevation_routes, env = "COSCA_TEST_ELEVATION_ROUTES", consent = "derives tokens, creates accounts and a scheduled task, launches copies of this test binary under derived tokens and scratch accounts, and plants a batch file that CreateProcessW may run");
test_group!(CGROUP => cgroup, env = "COSCA_TEST_CGROUP", consent = "creates, kills and removes cgroup v2 leaves, runs process trees in them, and unshares file tables and mount namespaces to mount over them", watching_leaves);
test_group!(TRACER => tracer_group, env = "COSCA_TEST_TRACER", consent = "attaches a tracer with ptrace to its own children as a debugger would, re-executes the test binary as that tracer (on macOS an ad-hoc signed copy with the debugger entitlement), and on Linux allows any process to trace its tracee");
test_group!(UID_SWITCH => uid_switch, env = "COSCA_TEST_UID_SWITCH", consent = "runs as real root and switches to other real uids, spawning and signalling processes under them");
test_group!(ELEVATION => elevation, env = "COSCA_TEST_ELEVATION", consent = "runs commands with real administrator or root privileges");
test_group!(PIDFD_GROUP_SIGNAL => pidfd_group_signal, env = "COSCA_TEST_PIDFD_GROUP_SIGNAL", precondition = kernel_signals_groups_through_pidfds);
test_group!(UNPRIVILEGED => unprivileged, env = "COSCA_TEST_UNPRIVILEGED");

/// The `PIDFD_GROUP_SIGNAL` group's precondition: the kernel takes `PIDFD_SIGNAL_PROCESS_GROUP`
/// (Linux 6.9+). Asked by a signal-0 send through this process's own pidfd, which signals nothing; a
/// kernel before 6.9 refuses the flag with `EINVAL`.
#[allow(dead_code, reason = "a root that includes this file may have no test in the group")]
fn kernel_signals_groups_through_pidfds(enabled_var: &str) -> Result<(), String> {
    let lacks = |why: String| {
        format!(
            "the group needs Linux 6.9+, whose pidfd_send_signal takes PIDFD_SIGNAL_PROCESS_GROUP, and {why}; \
             set {enabled_var}=0 to turn it off"
        )
    };
    #[cfg(target_os = "linux")]
    {
        // SAFETY: a plain syscall.
        let pidfd = unsafe { libc::syscall(libc::SYS_pidfd_open, libc::getpid(), 0) };
        if pidfd < 0 {
            return Err(lacks(format!(
                "pidfd_open failed ({})",
                std::io::Error::last_os_error()
            )));
        }
        // SAFETY: `pidfd` is the pidfd just opened, and a null `siginfo_t` asks for the defaults.
        let sent = unsafe {
            libc::syscall(
                libc::SYS_pidfd_send_signal,
                pidfd,
                0,
                std::ptr::null::<libc::siginfo_t>(),
                libc::PIDFD_SIGNAL_PROCESS_GROUP,
            )
        };
        let errno = std::io::Error::last_os_error();
        // SAFETY: closes the pidfd opened above, which nothing else holds.
        unsafe { libc::close(pidfd as libc::c_int) };
        // Any other answer (`ESRCH`: this process leads no group) comes from a kernel that took the flag.
        if sent < 0 && errno.raw_os_error() == Some(libc::EINVAL) {
            return Err(lacks(format!("this kernel refused the flag ({errno})")));
        }
        Ok(())
    }
    #[cfg(not(target_os = "linux"))]
    Err(lacks("this host is not Linux".to_owned()))
}