ms-lsat 0.1.0

MS-LSAT Local Security Authority (Translation) Remote Protocol client — SID↔name lookup over \PIPE\lsarpc via sealed DCE/RPC. LsarOpenPolicy2 + LsarLookupSids2 + LsarLookupNames2
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
//! **MS-LSAT** — Local Security Authority (Translation) Remote Protocol.
//!
//! Windows exposes LSA name↔SID lookup services over `\PIPE\lsarpc` and (some) LSA
//! policy queries. The most common opnums pentesters + defenders actually use:
//!
//! | Opnum | Name | Purpose |
//! |---|---|---|
//! | 6 | `LsarOpenPolicy2` | Get a policy handle (starting point for every other op) |
//! | 14 | `LsarLookupSids` | SID → account name (RID-brute enumeration when SAMR is blocked) |
//! | 15 | `LsarLookupNames` | Name → SID (works before authentication in some configs) |
//! | 57 | `LsarLookupSids2` / | Same as 14 but wide-string, PACKAGE-RPC-CONNECT capable |
//! | 58 | `LsarLookupNames2` | Same as 15 but wide-string |
//!
//! Rides an authenticated (or in some configs, anonymous) SMB pipe.
//!
//! # What this crate provides in v0.1
//!
//! Wire encoders + decoders for `LsarOpenPolicy2`, `LsarLookupSids2`, `LsarLookupNames2`,
//! and `LsarClose`, plus a small [`LsatClient`] wrapper that binds the interface over
//! [`dcerpc::transport::SmbPipe`] and exposes ergonomic `lookup_sids(&[Sid]) → Vec<Name>`
//! and `lookup_names(&[&str]) → Vec<Sid>` methods.
//!
//! # Byte-format
//!
//! Encoders match impacket's `lsat.*` / `lsad.*` NDR marshaling (byte-verified against
//! impacket wire captures on Server 2016/2019/2022/2025). The lookup response layouts are
//! the ones that require the most care — see the module docs on [`decode_lookup_sids2`]
//! and [`decode_lookup_names2`] for the pointer-shape.

use dcerpc::ndr::{NdrDecoder, NdrEncoder};
use dcerpc::transport::SmbPipe;
use dcerpc::{Result, Syntax};
use smb2_client::SmbClient;
use windows_sddl::sid::Sid;

/// The LSAT interface (v0.0). Same UUID as the LSA-Directory (LSAD) interface.
pub fn lsat_syntax() -> Syntax {
    Syntax::new("12345778-1234-abcd-ef00-0123456789ab", 0, 0)
}

pub mod opnum {
    pub const CLOSE: u16 = 0;
    pub const OPEN_POLICY: u16 = 6;
    pub const LOOKUP_NAMES: u16 = 14;
    pub const LOOKUP_SIDS: u16 = 15;
    pub const OPEN_POLICY2: u16 = 44;
    pub const LOOKUP_SIDS2: u16 = 57;
    pub const LOOKUP_NAMES2: u16 = 58;
}

/// Common LSA policy-access flags.
pub mod access {
    pub const POLICY_VIEW_LOCAL_INFORMATION: u32 = 0x0000_0001;
    pub const POLICY_LOOKUP_NAMES: u32 = 0x0000_0800;
    /// The "asks the server to pick" access — sufficient for lookups on most configs.
    pub const MAXIMUM_ALLOWED: u32 = 0x0200_0000;
}

/// SID-name-use enum values ([MS-LSAT] §2.2.13).
#[non_exhaustive]
#[repr(u16)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SidType {
    User = 1,
    Group = 2,
    Domain = 3,
    Alias = 4,
    WellKnownGroup = 5,
    DeletedAccount = 6,
    Invalid = 7,
    Unknown = 8,
    Computer = 9,
    Label = 10,
}

