ntds-parse 0.2.0

NTDS.dit-domain decode + crypto primitives — ESE file-header validation + PEK-list AES-CBC unwrap (SYSTEM bootkey → AES key) + RID→DES-key derivation for NT-hash decrypt + typed userAccountControl / sAMAccountType decoders. Byte-verified against impacket's secretsdump
Documentation
//! Decryption of the encrypted NT / LM hash bytes as they appear in NTDS.dit `unicodePwd`
//! and `dbcsPwd` attributes.
//!
//! ## Two-layer wrap (v0.2, inlined)
//!
//! ```text
//! datatable[user].unicodePwd  =  Header(8) | KeyMaterial(16) | Ciphertext(16)
//!
//!    Header[0..4]  = 0x13 0x00 0x00 0x00           (constant marker)
//!    Header[4..8]  = PEK index (u32 LE)            (which PEK key encrypted this)
//!    KeyMaterial   = 16-byte AES-CBC IV
//!    Ciphertext    = 16-byte AES-CBC ciphertext
//!
//!    AES-256-CBC decrypt with key = PEK[pek_index], IV = KeyMaterial
//!       → 16-byte "RID-encrypted" NT hash (aka tmp_hash)
//!
//!    DES-ECB decrypt tmp_hash[0..8] with key1 = derive_des_keys_from_rid(rid).0
//!    DES-ECB decrypt tmp_hash[8..16] with key2 = derive_des_keys_from_rid(rid).1
//!       → 16-byte plaintext NT hash
//! ```
//!
//! Verified byte-for-byte against impacket's `secretsdump.py` `NTDSHashes.__decryptHash` for
//! the AES-CBC + DES-ECB path.

use crate::Error;
use aes::cipher::{block_padding::NoPadding, BlockDecryptMut, KeyIvInit};
use des::cipher::{generic_array::GenericArray, BlockDecrypt, KeyInit as DesKeyInit};

type Aes256CbcDec = cbc::Decryptor<aes::Aes256>;

/// Format a hash as lowercase hex (canonical mimikatz-style output).
pub fn hex(bytes: &[u8]) -> String {
    let mut s = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        s.push(nibble(b >> 4));
        s.push(nibble(b & 0x0f));
    }
    s
}

fn nibble(n: u8) -> char {
    match n {
        0..=9 => (b'0' + n) as char,
        _ => (b'a' + n - 10) as char,
    }
}

/// Derive the two 8-byte DES keys used by SAM/NTDS to RID-obfuscate an NT hash.
///
/// ```text
///   rid_bytes    = rid.to_le_bytes()          // 4 bytes
///   key1_raw     = [rid_bytes[0], rid_bytes[1], rid_bytes[2], rid_bytes[3],
///                   rid_bytes[0], rid_bytes[1], rid_bytes[2]]
///   key2_raw     = [rid_bytes[3], rid_bytes[0], rid_bytes[1], rid_bytes[2],
///                   rid_bytes[3], rid_bytes[0], rid_bytes[1]]
///   key1, key2   = expand_des_key(key1_raw), expand_des_key(key2_raw)
/// ```
pub fn derive_des_keys_from_rid(rid: u32) -> ([u8; 8], [u8; 8]) {
    let r = rid.to_le_bytes();
    let raw1 = [r[0], r[1], r[2], r[3], r[0], r[1], r[2]];
    let raw2 = [r[3], r[0], r[1], r[2], r[3], r[0], r[1]];
    (expand_des_key(&raw1), expand_des_key(&raw2))
}

