ms-lsad 0.1.0

MS-LSAD (Local Security Authority Domain Policy Remote Protocol) client — trusted-domain enumeration + trust-relationship read over the shared LSARPC pipe. Companion crate to ms-lsat (LSA translation). Dual-use: forest / trust audit + offensive trust manipulation for cross-forest golden ticket.
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
//! **MS-LSAD** — Local Security Authority (Domain Policy) Remote Protocol.
//!
//! Companion crate to [`ms-lsat`](https://crates.io/crates/ms-lsat) (LSA Translation).
//! Both share the interface UUID `12345778-1234-abcd-ef00-0123456789ab` (v0.0) on
//! `\PIPE\lsarpc`. LSAT covers SID↔name lookups; this crate covers **domain policy
//! read/write** and **trusted-domain object management**.
//!
//! v0.1 opnums:
//!
//! | Opnum | Name | Purpose |
//! |---|---|---|
//! | 44 | `LsarOpenPolicy2` | (reused from `ms-lsat`) get policy handle |
//! | 13 | `LsarEnumerateTrustedDomains` | enumerate configured trusts (v1 API) |
//! | 0  | `LsarClose` | (reused) close policy handle |
//!
//! # Dual use
//!
//! - **Audit / DFIR** — enumerate every configured trust and its direction / attributes
//!   for defensive posture. Currently no pure-Rust way to do this over the wire without
//!   linking a full Windows SDK.
//! - **Offensive** — enumerate trusts as a scouting step before cross-forest attack
//!   chains (the trust-key extraction path lands with `LsarQueryTrustedDomainInfoByName`
//!   / opnum 48 or via DRS bulk `GetNCChanges` — target for v0.2).
//!
//! # Composes with
//!
//! - [`dcerpc`](https://crates.io/crates/dcerpc) — sealed LSARPC transport.
//! - [`ms-lsat`](https://crates.io/crates/ms-lsat) — shares the policy handle with
//!   SID/name translation calls.
//! - [`ms-drsr`](https://crates.io/crates/ms-drsr) — alternative trust-key path via
//!   DRS replication.
//!
//! # Spec
//!
//! [MS-LSAD]: <https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-lsad/>

#![deny(unsafe_code)]

use dcerpc::ndr::{NdrDecoder, NdrEncoder};
use dcerpc::transport::SmbPipe;
use dcerpc::{Result, Syntax};
use ms_lsat::{access, opnum as lsat_opnum, PolicyHandle};
use smb2_client::SmbClient;
use windows_sddl::sid::Sid;

/// The shared LSA interface (v0.0) — same UUID as LSAT.
pub fn lsad_syntax() -> Syntax {
    Syntax::new("12345778-1234-abcd-ef00-0123456789ab", 0, 0)
}

/// MS-LSAD opnum table ([MS-LSAD] §3.1.4). LSA interface shares the numbering with LSAT
/// but the two carve up different opnum ranges. Values here are LSAD-only.
pub mod opnum {
    /// `LsarClose` — reused from LSAT.
    pub const CLOSE: u16 = 0;
    /// `LsarEnumerateTrustedDomains` (v1) — [MS-LSAD] §3.1.4.7.7.
    pub const ENUMERATE_TRUSTED_DOMAINS: u16 = 13;
    /// `LsarOpenPolicy2` — reused from LSAT.
    pub const OPEN_POLICY2: u16 = 44;
    /// `LsarQueryTrustedDomainInfoByName` — [MS-LSAD] §3.1.4.7.4. Target for v0.2 (trust-key read).
    pub const QUERY_TRUSTED_DOMAIN_INFO_BY_NAME: u16 = 48;
    /// `LsarEnumerateTrustedDomainsEx` (v2) — [MS-LSAD] §3.1.4.7.8. Target for v0.2 (richer TDO info).
    pub const ENUMERATE_TRUSTED_DOMAINS_EX: u16 = 50;
}