impl SidType {
    pub fn from_u16(v: u16) -> Self {
        match v {
            1 => SidType::User,
            2 => SidType::Group,
            3 => SidType::Domain,
            4 => SidType::Alias,
            5 => SidType::WellKnownGroup,
            6 => SidType::DeletedAccount,
            7 => SidType::Invalid,
            9 => SidType::Computer,
            10 => SidType::Label,
            _ => SidType::Unknown,
        }
    }
}

/// A 20-byte RPC context handle (attributes u32 + 16-byte GUID). Same shape as SAMR's.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PolicyHandle(pub [u8; 20]);

impl PolicyHandle {
    pub fn decode(d: &mut NdrDecoder) -> Result<Self> {
        let attrs = d.u32()?;
        let uuid = d.uuid()?;
        let mut h = [0u8; 20];
        h[..4].copy_from_slice(&attrs.to_le_bytes());
        h[4..].copy_from_slice(&uuid);
        Ok(PolicyHandle(h))
    }
    pub fn encode(&self, e: &mut NdrEncoder) {
        e.bytes(&self.0);
    }
}

// ---- LsarOpenPolicy2 -------------------------------------------------------

/// LsarOpenPolicy2(SystemName [in,unique,string], ObjectAttributes [in], DesiredAccess [in])
///
/// ObjectAttributes is an LSAPR_OBJECT_ATTRIBUTES: `Length + RootDirectory + ObjectName +
/// Attributes + SecurityDescriptor + SecurityQualityOfService`. Every field is 0/NULL for
/// a lookup client (the spec says all fields are ignored by the server for OpenPolicy).
pub fn encode_open_policy2(system_name: &str, desired_access: u32) -> Vec<u8> {
    let mut e = NdrEncoder::new();
    // SystemName is [unique,string] — referent + WSTR pointee
    e.referent();
    e.conformant_varying_wstr(system_name);
    e.align(4);
    // LSAPR_OBJECT_ATTRIBUTES { Length, RootDirectory, ObjectName, Attributes,
    //                          SecurityDescriptor, SecurityQualityOfService }
    e.u32(24); // Length = sizeof(LSAPR_OBJECT_ATTRIBUTES) = 24 (per MS-LSAD)
    e.null_ptr(); // RootDirectory (unused, MBZ)
    e.null_ptr(); // ObjectName pointer
    e.u32(0); // Attributes
    e.null_ptr(); // SecurityDescriptor pointer
    e.null_ptr(); // SecurityQualityOfService pointer
    e.u32(desired_access);
    e.into_bytes()
}

// ---- RPC_SID marshaling (shared with SAMR) --------------------------------

/// Encode an RPC_SID conformant array. `max_count` (u32) hoisted then Revision +
/// SubAuthorityCount + Authority + SubAuthority[]. Same layout as SAMR uses.
fn encode_sid(e: &mut NdrEncoder, sid: &Sid) {
    e.u32(sid.sub_authorities.len() as u32);
    e.u8(sid.revision);
    e.u8(sid.sub_authorities.len() as u8);
    let a = sid.identifier_authority;
    e.bytes(&[
        (a >> 40) as u8,
        (a >> 32) as u8,
        (a >> 24) as u8,
        (a >> 16) as u8,
        (a >> 8) as u8,
        a as u8,
    ]);
    for s in &sid.sub_authorities {
        e.u32(*s);
    }
}

fn decode_sid(d: &mut NdrDecoder) -> Result<Sid> {
    let _max = d.u32()?;
    let revision = d.u8()?;
    let count = d.u8()? as usize;
    let auth = d.read_bytes(6)?;
    let identifier_authority = auth.iter().fold(0u64, |acc, &b| (acc << 8) | b as u64);
    let mut sub_authorities = Vec::with_capacity(count);
    for _ in 0..count {
        sub_authorities.push(d.u32()?);
    }
    Ok(Sid {
        revision,
        identifier_authority,
        sub_authorities,
    })
}

// ---- LsarLookupSids2 ------------------------------------------------------

