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
//! **ntds-parse** — NTDS.dit-domain decode primitives.
//!
//! Ntds.dit is Windows Active Directory's on-disk copy of the domain: users, groups,
//! password hashes, computer accounts, GPO links. Physically it's a Microsoft Extensible
//! Storage Engine (ESE / Jet Blue) database. Semantically the interesting rows sit in the
//! `datatable` and `link_table` tables, and the password material is encrypted with a chain
//! that starts at the SYSTEM hive's boot key.
//!
//! This crate is the **NTDS-domain** layer:
//!
//! - [`NtdsFile::open`] — validate the ESE file header (magic, page size, format version).
//! - [`pek::unwrap_peklist`] — SYSTEM bootkey + NTDS `PEKLIST` blob → the PEK (Password
//!   Encryption Key) that decrypts every hash in the datatable.
//! - [`hash::decrypt_nt_hash`] — encrypted NT-hash bytes (as they appear in the `unicodePwd`
//!   attribute) + PEK + RID → plaintext NT hash. Same shape for LM.
//! - [`uac`] — decode `userAccountControl` bits (disabled, dontrequirepreauth, notdelegated,
//!   trusteddelegation, useDesKeyOnly, etc.) into a boolean-typed struct.
//! - [`sam`] — decode `sAMAccountType` numeric values into a symbolic enum
//!   (NORMAL_USER_ACCOUNT, MACHINE_ACCOUNT, TRUST_ACCOUNT, GROUP_OBJECT, …).
//!
//! # What this crate is *not*
//!
//! Not an ESE row walker. Full `datatable` decode needs an ESE B-tree traversal plus long-
//! value / multi-value column reassembly — 3000+ LOC of file-format work. For v0.1 that lives
//! behind the [`EseBackend`] trait; downstream can plug in `libesedb` FFI, the `esed` crate,
//! or a from-scratch walker. What this crate *guarantees* is that once you have the raw
//! attribute bytes, the crypto and semantic decoders here are correct.
//!
//! # Example
//!
//! ```ignore
//! use ntds_parse::{NtdsFile, pek, hash};
//!
//! // 1. Confirm this is a valid NTDS.dit
//! let f = NtdsFile::open("C:\\Windows\\NTDS\\ntds.dit")?;
//! println!("ESE format {}, page size {} bytes", f.format_version(), f.page_size());
//!
//! // 2. Unwrap the PEK using the SYSTEM hive bootkey
//! let bootkey: [u8; 16] = *b"boot_key_16bytes";       // from windows-secrets::bootkey()
//! let peklist_bytes: Vec<u8> = /* from datatable[Pek-List].pekList */ vec![];
//! let pek = pek::unwrap_peklist(&bootkey, &peklist_bytes)?;
//!
//! // 3. Decrypt one user's NT hash
//! let encrypted_nt: Vec<u8> = /* from datatable[user].unicodePwd */ vec![];
//! let rid = 1105u32;
//! let plaintext = hash::decrypt_nt_hash(&encrypted_nt, &pek, rid)?;
//! println!("NT hash: {}", hash::hex(&plaintext));
//! # Ok::<_, ntds_parse::Error>(())
//! ```

pub mod hash;
pub mod pek;
pub mod sam;
pub mod uac;

use std::io::Read;
use std::path::Path;

/// A minimally-parsed NTDS.dit — enough to confirm the file is a valid ESE database and
/// expose its format metadata. Full row iteration is the caller's job via [`EseBackend`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct NtdsFile {
    format_version: u32,
    page_size: u32,
    file_type: u32,
}

impl NtdsFile {
    /// Open + validate an NTDS.dit file. Reads only the 668-byte database header.
    pub fn open(path: impl AsRef<Path>) -> Result<Self, Error> {
        let mut f = std::fs::File::open(path).map_err(Error::Io)?;
        let mut buf = [0u8; 668];
        f.read_exact(&mut buf).map_err(Error::Io)?;
        Self::parse_header(&buf)
    }

