subc-os 0.1.60

Operating-system primitives for the subc daemon that need unsafe code, behind a safe API: per-process identity, signalling, memory and CPU usage, and the launch-nonce descriptor handoff.
Documentation
use super::{privileges, Handle};
use std::{io, process::Command, sync::mpsc, thread, time::Duration};
use windows_sys::Win32::{
    Foundation::ERROR_ACCESS_DENIED,
    Storage::FileSystem::WRITE_DAC,
    System::Threading::{
        GetCurrentThreadId, OpenThread, PROCESS_SYNCHRONIZE as SYNCHRONIZE, THREAD_GET_CONTEXT,
        THREAD_QUERY_LIMITED_INFORMATION, THREAD_SET_CONTEXT, THREAD_SUSPEND_RESUME,
    },
};

const TEST: &str = "windows_acl::process_restriction_tests::thread_acl::protect_current_thread_restricts_new_handles";
const CHILD: &str = "SUBC_OS_THREAD_RESTRICTION_CHILD";
const RIGHTS: [(&str, u32); 5] = [
    ("THREAD_SET_CONTEXT", THREAD_SET_CONTEXT),
    ("THREAD_SUSPEND_RESUME", THREAD_SUSPEND_RESUME),
    ("THREAD_GET_CONTEXT", THREAD_GET_CONTEXT),
    ("WRITE_DAC", WRITE_DAC),
    (
        "THREAD_QUERY_LIMITED_INFORMATION | SYNCHRONIZE",
        THREAD_QUERY_LIMITED_INFORMATION | SYNCHRONIZE,
    ),
];

#[test]
fn protect_current_thread_restricts_new_handles() {
    if std::env::var_os(CHILD).is_some() {
        // A debug-enabled opener bypasses the DACL. Remove the privilege in a
        // dedicated process so other tests' tokens are not changed.
        let token = privileges::remove_debug_privilege().expect("remove debug privilege");
        assert_eq!(thread_access(false), [None; RIGHTS.len()], "{token}");
        let access = thread_access(true);
        for ((name, _), actual) in RIGHTS.into_iter().zip(access) {
            let expected = (name != RIGHTS[4].0).then_some(ERROR_ACCESS_DENIED as i32);
            assert_eq!(actual, expected, "protected OpenThread({name}); {token}");
        }
        return;
    }

    let child = Command::new(std::env::current_exe().unwrap())
        .args(["--exact", TEST, "--nocapture"])
        .env(CHILD, "1")
        .output()
        .expect("run same-process thread access probe");
    let stdout = String::from_utf8_lossy(&child.stdout);
    let stderr = String::from_utf8_lossy(&child.stderr);
    assert!(
        child.status.success() && stdout.contains("1 passed"),
        "same-process thread access probe: {}\n{stdout}\n{stderr}",
        child.status
    );
}

fn thread_access(protected: bool) -> [Option<i32>; RIGHTS.len()] {
    let (ready, tid) = mpsc::channel();
    let (release, wait) = mpsc::channel::<()>();
    let worker = thread::spawn(move || {
        if protected {
            crate::protect_current_thread().expect("protect probe thread");
        }
        // SAFETY: GetCurrentThreadId has no arguments and returns a live ID.
        ready.send(unsafe { GetCurrentThreadId() }).unwrap();
        // Keep the worker alive until the opener has finished all probes.
        let _ = wait.recv();
    });
    let tid = tid
        .recv_timeout(Duration::from_secs(30))
        .expect("worker did not report its native thread ID");
    let access = RIGHTS.map(|(_, rights)| {
        // SAFETY: OpenThread takes values; the returned handle is closed on success.
        let handle = unsafe { OpenThread(rights, 0, tid) };
        if handle.is_null() {
            Some(io::Error::last_os_error().raw_os_error().unwrap())
        } else {
            drop(Handle(handle));
            None
        }
    });
    drop(release);
    worker.join().unwrap();
    access
}