sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use std::{fmt::Display, str::FromStr};

#[cfg(feature = "user")]
use windows::Win32::Foundation::ERROR_INSUFFICIENT_BUFFER;
use windows::Win32::Foundation::{HLOCAL, LocalFree};
use windows::Win32::Security::Authorization::{ConvertSidToStringSidW, ConvertStringSidToSidW};
use windows::Win32::Security::{CopySid, GetLengthSid, IsValidSid, PSID};
#[cfg(feature = "user")]
use windows::Win32::Security::{LookupAccountNameW, LookupAccountSidW, SidTypeUnknown};
use windows::core::{PCWSTR, PWSTR};

use crate::sys::utils::to_utf8_str;

#[doc = "Opaque type encapsulating a Windows SID."]
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Sid {
    sid: Vec<u8>,
}

impl Sid {
    /// Creates an `Sid` by copying the given raw SID.
    pub(crate) unsafe fn from_psid(psid: PSID) -> Option<Self> {
        if psid.is_invalid() {
            return None;
        }

        if unsafe { !IsValidSid(psid).as_bool() } {
            return None;
        }

        let length = unsafe { GetLengthSid(psid) };

        let mut sid = vec![0; length as usize];

        if unsafe { CopySid(length, PSID(sid.as_mut_ptr().cast()), psid).is_err() } {
            sinf_debug!("CopySid failed: {:?}", std::io::Error::last_os_error());
            return None;
        }

        // This code assumes the internal SID structure, and the assumptions hold only when the revision is 1:
        assert_eq!(sid[0], 1, "Expected SID revision to be 1");

        Some(Self { sid })
    }

    /// Resolves an account or group name to a SID.
    #[cfg(feature = "user")]
    pub(crate) fn from_account_name(name: &str) -> Option<Self> {
        let mut account: Vec<u16> = name.encode_utf16().collect();
        account.push(0);

        unsafe {
            let mut sid_len = 0u32;
            let mut domain_len = 0u32;
            let mut sid_type = SidTypeUnknown;

            let result = LookupAccountNameW(
                PCWSTR::null(),
                PCWSTR::from_raw(account.as_ptr()),
                None,
                &mut sid_len,
                None,
                &mut domain_len,
                &mut sid_type,
            );
            if let Err(err) = result
                && err.code() != ERROR_INSUFFICIENT_BUFFER.to_hresult()
            {
                sinf_debug!("LookupAccountNameW failed for {name:?}: {err:?}");
                return None;
            }
            if sid_len == 0 {
                return None;
            }

            let mut sid = vec![0u8; sid_len as usize];
            let mut domain = vec![0u16; domain_len as usize];

            if LookupAccountNameW(
                PCWSTR::null(),
                PCWSTR::from_raw(account.as_ptr()),
                Some(PSID(sid.as_mut_ptr().cast())),
                &mut sid_len,
                Some(PWSTR::from_raw(domain.as_mut_ptr())),
                &mut domain_len,
                &mut sid_type,
            )
            .is_err()
            {
                sinf_debug!(
                    "LookupAccountNameW failed for {name:?}: {:?}",
                    std::io::Error::last_os_error()
                );
                return None;
            }

            Self::from_psid(PSID(sid.as_mut_ptr().cast()))
        }
    }

    /// Returns this SID with its last subauthority replaced by `rid`.
    #[cfg(feature = "user")]
    pub(crate) fn with_rid(&self, rid: u32) -> Option<Self> {
        let mut sid = self.sid.clone();
        let count = *sid.get(1)? as usize;
        if count == 0 {
            return None;
        }
        let offset = 8 + (count - 1) * 4;
        let end = offset.checked_add(4)?;
        if end > sid.len() {
            return None;
        }
        sid[offset..end].copy_from_slice(&rid.to_le_bytes());

        // SAFETY: `sid` is a byte buffer returned by the SID APIs with the same
        // length, so checking it as a PSID is valid.
        unsafe {
            if !IsValidSid(PSID(sid.as_mut_ptr().cast())).as_bool() {
                return None;
            }
        }

        Some(Self { sid })
    }