    /// Parse an already-read 668-byte ESE database header. Useful for tests and for callers
    /// that already hold the bytes.
    pub fn parse_header(hdr: &[u8]) -> Result<Self, Error> {
        if hdr.len() < 668 {
            return Err(Error::Format("header too short (< 668 bytes)".into()));
        }
        // ESE db-header layout (subset — see [MS-ESE] and Metz's libesedb docs):
        //   offset 4:  file-signature magic — 0xEF CD AB 89  (little-endian 0x89ABCDEF)
        //   offset 8:  format-version       (u32)
        //   offset 12: file-type            (u32) — 0 = database, 1 = streaming file
        //   offset 236:page size            (u32)
        let magic = u32::from_le_bytes([hdr[4], hdr[5], hdr[6], hdr[7]]);
        if magic != 0x89AB_CDEF {
            return Err(Error::Format(format!(
                "bad ESE magic: got {magic:#010x}, want 0x89abcdef"
            )));
        }
        let format_version = u32::from_le_bytes([hdr[8], hdr[9], hdr[10], hdr[11]]);
        let file_type = u32::from_le_bytes([hdr[12], hdr[13], hdr[14], hdr[15]]);
        let page_size = u32::from_le_bytes([hdr[236], hdr[237], hdr[238], hdr[239]]);
        if ![2048, 4096, 8192, 16384, 32768].contains(&page_size) {
            return Err(Error::Format(format!("odd page size {page_size}")));
        }
        Ok(NtdsFile {
            format_version,
            page_size,
            file_type,
        })
    }

    pub fn format_version(&self) -> u32 {
        self.format_version
    }
    pub fn page_size(&self) -> u32 {
        self.page_size
    }
    pub fn file_type(&self) -> u32 {
        self.file_type
    }
}

/// Trait for pluggable ESE row iteration — implement this to plug in a backend like
/// `libesedb` FFI, the pure-Rust `esed` crate, or an in-tree walker. This crate doesn't
/// ship a backend in v0.1; the decoders (pek/hash/uac/sam) are what you use once you have
/// raw attribute bytes from *any* backend.
pub trait EseBackend {
    type Row;
    type Error;

    /// Iterate every row in the given table name (e.g. `"datatable"`).
    fn iter_table(
        &self,
        table: &str,
    ) -> Result<Box<dyn Iterator<Item = Self::Row> + '_>, Self::Error>;
}

/// Errors this crate returns.
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
    /// The file could not be read from disk.
    Io(std::io::Error),
    /// The bytes did not match the expected ESE / NTDS shape.
    Format(String),
    /// A cryptographic step failed (bad key, wrong RID, truncated ciphertext).
    Crypto(String),
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::Io(e) => write!(f, "io: {e}"),
            Error::Format(s) => write!(f, "format: {s}"),
            Error::Crypto(s) => write!(f, "crypto: {s}"),
        }
    }
}

impl std::error::Error for Error {}

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

    fn synthetic_header(page_size: u32) -> Vec<u8> {
        let mut hdr = vec![0u8; 668];
        // magic at offset 4
        hdr[4..8].copy_from_slice(&0x89AB_CDEFu32.to_le_bytes());
        // format-version at offset 8
        hdr[8..12].copy_from_slice(&620u32.to_le_bytes());
        // file-type at offset 12 (0 = database)
        hdr[12..16].copy_from_slice(&0u32.to_le_bytes());
        // page size at offset 236
        hdr[236..240].copy_from_slice(&page_size.to_le_bytes());
        hdr
    }

    #[test]
    fn accepts_valid_synthetic_header() {
        let hdr = synthetic_header(8192);
        let f = NtdsFile::parse_header(&hdr).unwrap();
        assert_eq!(f.page_size(), 8192);
        assert_eq!(f.format_version(), 620);
        assert_eq!(f.file_type(), 0);
    }

    #[test]
    fn rejects_wrong_magic() {
        let mut hdr = synthetic_header(8192);
        hdr[4..8].copy_from_slice(&0xdeadbeefu32.to_le_bytes());
        let err = NtdsFile::parse_header(&hdr).unwrap_err();
        assert!(matches!(err, Error::Format(_)));
    }

    #[test]
    fn rejects_short_header() {
        let hdr = vec![0u8; 100];
        assert!(matches!(
            NtdsFile::parse_header(&hdr).unwrap_err(),
            Error::Format(_)
        ));
    }

    #[test]
    fn rejects_bad_page_size() {
        let hdr = synthetic_header(1234);
        assert!(matches!(
            NtdsFile::parse_header(&hdr).unwrap_err(),
            Error::Format(_)
        ));
    }
}