subc-os 0.1.59

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
//! Access probes run from a child whose token holds no privileges, the way an
//! ordinary same-user program runs. A test process holding an enabled
//! SeDebugPrivilege (an elevated administrator, as on hosted CI runners) opens
//! any process or thread whatever its discretionary access control list
//! (DACL), so probing from the test process itself would measure the
//! privilege rather than the access list.

use super::{process_probe, thread_probe, WAIT};
use crate::windows_spawn::{command_line, environment::wide_without_nul, Environment};
use cortexkit_test_support::ScratchDir;
use std::{
    ffi::OsStr,
    fs, io,
    mem::size_of,
    os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle},
    ptr::{addr_of, null, null_mut},
};
use windows_sys::Win32::{
    Foundation::{LocalFree, HANDLE, WAIT_OBJECT_0},
    Security::{
        Authorization::ConvertSidToStringSidW, CreateRestrictedToken, GetTokenInformation,
        LookupPrivilegeNameW, TokenElevation, TokenPrivileges, TokenUser, DISABLE_MAX_PRIVILEGE,
        LUID_AND_ATTRIBUTES, SE_PRIVILEGE_ENABLED, TOKEN_ACCESS_MASK, TOKEN_ASSIGN_PRIMARY,
        TOKEN_DUPLICATE, TOKEN_ELEVATION, TOKEN_INFORMATION_CLASS, TOKEN_PRIVILEGES, TOKEN_QUERY,
        TOKEN_USER,
    },
    System::Threading::{
        CreateProcessAsUserW, GetCurrentProcess, GetExitCodeProcess, OpenProcessToken,
        TerminateProcess, WaitForSingleObject, CREATE_NO_WINDOW, CREATE_UNICODE_ENVIRONMENT,
        PROCESS_INFORMATION, STARTUPINFOW,
    },
};

const PROBE: &str = "windows_spawn::tests::probe::windows_spawn_probe_fixture";
const PROBE_OUT: &str = "SUBC_TEST_WINDOWS_SPAWN_PROBE_OUT";
const PROBE_TARGET: &str = "SUBC_TEST_WINDOWS_SPAWN_PROBE_TARGET";

/// What the unprivileged child saw, and a description of its token.
pub(super) struct ProbeReport {
    pub(super) results: String,
    pub(super) token: String,
}

/// Runs only inside the child started by `unprivileged_probe`; a normal test
/// run finds no probe target and returns.
#[test]
fn windows_spawn_probe_fixture() {
    let (Some(out), Ok(target)) = (std::env::var_os(PROBE_OUT), std::env::var(PROBE_TARGET)) else {
        return;
    };
    let (kind, id) = target.split_once(':').unwrap();
    let id = id.parse().unwrap();
    let results = match kind {
        "process" => format!("{:?}", process_probe(id)),
        "thread" => format!("{:?}", thread_probe(id)),
        _ => panic!("unknown probe target {target}"),
    };
    let token = token_summary(&current_token(TOKEN_QUERY));
    fs::write(out, format!("{results}\n{token}")).unwrap();
}

/// Open the process or thread `id` (`kind` is "process" or "thread") from a
/// child of this test binary whose token is this process's token with every
/// privilege but SeChangeNotify removed.
pub(super) fn unprivileged_probe(kind: &str, id: u32) -> ProbeReport {
    let dir = ScratchDir::new("windows-spawn-probe");
    let out = dir.join("result");
    let target = format!("{kind}:{id}");
    let environment = Environment::from_entries(
        std::env::vars_os(),
        [
            (OsStr::new(PROBE_OUT), Some(out.as_os_str())),
            (OsStr::new(PROBE_TARGET), Some(OsStr::new(&target))),
        ],
    )
    .unwrap();
    let exe = std::env::current_exe().unwrap();
    let mut application = wide_without_nul(exe.as_os_str()).unwrap();
    application.push(0);
    let mut line = command_line(exe.as_os_str(), ["--exact", PROBE].map(OsStr::new)).unwrap();

    let token = current_token(TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY | TOKEN_QUERY);
    let mut restricted = null_mut();
    // SAFETY: The source token is live and the output pointer is writable;
    // no SIDs or individual privileges are listed.
    let created = unsafe {
        CreateRestrictedToken(
            token.as_raw_handle(),
            DISABLE_MAX_PRIVILEGE,
            0,
            null(),
            0,
            null(),
            0,
            null(),
            &mut restricted,
        )
    };
    assert_ne!(
        created,
        0,
        "CreateRestrictedToken: {}",
        io::Error::last_os_error()
    );
    // SAFETY: CreateRestrictedToken returned a new token handle.
    let restricted = unsafe { OwnedHandle::from_raw_handle(restricted) };

    let startup = STARTUPINFOW {
        cb: size_of::<STARTUPINFOW>() as u32,
        ..Default::default()
    };
    let mut info = PROCESS_INFORMATION::default();
    // SAFETY: Every string and the environment block are terminated and live
    // through the call. A restricted copy of the caller's own token needs no
    // SeAssignPrimaryTokenPrivilege. No handles are inherited.
    let created = unsafe {
        CreateProcessAsUserW(
            restricted.as_raw_handle(),
            application.as_ptr(),
            line.as_mut_ptr(),
            null(),
            null(),
            0,
            CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT,
            environment.0.as_ptr().cast(),
            null(),
            &startup,
            &mut info,
        )
    };
    assert_ne!(
        created,
        0,
        "CreateProcessAsUserW: {}",
        io::Error::last_os_error()
    );
    // SAFETY: Successful process creation transferred both handles.
    let (process, _thread) = unsafe {
        (
            OwnedHandle::from_raw_handle(info.hProcess),
            OwnedHandle::from_raw_handle(info.hThread),
        )
    };
    // SAFETY: The process handle is live for the wait.
    if unsafe { WaitForSingleObject(process.as_raw_handle(), WAIT.as_millis() as u32) }
        != WAIT_OBJECT_0
    {
        // SAFETY: The process handle is live and has full creator access.
        unsafe { TerminateProcess(process.as_raw_handle(), 1) };
        panic!("unprivileged probe child did not exit");
    }
    let mut code = 0;
    // SAFETY: The process has exited and code is a writable DWORD.
    assert_ne!(
        unsafe { GetExitCodeProcess(process.as_raw_handle(), &mut code) },
        0
    );
    assert_eq!(code, 0, "unprivileged probe child failed");
    let output = fs::read_to_string(&out).unwrap();
    let (results, token) = output.split_once('\n').unwrap();
    ProbeReport {
        results: results.to_owned(),
        token: token.to_owned(),
    }
}