/// One row of a LookupSids response: the resolved name (or empty) and its type.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct LookedUpSid {
    /// The (relative) account name — `""` when the SID couldn't be resolved.
    pub name: String,
    /// The referenced domain name (from ReferencedDomainList) — `""` when unresolvable.
    pub domain: String,
    /// Object type (User / Group / Domain / …).
    pub kind: SidType,
}

/// LsarLookupSids2(PolicyHandle, SidEnumBuffer, [out]RefDomains, [in,out]Names, LookupLevel,
/// [in,out]MappedCount, LookupOptions, ClientRevision).
///
/// - `lookup_level` = 1 (LsapLookupWksta) is the safest default.
/// - `client_revision` = 2 for modern Windows.
pub fn encode_lookup_sids2(
    handle: &PolicyHandle,
    sids: &[Sid],
    lookup_level: u16,
    client_revision: u32,
) -> Vec<u8> {
    let mut e = NdrEncoder::new();
    handle.encode(&mut e);

    // SidEnumBuffer = { Entries: u32, SidInfo: [ref]PSIDENUMBUFFER→[size_is(Entries)]RPC_SID_INFORMATION[] }
    // RPC_SID_INFORMATION = { Sid: [ref]PRPC_SID }
    e.u32(sids.len() as u32); // Entries
    e.referent(); // SidInfo array pointer
    e.u32(sids.len() as u32); // conformant max_count

    // First pass: for each entry, emit its RPC_SID_INFORMATION fixed part (a pointer).
    for _ in sids {
        e.referent(); // Sid pointer (deferred)
    }
    // Deferred: RPC_SID for each entry (in order).
    for sid in sids {
        encode_sid(&mut e, sid);
    }

    // [out] TranslatedName_2 buffer: caller supplies an empty structure to be filled.
    // { Entries: u32 = 0, Names: [unique] = NULL }
    e.u32(0); // Entries
    e.null_ptr(); // Names pointer NULL

    e.u16(lookup_level);
    e.align(4);
    e.u32(0); // MappedCount [in] = 0

    e.u32(0); // LookupOptions
    e.u32(client_revision);
    e.into_bytes()
}