/// Expand a 7-byte raw DES key into the 8-byte parity-bit form the DES primitive expects.
pub fn expand_des_key(raw: &[u8; 7]) -> [u8; 8] {
    let mut out = [0u8; 8];
    // Every byte reserves bit 0 for odd-parity fixup. `raw[0]`'s bit 0 is preserved as
    // data in `out[1]`'s bit 7 (via `raw[0] << 7` below) — so we must mask bit 0 off
    // `out[0]` here or that bit ends up duplicated + parity comes out even. Concrete
    // symptom: RIDs whose low byte is 0xF5 (e.g. 501/Guest) produced 0xF5 instead of
    // impacket's 0xF4.
    out[0] = raw[0] & 0xfe;
    out[1] = ((raw[0] << 7) | (raw[1] >> 1)) & 0xfe;
    out[2] = ((raw[1] << 6) | (raw[2] >> 2)) & 0xfe;
    out[3] = ((raw[2] << 5) | (raw[3] >> 3)) & 0xfe;
    out[4] = ((raw[3] << 4) | (raw[4] >> 4)) & 0xfe;
    out[5] = ((raw[4] << 3) | (raw[5] >> 5)) & 0xfe;
    out[6] = ((raw[5] << 2) | (raw[6] >> 6)) & 0xfe;
    out[7] = (raw[6] << 1) & 0xfe;
    // Add odd parity.
    for b in out.iter_mut() {
        let ones = b.count_ones();
        if ones % 2 == 0 {
            *b |= 1;
        }
    }
    out
}

/// Decrypt an encrypted NT-hash attribute value from NTDS.dit.
///
/// - `encrypted` — the raw `unicodePwd` (or `dbcsPwd` for LM) attribute bytes: at least
///   40 bytes = 8-byte header + 16-byte IV + 16-byte ciphertext.
/// - `pek_list` — the unwrapped [`crate::pek::PekList`]. This fn reads the PEK index from
///   `encrypted[4..8]` and looks up the matching key.
/// - `rid` — the account's Relative ID (from its SID), used for the DES-ECB layer.
///
/// Returns the 16-byte plaintext NT hash. Fails if the attribute is malformed, the PEK
/// index is out of range, or the AES ciphertext length is invalid.
pub fn decrypt_nt_hash(
    encrypted: &[u8],
    pek_list: &crate::pek::PekList,
    rid: u32,
) -> Result<[u8; 16], Error> {
    if encrypted.len() < 8 + 16 + 16 {
        return Err(Error::Crypto(format!(
            "encrypted hash too short ({} bytes, need at least 40)",
            encrypted.len()
        )));
    }
    let pek_index = u32::from_le_bytes(encrypted[4..8].try_into().unwrap());
    let pek = pek_list.key_for(pek_index).ok_or_else(|| {
        Error::Crypto(format!(
            "PEK index {pek_index} out of range (have {})",
            pek_list.keys.len()
        ))
    })?;

    let iv: &[u8; 16] = encrypted[8..24].try_into().unwrap();
    let ciphertext: &[u8; 16] = encrypted[24..40].try_into().unwrap();

    // Modern NTDS uses AES-128-CBC with the 16-byte PEK as the key (not AES-256; the PEK
    // is only 16 bytes).
    let mut tmp = [0u8; 16];
    tmp.copy_from_slice(ciphertext);
    cbc::Decryptor::<aes::Aes128>::new(pek.bytes().into(), iv.into())
        .decrypt_padded_mut::<NoPadding>(&mut tmp)
        .map_err(|e| Error::Crypto(format!("AES-128-CBC decrypt failed: {e}")))?;

    // DES-ECB unwrap the RID obfuscation.
    let (k1, k2) = derive_des_keys_from_rid(rid);
    let mut out = [0u8; 16];
    let mut block1 = GenericArray::clone_from_slice(&tmp[0..8]);
    let mut block2 = GenericArray::clone_from_slice(&tmp[8..16]);
    des::Des::new_from_slice(&k1)
        .map_err(|e| Error::Crypto(format!("DES key1: {e}")))?
        .decrypt_block(&mut block1);
    des::Des::new_from_slice(&k2)
        .map_err(|e| Error::Crypto(format!("DES key2: {e}")))?
        .decrypt_block(&mut block2);
    out[0..8].copy_from_slice(&block1);
    out[8..16].copy_from_slice(&block2);
    Ok(out)
}

