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 }
}
#[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()),
}
}
}
#[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}");
}
}
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())
}
#[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);
}
}
#[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;
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)
}
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(())
}
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()),
Ok(false) => Err(format!("{enabled_var}=0")),
Err(why) => Err(format!("the group {what}: {why}")),
}
}
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) => {
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 and creates a suspended process");
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");