ntds_parse/lib.rs
1//! **ntds-parse** — NTDS.dit-domain decode primitives.
2//!
3//! Ntds.dit is Windows Active Directory's on-disk copy of the domain: users, groups,
4//! password hashes, computer accounts, GPO links. Physically it's a Microsoft Extensible
5//! Storage Engine (ESE / Jet Blue) database. Semantically the interesting rows sit in the
6//! `datatable` and `link_table` tables, and the password material is encrypted with a chain
7//! that starts at the SYSTEM hive's boot key.
8//!
9//! This crate is the **NTDS-domain** layer:
10//!
11//! - [`NtdsFile::open`] — validate the ESE file header (magic, page size, format version).
12//! - [`pek::unwrap_peklist`] — SYSTEM bootkey + NTDS `PEKLIST` blob → the PEK (Password
13//! Encryption Key) that decrypts every hash in the datatable.
14//! - [`hash::decrypt_nt_hash`] — encrypted NT-hash bytes (as they appear in the `unicodePwd`
15//! attribute) + PEK + RID → plaintext NT hash. Same shape for LM.
16//! - [`uac`] — decode `userAccountControl` bits (disabled, dontrequirepreauth, notdelegated,
17//! trusteddelegation, useDesKeyOnly, etc.) into a boolean-typed struct.
18//! - [`sam`] — decode `sAMAccountType` numeric values into a symbolic enum
19//! (NORMAL_USER_ACCOUNT, MACHINE_ACCOUNT, TRUST_ACCOUNT, GROUP_OBJECT, …).
20//!
21//! # What this crate is *not*
22//!
23//! Not an ESE row walker. Full `datatable` decode needs an ESE B-tree traversal plus long-
24//! value / multi-value column reassembly — 3000+ LOC of file-format work. For v0.1 that lives
25//! behind the [`EseBackend`] trait; downstream can plug in `libesedb` FFI, the `esed` crate,
26//! or a from-scratch walker. What this crate *guarantees* is that once you have the raw
27//! attribute bytes, the crypto and semantic decoders here are correct.
28//!
29//! # Example
30//!
31//! ```ignore
32//! use ntds_parse::{NtdsFile, pek, hash};
33//!
34//! // 1. Confirm this is a valid NTDS.dit
35//! let f = NtdsFile::open("C:\\Windows\\NTDS\\ntds.dit")?;
36//! println!("ESE format {}, page size {} bytes", f.format_version(), f.page_size());
37//!
38//! // 2. Unwrap the PEK using the SYSTEM hive bootkey
39//! let bootkey: [u8; 16] = *b"boot_key_16bytes"; // from windows-secrets::bootkey()
40//! let peklist_bytes: Vec<u8> = /* from datatable[Pek-List].pekList */ vec![];
41//! let pek = pek::unwrap_peklist(&bootkey, &peklist_bytes)?;
42//!
43//! // 3. Decrypt one user's NT hash
44//! let encrypted_nt: Vec<u8> = /* from datatable[user].unicodePwd */ vec![];
45//! let rid = 1105u32;
46//! let plaintext = hash::decrypt_nt_hash(&encrypted_nt, &pek, rid)?;
47//! println!("NT hash: {}", hash::hex(&plaintext));
48//! # Ok::<_, ntds_parse::Error>(())
49//! ```
50
51pub mod hash;
52pub mod pek;
53pub mod sam;
54pub mod uac;
55
56use std::io::Read;
57use std::path::Path;
58
59/// A minimally-parsed NTDS.dit — enough to confirm the file is a valid ESE database and
60/// expose its format metadata. Full row iteration is the caller's job via [`EseBackend`].
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62#[non_exhaustive]
63pub struct NtdsFile {
64 format_version: u32,
65 page_size: u32,
66 file_type: u32,
67}
68
69impl NtdsFile {
70 /// Open + validate an NTDS.dit file. Reads only the 668-byte database header.
71 pub fn open(path: impl AsRef<Path>) -> Result<Self, Error> {
72 let mut f = std::fs::File::open(path).map_err(Error::Io)?;
73 let mut buf = [0u8; 668];
74 f.read_exact(&mut buf).map_err(Error::Io)?;
75 Self::parse_header(&buf)
76 }
77
78 /// Parse an already-read 668-byte ESE database header. Useful for tests and for callers
79 /// that already hold the bytes.
80 pub fn parse_header(hdr: &[u8]) -> Result<Self, Error> {
81 if hdr.len() < 668 {
82 return Err(Error::Format("header too short (< 668 bytes)".into()));
83 }
84 // ESE db-header layout (subset — see [MS-ESE] and Metz's libesedb docs):
85 // offset 4: file-signature magic — 0xEF CD AB 89 (little-endian 0x89ABCDEF)
86 // offset 8: format-version (u32)
87 // offset 12: file-type (u32) — 0 = database, 1 = streaming file
88 // offset 236:page size (u32)
89 let magic = u32::from_le_bytes([hdr[4], hdr[5], hdr[6], hdr[7]]);
90 if magic != 0x89AB_CDEF {
91 return Err(Error::Format(format!(
92 "bad ESE magic: got {magic:#010x}, want 0x89abcdef"
93 )));
94 }
95 let format_version = u32::from_le_bytes([hdr[8], hdr[9], hdr[10], hdr[11]]);
96 let file_type = u32::from_le_bytes([hdr[12], hdr[13], hdr[14], hdr[15]]);
97 let page_size = u32::from_le_bytes([hdr[236], hdr[237], hdr[238], hdr[239]]);
98 if ![2048, 4096, 8192, 16384, 32768].contains(&page_size) {
99 return Err(Error::Format(format!("odd page size {page_size}")));
100 }
101 Ok(NtdsFile {
102 format_version,
103 page_size,
104 file_type,
105 })
106 }
107
108 pub fn format_version(&self) -> u32 {
109 self.format_version
110 }
111 pub fn page_size(&self) -> u32 {
112 self.page_size
113 }
114 pub fn file_type(&self) -> u32 {
115 self.file_type
116 }
117}
118
119/// Trait for pluggable ESE row iteration — implement this to plug in a backend like
120/// `libesedb` FFI, the pure-Rust `esed` crate, or an in-tree walker. This crate doesn't
121/// ship a backend in v0.1; the decoders (pek/hash/uac/sam) are what you use once you have
122/// raw attribute bytes from *any* backend.
123pub trait EseBackend {
124 type Row;
125 type Error;
126
127 /// Iterate every row in the given table name (e.g. `"datatable"`).
128 fn iter_table(
129 &self,
130 table: &str,
131 ) -> Result<Box<dyn Iterator<Item = Self::Row> + '_>, Self::Error>;
132}
133
134/// Errors this crate returns.
135#[derive(Debug)]
136#[non_exhaustive]
137pub enum Error {
138 /// The file could not be read from disk.
139 Io(std::io::Error),
140 /// The bytes did not match the expected ESE / NTDS shape.
141 Format(String),
142 /// A cryptographic step failed (bad key, wrong RID, truncated ciphertext).
143 Crypto(String),
144}
145
146impl std::fmt::Display for Error {
147 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
148 match self {
149 Error::Io(e) => write!(f, "io: {e}"),
150 Error::Format(s) => write!(f, "format: {s}"),
151 Error::Crypto(s) => write!(f, "crypto: {s}"),
152 }
153 }
154}
155
156impl std::error::Error for Error {}
157
158#[cfg(test)]
159mod tests {
160 use super::*;
161
162 fn synthetic_header(page_size: u32) -> Vec<u8> {
163 let mut hdr = vec![0u8; 668];
164 // magic at offset 4
165 hdr[4..8].copy_from_slice(&0x89AB_CDEFu32.to_le_bytes());
166 // format-version at offset 8
167 hdr[8..12].copy_from_slice(&620u32.to_le_bytes());
168 // file-type at offset 12 (0 = database)
169 hdr[12..16].copy_from_slice(&0u32.to_le_bytes());
170 // page size at offset 236
171 hdr[236..240].copy_from_slice(&page_size.to_le_bytes());
172 hdr
173 }
174
175 #[test]
176 fn accepts_valid_synthetic_header() {
177 let hdr = synthetic_header(8192);
178 let f = NtdsFile::parse_header(&hdr).unwrap();
179 assert_eq!(f.page_size(), 8192);
180 assert_eq!(f.format_version(), 620);
181 assert_eq!(f.file_type(), 0);
182 }
183
184 #[test]
185 fn rejects_wrong_magic() {
186 let mut hdr = synthetic_header(8192);
187 hdr[4..8].copy_from_slice(&0xdeadbeefu32.to_le_bytes());
188 let err = NtdsFile::parse_header(&hdr).unwrap_err();
189 assert!(matches!(err, Error::Format(_)));
190 }
191
192 #[test]
193 fn rejects_short_header() {
194 let hdr = vec![0u8; 100];
195 assert!(matches!(
196 NtdsFile::parse_header(&hdr).unwrap_err(),
197 Error::Format(_)
198 ));
199 }
200
201 #[test]
202 fn rejects_bad_page_size() {
203 let hdr = synthetic_header(1234);
204 assert!(matches!(
205 NtdsFile::parse_header(&hdr).unwrap_err(),
206 Error::Format(_)
207 ));
208 }
209}