/// Decode a LsarLookupSids2 response into per-input rows.
///
/// The wire shape (in order of appearance):
/// 1. `ReferencedDomainList` pointer (may be NULL if MappedCount == 0)
///    → { Entries: u32, Domains: array ptr, MaxEntries: u32 }
///    → each domain: { Name: RPC_UNICODE_STRING, Sid: [ref]PRPC_SID }
///    → deferred: Name.Buffer WSTR + RPC_SID for each domain (in emit order)
/// 2. `TranslatedNames` structure: { Entries: u32, Names: [ref]PLSAPR_TRANSLATED_NAME_EX[] }
///    → each name (20 bytes fixed): Use(u16) + pad(2) + Name.Length(u16) + Name.Max(u16) +
///      Buffer(u32/ptr) + DomainIndex(i32) + Flags(u32)
///    → deferred: Name.Buffer WSTR for each (in emit order)
/// 3. `MappedCount`: u32
/// 4. Trailing NTSTATUS
///
/// **Live-validated** against Windows Server 2022/2025 DC: 10-RID LookupSids batch
/// (S-1-5-21-…-{500,501,502,512,1000,1101,1102,1103,1108,1109}) returned Administrator /
/// Guest / krbtgt / Domain Admins / DC01$ / victim01 / dmsa01$ / svc_sql / labuser /
/// lowuser with correct SidType tags.
pub fn decode_lookup_sids2(stub: &[u8]) -> Result<Vec<LookedUpSid>> {
    let mut d = NdrDecoder::new(stub);

    // --- ReferencedDomainList ---
    let refdom_ptr = d.u32()?;
    let mut domain_names: Vec<String> = Vec::new();
    if refdom_ptr != 0 {
        let dom_entries = d.u32()? as usize;
        let dom_arr_ptr = d.u32()?;
        let _max_entries = d.u32()?;
        if dom_arr_ptr != 0 {
            let _dom_max_count = d.u32()?;
            let mut dom_headers: Vec<(u16, u32, u32)> = Vec::with_capacity(dom_entries);
            for _ in 0..dom_entries {
                let name_len = d.u16()?;
                let _name_max = d.u16()?;
                let name_ptr = d.u32()?;
                let sid_ptr = d.u32()?;
                dom_headers.push((name_len, name_ptr, sid_ptr));
            }
            for (_len, name_ptr, sid_ptr) in dom_headers {
                let name = if name_ptr != 0 {
                    d.conformant_varying_wstr()?
                } else {
                    String::new()
                };
                if sid_ptr != 0 {
                    let _ = decode_sid(&mut d)?; // parsed for advance, not returned in v0.1
                }
                domain_names.push(name);
            }
        }
    }

    // --- TranslatedNames ---
    let entries = d.u32()? as usize;
    let names_arr_ptr = d.u32()?;
    let mut out = Vec::with_capacity(entries);
    if names_arr_ptr != 0 {
        let _max_count = d.u32()?;
        let mut headers: Vec<(SidType, u32, i32)> = Vec::with_capacity(entries);
        // LSAPR_TRANSLATED_NAME_EX per-entry NDR layout (20 bytes):
        //   Use: u16          @ 0
        //   pad: 2            @ 2   (RPC_UNICODE_STRING starts at 4 for 4-alignment)
        //   Name.Length: u16  @ 4
        //   Name.Maximum: u16 @ 6
        //   Name.Buffer: u32  @ 8
        //   DomainIndex: i32  @ 12
        //   Flags: u32        @ 16
        for _ in 0..entries {
            let sid_type_raw = d.u16()?;
            d.align(4);
            let _name_len = d.u16()?;
            let _name_max = d.u16()?;
            let name_ptr = d.u32()?;
            let domain_idx = d.u32()? as i32;
            let _flags = d.u32()?;
            headers.push((SidType::from_u16(sid_type_raw), name_ptr, domain_idx));
        }
        for (kind, name_ptr, domain_idx) in headers {
            let name = if name_ptr != 0 {
                d.conformant_varying_wstr()?
            } else {
                String::new()
            };
            let domain = if domain_idx >= 0 {
                domain_names
                    .get(domain_idx as usize)
                    .cloned()
                    .unwrap_or_default()
            } else {
                String::new()
            };
            out.push(LookedUpSid { name, domain, kind });
        }
    }
    // MappedCount + NTSTATUS trail — we don't need them for the row shape.
    Ok(out)
}

// ---- LsarLookupNames2 -----------------------------------------------------

/// One row of a LookupNames response: the resolved SID (or the domain SID + a RID sentinel)
/// and its type.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct LookedUpName {
    /// The SID for the account.
    pub sid: Sid,
    /// The domain that returned the SID.
    pub domain: String,
    /// Object type.
    pub kind: SidType,
}

/// LsarLookupNames2(PolicyHandle, Count, Names, [out]RefDomains, [in,out]TranslatedSids,
/// LookupLevel, [in,out]MappedCount, LookupOptions, ClientRevision).
pub fn encode_lookup_names2(
    handle: &PolicyHandle,
    names: &[&str],
    lookup_level: u16,
    client_revision: u32,
) -> Vec<u8> {
    let mut e = NdrEncoder::new();
    handle.encode(&mut e);
    e.u32(names.len() as u32); // Count
                               // Names is [size_is(Count)]LSAPR_STRING[] — RPC_UNICODE_STRING each
    e.u32(names.len() as u32); // conformant max_count
    for name in names {
        let units: Vec<u16> = name.encode_utf16().collect();
        let blen = (units.len() * 2) as u16;
        e.u16(blen); // Length
        e.u16(blen); // MaximumLength
        e.referent(); // Buffer ptr (deferred)
    }
    for name in names {
        let units: Vec<u16> = name.encode_utf16().collect();
        let n = units.len() as u32;
        e.u32(n); // max_count (no NUL)
        e.u32(0); // offset
        e.u32(n); // actual_count
        for u in units {
            e.u16(u);
        }
    }
    // [in,out] TranslatedSids: empty on input
    e.u32(0); // Entries
    e.null_ptr(); // Sids ptr NULL

    e.u16(lookup_level);
    e.align(4);
    e.u32(0); // MappedCount
    e.u32(0); // LookupOptions
    e.u32(client_revision);
    e.into_bytes()
}

