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
//! The privileges of the process's access token, for `process::windows`.
//!
//! A privilege is known by a name (`SeLockMemoryPrivilege`) that the system
//! turns into a number of its own, a `LUID`. A token holds some of them,
//! each enabled or not; only an enabled one counts when the system checks.

use core::ffi::c_void;
use core::mem::size_of;
use core::ptr;

use crate::process::windows::PrivilegeState;
use crate::sys::{cvt, dll, last_error};
use crate::{Error, ErrorKind, OwnedHandle, Result};

/// `LUID`.
#[repr(C)]
#[derive(Clone, Copy, Default)]
struct Luid {
    low: u32,
    high: i32,
}

/// `LUID_AND_ATTRIBUTES`. The headers pack it to four bytes, which is the
/// alignment of its members anyway.
#[repr(C)]
#[derive(Clone, Copy, Default)]
struct LuidAndAttributes {
    luid: Luid,
    attributes: u32,
}

/// `TOKEN_PRIVILEGES`, with room for one privilege.
#[repr(C)]
struct TokenPrivileges {
    count: u32,
    privileges: [LuidAndAttributes; 1],
}

const _: () = {
    assert!(size_of::<Luid>() == 8);
    assert!(size_of::<LuidAndAttributes>() == 12);
    assert!(size_of::<TokenPrivileges>() == 16);
    assert!(core::mem::offset_of!(TokenPrivileges, privileges) == 4);
};

dll!("advapi32.dll" {
    fn OpenProcessToken(process: *mut c_void, access: u32, token: *mut *mut c_void) -> i32;
    fn LookupPrivilegeValueW(system: *const u16, name: *const u16, luid: *mut Luid) -> i32;
    fn AdjustTokenPrivileges(
        token: *mut c_void,
        disable_all: i32,
        new_state: *const TokenPrivileges,
        len: u32,
        previous: *mut c_void,
        returned: *mut u32,
    ) -> i32;
    fn GetTokenInformation(
        token: *mut c_void,
        class: u32,
        info: *mut c_void,
        len: u32,
        returned: *mut u32,
    ) -> i32;
});

dll!("kernel32.dll" {
    fn GetCurrentProcess() -> *mut c_void;
});

const TOKEN_QUERY: u32 = 0x8;
const TOKEN_ADJUST_PRIVILEGES: u32 = 0x20;
/// `TOKEN_INFORMATION_CLASS`.
const TOKEN_PRIVILEGES: u32 = 3;
const SE_PRIVILEGE_ENABLED: u32 = 0x2;
/// What `AdjustTokenPrivileges` reports, while succeeding, of a privilege
/// the token does not hold.
const ERROR_NOT_ALL_ASSIGNED: i32 = 1300;

/// How many privileges of a token are read at once. Windows defines 36.
const MAX_PRIVILEGES: usize = 126;

/// The access token of the process, open for `access`.
fn token(access: u32) -> Result<OwnedHandle> {
    let mut token = ptr::null_mut();
    // SAFETY: the pseudo-handle of the process needs no closing, and the
    // call writes one handle.
    cvt(unsafe { OpenProcessToken(GetCurrentProcess(), access, &raw mut token) })?;
    // SAFETY: the handle was just opened.
    Ok(unsafe { OwnedHandle::from_raw(token) })
}

/// The number this system has for the privilege `name`, a NUL-terminated
/// wide string.
pub(crate) fn lookup(name: &[u16]) -> Result<u64> {
    let mut luid = Luid::default();
    // SAFETY: the name is NUL-terminated; a null system is this one.
    cvt(unsafe { LookupPrivilegeValueW(ptr::null(), name.as_ptr(), &raw mut luid) })?;
    Ok(u64::from(luid.low) | (luid.high as u32 as u64) << 32)
}

fn luid(privilege: u64) -> Luid {
    Luid {
        low: privilege as u32,
        high: (privilege >> 32) as i32,
    }
}

/// What the token of the process has of `privilege`.
pub(crate) fn state(privilege: u64) -> Result<PrivilegeState> {
    /// `TOKEN_PRIVILEGES` with room for all of them.
    #[repr(C)]
    struct All {
        count: u32,
        privileges: [LuidAndAttributes; MAX_PRIVILEGES],
    }
    let token = token(TOKEN_QUERY)?;
    let mut all = All {
        count: 0,
        privileges: [LuidAndAttributes::default(); MAX_PRIVILEGES],
    };
    let mut returned = 0;
    // SAFETY: the call writes at most the size given, which is that of
    // the structure.
    cvt(unsafe {
        GetTokenInformation(
            token.as_raw(),
            TOKEN_PRIVILEGES,
            (&raw mut all).cast(),
            size_of::<All>() as u32,
            &raw mut returned,
        )
    })?;
    let wanted = luid(privilege);
    let held = all
        .privileges
        .get(..all.count as usize)
        .ok_or(Error::from(ErrorKind::Other))?;
    Ok(held
        .iter()
        .find(|held| held.luid.low == wanted.low && held.luid.high == wanted.high)
        .map_or(PrivilegeState::Absent, |held| {
            if held.attributes & SE_PRIVILEGE_ENABLED != 0 {
                PrivilegeState::Enabled
            } else {
                PrivilegeState::Disabled
            }
        }))
}

/// Enables or disables `privilege` in the token of the process.
pub(crate) fn set(privilege: u64, enabled: bool) -> Result<()> {
    let token = token(TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY)?;
    let new_state = TokenPrivileges {
        count: 1,
        privileges: [LuidAndAttributes {
            luid: luid(privilege),
            attributes: if enabled { SE_PRIVILEGE_ENABLED } else { 0 },
        }],
    };
    // SAFETY: the call reads the structure, and is asked for nothing of
    // the previous state.
    cvt(unsafe {
        AdjustTokenPrivileges(
            token.as_raw(),
            0,
            &raw const new_state,
            0,
            ptr::null_mut(),
            ptr::null_mut(),
        )
    })?;
    // The call succeeds also when it changed nothing, for a privilege the
    // token does not hold, and says so in the place of an error.
    let error = last_error();
    if error.raw_os_error() == ERROR_NOT_ALL_ASSIGNED {
        return Err(error);
    }
    Ok(())
}