// ---- RPC_SID marshaling (mirrors ms-lsat's private helper) ----------------

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);
    // Bounded-alloc preflight per the icedracon wire rule: each sub-authority is 4 bytes,
    // so count × 4 must fit in the remaining stub.
    if count
        .checked_mul(4)
        .map_or(true, |need| need > d.remaining())
    {
        return Err(dcerpc::RpcError::Protocol(format!(
            "RPC_SID: SubAuthorityCount={count} exceeds remaining stub"
        )));
    }
    let mut sub_authorities = Vec::with_capacity(count);
    for _ in 0..count {
        sub_authorities.push(d.u32()?);
    }
    Ok(Sid {
        revision,
        identifier_authority,
        sub_authorities,
    })
}

// ---- LsarEnumerateTrustedDomains ------------------------------------------

/// One row of a `LsarEnumerateTrustedDomains` response.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct TrustedDomainInfo {
    /// NetBIOS name of the trusted domain (from `LSAPR_TRUST_INFORMATION.Name`).
    pub name: String,
    /// SID of the trusted domain.
    pub sid: Sid,
}

/// `LsarEnumerateTrustedDomains(PolicyHandle, EnumerationContext, EnumerationBuffer, PreferedMaximumLength)`.
///
/// Request stub layout ([MS-LSAD] §3.1.4.7.7):
///
/// - `PolicyHandle`: 20 bytes (attrs + GUID)
/// - `EnumerationContext`: u32 — 0 for first call; server returns updated value if more entries remain
/// - `PreferedMaximumLength`: u32 — server hint, we pass a large default (e.g. 8192)
///
/// Total 28 bytes.
pub fn encode_enumerate_trusted_domains(
    handle: &PolicyHandle,
    enumeration_context: u32,
    prefered_maximum_length: u32,
) -> Vec<u8> {
    let mut e = NdrEncoder::new();
    handle.encode(&mut e);
    e.u32(enumeration_context);
    e.u32(prefered_maximum_length);
    e.into_bytes()
}

/// A batched enumeration response: the trust rows + the updated context.
///
/// Client code either calls once with a large `prefered_maximum_length` (rarely > a handful of
/// trusts in real domains, ~256 entries max for practical purposes), or loops feeding
/// `next_context` back until it comes back == 0 or the returned rows are empty.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct EnumerateTrustsPage {
    pub trusts: Vec<TrustedDomainInfo>,
    /// If non-zero, the client should call again with this value to fetch the next page.
    pub next_context: u32,
}

/// Decode a `LsarEnumerateTrustedDomains` response.
///
/// **Live-validated** against Windows Server 2025 DC (`testlab.local`, stand-alone —
/// 0 configured trusts). The end-to-end path is:
/// `SmbClient::connect → login → tree_connect(IPC$) → open_pipe(lsarpc) → bind(LSA UUID)
/// → LsarOpenPolicy2 (opnum 44) → LsarEnumerateTrustedDomains (opnum 13)` — completes with
/// no RPC fault, decoder returns the empty page cleanly. Real trust decoding is exercised
/// by the [`enumerate_multiple_trusts_deferred_order`](tests::enumerate_multiple_trusts_deferred_order)
/// synthetic test; a live positive-case requires adding a trust to the lab domain.
///
/// Wire shape (in order of appearance in the response stub):
///
/// 1. `EnumerationContext`: u32
/// 2. `LSAPR_TRUSTED_ENUM_BUFFER`:
///    - `EntriesRead`: u32
///    - `Information`: pointer to a conformant array of `LSAPR_TRUST_INFORMATION`
///      - hoisted `max_count`: u32
///      - per-entry fixed part (12 bytes): `Name.Length` u16 + `Name.MaximumLength` u16 +
///        `Name.Buffer` ptr u32 + `Sid` ptr u32
///      - deferred: each `Name.Buffer` (conformant-varying WSTR) and each `RPC_SID`, in entry order
/// 3. NTSTATUS trailer
///
/// Bounded-alloc: the `EntriesRead × 12` preflight before allocating the header vector
/// matches the pattern locked in across the wire stack in dcerpc 0.2.6.
pub fn decode_enumerate_trusted_domains(stub: &[u8]) -> Result<EnumerateTrustsPage> {
    let mut d = NdrDecoder::new(stub);

    let next_context = d.u32()?;
    let entries = d.u32()? as usize;
    let info_ptr = d.u32()?;

    if info_ptr == 0 {
        return Ok(EnumerateTrustsPage {
            trusts: Vec::new(),
            next_context,
        });
    }

    let _max_count = d.u32()?;

    // Bounded-alloc: each fixed-part header is 12 bytes.
    if entries
        .checked_mul(12)
        .map_or(true, |need| need > d.remaining())
    {
        return Err(dcerpc::RpcError::Protocol(format!(
            "LsarEnumerateTrustedDomains: EntriesRead={entries} exceeds remaining stub"
        )));
    }

    let mut headers: Vec<(u16, u32, u32)> = Vec::with_capacity(entries);
    for _ in 0..entries {
        let name_len = d.u16()?;
        let _name_max = d.u16()?;
        let name_ptr = d.u32()?;
        let sid_ptr = d.u32()?;
        headers.push((name_len, name_ptr, sid_ptr));
    }

    let mut trusts = Vec::with_capacity(entries);
    for (_len, name_ptr, sid_ptr) in headers {
        let name = if name_ptr != 0 {
            d.conformant_varying_wstr()?
        } else {
            String::new()
        };
        let sid = if sid_ptr != 0 {
            decode_sid(&mut d)?
        } else {
            Sid {
                revision: 1,
                identifier_authority: 0,
                sub_authorities: vec![],
            }
        };
        trusts.push(TrustedDomainInfo { name, sid });
    }

    Ok(EnumerateTrustsPage {
        trusts,
        next_context,
    })
}

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

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