/// Decode a LsarLookupNames2 response. Response = `LSAPR_TRANSLATED_SIDS_EX` (v2, not v3):
/// each entry carries `{ Use: u16, RelativeId: u32, DomainIndex: i32, Flags: u32 }` with the
/// RID inline (NOT a `PRPC_SID` pointer — that's `LsarLookupNames3` / opnum 68). We
/// reconstruct the full SID by concatenating the referenced-domain SID with the RID.
///
/// **Live-validated** against Windows Server 2022/2025 DC: Administrator/krbtgt/victim01
/// looked up + returned with correct RIDs 500/502/1101 and the correct domain SID.
pub fn decode_lookup_names2(stub: &[u8]) -> Result<Vec<LookedUpName>> {
    let mut d = NdrDecoder::new(stub);

    let refdom_ptr = d.u32()?;
    let mut domain_names: Vec<String> = Vec::new();
    let mut domain_sids: Vec<Option<Sid>> = Vec::new();
    if refdom_ptr != 0 {
        let dom_entries = d.u32()? as usize;
        let dom_arr_ptr = d.u32()?;
        let _max_entries = d.u32()?;
        if dom_arr_ptr != 0 {
            let _dom_max_count = d.u32()?;
            let mut dom_headers: Vec<(u16, u32, u32)> = Vec::with_capacity(dom_entries);
            for _ in 0..dom_entries {
                let name_len = d.u16()?;
                let _name_max = d.u16()?;
                let name_ptr = d.u32()?;
                let sid_ptr = d.u32()?;
                dom_headers.push((name_len, name_ptr, sid_ptr));
            }
            for (_len, name_ptr, sid_ptr) in dom_headers {
                let name = if name_ptr != 0 {
                    d.conformant_varying_wstr()?
                } else {
                    String::new()
                };
                let sid = if sid_ptr != 0 {
                    Some(decode_sid(&mut d)?)
                } else {
                    None
                };
                domain_names.push(name);
                domain_sids.push(sid);
            }
        }
    }

    // TranslatedSids_EX (opnum 58 response is v2 not v3; the entry embeds RelativeId
    // directly, NOT a pointer to a SID — only LsarLookupNames3 (opnum 68) uses PRPC_SID).
    // LSAPR_TRANSLATED_SID_EX per-entry NDR layout (16 bytes, no deferred data):
    //   Use: u16          @ 0
    //   pad: 2            @ 2
    //   RelativeId: u32   @ 4
    //   DomainIndex: i32  @ 8
    //   Flags: u32        @ 12
    let entries = d.u32()? as usize;
    let sids_arr_ptr = d.u32()?;
    let mut out = Vec::with_capacity(entries);
    if sids_arr_ptr != 0 {
        let _max_count = d.u32()?;
        for _ in 0..entries {
            let sid_type_raw = d.u16()?;
            d.align(4);
            let rid = d.u32()?;
            let domain_idx = d.u32()? as i32;
            let _flags = d.u32()?;
            let kind = SidType::from_u16(sid_type_raw);
            let (domain, sid) = if domain_idx >= 0 {
                let idx = domain_idx as usize;
                let dn = domain_names.get(idx).cloned().unwrap_or_default();
                let mut sid = domain_sids
                    .get(idx)
                    .and_then(|s| s.clone())
                    .unwrap_or_else(|| Sid {
                        revision: 1,
                        identifier_authority: 0,
                        sub_authorities: vec![],
                    });
                // For account rows, append the RID to the domain SID. For domain rows
                // (kind == Domain), the SID is already the domain SID — don't append.
                if kind != SidType::Domain {
                    sid.sub_authorities.push(rid);
                }
                (dn, sid)
            } else {
                (
                    String::new(),
                    Sid {
                        revision: 1,
                        identifier_authority: 0,
                        sub_authorities: vec![rid],
                    },
                )
            };
            out.push(LookedUpName { sid, domain, kind });
        }
    }
    Ok(out)
}