    /// Retrieves the account name of this SID.
    #[cfg(feature = "user")]
    pub(crate) fn account_name(&self) -> Option<String> {
        unsafe {
            let mut name_len = 0;
            let mut domain_len = 0;
            let mut name_use = SidTypeUnknown;

            let sid = PSID((self.sid.as_ptr() as *mut u8).cast());
            if let Err(err) = LookupAccountSidW(
                PCWSTR::null(),
                sid,
                None,
                &mut name_len,
                None,
                &mut domain_len,
                &mut name_use,
            ) && err.code() != ERROR_INSUFFICIENT_BUFFER.to_hresult()
            {
                sinf_debug!("LookupAccountSidW failed: {:?}", err);
                return None;
            }

            let mut name = vec![0; name_len as usize];

            // Reset the length to 0 because the domain is still passed as a NULL pointer.
            domain_len = 0;

            if LookupAccountSidW(
                PCWSTR::null(),
                sid,
                Some(PWSTR::from_raw(name.as_mut_ptr())),
                &mut name_len,
                None,
                &mut domain_len,
                &mut name_use,
            )
            .is_err()
            {
                sinf_debug!(
                    "LookupAccountSidW failed: {:?}",
                    std::io::Error::last_os_error()
                );
                return None;
            }

            Some(to_utf8_str(PWSTR::from_raw(name.as_mut_ptr())))
        }
    }
}

impl Display for Sid {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        unsafe fn convert_sid_to_string_sid(sid: PSID) -> Option<String> {
            let mut string_sid = PWSTR::null();
            unsafe {
                if let Err(_err) = ConvertSidToStringSidW(sid, &mut string_sid) {
                    sinf_debug!("ConvertSidToStringSidW failed: {:?}", _err);
                    return None;
                }
                let result = to_utf8_str(string_sid);
                let _err = LocalFree(Some(HLOCAL(string_sid.0 as _)));
                Some(result)
            }
        }

        let string_sid =
            unsafe { convert_sid_to_string_sid(PSID((self.sid.as_ptr() as *mut u8).cast())) };
        let string_sid = string_sid.ok_or(std::fmt::Error)?;

        write!(f, "{string_sid}")
    }
}

impl FromStr for Sid {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        unsafe {
            let mut string_sid: Vec<u16> = s.encode_utf16().collect();
            string_sid.push(0);

            let mut psid = PSID::default();
            if let Err(err) =
                ConvertStringSidToSidW(PCWSTR::from_raw(string_sid.as_ptr()), &mut psid)
            {
                return Err(format!("ConvertStringSidToSidW failed: {err:?}"));
            }
            let sid = Self::from_psid(psid);
            let _err = LocalFree(Some(HLOCAL(psid.0 as _)));

            // Unwrap because ConvertStringSidToSidW should have performed all the necessary validation.
            Ok(sid.expect("ConvertStringSidToSidW should have worked"))
        }
    }
}

#[cfg(all(test, feature = "user"))]
mod tests {
    use super::Sid;
    use std::str::FromStr;

    #[test]
    fn with_rid_replaces_last_subauthority() {
        let sid = Sid::from_str("S-1-5-21-1-2-3-1001").expect("valid SID");
        let group = sid.with_rid(513).expect("valid replacement");
        assert_eq!(group.to_string(), "S-1-5-21-1-2-3-513");
    }

    #[test]
    fn resolves_current_user_name() {
        let Ok(name) = std::env::var("USERNAME") else {
            return;
        };
        assert!(
            Sid::from_account_name(&name).is_some(),
            "failed to resolve the current user SID"
        );
    }

    #[test]
    fn with_rid_handles_authority_zero() {
        let sid = Sid::from_str("S-1-0-0").expect("valid SID");
        assert_eq!(
            sid.with_rid(1).map(|sid| sid.to_string()),
            Some("S-1-0-1".into())
        );
    }
}