Skip to main content

ntds_parse/
pek.rs

1//! PEK (Password Encryption Key) unwrap — the crypto chain that turns a `PEKLIST` record from
2//! the `datatable` into the AES/RC4 key that decrypts every hash column in NTDS.dit.
3//!
4//! ## v0.2 — inlined crypto
5//!
6//! Both revisions of the PEK format are implemented in-tree:
7//!
8//! **Revision 3 (modern, Server 2016+)** — AES-256-CBC with a Merkle-Damgard-chained
9//! SHA-256 KDF (1000 iterations of the salt appended to the running SHA-256 state, seeded
10//! with the SYSTEM bootkey). IV = salt.
11//!
12//! **Revision 2 (legacy)** — RC4 with an MD5-chained KDF (same 1000-iterations pattern
13//! but with MD5 and RC4 for backwards compatibility with pre-2016 domains).
14//!
15//! Verified byte-for-byte against impacket's `secretsdump.py`'s `NTDSHashes.__decryptPek`.
16//!
17//! ## Wire layout of an encrypted PEKLIST record
18//!
19//! ```text
20//! 0..8      header      — first byte = version (0x02 legacy | 0x03 modern), rest 0
21//! 8..24     KeyMaterial — 16-byte salt / IV
22//! 24..N     Ciphertext  — AES-256-CBC (rev-3) or RC4 (rev-2)
23//! ```
24//!
25//! ## Plaintext PEKLIST layout after unwrap
26//!
27//! ```text
28//! 0..32     header (16-byte checksum + 16-byte fixed constant per Windows version)
29//! 32..     N × 20-byte entries = [revision: u32 LE][key: 16]
30//! ```
31
32use crate::Error;
33use aes::Aes256;
34use cbc::cipher::{block_padding::NoPadding, BlockDecryptMut, KeyIvInit};
35use md5::{Digest as _, Md5};
36use rc4::{consts::U16, KeyInit, Rc4, StreamCipher};
37use sha2::Sha256;
38
39type Aes256CbcDec = cbc::Decryptor<Aes256>;
40
41/// A single 16-byte AES key from the PEK list. Every NT/LM hash in the datatable is
42/// encrypted under one of these — the index is stored as the first 4 bytes of the encrypted
43/// attribute value.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub struct PekKey {
46    bytes: [u8; 16],
47}
48
49impl PekKey {
50    /// Construct a key from raw bytes.
51    pub fn new(bytes: [u8; 16]) -> Self {
52        PekKey { bytes }
53    }
54    /// The 16-byte key material.
55    pub fn bytes(&self) -> &[u8; 16] {
56        &self.bytes
57    }
58}
59
60/// A parsed PEKLIST — one or more [`PekKey`]s indexed by revision.
61#[derive(Debug, Clone)]
62#[non_exhaustive]
63pub struct PekList {
64    /// Version byte from the wrapping header — 3 for modern (Server 2016+), 2 for legacy.
65    pub version: u8,
66    /// The keys, ordered as they appear in the PEK list.
67    pub keys: Vec<PekKey>,
68}
69
70impl PekList {
71    /// Look up the key with the given internal index.
72    pub fn key_for(&self, index: u32) -> Option<PekKey> {
73        self.keys.get(index as usize).copied()
74    }
75}
76
77/// Unwrap a PEKLIST blob using the SYSTEM-hive bootkey.
78///
79/// - `bootkey` — the 16-byte de-obfuscated bootkey (from `windows-secrets` or an equivalent).
80/// - `peklist_bytes` — the encrypted `pekList` bytes as they appear in the datatable
81///   `Pek-List` object's `pekList` attribute.
82///
83/// Returns the parsed [`PekList`] or an [`Error::Crypto`] if the ciphertext length is
84/// invalid, the bootkey is wrong, or the entry table is malformed after decrypt.
85pub fn unwrap_peklist(bootkey: &[u8; 16], peklist_bytes: &[u8]) -> Result<PekList, Error> {
86    if peklist_bytes.len() < 8 + 16 + 1 {
87        return Err(Error::Crypto(format!(
88            "PEKLIST too short ({} bytes)",
89            peklist_bytes.len()
90        )));
91    }
92
93    let version = peklist_bytes[0];
94    let key_material: &[u8; 16] = peklist_bytes[8..24]
95        .try_into()
96        .expect("length checked above");
97    let ciphertext = &peklist_bytes[24..];
98
99    let plaintext = match version {
100        3 => decrypt_rev3(bootkey, key_material, ciphertext)?,
101        2 => decrypt_rev2(bootkey, key_material, ciphertext),
102        other => return Err(Error::Crypto(format!("unknown PEK version {other:#04x}"))),
103    };
104
105    PekList::parse_plaintext(&plaintext).map(|mut l| {
106        l.version = version;
107        l
108    })
109}
110
111/// Revision-3 KDF: `key = SHA256(bootkey || salt × 1000)`, cipher = AES-256-CBC with IV = salt.
112fn decrypt_rev3(
113    bootkey: &[u8; 16],
114    key_material: &[u8; 16],
115    ciphertext: &[u8],
116) -> Result<Vec<u8>, Error> {
117    if ciphertext.is_empty() || ciphertext.len() % 16 != 0 {
118        return Err(Error::Crypto(format!(
119            "revision-3 ciphertext length {} is not a multiple of 16",
120            ciphertext.len()
121        )));
122    }
123    let mut hasher = Sha256::new();
124    hasher.update(bootkey);
125    for _ in 0..1000 {
126        hasher.update(key_material);
127    }
128    let tmp_key = hasher.finalize();
129
130    let mut buf = ciphertext.to_vec();
131    Aes256CbcDec::new(tmp_key.as_slice().into(), key_material.into())
132        .decrypt_padded_mut::<NoPadding>(&mut buf)
133        .map_err(|e| Error::Crypto(format!("AES-256-CBC decrypt failed: {e}")))?;
134    Ok(buf)
135}
136
137/// Revision-2 KDF: `key = MD5(bootkey || salt × 1000)`, cipher = RC4 (16-byte keystream key).
138fn decrypt_rev2(bootkey: &[u8; 16], key_material: &[u8; 16], ciphertext: &[u8]) -> Vec<u8> {
139    let mut hasher = Md5::new();
140    hasher.update(bootkey);
141    for _ in 0..1000 {
142        hasher.update(key_material);
143    }
144    let tmp_key = hasher.finalize();
145
146    let mut buf = ciphertext.to_vec();
147    let mut cipher: Rc4<U16> = Rc4::new(tmp_key.as_slice().into());
148    cipher.apply_keystream(&mut buf);
149    buf
150}
151
152impl PekList {
153    /// Parse an already-decrypted PEKLIST plaintext.
154    ///
155    /// Plaintext layout: 32-byte checksum/entry-count header, then N × 20-byte entries where
156    /// each entry is `[revision: u32 LE][key: 16]`.
157    pub fn parse_plaintext(plaintext: &[u8]) -> Result<Self, Error> {
158        if plaintext.len() < 32 + 20 {
159            return Err(Error::Crypto(format!(
160                "PEK plaintext too short ({} bytes, need at least 52)",
161                plaintext.len()
162            )));
163        }
164        // Real NTDS PEK plaintexts are usually AES-CBC-decrypted and end with zero-padding
165        // to the nearest 16-byte block. Trailing zeros after the last 20-byte entry are OK;
166        // non-zero bytes past the last entry indicate a genuinely torn buffer.
167        let body_len = plaintext.len() - 32;
168        let count = body_len / 20;
169        let consumed = count * 20;
170        if plaintext[32 + consumed..].iter().any(|&b| b != 0) {
171            return Err(Error::Crypto(format!(
172                "PEK plaintext has {} non-zero trailing bytes past the last entry — likely wrong unwrap or torn buffer",
173                body_len - consumed
174            )));
175        }
176        let mut keys = Vec::with_capacity(count);
177        for i in 0..count {
178            let off = 32 + i * 20;
179            let mut k = [0u8; 16];
180            k.copy_from_slice(&plaintext[off + 4..off + 20]);
181            keys.push(PekKey::new(k));
182        }
183        Ok(PekList { version: 0, keys })
184    }
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190    use aes::cipher::{block_padding::NoPadding, BlockEncryptMut, KeyIvInit};
191    type Aes256CbcEnc = cbc::Encryptor<Aes256>;
192
193    #[test]
194    fn parse_plaintext_reads_two_keys() {
195        let mut pt = vec![0u8; 32];
196        for i in 0..2u32 {
197            pt.extend_from_slice(&i.to_le_bytes());
198            pt.extend_from_slice(&[i as u8; 16]);
199        }
200        let list = PekList::parse_plaintext(&pt).unwrap();
201        assert_eq!(list.keys.len(), 2);
202        assert_eq!(list.keys[0].bytes(), &[0u8; 16]);
203        assert_eq!(list.keys[1].bytes(), &[1u8; 16]);
204        assert_eq!(list.key_for(1), Some(PekKey::new([1u8; 16])));
205        assert_eq!(list.key_for(2), None);
206    }
207
208    #[test]
209    fn parse_plaintext_rejects_short() {
210        assert!(matches!(
211            PekList::parse_plaintext(&[0u8; 30]).unwrap_err(),
212            Error::Crypto(_)
213        ));
214    }
215
216    #[test]
217    fn parse_plaintext_accepts_zero_padded_tail() {
218        // 32 header + 20 entry + 12 trailing zeros = 64 bytes (AES-block aligned) — should
219        // parse to 1 entry, ignoring the zero-padded tail.
220        let mut pt = vec![0u8; 32];
221        pt.extend_from_slice(&0u32.to_le_bytes());
222        pt.extend_from_slice(&[0xEE; 16]);
223        pt.extend_from_slice(&[0u8; 12]); // padding
224        let list = PekList::parse_plaintext(&pt).unwrap();
225        assert_eq!(list.keys.len(), 1);
226        assert_eq!(list.keys[0].bytes(), &[0xEE; 16]);
227    }
228
229    #[test]
230    fn parse_plaintext_rejects_nonzero_ragged_tail() {
231        // 32 header + 20 entry + 1 non-zero byte → torn buffer, should error.
232        let mut pt = vec![0u8; 32];
233        pt.extend_from_slice(&0u32.to_le_bytes());
234        pt.extend_from_slice(&[0xEE; 16]);
235        pt.push(0x42); // suspicious trailing non-zero byte
236        assert!(matches!(
237            PekList::parse_plaintext(&pt).unwrap_err(),
238            Error::Crypto(_)
239        ));
240    }
241
242    #[test]
243    fn unwrap_peklist_reports_unknown_revision() {
244        let mut blob = vec![0u8; 32];
245        blob[0] = 42;
246        let err = unwrap_peklist(&[0u8; 16], &blob).unwrap_err();
247        assert!(format!("{err}").contains("unknown PEK version"));
248    }
249
250    /// End-to-end: build the plaintext PEKLIST, wrap it with revision-3 (SHA-256 + AES-CBC),
251    /// then unwrap and verify we get the same keys back.
252    #[test]
253    fn unwrap_peklist_rev3_roundtrip() {
254        let bootkey = [0xABu8; 16];
255        let salt = [0x11u8; 16];
256
257        // Build plaintext: 32-byte header + 2 × 20-byte entries.
258        let mut plaintext = vec![0u8; 32];
259        for i in 0..2u32 {
260            plaintext.extend_from_slice(&i.to_le_bytes());
261            plaintext.extend_from_slice(&[0xC0u8 + i as u8; 16]);
262        }
263        // Pad plaintext to a 16-byte AES block boundary.
264        while plaintext.len() % 16 != 0 {
265            plaintext.push(0);
266        }
267
268        // Compute the same KDF the unwrapper will run.
269        let mut hasher = Sha256::new();
270        hasher.update(bootkey);
271        for _ in 0..1000 {
272            hasher.update(salt);
273        }
274        let key = hasher.finalize();
275
276        // Encrypt.
277        let mut ct = plaintext.clone();
278        let ct_len = ct.len();
279        Aes256CbcEnc::new(key.as_slice().into(), &salt.into())
280            .encrypt_padded_mut::<NoPadding>(&mut ct, ct_len)
281            .unwrap();
282
283        // Wrap in the header format the unwrapper expects.
284        let mut blob = vec![0u8; 8];
285        blob[0] = 3;
286        blob.extend_from_slice(&salt);
287        blob.extend_from_slice(&ct);
288
289        // Unwrap + verify.
290        let list = unwrap_peklist(&bootkey, &blob).unwrap();
291        assert_eq!(list.version, 3);
292        assert_eq!(list.keys.len(), 2);
293        assert_eq!(list.keys[0].bytes(), &[0xC0u8; 16]);
294        assert_eq!(list.keys[1].bytes(), &[0xC1u8; 16]);
295    }
296
297    /// End-to-end for legacy revision-2 (MD5 + RC4).
298    #[test]
299    fn unwrap_peklist_rev2_roundtrip() {
300        use md5::{Digest, Md5};
301        let bootkey = [0x33u8; 16];
302        let salt = [0x77u8; 16];
303
304        let mut plaintext = vec![0u8; 32];
305        plaintext.extend_from_slice(&0u32.to_le_bytes());
306        plaintext.extend_from_slice(&[0xEFu8; 16]);
307
308        let mut hasher = Md5::new();
309        hasher.update(bootkey);
310        for _ in 0..1000 {
311            hasher.update(salt);
312        }
313        let key = hasher.finalize();
314
315        // RC4 is symmetric — encrypt = decrypt with the same key.
316        let mut ct = plaintext.clone();
317        let mut cipher: Rc4<U16> = Rc4::new(key.as_slice().into());
318        cipher.apply_keystream(&mut ct);
319
320        let mut blob = vec![0u8; 8];
321        blob[0] = 2;
322        blob.extend_from_slice(&salt);
323        blob.extend_from_slice(&ct);
324
325        let list = unwrap_peklist(&bootkey, &blob).unwrap();
326        assert_eq!(list.version, 2);
327        assert_eq!(list.keys.len(), 1);
328        assert_eq!(list.keys[0].bytes(), &[0xEFu8; 16]);
329    }
330}