pub(super) fn current_token(access: TOKEN_ACCESS_MASK) -> OwnedHandle {
    let mut token = null_mut();
    // SAFETY: The pseudo-handle needs no closing and the output is writable.
    let opened = unsafe { OpenProcessToken(GetCurrentProcess(), access, &mut token) };
    assert_ne!(
        opened,
        0,
        "OpenProcessToken: {}",
        io::Error::last_os_error()
    );
    // SAFETY: OpenProcessToken returned a new handle.
    unsafe { OwnedHandle::from_raw_handle(token) }
}

fn token_information(token: HANDLE, class: TOKEN_INFORMATION_CLASS) -> Vec<usize> {
    let mut bytes = 0;
    // SAFETY: A null buffer of length zero is the documented size query.
    unsafe { GetTokenInformation(token, class, null_mut(), 0, &mut bytes) };
    let mut buffer = vec![0usize; (bytes as usize).div_ceil(size_of::<usize>())];
    // SAFETY: The pointer-aligned buffer holds at least `bytes` bytes.
    let read =
        unsafe { GetTokenInformation(token, class, buffer.as_mut_ptr().cast(), bytes, &mut bytes) };
    assert_ne!(
        read,
        0,
        "GetTokenInformation: {}",
        io::Error::last_os_error()
    );
    buffer
}

fn wide_string(text: &[u16]) -> String {
    let end = text.iter().position(|&ch| ch == 0).unwrap_or(text.len());
    String::from_utf16_lossy(&text[..end])
}

/// The token's user SID, elevation and enabled privileges, which together
/// decide whether a same-user open can bypass a process or thread DACL.
pub(super) fn token_summary(token: &OwnedHandle) -> String {
    let token = token.as_raw_handle();
    let elevation = token_information(token, TokenElevation);
    // SAFETY: GetTokenInformation filled a TOKEN_ELEVATION.
    let elevated = unsafe { (*elevation.as_ptr().cast::<TOKEN_ELEVATION>()).TokenIsElevated } != 0;

    let user = token_information(token, TokenUser);
    let mut sid = null_mut();
    // SAFETY: GetTokenInformation filled a TOKEN_USER whose SID points into
    // the same buffer; the output pointer is writable.
    let converted =
        unsafe { ConvertSidToStringSidW((*user.as_ptr().cast::<TOKEN_USER>()).User.Sid, &mut sid) };
    assert_ne!(
        converted,
        0,
        "ConvertSidToStringSidW: {}",
        io::Error::last_os_error()
    );
    // SAFETY: ConvertSidToStringSidW returned a terminated string, freed once read.
    let user = unsafe {
        let length = (0..).take_while(|&i| *sid.add(i) != 0).count();
        let text = String::from_utf16_lossy(std::slice::from_raw_parts(sid, length));
        LocalFree(sid.cast());
        text
    };

    let privileges = token_information(token, TokenPrivileges);
    let list = privileges.as_ptr().cast::<TOKEN_PRIVILEGES>();
    // SAFETY: GetTokenInformation filled a TOKEN_PRIVILEGES whose trailing
    // array holds PrivilegeCount entries within the same buffer.
    let entries: &[LUID_AND_ATTRIBUTES] = unsafe {
        std::slice::from_raw_parts(
            addr_of!((*list).Privileges).cast(),
            (*list).PrivilegeCount as usize,
        )
    };
    let enabled: Vec<String> = entries
        .iter()
        .filter(|entry| entry.Attributes & SE_PRIVILEGE_ENABLED != 0)
        .map(|entry| {
            let mut name = [0u16; 128];
            let mut length = name.len() as u32;
            // SAFETY: The LUID came from the token and the buffer length is exact.
            let found = unsafe {
                LookupPrivilegeNameW(null(), &entry.Luid, name.as_mut_ptr(), &mut length)
            };
            if found == 0 {
                format!("{:?}", (entry.Luid.HighPart, entry.Luid.LowPart))
            } else {
                wide_string(&name)
            }
        })
        .collect();
    format!("user={user} elevated={elevated} enabled_privileges={enabled:?}")
}