oscall 0.1.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! Tests of what `oscall::process::windows` has of the access token of the
//! process: privileges.
//!
//! They change the token of the process they run in, which is why they have
//! a file, and so a process, of their own.
#![cfg(windows)]

mod common;

/// Says what a test found: on the standard error output itself, which the
/// test harness does not capture.
macro_rules! note {
    ($($arg:tt)*) => {
        crate::common::note(&format!($($arg)*))
    };
}

use std::collections::HashMap;

use oscall::ErrorKind;
use oscall::process::windows::{self, Privilege, PrivilegeState};

const ERROR_NOT_ALL_ASSIGNED: i32 = 1300;
const ERROR_NO_SUCH_PRIVILEGE: i32 = 1313;

/// The names this crate has constants for.
const NAMES: [&str; 8] = [
    Privilege::LOCK_MEMORY,
    Privilege::CHANGE_NOTIFY,
    Privilege::DEBUG,
    Privilege::BACKUP,
    Privilege::RESTORE,
    Privilege::SHUTDOWN,
    Privilege::CREATE_SYMBOLIC_LINK,
    Privilege::INCREASE_WORKING_SET,
];

/// What `whoami /priv` says of the token of a process created now, which
/// is a copy of this one's: the privileges it holds, and whether each is
/// enabled.
fn whoami() -> HashMap<String, bool> {
    let output = std::process::Command::new("whoami")
        .args(["/priv", "/fo", "csv", "/nh"])
        .output()
        .unwrap();
    assert!(output.status.success(), "{output:?}");
    String::from_utf8_lossy(&output.stdout)
        .lines()
        .filter_map(|line| {
            let mut fields = line.split("\",\"");
            let name = fields.next()?.trim_start_matches('"');
            let state = fields.last()?.trim_end_matches('"');
            Some((name.to_owned(), state.eq_ignore_ascii_case("enabled")))
        })
        .collect()
}

/// Asserts that what oscall says of every privilege it names is what
/// `whoami` says.
#[track_caller]
fn assert_as_whoami() {
    let said = whoami();
    assert!(!said.is_empty());
    for name in NAMES {
        let privilege = Privilege::lookup(name).unwrap();
        let expected = match said.get(name) {
            None => PrivilegeState::Absent,
            Some(false) => PrivilegeState::Disabled,
            Some(true) => PrivilegeState::Enabled,
        };
        assert_eq!(
            windows::privilege_state(privilege).unwrap(),
            expected,
            "{name}"
        );
    }
}

#[test]
fn privileges() {
    // A name the system does not know, and one that is no name.
    let err = Privilege::lookup("SeNoSuchPrivilege").unwrap_err();
    assert_eq!(err.raw_os_error(), ERROR_NO_SUCH_PRIVILEGE, "{err:?}");
    let err = Privilege::lookup("Se\0Privilege").unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidInput);
    // Every name there is a constant for is one the system knows, each
    // with a number of its own; a name is looked up in any case.
    let all: Vec<Privilege> = NAMES
        .iter()
        .map(|name| Privilege::lookup(*name).unwrap())
        .collect();
    for (i, privilege) in all.iter().enumerate() {
        assert!(!all[..i].contains(privilege), "{}", NAMES[i]);
        assert_eq!(Privilege::lookup(NAMES[i]).unwrap(), *privilege);
        assert_eq!(
            Privilege::lookup(NAMES[i].to_ascii_lowercase().as_str()).unwrap(),
            *privilege
        );
        assert!(format!("{privilege:?}").starts_with("Privilege("));
    }

    let held: Vec<String> = NAMES
        .iter()
        .zip(&all)
        .map(|(name, privilege)| {
            format!(
                "{name}: {:?}",
                windows::privilege_state(*privilege).unwrap()
            )
        })
        .collect();
    note!("process::windows: the token of the tests has {held:?}");
    assert_as_whoami();

    // Every account passes through directories it may not list, and has
    // the privilege enabled.
    let change_notify = Privilege::lookup(Privilege::CHANGE_NOTIFY).unwrap();
    assert_eq!(
        windows::privilege_state(change_notify).unwrap(),
        PrivilegeState::Enabled
    );
    // Enabling what is enabled does nothing.
    windows::set_privilege(change_notify, true).unwrap();
    assert_eq!(
        windows::privilege_state(change_notify).unwrap(),
        PrivilegeState::Enabled
    );

    // A privilege that is held is switched off and on, for the process
    // and for those it creates, which is what `whoami` is.
    let toggled = NAMES
        .iter()
        .zip(&all)
        .find(|(name, privilege)| {
            **name != Privilege::CHANGE_NOTIFY
                && windows::privilege_state(**privilege).unwrap() != PrivilegeState::Absent
        })
        .map(|(name, privilege)| (*name, *privilege));
    match toggled {
        None => note!("process::windows: the token holds nothing to switch but SeChangeNotify"),
        Some((name, privilege)) => {
            let before = windows::privilege_state(privilege).unwrap();
            note!("process::windows: switching {name}, which was {before:?}");
            for enabled in [true, false, false, true, true] {
                windows::set_privilege(privilege, enabled).unwrap();
                let expected = if enabled {
                    PrivilegeState::Enabled
                } else {
                    PrivilegeState::Disabled
                };
                assert_eq!(windows::privilege_state(privilege).unwrap(), expected);
                assert_as_whoami();
            }
            windows::set_privilege(privilege, before == PrivilegeState::Enabled).unwrap();
            assert_eq!(windows::privilege_state(privilege).unwrap(), before);
        }
    }

    // Enabling is not acquiring: what the token does not hold stays out
    // of it, and the call says so. No token of a program holds the
    // privilege to make tokens.
    let absent = Privilege::lookup("SeCreateTokenPrivilege").unwrap();
    assert_eq!(
        windows::privilege_state(absent).unwrap(),
        PrivilegeState::Absent
    );
    let err = windows::set_privilege(absent, true).unwrap_err();
    assert_eq!(err.raw_os_error(), ERROR_NOT_ALL_ASSIGNED, "{err:?}");
    assert_eq!(err.kind(), ErrorKind::PermissionDenied);
    assert_eq!(
        windows::privilege_state(absent).unwrap(),
        PrivilegeState::Absent
    );
    let disabling = windows::set_privilege(absent, false);
    note!("process::windows: disabling a privilege the token does not hold: {disabling:?}");
    assert_eq!(
        disabling.unwrap_err().raw_os_error(),
        ERROR_NOT_ALL_ASSIGNED
    );
}