Skip to main content

safe_sid/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2
3//! Safe borrowed and owned wrappers for Windows security identifiers (SIDs).
4//!
5//! A SID identifies a user, group, logon session, or other security principal.
6//! This crate represents one with the same in-memory layout used by Windows:
7//!
8//! - [`Sid`] is a dynamically sized, borrowed SID, analogous to `str`.
9//! - [`SidBuf`] owns a SID, analogous to [`String`].
10//!
11//! `SidBuf` dereferences to `Sid`, and both types implement equality, ordering,
12//! hashing, and formatting. This makes owned SIDs suitable as map and set keys
13//! while still allowing lookup with a borrowed `&Sid`.
14//!
15//! # Creating SIDs
16//!
17//! Build a SID from its six-byte identifier authority and its sub-authorities:
18//!
19//! ```
20//! use safe_sid::SidBuf;
21//!
22//! // S-1-5-32-544 is the BUILTIN\Administrators SID.
23//! let administrators = SidBuf::new([0, 0, 0, 0, 0, 5], &[32, 544])?;
24//! assert_eq!(administrators.to_string(), "S-1-5-32-544");
25//! # Ok::<(), windows_core::Error>(())
26//! ```
27//!
28//! Or ask Windows to create a [well-known SID](well_known):
29//!
30//! ```
31//! use safe_sid::{SidBuf, WinLocalSystemSid};
32//!
33//! let local_system = SidBuf::well_known(WinLocalSystemSid, None)?;
34//! assert_eq!(local_system.to_string(), "S-1-5-18");
35//! # Ok::<(), windows_core::Error>(())
36//! ```
37//!
38//! Numeric SID strings can be parsed without calling Windows:
39//!
40//! ```
41//! use safe_sid::SidBuf;
42//!
43//! let sid: SidBuf = "S-1-5-18".parse()?;
44//! assert_eq!(sid.authority(), 5);
45//! assert_eq!(sid.sub_authorities(), [18]);
46//! # Ok::<(), safe_sid::ParseError>(())
47//! ```
48//!
49//! [`SidBuf::from_cstr_with_alias`] additionally accepts Windows aliases such
50//! as `BA` (BUILTIN\Administrators).
51//!
52//! # Windows API interoperability
53//!
54//! The default feature set has no dependency on the full `windows` crate.
55//! [`Sid::as_ptr`] and [`Sid::from_psid`] use raw `c_void` pointers in that
56//! configuration.
57//!
58//! Enable the `windows-full` feature to also accept and return
59//! [`windows::Win32::Security::PSID`](https://microsoft.github.io/windows-docs-rs/doc/windows/Win32/Security/struct.PSID.html)
60//! values directly:
61//!
62//! ```toml
63//! [dependencies]
64//! safe-sid = { version = "0.1", features = ["windows-full"] }
65//! windows = { version = "0.62", features = ["Win32_Security"] }
66//! ```
67//!
68//! A borrowed SID can be passed to an API for the duration of the call:
69//!
70//! ```
71//! # #[cfg(feature = "windows-full")]
72//! # {
73//! use safe_sid::SidBuf;
74//! use windows::Win32::Security::GetLengthSid;
75//!
76//! let sid: SidBuf = "S-1-5-18".parse().unwrap();
77//! // The API must not retain or mutate the borrowed pointer.
78//! let byte_len = unsafe { GetLengthSid(sid.as_psid()) };
79//! assert_eq!(byte_len as usize, sid.as_bytes().len());
80//! # }
81//! ```
82//!
83//! Use [`SidBuf::with_capacity`] and [`SidBuf::as_mut_ptr`] for APIs that fill
84//! a caller-supplied SID buffer. The usual Windows two-call pattern is:
85//!
86//! 1. Call the API with no buffer to obtain the required byte count.
87//! 2. Allocate that many bytes with [`SidBuf::with_capacity`].
88//! 3. Pass [`SidBuf::as_mut_ptr`] to the API.
89//! 4. Read the buffer only after the API has successfully written a valid SID.
90//!
91//! See [`SidBuf::as_mut_ptr`] for a complete buffer-filling example.
92
93use std::borrow::Borrow;
94use std::cmp::Ordering;
95use std::ffi::c_void;
96use std::fmt::{Debug, Display};
97use std::hash::{Hash, Hasher};
98use std::ops::Deref;
99use std::str::FromStr;
100use windows_core::{Error, HRESULT, Result};
101
102#[allow(
103    non_snake_case,
104    non_upper_case_globals,
105    non_camel_case_types,
106    dead_code,
107    clippy::all
108)]
109mod bindings {
110    include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
111}
112
113#[allow(
114    non_snake_case,
115    non_upper_case_globals,
116    non_camel_case_types,
117    dead_code,
118    clippy::all
119)]
120/// Constants for the SID types accepted by [`SidBuf::well_known`] and
121/// [`Sid::is_well_known`].
122///
123/// The names and values correspond to Windows'
124/// `WELL_KNOWN_SID_TYPE` enumeration.
125pub mod well_known {
126    include!(concat!(env!("OUT_DIR"), "/well_known.rs"));
127}
128
129#[doc(no_inline)]
130pub use well_known::*;
131
132#[cfg(feature = "windows-full")]
133use windows::Win32::Security::{PSID, WELL_KNOWN_SID_TYPE as WINDOWS_WELL_KNOWN_SID_TYPE};
134
135const SID_REVISION: u8 = 1;
136const SID_MAX_SUB_AUTHORITIES: u8 = 15;
137const SID_HEADER_WORDS: usize = 2;
138
139/// Creates an error representing `ERROR_INVALID_SID`.
140fn invalid_sid_err() -> Error {
141    Error::from_hresult(HRESULT::from_win32(0x0539))
142}
143
144/// Converts a supported pointer wrapper to the raw pointer used by SID APIs.
145///
146/// This trait lets [`Sid::from_psid`] and [`SidBuf::from_psid`] work with raw
147/// `c_void` pointers. With the `windows-full` feature they also accept
148/// [`windows::Win32::Security::PSID`](https://microsoft.github.io/windows-docs-rs/doc/windows/Win32/Security/struct.PSID.html).
149pub trait AsSidPtr {
150    /// Returns the wrapped SID pointer.
151    fn as_sid_ptr(&self) -> *const c_void;
152}
153
154/// Converts a well-known SID type to the value expected by Windows.
155///
156/// The crate's constants, such as [`WinLocalSystemSid`], implement this trait.
157/// With the `windows-full` feature, the equivalent constants from the
158/// `windows` crate do as well.
159pub trait AsWellKnownSidType {
160    /// Returns the numeric `WELL_KNOWN_SID_TYPE` value.
161    fn as_well_known_sid_type(&self) -> WELL_KNOWN_SID_TYPE;
162}
163
164impl AsWellKnownSidType for WELL_KNOWN_SID_TYPE {
165    fn as_well_known_sid_type(&self) -> WELL_KNOWN_SID_TYPE {
166        *self
167    }
168}
169
170#[cfg(feature = "windows-full")]
171impl AsWellKnownSidType for WINDOWS_WELL_KNOWN_SID_TYPE {
172    fn as_well_known_sid_type(&self) -> WELL_KNOWN_SID_TYPE {
173        self.0
174    }
175}
176
177#[cfg(feature = "windows-full")]
178impl AsSidPtr for PSID {
179    fn as_sid_ptr(&self) -> *const c_void {
180        self.0
181    }
182}
183
184impl AsSidPtr for *const c_void {
185    fn as_sid_ptr(&self) -> *const c_void {
186        *self
187    }
188}
189
190impl AsSidPtr for *mut c_void {
191    fn as_sid_ptr(&self) -> *const c_void {
192        *self
193    }
194}
195
196/// A borrowed SID.
197///
198/// `Sid` is byte-compatible with the Windows `SID` structure but represented as
199/// a dynamically sized type. It is normally obtained by dereferencing a
200/// [`SidBuf`] or, when borrowing memory owned elsewhere, by calling
201/// [`Sid::from_psid`].
202///
203/// Use [`ToOwned::to_owned`] to copy a borrowed SID into a [`SidBuf`].
204#[repr(C)]
205pub struct Sid {
206    revision: u8,
207    sub_authority_count: u8,
208    identifier_authority: [u8; 6],
209    sub_authority: [u32],
210}
211
212impl Sid {
213    /// Reinterpret already-validated SID words as a `&Sid`.
214    ///
215    /// `words` must be the two header words followed by the sub-authority words.
216    fn from_words_unchecked(words: &[u32]) -> &Sid {
217        debug_assert!(
218            words.len() >= SID_HEADER_WORDS,
219            "a SID has at least the two header words"
220        );
221        let sub_count = words.len() - SID_HEADER_WORDS;
222        let ptr = std::ptr::slice_from_raw_parts(words.as_ptr(), sub_count) as *const Sid;
223        // SAFETY: ptr is 4-byte aligned, see SidBuf::from_boxed_words for explanation on length validity
224        unsafe { &*ptr }
225    }
226
227    /// See [`Sid::from_words_unchecked`].
228    fn from_words_unchecked_mut(words: &mut [u32]) -> &mut Sid {
229        debug_assert!(
230            words.len() >= SID_HEADER_WORDS,
231            "a SID has at least the two header words"
232        );
233        let sub_count = words.len() - SID_HEADER_WORDS;
234        let ptr = std::ptr::slice_from_raw_parts_mut(words.as_mut_ptr(), sub_count) as *mut Sid;
235        // SAFETY: ptr is 4-byte aligned, see SidBuf::from_boxed_words for explanation on length validity
236        unsafe { &mut *ptr }
237    }
238
239    /// The number of sub-authorities, limited by the capacity of the actual buffer so we
240    /// can prevent out-of-bounds reads.
241    #[inline]
242    fn logical_sub_count(&self) -> usize {
243        (self.sub_authority_count as usize).min(self.sub_authority.len())
244    }
245
246    /// The SID's words, independent of any extra buffer capacity
247    /// (see [`with_capacity`](SidBuf::with_capacity)).
248    #[inline]
249    fn words(&self) -> &[u32] {
250        // SAFETY: logical_sub_count() is limited to our actual buffer size, so
251        // even if  sub_authority_count is oversized, it won't return a buffer
252        // that can allow out-of-bounds reads
253        unsafe {
254            std::slice::from_raw_parts(
255                self as *const Sid as *const u32,
256                SID_HEADER_WORDS + self.logical_sub_count(),
257            )
258        }
259    }
260
261    /// Returns the logical SID as raw bytes.
262    ///
263    /// The slice contains the eight-byte header followed by four bytes for each
264    /// sub-authority. Spare capacity in a [`SidBuf::with_capacity`] allocation
265    /// is not included.
266    #[inline]
267    pub fn as_bytes(&self) -> &[u8] {
268        let words = self.words();
269        // SAFETY: [u32] has a stronger alignment requirement than [u8], size is computed accurately
270        unsafe { std::slice::from_raw_parts(words.as_ptr() as *const u8, size_of_val(words)) }
271    }
272
273    /// The entire backing allocation, including any capacity beyond the logical SID.
274    /// Exposed for testing to validate allocations.
275    #[cfg(test)]
276    fn buffer_bytes(&self) -> &[u8] {
277        let word_len = SID_HEADER_WORDS + self.sub_authority.len();
278        // SAFETY: we know we have a 2 word header and sub_authority gives the allocated length,
279        // so this is an accurate representation of the bytes that can be accessed
280        unsafe {
281            std::slice::from_raw_parts(self as *const Sid as *const u8, word_len * size_of::<u32>())
282        }
283    }
284
285    /// Returns a `PSID` pointing at this SID for use with Windows APIs.
286    ///
287    /// # Safety
288    ///
289    /// The returned pointer is borrowed from `self` and must not outlive it.
290    /// Although `PSID` contains a mutable pointer, the pointee must not be
291    /// mutated through this shared reference.
292    #[cfg(feature = "windows-full")]
293    #[inline]
294    pub unsafe fn as_psid(&self) -> PSID {
295        PSID(self as *const Sid as *mut _)
296    }
297
298    /// Returns a raw pointer to this SID for use with Windows APIs.
299    ///
300    /// The pointer remains valid only while `self` is alive and has not been
301    /// mutably borrowed. The called API must not mutate the SID through it.
302    pub fn as_ptr(&self) -> *const c_void {
303        self as *const Sid as *const c_void
304    }
305
306    /// Borrow a raw `PSID` as `&'a Sid`, validating its structure.
307    ///
308    /// Returns `ERROR_INVALID_SID` if `psid` is not a valid SID.
309    ///
310    /// # Safety
311    ///
312    /// `psid` must point to a readable SID that stays valid for `'a`. It must also be 4-byte
313    /// aligned since the words are borrowed as `&[u32]`. The sub-authority count must be accurate
314    /// to prevent out-of-bounds reads. Every SID Windows hands out is already aligned with a correct
315    /// count.
316    ///
317    /// # Errors
318    ///
319    /// Returns `ERROR_INVALID_SID` if the revision or sub-authority count is
320    /// outside the range allowed by Windows.
321    pub unsafe fn from_psid<'a>(psid: impl AsSidPtr) -> Result<&'a Sid> {
322        let psid = psid.as_sid_ptr();
323
324        // SAFETY: the safety rules stated to the caller apply here
325        let p = psid as *const u8;
326        let (revision, sub_count) = unsafe { (*p, *p.add(1)) };
327        if revision != SID_REVISION || sub_count > SID_MAX_SUB_AUTHORITIES {
328            return Err(invalid_sid_err());
329        }
330
331        // Validate 4-byte alignment in debug mode
332        debug_assert!(
333            (psid as usize).is_multiple_of(align_of::<u32>()),
334            "SID pointer is not 4-byte aligned",
335        );
336
337        // Header + sub-authorities
338        let word_len = SID_HEADER_WORDS + sub_count as usize;
339
340        // SAFETY: the safety rules stated to the caller apply here
341        let words = unsafe { std::slice::from_raw_parts(psid as *const u32, word_len) };
342        Ok(Sid::from_words_unchecked(words))
343    }
344
345    /// Returns the SID revision.
346    ///
347    /// Valid Windows SIDs currently have revision 1.
348    #[inline]
349    pub fn revision(&self) -> u8 {
350        self.revision
351    }
352
353    /// Returns the number of sub-authorities recorded in the SID header.
354    #[inline]
355    pub fn sub_authority_count(&self) -> u8 {
356        self.sub_authority_count
357    }
358
359    /// Returns the 48-bit identifier authority as an integer.
360    #[inline]
361    pub fn authority(&self) -> u64 {
362        let [a0, a1, a2, a3, a4, a5] = self.identifier_authority;
363        u64::from_be_bytes([0, 0, a0, a1, a2, a3, a4, a5])
364    }
365
366    /// Returns the sub-authority at `idx`, or `None` if it is out of bounds.
367    #[inline]
368    pub fn sub_authority(&self, idx: u8) -> Option<u32> {
369        self.sub_authorities().get(idx as usize).copied()
370    }
371
372    /// Returns all of the SID's sub-authorities.
373    #[inline]
374    pub fn sub_authorities(&self) -> &[u32] {
375        &self.sub_authority[..self.logical_sub_count()]
376    }
377
378    /// Tests whether this SID and `other` have equal prefixes.
379    ///
380    /// A SID prefix contains the revision, identifier authority, sub-authority
381    /// count, and every sub-authority except the last.
382    #[inline]
383    pub fn equal_prefix(&self, other: &Sid) -> bool {
384        self.revision == other.revision
385            && self.identifier_authority == other.identifier_authority
386            && self.sub_authority_count == other.sub_authority_count
387            && match (
388                self.sub_authorities().split_last(),
389                other.sub_authorities().split_last(),
390            ) {
391                (Some((_, prefix1)), Some((_, prefix2))) => prefix1 == prefix2,
392                (None, None) => true,
393                _ => false,
394            }
395    }
396
397    /// Determines whether this SID and `other` belong to the same Windows account domain.
398    ///
399    /// Calls the Windows `EqualDomainSid` function.
400    ///
401    /// Both SIDs must be account-domain SIDs or BUILTIN SIDs.
402    ///
403    /// # Errors
404    ///
405    /// Returns the error reported by `EqualDomainSid`.
406    #[inline]
407    pub fn equal_domain(&self, other: &Sid) -> Result<bool> {
408        let mut equal = 0;
409        // SAFETY: both pointers refer to valid SIDs and equal is a valid output pointer
410        if unsafe {
411            bindings::EqualDomainSid(
412                self.as_ptr().cast_mut(),
413                other.as_ptr().cast_mut(),
414                &mut equal,
415            )
416        } == 0
417        {
418            return Err(Error::from_thread());
419        }
420        Ok(equal != 0)
421    }
422
423    /// Returns the Windows account-domain SID containing this SID.
424    ///
425    /// Calls the Windows `GetWindowsAccountDomainSid` function.
426    ///
427    /// # Errors
428    ///
429    /// Returns the error reported by `GetWindowsAccountDomainSid`.
430    #[inline]
431    pub fn account_domain_sid(&self) -> Result<SidBuf> {
432        unsafe {
433            let mut len = 0u32;
434            if bindings::GetWindowsAccountDomainSid(
435                self.as_ptr().cast_mut(),
436                std::ptr::null_mut(),
437                &mut len,
438            ) == 0
439            {
440                let error = Error::from_thread();
441                if error.code() != HRESULT::from_win32(bindings::ERROR_INSUFFICIENT_BUFFER) {
442                    return Err(error);
443                }
444            }
445
446            let mut domain_sid = SidBuf::with_capacity(len as usize);
447            if bindings::GetWindowsAccountDomainSid(
448                self.as_ptr().cast_mut(),
449                domain_sid.as_mut_ptr(),
450                &mut len,
451            ) == 0
452            {
453                return Err(Error::from_thread());
454            }
455            Ok(domain_sid)
456        }
457    }
458
459    /// Tests whether this SID has the specified well-known SID type.
460    ///
461    /// Calls the Windows `IsWellKnownSid` function.
462    #[inline]
463    pub fn is_well_known(&self, well_known_type: impl AsWellKnownSidType) -> bool {
464        // SAFETY: self supplies a valid SID pointer
465        unsafe {
466            bindings::IsWellKnownSid(
467                self.as_ptr().cast_mut(),
468                well_known_type.as_well_known_sid_type(),
469            ) != 0
470        }
471    }
472}
473
474impl ToOwned for Sid {
475    type Owned = SidBuf;
476    fn to_owned(&self) -> SidBuf {
477        SidBuf::from_boxed_words(self.words().to_vec().into_boxed_slice())
478    }
479}
480
481impl Eq for Sid {}
482
483impl PartialEq for Sid {
484    #[inline]
485    fn eq(&self, other: &Self) -> bool {
486        self.as_bytes() == other.as_bytes()
487    }
488}
489
490impl Hash for Sid {
491    fn hash<H: Hasher>(&self, state: &mut H) {
492        state.write(self.as_bytes());
493    }
494}
495
496impl PartialOrd for Sid {
497    #[inline]
498    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
499        Some(self.cmp(other))
500    }
501}
502
503impl Ord for Sid {
504    #[inline]
505    fn cmp(&self, other: &Self) -> Ordering {
506        self.as_bytes().cmp(other.as_bytes())
507    }
508}
509
510impl Display for Sid {
511    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
512        f.write_str("S-1-")?;
513        let authority = self.authority();
514        if authority <= 0xFFFFFFFF {
515            write!(f, "{}", authority)?;
516        } else {
517            // 12 byte hex display for authorities that don't fit in 8 bytes
518            write!(f, "0x{:012X}", authority)?;
519        }
520
521        for sa in self.sub_authorities() {
522            write!(f, "-{}", sa)?;
523        }
524
525        Ok(())
526    }
527}
528
529impl Debug for Sid {
530    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
531        write!(f, "\"{}\"", self)
532    }
533}
534
535/// An owned copy of a SID's bytes.
536///
537/// `SidBuf` dereferences to [`Sid`], so all borrowed-SID operations are
538/// available directly on an owned value. Clone a `SidBuf` to duplicate its
539/// bytes, or borrow it as `&Sid` without allocating.
540///
541/// # Examples
542///
543/// ```
544/// use safe_sid::{Sid, SidBuf};
545///
546/// let owned: SidBuf = "S-1-5-18".parse()?;
547/// let borrowed: &Sid = &owned;
548///
549/// assert_eq!(borrowed.to_string(), "S-1-5-18");
550/// assert_eq!(borrowed.to_owned(), owned);
551/// # Ok::<(), safe_sid::ParseError>(())
552/// ```
553pub struct SidBuf {
554    sid: Box<Sid>,
555}
556
557impl Clone for SidBuf {
558    fn clone(&self) -> Self {
559        (**self).to_owned()
560    }
561}
562
563#[derive(Debug)]
564/// The error returned when a string is not a valid numeric SID.
565///
566/// See [`SidBuf::from_str`](FromStr::from_str) for the accepted format.
567pub struct ParseError;
568
569impl std::error::Error for ParseError {}
570impl Display for ParseError {
571    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
572        write!(f, "invalid SID string")
573    }
574}
575
576impl FromStr for SidBuf {
577    type Err = ParseError;
578
579    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
580        let mut parts = s.split('-');
581
582        // Leading "S", case-insensitive
583        match parts.next() {
584            Some(p) if p.eq_ignore_ascii_case("S") => {}
585            _ => return Err(ParseError),
586        }
587
588        // Revision (only 1 is allowed)
589        if parts.next() != Some("1") {
590            return Err(ParseError);
591        }
592
593        // Identifier authority: decimal or 0x-prefixed hex, 48 bits max
594        let authority_str = parts.next().ok_or(ParseError)?;
595        let authority = match authority_str
596            .strip_prefix("0x")
597            .or_else(|| authority_str.strip_prefix("0X"))
598        {
599            Some(hex) => u64::from_str_radix(hex, 16).map_err(|_| ParseError)?,
600            None => authority_str.parse::<u64>().map_err(|_| ParseError)?,
601        };
602        if authority > 0xFFFF_FFFF_FFFF {
603            return Err(ParseError);
604        }
605        let identifier_authority: [u8; 6] = authority.to_be_bytes()[2..].try_into().unwrap();
606
607        // Remaining fields are decimal sub-authorities
608        let sub_authorities = parts
609            .map(|p| p.parse::<u32>())
610            .collect::<std::result::Result<Vec<u32>, _>>()
611            .map_err(|_| ParseError)?;
612
613        SidBuf::new(identifier_authority, &sub_authorities).map_err(|_| ParseError)
614    }
615}
616
617impl SidBuf {
618    /// Takes ownership of already-validated SID data as a `Box<Sid>`.
619    ///
620    /// `words` must be the two header words followed by the sub-authority words.
621    fn from_boxed_words(words: Box<[u32]>) -> SidBuf {
622        debug_assert!(
623            words.len() >= SID_HEADER_WORDS,
624            "a SID has at least the two header words"
625        );
626        let sub_count = words.len() - SID_HEADER_WORDS;
627        // A DST only tracks the size of the array. Our input box is entirely an array while our
628        // Sid struct has 2 words before the array. When creating a Sid pointer from the u64 slice
629        // we have to account for that by subtracting off the header.
630        let data = Box::into_raw(words).cast::<u32>();
631        let ptr = std::ptr::slice_from_raw_parts_mut(data, sub_count) as *mut Sid;
632        // SAFETY: We are reboxing a pointer with the same alignment as the one it was detached from
633        SidBuf {
634            sid: unsafe { Box::from_raw(ptr) },
635        }
636    }
637
638    /// Builds a SID from its identifier authority and sub-authorities.
639    ///
640    /// Returns `ERROR_INVALID_SID` if more than 15 sub-authorities are given.
641    ///
642    /// # Examples
643    ///
644    /// ```
645    /// use safe_sid::SidBuf;
646    ///
647    /// let administrators = SidBuf::new([0, 0, 0, 0, 0, 5], &[32, 544])?;
648    /// assert_eq!(administrators.to_string(), "S-1-5-32-544");
649    /// # Ok::<(), windows_core::Error>(())
650    /// ```
651    pub fn new(identifier_authority: [u8; 6], sub_authorities: &[u32]) -> Result<Self> {
652        let count = sub_authorities.len();
653        if count > SID_MAX_SUB_AUTHORITIES as usize {
654            return Err(invalid_sid_err());
655        }
656
657        let mut words = vec![0u32; SID_HEADER_WORDS + count].into_boxed_slice();
658        let sid = Sid::from_words_unchecked_mut(&mut words);
659        sid.revision = SID_REVISION;
660        sid.sub_authority_count = count as u8;
661        sid.identifier_authority = identifier_authority;
662        sid.sub_authority.copy_from_slice(sub_authorities);
663
664        Ok(Self::from_boxed_words(words))
665    }
666
667    /// Allocates a `SidBuf` of `len` bytes for a Windows API to fill.
668    ///
669    /// The buffer initially contains the null SID (`S-1-0-0`). `len` is the
670    /// total requested size of the SID structure in bytes. It is rounded up to
671    /// the next four-byte boundary, with a minimum allocation of 12 bytes.
672    ///
673    /// Extra capacity is not exposed by [`Sid::as_bytes`]; the logical length is
674    /// determined by [`Sid::sub_authority_count`].
675    pub fn with_capacity(len: usize) -> SidBuf {
676        let word_len = len.div_ceil(size_of::<u32>()).max(SID_HEADER_WORDS + 1);
677
678        let mut words = vec![0u32; word_len].into_boxed_slice();
679        let sid = Sid::from_words_unchecked_mut(&mut words);
680        sid.revision = SID_REVISION;
681        sid.sub_authority_count = 1;
682
683        SidBuf::from_boxed_words(words)
684    }
685
686    /// Returns a mutable pointer to this SID's bytes, for passing to a Windows API that
687    /// fills a caller-supplied buffer.
688    ///
689    /// This is intended for the second call of Windows APIs that first report a
690    /// required buffer length. Allocate that length with
691    /// [`SidBuf::with_capacity`], then pass this pointer to the API.
692    ///
693    /// # Safety
694    ///
695    /// Writing through the pointer can leave the buffer holding bytes that are not
696    /// a valid SID. The caller must not write past the length supplied to
697    /// [`SidBuf::with_capacity`] and must leave a valid SID behind before the
698    /// buffer is read through `&Sid`. Dropping the buffer remains safe even if
699    /// the API fails or writes malformed data.
700    ///
701    /// # Examples
702    ///
703    /// This example uses the standard two-call pattern to look up an account
704    /// name. The first call obtains the two buffer lengths, and the second fills
705    /// the allocated SID and domain-name buffers.
706    ///
707    /// ```no_run
708    /// # #[cfg(feature = "windows-full")]
709    /// # {
710    /// use safe_sid::SidBuf;
711    /// use std::ffi::CStr;
712    /// use windows::Win32::Security::{LookupAccountNameA, PSID, SID_NAME_USE};
713    /// use windows_core::{HRESULT, PCSTR, PSTR, Result};
714    ///
715    /// fn lookup_account_name(name: &CStr) -> Result<SidBuf> {
716    ///     let mut sid_use = SID_NAME_USE::default();
717    ///     let mut sid_len = 0u32;
718    ///     let mut domain_len = 0u32;
719    ///
720    ///     unsafe {
721    ///         if let Err(error) = LookupAccountNameA(
722    ///             PCSTR::null(),
723    ///             PCSTR(name.as_ptr().cast()),
724    ///             None,
725    ///             &mut sid_len,
726    ///             None,
727    ///             &mut domain_len,
728    ///             &mut sid_use,
729    ///         ) && error.code() != HRESULT::from_win32(122) // ERROR_INSUFFICIENT_BUFFER
730    ///         {
731    ///             return Err(error);
732    ///         }
733    ///
734    ///         let mut sid = SidBuf::with_capacity(sid_len as usize);
735    ///         let mut domain = vec![0u8; domain_len as usize];
736    ///         LookupAccountNameA(
737    ///             PCSTR::null(),
738    ///             PCSTR(name.as_ptr().cast()),
739    ///             Some(PSID(sid.as_mut_ptr())),
740    ///             &mut sid_len,
741    ///             Some(PSTR(domain.as_mut_ptr())),
742    ///             &mut domain_len,
743    ///             &mut sid_use,
744    ///         )?;
745    ///         Ok(sid)
746    ///     }
747    /// }
748    ///
749    /// # let _ = lookup_account_name;
750    /// # }
751    /// ```
752    pub unsafe fn as_mut_ptr(&mut self) -> *mut c_void {
753        let sid: &mut Sid = &mut self.sid;
754        sid as *mut Sid as *mut c_void
755    }
756
757    /// Builds a well-known SID with `CreateWellKnownSid`.
758    ///
759    /// `domain_sid` is required for well-known types whose value depends on a
760    /// Windows domain and should otherwise be `None`.
761    ///
762    /// # Errors
763    ///
764    /// Returns the error reported by `CreateWellKnownSid`.
765    ///
766    /// # Examples
767    ///
768    /// ```
769    /// use safe_sid::{SidBuf, WinLocalSystemSid};
770    ///
771    /// let local_system = SidBuf::well_known(WinLocalSystemSid, None)?;
772    /// assert_eq!(local_system.to_string(), "S-1-5-18");
773    /// # Ok::<(), windows_core::Error>(())
774    /// ```
775    pub fn well_known(
776        well_known_type: impl AsWellKnownSidType,
777        domain_sid: Option<&Sid>,
778    ) -> Result<SidBuf> {
779        unsafe {
780            let well_known_type = well_known_type.as_well_known_sid_type();
781            let domain_psid = domain_sid
782                .map(|sid| sid.as_ptr().cast_mut())
783                .unwrap_or(std::ptr::null_mut());
784            let mut len = 0u32;
785            if bindings::CreateWellKnownSid(
786                well_known_type,
787                domain_psid,
788                std::ptr::null_mut(),
789                &mut len,
790            ) == 0
791            {
792                let error = Error::from_thread();
793                if error.code() != HRESULT::from_win32(bindings::ERROR_INSUFFICIENT_BUFFER) {
794                    return Err(error);
795                }
796            }
797
798            let word_len = (len as usize).div_ceil(size_of::<u32>());
799            let mut words: Box<[u32]> = vec![0u32; word_len].into_boxed_slice();
800            if bindings::CreateWellKnownSid(
801                well_known_type,
802                domain_psid,
803                words.as_mut_ptr().cast(),
804                &mut len,
805            ) == 0
806            {
807                return Err(Error::from_thread());
808            }
809
810            Ok(SidBuf::from_boxed_words(words))
811        }
812    }
813
814    /// Converts a C string to a SID with `ConvertStringSidToSidA`.
815    ///
816    /// Unlike [`FromStr`], this accepts string constants such as `BA` and `AU`
817    /// in addition to numeric SIDs. Windows performs the parsing and may clamp
818    /// overflowing numeric components instead of rejecting them.
819    ///
820    /// # Errors
821    ///
822    /// Returns the error reported by `ConvertStringSidToSidA`.
823    ///
824    /// # Examples
825    ///
826    /// ```
827    /// use safe_sid::SidBuf;
828    ///
829    /// let administrators = SidBuf::from_cstr_with_alias(c"BA")?;
830    /// assert_eq!(administrators.to_string(), "S-1-5-32-544");
831    /// # Ok::<(), windows_core::Error>(())
832    /// ```
833    pub fn from_cstr_with_alias(s: &std::ffi::CStr) -> Result<SidBuf> {
834        unsafe {
835            let mut sid = std::ptr::null_mut();
836            if bindings::ConvertStringSidToSidA(s.as_ptr().cast(), &mut sid) == 0 {
837                return Err(Error::from_thread());
838            }
839            let res = SidBuf::from_psid(sid);
840            bindings::LocalFree(sid);
841            res
842        }
843    }
844
845    /// Validates and copies the SID pointed to by `psid` into an owned buffer.
846    ///
847    /// Returns `ERROR_INVALID_SID` if the pointer does not reference a valid SID.
848    ///
849    /// # Safety
850    ///
851    /// `psid` must point to a 4-byte-aligned SID structure valid for the duration of this
852    /// call. The data is copied so there is no lifetime requirement for `psid` after this returns.
853    ///
854    /// # Examples
855    ///
856    /// ```
857    /// use safe_sid::{Sid, SidBuf};
858    ///
859    /// let source: SidBuf = "S-1-5-18".parse().unwrap();
860    ///
861    /// let borrowed: &Sid = unsafe { Sid::from_psid(source.as_ptr())? };
862    /// let copied = unsafe { SidBuf::from_psid(source.as_ptr())? };
863    ///
864    /// assert_eq!(borrowed, &*source);
865    /// assert_eq!(copied, source);
866    /// # Ok::<(), windows_core::Error>(())
867    /// ```
868    pub unsafe fn from_psid(psid: impl AsSidPtr) -> Result<Self> {
869        // SAFETY: safety requirements noted to called in the doc comment
870        let src = unsafe { Sid::from_psid(psid) }?;
871        Ok(src.to_owned())
872    }
873}
874
875impl Deref for SidBuf {
876    type Target = Sid;
877    #[inline]
878    fn deref(&self) -> &Sid {
879        &self.sid
880    }
881}
882
883impl Borrow<Sid> for SidBuf {
884    #[inline]
885    fn borrow(&self) -> &Sid {
886        self
887    }
888}
889
890impl AsRef<Sid> for SidBuf {
891    #[inline]
892    fn as_ref(&self) -> &Sid {
893        self
894    }
895}
896
897impl Eq for SidBuf {}
898
899impl PartialEq for SidBuf {
900    #[inline]
901    fn eq(&self, other: &Self) -> bool {
902        (**self).eq(&**other)
903    }
904}
905
906impl Hash for SidBuf {
907    fn hash<H: Hasher>(&self, state: &mut H) {
908        (**self).hash(state);
909    }
910}
911
912impl PartialOrd for SidBuf {
913    #[inline]
914    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
915        Some(self.cmp(other))
916    }
917}
918
919impl Ord for SidBuf {
920    #[inline]
921    fn cmp(&self, other: &Self) -> Ordering {
922        (**self).cmp(&**other)
923    }
924}
925
926impl Display for SidBuf {
927    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
928        Display::fmt(&**self, f)
929    }
930}
931
932impl Debug for SidBuf {
933    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
934        Debug::fmt(&**self, f)
935    }
936}
937
938impl Default for SidBuf {
939    fn default() -> Self {
940        SidBuf::new([0, 0, 0, 0, 0, 0], &[0]).unwrap()
941    }
942}
943
944impl PartialEq<SidBuf> for Sid {
945    #[inline]
946    fn eq(&self, other: &SidBuf) -> bool {
947        self == &**other
948    }
949}
950
951impl PartialEq<Sid> for SidBuf {
952    #[inline]
953    fn eq(&self, other: &Sid) -> bool {
954        &**self == other
955    }
956}
957
958#[cfg(test)]
959mod tests {
960    use super::*;
961
962    const NT_AUTHORITY: [u8; 6] = [0, 0, 0, 0, 0, 5];
963
964    fn nt_sid(sub_authorities: &[u32]) -> SidBuf {
965        SidBuf::new(NT_AUTHORITY, sub_authorities).unwrap()
966    }
967
968    #[test]
969    fn from_psid_rejects_invalid_headers() {
970        for header in [[0, 0], [SID_REVISION, SID_MAX_SUB_AUTHORITIES + 1]] {
971            let words = [u32::from_ne_bytes([header[0], header[1], 0, 0]), 0];
972            let psid = words.as_ptr() as *const c_void;
973
974            assert!(unsafe { Sid::from_psid(psid) }.is_err());
975            assert!(unsafe { SidBuf::from_psid(psid) }.is_err());
976        }
977    }
978
979    #[test]
980    fn new_enforces_the_sub_authority_limit() {
981        assert_eq!(
982            SidBuf::new([0; 6], &[7; 15]).unwrap().sub_authority_count(),
983            15
984        );
985        assert!(SidBuf::new([0; 6], &[0; 16]).is_err());
986    }
987
988    #[test]
989    fn well_known_sids_construct() {
990        for (kind, expected) in [
991            (WinNullSid, "S-1-0-0"),
992            (WinLocalSystemSid, "S-1-5-18"),
993            (WinBuiltinAdministratorsSid, "S-1-5-32-544"),
994        ] {
995            assert_eq!(
996                SidBuf::well_known(kind, None).unwrap().to_string(),
997                expected
998            );
999        }
1000    }
1001
1002    #[test]
1003    fn new_builds_the_expected_sid() {
1004        let sid = nt_sid(&[32, 544]);
1005
1006        assert_eq!(
1007            sid.as_bytes(),
1008            &[
1009                0x01, // revision
1010                0x02, // sub-authority count
1011                0x00, 0x00, 0x00, 0x00, 0x00, 0x05, // authority, big-endian
1012                0x20, 0x00, 0x00, 0x00, // sub-authority #1, little-endian
1013                0x20, 0x02, 0x00, 0x00, // sub-authority #2, little-endian
1014            ]
1015        );
1016        assert_eq!(sid.revision(), SID_REVISION);
1017        assert_eq!(sid.sub_authority_count(), 2);
1018        assert_eq!(sid.authority(), 5);
1019        assert_eq!(sid.sub_authority(0), Some(32));
1020        assert_eq!(sid.sub_authority(1), Some(544));
1021        assert_eq!(sid.sub_authority(2), None);
1022        assert_eq!(sid.sub_authorities(), [32, 544]);
1023    }
1024
1025    #[test]
1026    fn from_psid_borrows_or_copies_as_requested() {
1027        let copied = {
1028            let src = nt_sid(&[18]);
1029            let borrowed = unsafe { Sid::from_psid(src.as_ptr()) }.expect("valid SID");
1030            let copied = unsafe { SidBuf::from_psid(src.as_ptr()) }.expect("valid SID");
1031
1032            assert_eq!(borrowed, &*src);
1033            assert_eq!(copied, src);
1034            copied
1035        };
1036
1037        assert_eq!(copied.to_string(), "S-1-5-18");
1038    }
1039
1040    #[cfg(feature = "windows-full")]
1041    #[test]
1042    fn windows_psid_interoperates_when_enabled() {
1043        let source = nt_sid(&[18]);
1044        let psid = unsafe { source.as_psid() };
1045
1046        assert_eq!(unsafe { Sid::from_psid(psid) }.unwrap(), &*source);
1047    }
1048
1049    #[cfg(feature = "windows-full")]
1050    #[test]
1051    fn windows_well_known_sid_types_interoperate_when_enabled() {
1052        use windows::Win32::Security::WinLocalSystemSid as WindowsWinLocalSystemSid;
1053
1054        let local_system = SidBuf::well_known(WindowsWinLocalSystemSid, None).unwrap();
1055
1056        assert!(local_system.is_well_known(WindowsWinLocalSystemSid));
1057    }
1058
1059    #[test]
1060    fn with_capacity_separates_logical_length_from_buffer_length() {
1061        for (requested, allocated) in [(0, 12), (12, 12), (13, 16), (200, 200)] {
1062            let sid = SidBuf::with_capacity(requested);
1063
1064            assert_eq!(sid.buffer_bytes().len(), allocated);
1065            assert_eq!(sid.as_bytes().len(), 12);
1066            assert_eq!(sid, SidBuf::default());
1067        }
1068    }
1069
1070    #[test]
1071    fn as_mut_ptr_lets_a_caller_fill_the_buffer() {
1072        // Size a buffer for S-1-5-32-544, then fill it through the raw pointer the
1073        // way a Windows API would write into a caller-supplied buffer
1074        let admins = nt_sid(&[32, 544]);
1075        let mut buf = SidBuf::with_capacity(admins.as_bytes().len());
1076
1077        unsafe {
1078            let dst = buf.as_mut_ptr() as *mut u8;
1079            std::ptr::copy_nonoverlapping(admins.as_bytes().as_ptr(), dst, admins.as_bytes().len());
1080        }
1081
1082        assert_eq!(buf, admins);
1083    }
1084
1085    #[test]
1086    fn value_traits_ignore_spare_buffer_capacity() {
1087        use std::collections::hash_map::DefaultHasher;
1088
1089        let oversized = SidBuf::with_capacity(200);
1090        let null_sid = SidBuf::default();
1091
1092        assert_eq!(oversized, null_sid);
1093        assert_eq!(oversized.as_bytes(), null_sid.as_bytes());
1094        assert_eq!(oversized.cmp(&null_sid), Ordering::Equal);
1095
1096        let mut oversized_hash = DefaultHasher::new();
1097        oversized.hash(&mut oversized_hash);
1098        let mut null_hash = DefaultHasher::new();
1099        null_sid.hash(&mut null_hash);
1100        assert_eq!(oversized_hash.finish(), null_hash.finish());
1101    }
1102
1103    #[test]
1104    fn owned_and_borrowed_views_agree() {
1105        let owned = nt_sid(&[18]);
1106        let via_deref: &Sid = &owned;
1107        let via_borrow: &Sid = owned.borrow();
1108        let via_as_ref: &Sid = owned.as_ref();
1109
1110        assert_eq!(via_deref, via_borrow);
1111        assert_eq!(via_deref, via_as_ref);
1112        assert_eq!(via_deref.to_owned(), owned);
1113        assert_eq!(*via_deref, owned);
1114        assert_eq!(owned, *via_deref);
1115    }
1116
1117    #[test]
1118    fn display_and_debug_render_canonical_strings() {
1119        let cases = [
1120            (SidBuf::default(), "S-1-0-0"),
1121            (nt_sid(&[18]), "S-1-5-18"),
1122            (nt_sid(&[32, 544]), "S-1-5-32-544"),
1123            (
1124                SidBuf::new([0, 0, 0xFF, 0xFF, 0xFF, 0xFF], &[1]).unwrap(),
1125                "S-1-4294967295-1",
1126            ),
1127            (
1128                SidBuf::new([0, 1, 0, 0, 0, 0], &[1, 2]).unwrap(),
1129                "S-1-0x000100000000-1-2",
1130            ),
1131        ];
1132
1133        for (sid, expected) in cases {
1134            assert_eq!(sid.to_string(), expected);
1135            assert_eq!(format!("{sid:?}"), format!("{expected:?}"));
1136            assert_eq!(format!("{:?}", &*sid), format!("{expected:?}"));
1137        }
1138    }
1139
1140    #[test]
1141    fn from_str_parses_and_round_trips_display() {
1142        // Display and parse are inverse of each-other for our SID, so ensure that they round-trip
1143        for s in [
1144            "S-1-0-0",
1145            "S-1-5-18",
1146            "S-1-5-32-544",
1147            "S-1-0x000100000000-1-2",
1148        ] {
1149            let sid: SidBuf = s.parse().unwrap();
1150            assert_eq!(sid.to_string(), s);
1151        }
1152
1153        // Validate that both decimal and hex forms of the same SID are equal
1154        assert_eq!(
1155            "s-1-4294967296-1".parse::<SidBuf>().unwrap(),
1156            "S-1-0x000100000000-1".parse::<SidBuf>().unwrap(),
1157        );
1158
1159        // A SID can have zero sub-authorities
1160        assert_eq!(
1161            "S-1-5".parse::<SidBuf>().unwrap().sub_authorities(),
1162            &[] as &[u32]
1163        );
1164    }
1165
1166    #[test]
1167    fn from_str_rejects_malformed_input() {
1168        for s in [
1169            "",                                             // empty
1170            "X-1-5-18",                                     // wrong prefix
1171            "S-2-5-18",                                     // unsupported revision
1172            "S-1",                                          // missing authority
1173            "S-1-5-",                                       // trailing separator
1174            "S-1-5-4294967296",                             // sub-authority overflows u32
1175            "S-1-0x1000000000000-1",                        // authority overflows 48 bits
1176            "S-1-5-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16", // more than 15 sub-authorities
1177        ] {
1178            assert!(s.parse::<SidBuf>().is_err(), "parsing should reject {s:?}");
1179        }
1180    }
1181
1182    #[test]
1183    fn equality_and_ordering_follow_sid_bytes() {
1184        let a = nt_sid(&[18]);
1185        let b = nt_sid(&[18]);
1186        let c = nt_sid(&[19]);
1187        assert_eq!(a, b);
1188        assert_ne!(a, c);
1189
1190        assert!(a < nt_sid(&[32, 544]));
1191    }
1192
1193    #[test]
1194    fn equal_prefix_ignores_only_the_last_sub_authority() {
1195        let first = nt_sid(&[21, 1, 2, 3, 1000]);
1196        let same_prefix = nt_sid(&[21, 1, 2, 3, 2000]);
1197        let different_prefix = nt_sid(&[21, 1, 2, 4, 1000]);
1198        let different_count = nt_sid(&[21, 1, 2, 3]);
1199        let different_authority = SidBuf::new([0, 0, 0, 0, 0, 4], &[21, 1, 2, 3, 2000]).unwrap();
1200
1201        assert!(first.equal_prefix(&same_prefix));
1202        assert!(!first.equal_prefix(&different_prefix));
1203        assert!(!first.equal_prefix(&different_count));
1204        assert!(!first.equal_prefix(&different_authority));
1205
1206        let no_sub_authorities = SidBuf::new(NT_AUTHORITY, &[]).unwrap();
1207        assert!(no_sub_authorities.equal_prefix(&no_sub_authorities));
1208    }
1209
1210    #[test]
1211    fn windows_domain_helpers_compare_and_extract_domains() {
1212        let first = nt_sid(&[21, 1, 2, 3, 1000]);
1213        let same_domain = nt_sid(&[21, 1, 2, 3, 2000]);
1214        let different_domain = nt_sid(&[21, 1, 2, 4, 1000]);
1215        let expected_domain = nt_sid(&[21, 1, 2, 3]);
1216
1217        assert!(first.equal_domain(&same_domain).unwrap());
1218        assert!(!first.equal_domain(&different_domain).unwrap());
1219        assert_eq!(first.account_domain_sid().unwrap(), expected_domain);
1220    }
1221
1222    #[test]
1223    fn well_known_sid_helper_classifies_sids() {
1224        let local_system = nt_sid(&[18]);
1225        assert!(local_system.is_well_known(WinLocalSystemSid));
1226        assert!(!local_system.is_well_known(WinWorldSid));
1227    }
1228
1229    #[test]
1230    fn borrowed_sid_looks_up_owned_key() {
1231        use std::collections::HashMap;
1232
1233        let mut map = HashMap::new();
1234        map.insert(nt_sid(&[18]), "LocalSystem");
1235
1236        let key = nt_sid(&[18]);
1237        let probe: &Sid = &key;
1238        assert_eq!(map.get(probe), Some(&"LocalSystem"));
1239    }
1240
1241    #[test]
1242    fn from_cstr_supports_numeric_and_aliases() {
1243        let ba = nt_sid(&[32, 544]);
1244        assert_eq!(SidBuf::from_cstr_with_alias(c"BA").unwrap(), ba);
1245        assert_eq!(SidBuf::from_cstr_with_alias(c"S-1-5-32-544").unwrap(), ba);
1246    }
1247
1248    #[test]
1249    fn from_cstr_fails_on_bad_input() {
1250        assert!(SidBuf::from_cstr_with_alias(c"").is_err());
1251        assert!(SidBuf::from_cstr_with_alias(c"not-a-sid").is_err());
1252    }
1253}