// ---- High-level client ----------------------------------------------------

/// Ergonomic LSAT client. Binds the interface over an already-open `\lsarpc` pipe, opens
/// the policy handle lazily on the first lookup call.
pub struct LsatClient<'a> {
    pipe: SmbPipe<'a>,
    handle: Option<PolicyHandle>,
}

impl<'a> LsatClient<'a> {
    pub async fn bind(client: &'a mut SmbClient, file_id: [u8; 16]) -> Result<Self> {
        let mut pipe = SmbPipe::new(client, file_id);
        pipe.bind(lsat_syntax()).await?;
        Ok(LsatClient { pipe, handle: None })
    }

    async fn ensure_handle(&mut self, system_name: &str) -> Result<PolicyHandle> {
        if let Some(h) = self.handle {
            return Ok(h);
        }
        let stub = encode_open_policy2(system_name, access::MAXIMUM_ALLOWED);
        let resp = self.pipe.call(opnum::OPEN_POLICY2, &stub).await?;
        let mut d = NdrDecoder::new(&resp);
        let h = PolicyHandle::decode(&mut d)?;
        self.handle = Some(h);
        Ok(h)
    }

    /// SID → name lookup. Returns a vector aligned 1:1 with the input.
    pub async fn lookup_sids(
        &mut self,
        system_name: &str,
        sids: &[Sid],
    ) -> Result<Vec<LookedUpSid>> {
        let h = self.ensure_handle(system_name).await?;
        let stub = encode_lookup_sids2(&h, sids, 1, 2);
        let resp = self.pipe.call(opnum::LOOKUP_SIDS2, &stub).await?;
        decode_lookup_sids2(&resp)
    }

    /// Name → SID lookup. Returns a vector aligned 1:1 with the input.
    pub async fn lookup_names(
        &mut self,
        system_name: &str,
        names: &[&str],
    ) -> Result<Vec<LookedUpName>> {
        let h = self.ensure_handle(system_name).await?;
        let stub = encode_lookup_names2(&h, names, 1, 2);
        let resp = self.pipe.call(opnum::LOOKUP_NAMES2, &stub).await?;
        decode_lookup_names2(&resp)
    }
}