impl<'a> LsadClient<'a> {
    /// Bind the LSA interface over a fresh `\lsarpc` pipe.
    pub async fn bind(client: &'a mut SmbClient, file_id: [u8; 16]) -> Result<Self> {
        let mut pipe = SmbPipe::new(client, file_id);
        pipe.bind(lsad_syntax()).await?;
        Ok(LsadClient { 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 = ms_lsat::encode_open_policy2(system_name, access::MAXIMUM_ALLOWED);
        let resp = self.pipe.call(lsat_opnum::OPEN_POLICY2, &stub).await?;
        let mut d = NdrDecoder::new(&resp);
        let h = PolicyHandle::decode(&mut d)?;
        self.handle = Some(h);
        Ok(h)
    }

    /// Enumerate every trust in one page (loops the paging cursor internally until the server
    /// returns `next_context == 0`). Real-world domains have < 256 trusts; a single page is
    /// almost always sufficient.
    pub async fn enumerate_trusts(&mut self, system_name: &str) -> Result<Vec<TrustedDomainInfo>> {
        let h = self.ensure_handle(system_name).await?;
        let mut out: Vec<TrustedDomainInfo> = Vec::new();
        let mut ctx: u32 = 0;
        loop {
            let stub = encode_enumerate_trusted_domains(&h, ctx, 8192);
            let resp = self
                .pipe
                .call(opnum::ENUMERATE_TRUSTED_DOMAINS, &stub)
                .await?;
            let page = decode_enumerate_trusted_domains(&resp)?;
            let got = page.trusts.len();
            out.extend(page.trusts);
            if page.next_context == 0 || got == 0 {
                break;
            }
            ctx = page.next_context;
        }
        Ok(out)
    }
}

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

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

    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);
        }
    }

    #[test]
    fn enumerate_request_stub_is_fixed_28_bytes() {
        let stub = encode_enumerate_trusted_domains(&PolicyHandle([0u8; 20]), 0, 8192);
        // handle(20) + context(4) + max_len(4) = 28 exactly, no NDR padding.
        assert_eq!(stub.len(), 28);
        assert_eq!(u32::from_le_bytes(stub[20..24].try_into().unwrap()), 0);
        assert_eq!(u32::from_le_bytes(stub[24..28].try_into().unwrap()), 8192);
    }

    #[test]
    fn enumerate_context_is_returned_intact_on_empty_page() {
        // Build a synthetic response with EntriesRead=0 and next_context=42.
        let mut e = NdrEncoder::new();
        e.u32(42); // next_context
        e.u32(0); // EntriesRead
        e.u32(0); // Information ptr = NULL
        let stub = e.into_bytes();
        let page = decode_enumerate_trusted_domains(&stub).unwrap();
        assert_eq!(page.next_context, 42);
        assert!(page.trusts.is_empty());
    }

    /// Encode a synthetic response with one trust (name + domain SID), then decode and
    /// verify. Locks in the per-entry deferred-data ordering.
    #[test]
    fn enumerate_roundtrip_single_trust() {
        let dom_sid = Sid::parse("S-1-5-21-1111-2222-3333").unwrap();
        let dn: Vec<u16> = "TRUSTED-CORP".encode_utf16().collect();
        let dl = (dn.len() * 2) as u16;

        let mut e = NdrEncoder::new();
        e.u32(0); // next_context — no more pages
        e.u32(1); // EntriesRead
        e.referent(); // Information array ptr
        e.u32(1); // conformant max_count
                  // fixed header: Length + Max + BufferPtr + SidPtr = 12 bytes
        e.u16(dl);
        e.u16(dl);
        e.referent(); // Name.Buffer ptr
        e.referent(); // Sid ptr
                      // deferred: name buffer WSTR
        e.u32(dn.len() as u32);
        e.u32(0);
        e.u32(dn.len() as u32);
        for u in &dn {
            e.u16(*u);
        }
        // deferred: RPC_SID
        encode_sid(&mut e, &dom_sid);
        // NTSTATUS trailer — not read by decoder
        e.u32(0);

        let stub = e.into_bytes();
        let page = decode_enumerate_trusted_domains(&stub).unwrap();
        assert_eq!(page.next_context, 0);
        assert_eq!(page.trusts.len(), 1);
        assert_eq!(page.trusts[0].name, "TRUSTED-CORP");
        assert_eq!(page.trusts[0].sid.to_string(), "S-1-5-21-1111-2222-3333");
    }

    #[test]
    fn enumerate_multiple_trusts_deferred_order() {
        // Two trusts. Encoder must emit BOTH fixed headers THEN both deferred payloads in
        // header order — the classic NDR pointer-shape gotcha.
        let sids = [
            Sid::parse("S-1-5-21-10-20-30").unwrap(),
            Sid::parse("S-1-5-21-40-50-60").unwrap(),
        ];
        let names: Vec<Vec<u16>> = ["FOREST-A", "FOREST-B"]
            .iter()
            .map(|s| s.encode_utf16().collect())
            .collect();

        let mut e = NdrEncoder::new();
        e.u32(0); // next_context
        e.u32(2); // EntriesRead
        e.referent(); // Information array ptr
        e.u32(2); // conformant max_count

        // Both fixed headers first
        for name in &names {
            let l = (name.len() * 2) as u16;
            e.u16(l);
            e.u16(l);
            e.referent(); // Name.Buffer ptr
            e.referent(); // Sid ptr
        }
        // Then all deferred, in entry order: name0, sid0, name1, sid1
        for (name, sid) in names.iter().zip(sids.iter()) {
            e.u32(name.len() as u32);
            e.u32(0);
            e.u32(name.len() as u32);
            for u in name {
                e.u16(*u);
            }
            encode_sid(&mut e, sid);
        }
        e.u32(0); // NTSTATUS

        let stub = e.into_bytes();
        let page = decode_enumerate_trusted_domains(&stub).unwrap();
        assert_eq!(page.trusts.len(), 2);
        assert_eq!(page.trusts[0].name, "FOREST-A");
        assert_eq!(page.trusts[0].sid.to_string(), "S-1-5-21-10-20-30");
        assert_eq!(page.trusts[1].name, "FOREST-B");
        assert_eq!(page.trusts[1].sid.to_string(), "S-1-5-21-40-50-60");
    }

    #[test]
    fn hostile_entries_read_is_bounded_against_stub() {
        // Server-returned EntriesRead = u32::MAX must not force a giant Vec::with_capacity
        // before the header preflight rejects the reply.
        let mut e = NdrEncoder::new();
        e.u32(0); // next_context
        e.u32(u32::MAX); // EntriesRead — hostile
        e.referent(); // Information array ptr
        e.u32(u32::MAX); // conformant max_count
                         // No headers follow — the preflight must reject.
        let stub = e.into_bytes();
        let err = decode_enumerate_trusted_domains(&stub).unwrap_err();
        // Just check that we didn't panic / OOM. Any error is fine here.
        let _ = err;
    }
}