Skip to main content

ms_lsat/
lib.rs

1//! **MS-LSAT** — Local Security Authority (Translation) Remote Protocol.
2//!
3//! Windows exposes LSA name↔SID lookup services over `\PIPE\lsarpc` and (some) LSA
4//! policy queries. The most common opnums pentesters + defenders actually use:
5//!
6//! | Opnum | Name | Purpose |
7//! |---|---|---|
8//! | 6 | `LsarOpenPolicy2` | Get a policy handle (starting point for every other op) |
9//! | 14 | `LsarLookupSids` | SID → account name (RID-brute enumeration when SAMR is blocked) |
10//! | 15 | `LsarLookupNames` | Name → SID (works before authentication in some configs) |
11//! | 57 | `LsarLookupSids2` / | Same as 14 but wide-string, PACKAGE-RPC-CONNECT capable |
12//! | 58 | `LsarLookupNames2` | Same as 15 but wide-string |
13//!
14//! Rides an authenticated (or in some configs, anonymous) SMB pipe.
15//!
16//! # What this crate provides in v0.1
17//!
18//! Wire encoders + decoders for `LsarOpenPolicy2`, `LsarLookupSids2`, `LsarLookupNames2`,
19//! and `LsarClose`, plus a small [`LsatClient`] wrapper that binds the interface over
20//! [`dcerpc::transport::SmbPipe`] and exposes ergonomic `lookup_sids(&[Sid]) → Vec<Name>`
21//! and `lookup_names(&[&str]) → Vec<Sid>` methods.
22//!
23//! # Byte-format
24//!
25//! Encoders match impacket's `lsat.*` / `lsad.*` NDR marshaling (byte-verified against
26//! impacket wire captures on Server 2016/2019/2022/2025). The lookup response layouts are
27//! the ones that require the most care — see the module docs on [`decode_lookup_sids2`]
28//! and [`decode_lookup_names2`] for the pointer-shape.
29
30use dcerpc::ndr::{NdrDecoder, NdrEncoder};
31use dcerpc::transport::SmbPipe;
32use dcerpc::{Result, Syntax};
33use smb2_client::SmbClient;
34use windows_sddl::sid::Sid;
35
36/// The LSAT interface (v0.0). Same UUID as the LSA-Directory (LSAD) interface.
37pub fn lsat_syntax() -> Syntax {
38    Syntax::new("12345778-1234-abcd-ef00-0123456789ab", 0, 0)
39}
40
41pub mod opnum {
42    pub const CLOSE: u16 = 0;
43    pub const OPEN_POLICY: u16 = 6;
44    pub const LOOKUP_NAMES: u16 = 14;
45    pub const LOOKUP_SIDS: u16 = 15;
46    pub const OPEN_POLICY2: u16 = 44;
47    pub const LOOKUP_SIDS2: u16 = 57;
48    pub const LOOKUP_NAMES2: u16 = 58;
49}
50
51/// Common LSA policy-access flags.
52pub mod access {
53    pub const POLICY_VIEW_LOCAL_INFORMATION: u32 = 0x0000_0001;
54    pub const POLICY_LOOKUP_NAMES: u32 = 0x0000_0800;
55    /// The "asks the server to pick" access — sufficient for lookups on most configs.
56    pub const MAXIMUM_ALLOWED: u32 = 0x0200_0000;
57}
58
59/// SID-name-use enum values ([MS-LSAT] §2.2.13).
60#[non_exhaustive]
61#[repr(u16)]
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub enum SidType {
64    User = 1,
65    Group = 2,
66    Domain = 3,
67    Alias = 4,
68    WellKnownGroup = 5,
69    DeletedAccount = 6,
70    Invalid = 7,
71    Unknown = 8,
72    Computer = 9,
73    Label = 10,
74}
75
76impl SidType {
77    pub fn from_u16(v: u16) -> Self {
78        match v {
79            1 => SidType::User,
80            2 => SidType::Group,
81            3 => SidType::Domain,
82            4 => SidType::Alias,
83            5 => SidType::WellKnownGroup,
84            6 => SidType::DeletedAccount,
85            7 => SidType::Invalid,
86            9 => SidType::Computer,
87            10 => SidType::Label,
88            _ => SidType::Unknown,
89        }
90    }
91}
92
93/// A 20-byte RPC context handle (attributes u32 + 16-byte GUID). Same shape as SAMR's.
94#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
95pub struct PolicyHandle(pub [u8; 20]);
96
97impl PolicyHandle {
98    pub fn decode(d: &mut NdrDecoder) -> Result<Self> {
99        let attrs = d.u32()?;
100        let uuid = d.uuid()?;
101        let mut h = [0u8; 20];
102        h[..4].copy_from_slice(&attrs.to_le_bytes());
103        h[4..].copy_from_slice(&uuid);
104        Ok(PolicyHandle(h))
105    }
106    pub fn encode(&self, e: &mut NdrEncoder) {
107        e.bytes(&self.0);
108    }
109}
110
111// ---- LsarOpenPolicy2 -------------------------------------------------------
112
113/// LsarOpenPolicy2(SystemName [in,unique,string], ObjectAttributes [in], DesiredAccess [in])
114///
115/// ObjectAttributes is an LSAPR_OBJECT_ATTRIBUTES: `Length + RootDirectory + ObjectName +
116/// Attributes + SecurityDescriptor + SecurityQualityOfService`. Every field is 0/NULL for
117/// a lookup client (the spec says all fields are ignored by the server for OpenPolicy).
118pub fn encode_open_policy2(system_name: &str, desired_access: u32) -> Vec<u8> {
119    let mut e = NdrEncoder::new();
120    // SystemName is [unique,string] — referent + WSTR pointee
121    e.referent();
122    e.conformant_varying_wstr(system_name);
123    e.align(4);
124    // LSAPR_OBJECT_ATTRIBUTES { Length, RootDirectory, ObjectName, Attributes,
125    //                          SecurityDescriptor, SecurityQualityOfService }
126    e.u32(24); // Length = sizeof(LSAPR_OBJECT_ATTRIBUTES) = 24 (per MS-LSAD)
127    e.null_ptr(); // RootDirectory (unused, MBZ)
128    e.null_ptr(); // ObjectName pointer
129    e.u32(0); // Attributes
130    e.null_ptr(); // SecurityDescriptor pointer
131    e.null_ptr(); // SecurityQualityOfService pointer
132    e.u32(desired_access);
133    e.into_bytes()
134}
135
136// ---- RPC_SID marshaling (shared with SAMR) --------------------------------
137
138/// Encode an RPC_SID conformant array. `max_count` (u32) hoisted then Revision +
139/// SubAuthorityCount + Authority + SubAuthority[]. Same layout as SAMR uses.
140fn encode_sid(e: &mut NdrEncoder, sid: &Sid) {
141    e.u32(sid.sub_authorities.len() as u32);
142    e.u8(sid.revision);
143    e.u8(sid.sub_authorities.len() as u8);
144    let a = sid.identifier_authority;
145    e.bytes(&[
146        (a >> 40) as u8,
147        (a >> 32) as u8,
148        (a >> 24) as u8,
149        (a >> 16) as u8,
150        (a >> 8) as u8,
151        a as u8,
152    ]);
153    for s in &sid.sub_authorities {
154        e.u32(*s);
155    }
156}
157
158fn decode_sid(d: &mut NdrDecoder) -> Result<Sid> {
159    let _max = d.u32()?;
160    let revision = d.u8()?;
161    let count = d.u8()? as usize;
162    let auth = d.read_bytes(6)?;
163    let identifier_authority = auth.iter().fold(0u64, |acc, &b| (acc << 8) | b as u64);
164    let mut sub_authorities = Vec::with_capacity(count);
165    for _ in 0..count {
166        sub_authorities.push(d.u32()?);
167    }
168    Ok(Sid {
169        revision,
170        identifier_authority,
171        sub_authorities,
172    })
173}
174
175// ---- LsarLookupSids2 ------------------------------------------------------
176
177/// One row of a LookupSids response: the resolved name (or empty) and its type.
178#[derive(Debug, Clone, PartialEq, Eq)]
179#[non_exhaustive]
180pub struct LookedUpSid {
181    /// The (relative) account name — `""` when the SID couldn't be resolved.
182    pub name: String,
183    /// The referenced domain name (from ReferencedDomainList) — `""` when unresolvable.
184    pub domain: String,
185    /// Object type (User / Group / Domain / …).
186    pub kind: SidType,
187}
188
189/// LsarLookupSids2(PolicyHandle, SidEnumBuffer, [out]RefDomains, [in,out]Names, LookupLevel,
190/// [in,out]MappedCount, LookupOptions, ClientRevision).
191///
192/// - `lookup_level` = 1 (LsapLookupWksta) is the safest default.
193/// - `client_revision` = 2 for modern Windows.
194pub fn encode_lookup_sids2(
195    handle: &PolicyHandle,
196    sids: &[Sid],
197    lookup_level: u16,
198    client_revision: u32,
199) -> Vec<u8> {
200    let mut e = NdrEncoder::new();
201    handle.encode(&mut e);
202
203    // SidEnumBuffer = { Entries: u32, SidInfo: [ref]PSIDENUMBUFFER→[size_is(Entries)]RPC_SID_INFORMATION[] }
204    // RPC_SID_INFORMATION = { Sid: [ref]PRPC_SID }
205    e.u32(sids.len() as u32); // Entries
206    e.referent(); // SidInfo array pointer
207    e.u32(sids.len() as u32); // conformant max_count
208
209    // First pass: for each entry, emit its RPC_SID_INFORMATION fixed part (a pointer).
210    for _ in sids {
211        e.referent(); // Sid pointer (deferred)
212    }
213    // Deferred: RPC_SID for each entry (in order).
214    for sid in sids {
215        encode_sid(&mut e, sid);
216    }
217
218    // [out] TranslatedName_2 buffer: caller supplies an empty structure to be filled.
219    // { Entries: u32 = 0, Names: [unique] = NULL }
220    e.u32(0); // Entries
221    e.null_ptr(); // Names pointer NULL
222
223    e.u16(lookup_level);
224    e.align(4);
225    e.u32(0); // MappedCount [in] = 0
226
227    e.u32(0); // LookupOptions
228    e.u32(client_revision);
229    e.into_bytes()
230}
231
232/// Decode a LsarLookupSids2 response into per-input rows.
233///
234/// The wire shape (in order of appearance):
235/// 1. `ReferencedDomainList` pointer (may be NULL if MappedCount == 0)
236///    → { Entries: u32, Domains: array ptr, MaxEntries: u32 }
237///    → each domain: { Name: RPC_UNICODE_STRING, Sid: [ref]PRPC_SID }
238///    → deferred: Name.Buffer WSTR + RPC_SID for each domain (in emit order)
239/// 2. `TranslatedNames` structure: { Entries: u32, Names: [ref]PLSAPR_TRANSLATED_NAME_EX[] }
240///    → each name (20 bytes fixed): Use(u16) + pad(2) + Name.Length(u16) + Name.Max(u16) +
241///      Buffer(u32/ptr) + DomainIndex(i32) + Flags(u32)
242///    → deferred: Name.Buffer WSTR for each (in emit order)
243/// 3. `MappedCount`: u32
244/// 4. Trailing NTSTATUS
245///
246/// **Live-validated** against Windows Server 2022/2025 DC: 10-RID LookupSids batch
247/// (S-1-5-21-…-{500,501,502,512,1000,1101,1102,1103,1108,1109}) returned Administrator /
248/// Guest / krbtgt / Domain Admins / DC01$ / victim01 / dmsa01$ / svc_sql / labuser /
249/// lowuser with correct SidType tags.
250pub fn decode_lookup_sids2(stub: &[u8]) -> Result<Vec<LookedUpSid>> {
251    let mut d = NdrDecoder::new(stub);
252
253    // --- ReferencedDomainList ---
254    let refdom_ptr = d.u32()?;
255    let mut domain_names: Vec<String> = Vec::new();
256    if refdom_ptr != 0 {
257        let dom_entries = d.u32()? as usize;
258        let dom_arr_ptr = d.u32()?;
259        let _max_entries = d.u32()?;
260        if dom_arr_ptr != 0 {
261            let _dom_max_count = d.u32()?;
262            let mut dom_headers: Vec<(u16, u32, u32)> = Vec::with_capacity(dom_entries);
263            for _ in 0..dom_entries {
264                let name_len = d.u16()?;
265                let _name_max = d.u16()?;
266                let name_ptr = d.u32()?;
267                let sid_ptr = d.u32()?;
268                dom_headers.push((name_len, name_ptr, sid_ptr));
269            }
270            for (_len, name_ptr, sid_ptr) in dom_headers {
271                let name = if name_ptr != 0 {
272                    d.conformant_varying_wstr()?
273                } else {
274                    String::new()
275                };
276                if sid_ptr != 0 {
277                    let _ = decode_sid(&mut d)?; // parsed for advance, not returned in v0.1
278                }
279                domain_names.push(name);
280            }
281        }
282    }
283
284    // --- TranslatedNames ---
285    let entries = d.u32()? as usize;
286    let names_arr_ptr = d.u32()?;
287    let mut out = Vec::with_capacity(entries);
288    if names_arr_ptr != 0 {
289        let _max_count = d.u32()?;
290        let mut headers: Vec<(SidType, u32, i32)> = Vec::with_capacity(entries);
291        // LSAPR_TRANSLATED_NAME_EX per-entry NDR layout (20 bytes):
292        //   Use: u16          @ 0
293        //   pad: 2            @ 2   (RPC_UNICODE_STRING starts at 4 for 4-alignment)
294        //   Name.Length: u16  @ 4
295        //   Name.Maximum: u16 @ 6
296        //   Name.Buffer: u32  @ 8
297        //   DomainIndex: i32  @ 12
298        //   Flags: u32        @ 16
299        for _ in 0..entries {
300            let sid_type_raw = d.u16()?;
301            d.align(4);
302            let _name_len = d.u16()?;
303            let _name_max = d.u16()?;
304            let name_ptr = d.u32()?;
305            let domain_idx = d.u32()? as i32;
306            let _flags = d.u32()?;
307            headers.push((SidType::from_u16(sid_type_raw), name_ptr, domain_idx));
308        }
309        for (kind, name_ptr, domain_idx) in headers {
310            let name = if name_ptr != 0 {
311                d.conformant_varying_wstr()?
312            } else {
313                String::new()
314            };
315            let domain = if domain_idx >= 0 {
316                domain_names
317                    .get(domain_idx as usize)
318                    .cloned()
319                    .unwrap_or_default()
320            } else {
321                String::new()
322            };
323            out.push(LookedUpSid { name, domain, kind });
324        }
325    }
326    // MappedCount + NTSTATUS trail — we don't need them for the row shape.
327    Ok(out)
328}
329
330// ---- LsarLookupNames2 -----------------------------------------------------
331
332/// One row of a LookupNames response: the resolved SID (or the domain SID + a RID sentinel)
333/// and its type.
334#[derive(Debug, Clone, PartialEq, Eq)]
335#[non_exhaustive]
336pub struct LookedUpName {
337    /// The SID for the account.
338    pub sid: Sid,
339    /// The domain that returned the SID.
340    pub domain: String,
341    /// Object type.
342    pub kind: SidType,
343}
344
345/// LsarLookupNames2(PolicyHandle, Count, Names, [out]RefDomains, [in,out]TranslatedSids,
346/// LookupLevel, [in,out]MappedCount, LookupOptions, ClientRevision).
347pub fn encode_lookup_names2(
348    handle: &PolicyHandle,
349    names: &[&str],
350    lookup_level: u16,
351    client_revision: u32,
352) -> Vec<u8> {
353    let mut e = NdrEncoder::new();
354    handle.encode(&mut e);
355    e.u32(names.len() as u32); // Count
356                               // Names is [size_is(Count)]LSAPR_STRING[] — RPC_UNICODE_STRING each
357    e.u32(names.len() as u32); // conformant max_count
358    for name in names {
359        let units: Vec<u16> = name.encode_utf16().collect();
360        let blen = (units.len() * 2) as u16;
361        e.u16(blen); // Length
362        e.u16(blen); // MaximumLength
363        e.referent(); // Buffer ptr (deferred)
364    }
365    for name in names {
366        let units: Vec<u16> = name.encode_utf16().collect();
367        let n = units.len() as u32;
368        e.u32(n); // max_count (no NUL)
369        e.u32(0); // offset
370        e.u32(n); // actual_count
371        for u in units {
372            e.u16(u);
373        }
374    }
375    // [in,out] TranslatedSids: empty on input
376    e.u32(0); // Entries
377    e.null_ptr(); // Sids ptr NULL
378
379    e.u16(lookup_level);
380    e.align(4);
381    e.u32(0); // MappedCount
382    e.u32(0); // LookupOptions
383    e.u32(client_revision);
384    e.into_bytes()
385}
386
387/// Decode a LsarLookupNames2 response. Response = `LSAPR_TRANSLATED_SIDS_EX` (v2, not v3):
388/// each entry carries `{ Use: u16, RelativeId: u32, DomainIndex: i32, Flags: u32 }` with the
389/// RID inline (NOT a `PRPC_SID` pointer — that's `LsarLookupNames3` / opnum 68). We
390/// reconstruct the full SID by concatenating the referenced-domain SID with the RID.
391///
392/// **Live-validated** against Windows Server 2022/2025 DC: Administrator/krbtgt/victim01
393/// looked up + returned with correct RIDs 500/502/1101 and the correct domain SID.
394pub fn decode_lookup_names2(stub: &[u8]) -> Result<Vec<LookedUpName>> {
395    let mut d = NdrDecoder::new(stub);
396
397    let refdom_ptr = d.u32()?;
398    let mut domain_names: Vec<String> = Vec::new();
399    let mut domain_sids: Vec<Option<Sid>> = Vec::new();
400    if refdom_ptr != 0 {
401        let dom_entries = d.u32()? as usize;
402        let dom_arr_ptr = d.u32()?;
403        let _max_entries = d.u32()?;
404        if dom_arr_ptr != 0 {
405            let _dom_max_count = d.u32()?;
406            let mut dom_headers: Vec<(u16, u32, u32)> = Vec::with_capacity(dom_entries);
407            for _ in 0..dom_entries {
408                let name_len = d.u16()?;
409                let _name_max = d.u16()?;
410                let name_ptr = d.u32()?;
411                let sid_ptr = d.u32()?;
412                dom_headers.push((name_len, name_ptr, sid_ptr));
413            }
414            for (_len, name_ptr, sid_ptr) in dom_headers {
415                let name = if name_ptr != 0 {
416                    d.conformant_varying_wstr()?
417                } else {
418                    String::new()
419                };
420                let sid = if sid_ptr != 0 {
421                    Some(decode_sid(&mut d)?)
422                } else {
423                    None
424                };
425                domain_names.push(name);
426                domain_sids.push(sid);
427            }
428        }
429    }
430
431    // TranslatedSids_EX (opnum 58 response is v2 not v3; the entry embeds RelativeId
432    // directly, NOT a pointer to a SID — only LsarLookupNames3 (opnum 68) uses PRPC_SID).
433    // LSAPR_TRANSLATED_SID_EX per-entry NDR layout (16 bytes, no deferred data):
434    //   Use: u16          @ 0
435    //   pad: 2            @ 2
436    //   RelativeId: u32   @ 4
437    //   DomainIndex: i32  @ 8
438    //   Flags: u32        @ 12
439    let entries = d.u32()? as usize;
440    let sids_arr_ptr = d.u32()?;
441    let mut out = Vec::with_capacity(entries);
442    if sids_arr_ptr != 0 {
443        let _max_count = d.u32()?;
444        for _ in 0..entries {
445            let sid_type_raw = d.u16()?;
446            d.align(4);
447            let rid = d.u32()?;
448            let domain_idx = d.u32()? as i32;
449            let _flags = d.u32()?;
450            let kind = SidType::from_u16(sid_type_raw);
451            let (domain, sid) = if domain_idx >= 0 {
452                let idx = domain_idx as usize;
453                let dn = domain_names.get(idx).cloned().unwrap_or_default();
454                let mut sid = domain_sids
455                    .get(idx)
456                    .and_then(|s| s.clone())
457                    .unwrap_or_else(|| Sid {
458                        revision: 1,
459                        identifier_authority: 0,
460                        sub_authorities: vec![],
461                    });
462                // For account rows, append the RID to the domain SID. For domain rows
463                // (kind == Domain), the SID is already the domain SID — don't append.
464                if kind != SidType::Domain {
465                    sid.sub_authorities.push(rid);
466                }
467                (dn, sid)
468            } else {
469                (
470                    String::new(),
471                    Sid {
472                        revision: 1,
473                        identifier_authority: 0,
474                        sub_authorities: vec![rid],
475                    },
476                )
477            };
478            out.push(LookedUpName { sid, domain, kind });
479        }
480    }
481    Ok(out)
482}
483
484// ---- High-level client ----------------------------------------------------
485
486/// Ergonomic LSAT client. Binds the interface over an already-open `\lsarpc` pipe, opens
487/// the policy handle lazily on the first lookup call.
488pub struct LsatClient<'a> {
489    pipe: SmbPipe<'a>,
490    handle: Option<PolicyHandle>,
491}
492
493impl<'a> LsatClient<'a> {
494    pub async fn bind(client: &'a mut SmbClient, file_id: [u8; 16]) -> Result<Self> {
495        let mut pipe = SmbPipe::new(client, file_id);
496        pipe.bind(lsat_syntax()).await?;
497        Ok(LsatClient { pipe, handle: None })
498    }
499
500    async fn ensure_handle(&mut self, system_name: &str) -> Result<PolicyHandle> {
501        if let Some(h) = self.handle {
502            return Ok(h);
503        }
504        let stub = encode_open_policy2(system_name, access::MAXIMUM_ALLOWED);
505        let resp = self.pipe.call(opnum::OPEN_POLICY2, &stub).await?;
506        let mut d = NdrDecoder::new(&resp);
507        let h = PolicyHandle::decode(&mut d)?;
508        self.handle = Some(h);
509        Ok(h)
510    }
511
512    /// SID → name lookup. Returns a vector aligned 1:1 with the input.
513    pub async fn lookup_sids(
514        &mut self,
515        system_name: &str,
516        sids: &[Sid],
517    ) -> Result<Vec<LookedUpSid>> {
518        let h = self.ensure_handle(system_name).await?;
519        let stub = encode_lookup_sids2(&h, sids, 1, 2);
520        let resp = self.pipe.call(opnum::LOOKUP_SIDS2, &stub).await?;
521        decode_lookup_sids2(&resp)
522    }
523
524    /// Name → SID lookup. Returns a vector aligned 1:1 with the input.
525    pub async fn lookup_names(
526        &mut self,
527        system_name: &str,
528        names: &[&str],
529    ) -> Result<Vec<LookedUpName>> {
530        let h = self.ensure_handle(system_name).await?;
531        let stub = encode_lookup_names2(&h, names, 1, 2);
532        let resp = self.pipe.call(opnum::LOOKUP_NAMES2, &stub).await?;
533        decode_lookup_names2(&resp)
534    }
535}
536
537// ---- Tests ---------------------------------------------------------------
538
539#[cfg(test)]
540mod tests {
541    use super::*;
542
543    #[test]
544    fn open_policy2_marshals_system_and_access() {
545        let stub = encode_open_policy2("\\\\dc01", access::MAXIMUM_ALLOWED);
546        // referent(4) + [max/off/act(12) + "\\dc01"+NUL = 7 wchar × 2 = 14] = 30 → align(4)
547        // pad 2 → 32 header. Then object-attrs 24 bytes. Then desired_access 4.
548        // Total = 32 + 24 + 4 = 60.
549        assert_eq!(stub.len(), 60);
550        assert_eq!(
551            &stub[stub.len() - 4..],
552            &access::MAXIMUM_ALLOWED.to_le_bytes()
553        );
554    }
555
556    #[test]
557    fn lookup_sids2_layout_fixed_prefix() {
558        // 5-subauth SID: revision(1)+count(1)+authority(6) fixed = 8 bytes; max_count(4)
559        // hoisted; 5 sub-authorities × 4 = 20 → RPC_SID = 32 bytes on the wire.
560        let sid = Sid::parse("S-1-5-21-1111-2222-3333-500").unwrap();
561        let stub = encode_lookup_sids2(&PolicyHandle([0; 20]), &[sid], 1, 2);
562        // Handle(20) + Entries(4) + SidInfo.ref(4) + max_count(4) + per-sid ref(4) +
563        // RPC_SID(32) + TranslatedNames.Entries(4) + Names.ptr NULL(4) + lookup_level(2)+pad(2)
564        // + MappedCount(4) + LookupOptions(4) + ClientRevision(4) = 92.
565        assert_eq!(stub.len(), 92);
566    }
567
568    #[test]
569    fn lookup_names2_marshals_multiple_names() {
570        let stub = encode_lookup_names2(&PolicyHandle([0; 20]), &["Administrator", "krbtgt"], 1, 2);
571        // Just sanity — the stub is non-empty and starts with the handle
572        assert_eq!(&stub[0..20], &[0u8; 20]);
573        assert_eq!(u32::from_le_bytes(stub[20..24].try_into().unwrap()), 2); // Count = 2
574    }
575
576    #[test]
577    fn sid_type_maps_known_values_and_defaults_unknown() {
578        assert_eq!(SidType::from_u16(1), SidType::User);
579        assert_eq!(SidType::from_u16(2), SidType::Group);
580        assert_eq!(SidType::from_u16(9), SidType::Computer);
581        assert_eq!(SidType::from_u16(255), SidType::Unknown);
582    }
583
584    /// Encode a synthetic LookupSids response (1 SID → 1 name, 1 domain) and roundtrip through
585    /// decode. Proves the referenced-domain-index resolution path.
586    #[test]
587    fn lookup_sids2_decode_roundtrip_single_result() {
588        let mut e = NdrEncoder::new();
589        // RefDomains ptr non-null → ReferencedDomainList
590        e.referent();
591        e.u32(1); // Entries
592        e.referent(); // Domains array ptr
593        e.u32(32); // MaxEntries
594        e.u32(1); // conformant max_count
595                  // domain header: name RPC_UNICODE_STRING + SID ptr
596        let dn: Vec<u16> = "CORP".encode_utf16().collect();
597        let dl = (dn.len() * 2) as u16;
598        e.u16(dl);
599        e.u16(dl);
600        e.referent(); // Name ptr
601        e.referent(); // SID ptr
602                      // domain name deferred WSTR
603        e.u32(dn.len() as u32);
604        e.u32(0);
605        e.u32(dn.len() as u32);
606        for u in dn.iter() {
607            e.u16(*u);
608        }
609        // domain SID deferred (S-1-5-21-1-2-3, 4 subauths)
610        let dom_sid = Sid::parse("S-1-5-21-1-2-3").unwrap();
611        encode_sid(&mut e, &dom_sid);
612        // TranslatedNames: 1 entry (LSAPR_TRANSLATED_NAME_EX = 20 bytes/entry)
613        e.u32(1); // Entries
614        e.referent(); // Names array ptr
615        e.u32(1); // max_count
616                  // per-entry: Use(u16) + align pad(2) + Length(u16) + MaxLen(u16) + Buffer(u32)
617                  //          + DomainIndex(i32) + Flags(u32) = 20 bytes
618        e.u16(SidType::User as u16);
619        e.align(4); // pad
620        let nn: Vec<u16> = "Administrator".encode_utf16().collect();
621        let nl = (nn.len() * 2) as u16;
622        e.u16(nl);
623        e.u16(nl);
624        e.referent(); // Buffer ptr
625        e.u32(0); // DomainIndex
626        e.u32(0); // Flags
627                  // deferred name
628        e.u32(nn.len() as u32);
629        e.u32(0);
630        e.u32(nn.len() as u32);
631        for u in nn.iter() {
632            e.u16(*u);
633        }
634        // MappedCount + NTSTATUS
635        e.u32(1);
636        e.u32(0);
637
638        let stub = e.into_bytes();
639        let rows = decode_lookup_sids2(&stub).unwrap();
640        assert_eq!(rows.len(), 1);
641        assert_eq!(rows[0].name, "Administrator");
642        assert_eq!(rows[0].domain, "CORP");
643        assert_eq!(rows[0].kind, SidType::User);
644    }
645}