/// Silence the unused-import warning when the crate is built without `aes::Aes256`.
#[allow(dead_code)]
type _UnusedShim = Aes256CbcDec;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pek::PekKey;
    use aes::cipher::{block_padding::NoPadding, BlockEncryptMut, KeyIvInit};
    use des::cipher::{BlockEncrypt, KeyInit as _DesKeyInit};

    #[test]
    fn hex_lowercases_and_pads() {
        assert_eq!(hex(&[0x00, 0xff, 0x1a, 0xb3]), "00ff1ab3");
        assert_eq!(hex(&[]), "");
    }

    #[test]
    fn expand_des_key_adds_odd_parity() {
        let out = expand_des_key(&[0; 7]);
        for b in out.iter() {
            assert_eq!(b.count_ones() % 2, 1);
        }
    }

    #[test]
    fn derive_des_keys_from_rid_uses_rid_bytes() {
        let (k1, k2) = derive_des_keys_from_rid(0x11223344);
        assert_ne!(k1, k2);
        assert_eq!(k1[0], 0x45); // parity fix on 0x44
    }

    #[test]
    fn derive_des_keys_from_rid_stable_across_calls() {
        assert_eq!(derive_des_keys_from_rid(500), derive_des_keys_from_rid(500));
    }

    /// End-to-end: build a fake encrypted NT-hash attribute the way NTDS does it, then
    /// verify decrypt_nt_hash inverts it byte-for-byte.
    #[test]
    fn decrypt_nt_hash_roundtrip() {
        let pek = PekKey::new([0x11u8; 16]);
        let pek_list = crate::pek::PekList {
            version: 3,
            keys: vec![pek],
        };
        let rid: u32 = 1105;
        let iv = [0x22u8; 16];
        let plaintext_nt = *b"ABCDEFGHIJKLMNOP"; // 16 bytes = a synthetic NT hash

        // Forward: apply RID DES-ECB encrypt first (this is what SAM does before AES).
        let (k1, k2) = derive_des_keys_from_rid(rid);
        let mut b1 = GenericArray::clone_from_slice(&plaintext_nt[0..8]);
        let mut b2 = GenericArray::clone_from_slice(&plaintext_nt[8..16]);
        des::Des::new_from_slice(&k1)
            .unwrap()
            .encrypt_block(&mut b1);
        des::Des::new_from_slice(&k2)
            .unwrap()
            .encrypt_block(&mut b2);
        let mut tmp = [0u8; 16];
        tmp[0..8].copy_from_slice(&b1);
        tmp[8..16].copy_from_slice(&b2);

        // Then AES-128-CBC encrypt with PEK as key, IV = KeyMaterial.
        let mut ct = tmp;
        cbc::Encryptor::<aes::Aes128>::new(pek.bytes().into(), &iv.into())
            .encrypt_padded_mut::<NoPadding>(&mut ct, 16)
            .unwrap();

        // Package: Header(8) [0x13 constant + 4-byte PEK index=0] | IV(16) | Ciphertext(16)
        let mut encrypted = vec![0x13, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
        encrypted.extend_from_slice(&iv);
        encrypted.extend_from_slice(&ct);

        // Decrypt + verify.
        let recovered = decrypt_nt_hash(&encrypted, &pek_list, rid).unwrap();
        assert_eq!(recovered, plaintext_nt);
    }

    #[test]
    fn decrypt_nt_hash_rejects_short() {
        let pek_list = crate::pek::PekList {
            version: 3,
            keys: vec![PekKey::new([0u8; 16])],
        };
        let err = decrypt_nt_hash(&[0u8; 30], &pek_list, 500).unwrap_err();
        assert!(format!("{err}").contains("too short"));
    }

    #[test]
    fn decrypt_nt_hash_rejects_bad_pek_index() {
        let pek_list = crate::pek::PekList {
            version: 3,
            keys: vec![PekKey::new([0u8; 16])],
        };
        let mut enc = vec![0x13, 0, 0, 0, 99, 0, 0, 0]; // pek_index = 99
        enc.extend_from_slice(&[0u8; 32]);
        let err = decrypt_nt_hash(&enc, &pek_list, 500).unwrap_err();
        assert!(format!("{err}").contains("out of range"));
    }
}