// ---- Tests ---------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn open_policy2_marshals_system_and_access() {
        let stub = encode_open_policy2("\\\\dc01", access::MAXIMUM_ALLOWED);
        // referent(4) + [max/off/act(12) + "\\dc01"+NUL = 7 wchar × 2 = 14] = 30 → align(4)
        // pad 2 → 32 header. Then object-attrs 24 bytes. Then desired_access 4.
        // Total = 32 + 24 + 4 = 60.
        assert_eq!(stub.len(), 60);
        assert_eq!(
            &stub[stub.len() - 4..],
            &access::MAXIMUM_ALLOWED.to_le_bytes()
        );
    }

    #[test]
    fn lookup_sids2_layout_fixed_prefix() {
        // 5-subauth SID: revision(1)+count(1)+authority(6) fixed = 8 bytes; max_count(4)
        // hoisted; 5 sub-authorities × 4 = 20 → RPC_SID = 32 bytes on the wire.
        let sid = Sid::parse("S-1-5-21-1111-2222-3333-500").unwrap();
        let stub = encode_lookup_sids2(&PolicyHandle([0; 20]), &[sid], 1, 2);
        // Handle(20) + Entries(4) + SidInfo.ref(4) + max_count(4) + per-sid ref(4) +
        // RPC_SID(32) + TranslatedNames.Entries(4) + Names.ptr NULL(4) + lookup_level(2)+pad(2)
        // + MappedCount(4) + LookupOptions(4) + ClientRevision(4) = 92.
        assert_eq!(stub.len(), 92);
    }

    #[test]
    fn lookup_names2_marshals_multiple_names() {
        let stub = encode_lookup_names2(&PolicyHandle([0; 20]), &["Administrator", "krbtgt"], 1, 2);
        // Just sanity — the stub is non-empty and starts with the handle
        assert_eq!(&stub[0..20], &[0u8; 20]);
        assert_eq!(u32::from_le_bytes(stub[20..24].try_into().unwrap()), 2); // Count = 2
    }

    #[test]
    fn sid_type_maps_known_values_and_defaults_unknown() {
        assert_eq!(SidType::from_u16(1), SidType::User);
        assert_eq!(SidType::from_u16(2), SidType::Group);
        assert_eq!(SidType::from_u16(9), SidType::Computer);
        assert_eq!(SidType::from_u16(255), SidType::Unknown);
    }

    /// Encode a synthetic LookupSids response (1 SID → 1 name, 1 domain) and roundtrip through
    /// decode. Proves the referenced-domain-index resolution path.
    #[test]
    fn lookup_sids2_decode_roundtrip_single_result() {
        let mut e = NdrEncoder::new();
        // RefDomains ptr non-null → ReferencedDomainList
        e.referent();
        e.u32(1); // Entries
        e.referent(); // Domains array ptr
        e.u32(32); // MaxEntries
        e.u32(1); // conformant max_count
                  // domain header: name RPC_UNICODE_STRING + SID ptr
        let dn: Vec<u16> = "CORP".encode_utf16().collect();
        let dl = (dn.len() * 2) as u16;
        e.u16(dl);
        e.u16(dl);
        e.referent(); // Name ptr
        e.referent(); // SID ptr
                      // domain name deferred WSTR
        e.u32(dn.len() as u32);
        e.u32(0);
        e.u32(dn.len() as u32);
        for u in dn.iter() {
            e.u16(*u);
        }
        // domain SID deferred (S-1-5-21-1-2-3, 4 subauths)
        let dom_sid = Sid::parse("S-1-5-21-1-2-3").unwrap();
        encode_sid(&mut e, &dom_sid);
        // TranslatedNames: 1 entry (LSAPR_TRANSLATED_NAME_EX = 20 bytes/entry)
        e.u32(1); // Entries
        e.referent(); // Names array ptr
        e.u32(1); // max_count
                  // per-entry: Use(u16) + align pad(2) + Length(u16) + MaxLen(u16) + Buffer(u32)
                  //          + DomainIndex(i32) + Flags(u32) = 20 bytes
        e.u16(SidType::User as u16);
        e.align(4); // pad
        let nn: Vec<u16> = "Administrator".encode_utf16().collect();
        let nl = (nn.len() * 2) as u16;
        e.u16(nl);
        e.u16(nl);
        e.referent(); // Buffer ptr
        e.u32(0); // DomainIndex
        e.u32(0); // Flags
                  // deferred name
        e.u32(nn.len() as u32);
        e.u32(0);
        e.u32(nn.len() as u32);
        for u in nn.iter() {
            e.u16(*u);
        }
        // MappedCount + NTSTATUS
        e.u32(1);
        e.u32(0);

        let stub = e.into_bytes();
        let rows = decode_lookup_sids2(&stub).unwrap();
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].name, "Administrator");
        assert_eq!(rows[0].domain, "CORP");
        assert_eq!(rows[0].kind, SidType::User);
    }
}