//! 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!(PIDFD_GET_INFO => pidfd_get_info, env = "COSCA_TEST_PIDFD_GET_INFO", precondition = kernel_answers_pidfd_get_info);
test_group!(CLONE3 => clone3, env = "COSCA_TEST_CLONE3");
test_group!(STRAY_SIGNAL => stray_signal, env = "COSCA_TEST_STRAY_SIGNAL", consent = "may signal an unrelated process (a number no live process of the test pins, or a walk from a reaped root's pid)");
test_group!(UNPRIVILEGED => unprivileged, env = "COSCA_TEST_UNPRIVILEGED");
test_group!(CTRL_PROXY => ctrl_proxy, env = "COSCA_TEST_CTRL_PROXY", consent = "sends a console control event to a whole console");
/// A pidfd of this process, for the kernel preconditions to query.
#[cfg(target_os = "linux")]
fn own_pidfd() -> std::io::Result<std::os::fd::OwnedFd> {
Ok(rustix::process::pidfd_open(
rustix::process::getpid(),
rustix::process::PidfdFlags::empty(),
)?)
}
/// 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")]
{
use std::os::fd::AsRawFd as _;
// Other failures (seccomp/LSM refusal, `ENOSYS`) are the probe's own.
let probe_failed = |what: String| {
format!(
"the PIDFD_GROUP_SIGNAL group could not ask the kernel whether it takes PIDFD_SIGNAL_PROCESS_GROUP \
({what}); set {enabled_var}=0 to turn it off"
)
};
let pidfd = own_pidfd().map_err(|e| probe_failed(format!("pidfd_open failed: {e}")))?;
// SAFETY: `pidfd` is open, and a null `siginfo_t` asks for the defaults.
let sent = unsafe {
libc::syscall(
libc::SYS_pidfd_send_signal,
pidfd.as_raw_fd(),
0,
std::ptr::null::<libc::siginfo_t>(),
libc::PIDFD_SIGNAL_PROCESS_GROUP,
)
};
if sent < 0 {
let errno = std::io::Error::last_os_error();
return match errno.raw_os_error() {
Some(libc::EINVAL) => Err(lacks(format!("this kernel refused the flag ({errno})"))),
// This process leads no group: the answer of a kernel that took the flag.
Some(libc::ESRCH) => Ok(()),
_ => Err(probe_failed(format!("the send failed: {errno}"))),
};
}
Ok(())
}
#[cfg(not(target_os = "linux"))]
Err(lacks("this host is not Linux".to_owned()))
}
/// The library's `PIDFD_GET_INFO_VER0` request (`containment::cgroup::reach`), repeated because integration roots
/// cannot name it.
#[cfg(target_os = "linux")]
const PIDFD_GET_INFO_VER0: libc::Ioctl = libc::_IOWR::<[u8; libc::PIDFD_INFO_SIZE_VER0 as usize]>(0xFF, 11);
#[cfg(target_os = "linux")]
const _: () = assert!(size_of::<libc::pidfd_info>() >= libc::PIDFD_INFO_SIZE_VER0 as usize);
/// The `PIDFD_GET_INFO` group's precondition: the kernel answers `PIDFD_GET_INFO` with a cgroup id
/// (Linux 6.13+). Asked by the ioctl on this process's own pidfd; a kernel before 6.13 refuses it with `ENOTTY` or
/// `EINVAL`. It does not call the library's
/// `pidfd_cgroup_id`, so a defect there cannot read as a missing kernel feature.
#[allow(dead_code, reason = "a root that includes this file may have no test in the group")]
fn kernel_answers_pidfd_get_info(enabled_var: &str) -> Result<(), String> {
let lacks = |why: String| {
format!(
"the group needs Linux 6.13+, whose pidfds answer PIDFD_GET_INFO with a cgroup id, and {why}; \
set {enabled_var}=0 to turn it off"
)
};
#[cfg(target_os = "linux")]
{
use std::os::fd::AsRawFd as _;
// Any other failure (a seccomp or LSM refusal, `ENOSYS`) is the probe's own, not the kernel's.
let probe_failed = |what: String| {
format!(
"the PIDFD_GET_INFO group could not ask the kernel whether it answers PIDFD_GET_INFO ({what}); \
set {enabled_var}=0 to turn it off"
)
};
let pidfd = own_pidfd().map_err(|e| probe_failed(format!("pidfd_open failed: {e}")))?;
// SAFETY: all-zero is a valid `pidfd_info` (plain integers).
let mut info: libc::pidfd_info = unsafe { std::mem::zeroed() };
info.mask = u64::from(libc::PIDFD_INFO_CGROUPID);
// SAFETY: `pidfd` is open, and `info` is a valid, writable `struct pidfd_info`, at least as large as the first
// version the request encodes.
let rc = unsafe {
libc::ioctl(
pidfd.as_raw_fd(),
PIDFD_GET_INFO_VER0,
&mut info as *mut libc::pidfd_info,
)
};
if rc != 0 {
let errno = std::io::Error::last_os_error();
return match errno.raw_os_error() {
Some(libc::ENOTTY | libc::EINVAL) => Err(lacks(format!("this kernel refused the ioctl ({errno})"))),
_ => Err(probe_failed(format!("the ioctl failed: {errno}"))),
};
}
if info.mask & u64::from(libc::PIDFD_INFO_CGROUPID) == 0 {
return Err(lacks("this kernel's answer carries no cgroup id".to_owned()));
}
Ok(())
}
#[cfg(not(target_os = "linux"))]
Err(lacks("this host is not Linux".to_owned()))
}