Skip to main content

dpapi_offline/
lib.rs

1//! Offline Windows **DPAPI** decryption — a DonPAPI/dploot-class core in pure Rust. No FFI, no
2//! live host: point it at files copied off disk.
3//!
4//! - [`masterkey`] — parse a user masterkey file and decrypt it from the user's password + SID.
5//! - [`blob`] — parse a `DPAPI_BLOB` (`CryptProtectData` output) and decrypt it with a masterkey.
6//! - [`crypto`] — the underlying primitives.
7//!
8//! # VALIDATION STATUS (read this)
9//!
10//! This is the one crate in the ADhammer set that is a **from-scratch crypto build**, not an
11//! extraction of already-live code. Its honesty bar is therefore explicit:
12//!
13//! * **Primitives — VALIDATED.** PBKDF2-HMAC-SHA1 (RFC 6070), HMAC-SHA1 (RFC 2202) and
14//!   HMAC-SHA512 (RFC 4231) are checked against published known-answer vectors in
15//!   `crypto`'s tests — a genuine external oracle, not a self-round-trip.
16//! * **Parsers — VALIDATED (structure).** Deterministic layout tests for the masterkey file,
17//!   masterkey subfield, and `DPAPI_BLOB`, plus truncation-safety.
18//! * **Masterkey decrypt chain — VALIDATED (0.1.2, 2026-08-31).** The full parser +
19//!   `ms_derive_key` + AES256-CBC + HMAC-verify chain is exercised on every test run
20//!   against a deterministic KAT (`KAT_MK_SUBFIELD` in `masterkey::tests`). 0.1.2 rebuilt
21//!   the KAT from **synthetic** throwaway credentials via `docs/synthetic_kat.py` — earlier
22//!   0.1.1 embedded values derived from a real lab masterkey (Administrator on the icedracon
23//!   testlab) and was yanked to stop the credential-material distribution; the synthetic
24//!   KAT still exercises byte-oracle equivalence with impacket 0.14 `dpapi.py` because it
25//!   uses the same algorithm that impacket implements — but nothing in the fixture maps
26//!   back to a real account.
27//!
28//!   The masterkey chain itself was proved correct against a real Windows Server 2025 domain
29//!   Administrator masterkey during the 0.1.1 development cycle; that experiment is what
30//!   discovered 0.1.0's PBKDF2 used the RFC 8018 formulation, while Windows DPAPI uses a
31//!   non-standard variant that feeds the running XOR back into the PRF at every round
32//!   (`ms_derive_key`). 0.1.1+ routes every masterkey decrypt through that variant, adds MD4
33//!   + Protected-Users pre-key derivations, and `unlock_masterkey` handles standalone,
34//!   pre-2019 domain-joined, and 2019+ domain-joined / Protected-Users accounts
35//!   transparently. Operators can re-run the live byte-oracle themselves via the ignored
36//!   `test_real_masterkey` / `test_real_masterkey_with_pwdkey` tests + `DPAPI_MK_FILE=…`
37//!   / `DPAPI_MK_PWDKEY=…` env vars.
38//! * **Blob decrypt chain — NOT YET VALIDATED end-to-end.** The `blob` derivation follows
39//!   MS-DPAPI and impacket, but has **not** been run against a real Windows-generated blob
40//!   yet — validate the same way: run impacket `dpapi.py credential`/`vault` against the
41//!   same bytes as the byte-oracle.
42
43pub mod blob;
44pub mod crypto;
45pub mod masterkey;
46
47pub use blob::DpapiBlob;
48pub use masterkey::{MasterKey, MasterKeyFile};
49
50/// Errors from parsing or decrypting DPAPI structures.
51#[derive(Debug, thiserror::Error)]
52pub enum DpapiError {
53    #[error("parse: {0}")]
54    Parse(String),
55    #[error("unsupported algorithm: {0}")]
56    Unsupported(String),
57    #[error("CBC decryption failed")]
58    Decrypt,
59    #[error("masterkey HMAC verification failed (wrong password/SID?)")]
60    HmacMismatch,
61}
62
63/// Convenience: decrypt a masterkey file's masterkey from a password + SID. Tries all three
64/// pre-key derivations in this order — standalone SHA1, domain MD4, Protected-Users PBKDF2-
65/// SHA256 — and returns the first that HMAC-verifies. On a Server 2019+ domain admin the
66/// Protected-Users variant is what wins; on an old Server 2012 standalone box it's the SHA1
67/// variant. Caller doesn't have to know which category the account is in.
68pub fn unlock_masterkey(
69    masterkey_file: &[u8],
70    password: &str,
71    sid: &str,
72) -> Result<[u8; 64], DpapiError> {
73    let mkf = MasterKeyFile::parse(masterkey_file)?;
74    let mk = mkf
75        .master_key
76        .ok_or_else(|| DpapiError::Parse("file has no masterkey subfield".into()))?;
77    let candidates: [&[u8]; 3] = [
78        &masterkey::derive_local_prekey(password, sid),
79        &masterkey::derive_domain_prekey_md4(password, sid),
80        &masterkey::derive_domain_prekey_protected(password, sid),
81    ];
82    let mut last_err = DpapiError::HmacMismatch;
83    for pwdkey in candidates {
84        match mk.decrypt_with_key(pwdkey) {
85            Ok(k) => return Ok(k),
86            Err(e) => last_err = e,
87        }
88    }
89    Err(last_err)
90}
91
92#[cfg(test)]
93mod integration {
94    use super::*;
95
96    /// The one test that actually proves the crypto chain. It stays `#[ignore]` until you point it
97    /// at a REAL masterkey file (copied from `%APPDATA%\Microsoft\Protect\<SID>\<guid>`) whose
98    /// password/SID you know. Run it, then cross-check with impacket on Kali:
99    ///   `dpapi.py masterkey -file <guid> -sid <SID> -password <pw>`
100    /// and confirm the 64-byte key matches.
101    ///
102    /// Env: DPAPI_MK_FILE (path), DPAPI_MK_PASSWORD, DPAPI_MK_SID, optional DPAPI_MK_EXPECTED (hex).
103    #[test]
104    #[ignore = "needs a real masterkey file (see VALIDATION STATUS)"]
105    fn test_real_masterkey() {
106        let Ok(path) = std::env::var("DPAPI_MK_FILE") else {
107            return;
108        };
109        let pw = std::env::var("DPAPI_MK_PASSWORD").expect("DPAPI_MK_PASSWORD");
110        let sid = std::env::var("DPAPI_MK_SID").expect("DPAPI_MK_SID");
111        let bytes = std::fs::read(&path).expect("read masterkey file");
112        let key = unlock_masterkey(&bytes, &pw, &sid).expect("decrypt masterkey");
113        let hexkey: String = key.iter().map(|b| format!("{b:02x}")).collect();
114        eprintln!("[dpapi] recovered masterkey: {hexkey}");
115        if let Ok(expected) = std::env::var("DPAPI_MK_EXPECTED") {
116            assert_eq!(
117                hexkey,
118                expected.to_lowercase(),
119                "masterkey mismatch vs oracle"
120            );
121        }
122    }
123
124    /// Byte-oracle variant: pwdkey pre-derived externally, so this exercises
125    /// only the parser + `ms_derive_key` + CBC + HMAC-verify without any
126    /// pre-key-derivation ambiguity. Useful when validating a masterkey file
127    /// whose account type (standalone / domain / Protected-Users) isn't
128    /// known — grep the winning pwdkey out of `dpapi.py` on Kali, feed it
129    /// straight in, and confirm this crate returns the same 64 bytes.
130    ///
131    /// Env: DPAPI_MK_FILE, DPAPI_MK_PWDKEY (40-char hex = 20 bytes), optional
132    /// DPAPI_MK_EXPECTED (hex).
133    #[test]
134    #[ignore = "needs a real masterkey file + externally derived pwdkey"]
135    fn test_real_masterkey_with_pwdkey() {
136        let Ok(path) = std::env::var("DPAPI_MK_FILE") else {
137            return;
138        };
139        let key_hex = std::env::var("DPAPI_MK_PWDKEY").expect("DPAPI_MK_PWDKEY");
140        let pwdkey: Vec<u8> = (0..key_hex.len())
141            .step_by(2)
142            .map(|i| u8::from_str_radix(&key_hex[i..i + 2], 16).unwrap())
143            .collect();
144        let bytes = std::fs::read(&path).expect("read masterkey file");
145        let mkf = MasterKeyFile::parse(&bytes).expect("parse mk file");
146        let mk = mkf.master_key.expect("mk file has no MasterKey subfield");
147        let key = mk.decrypt_with_key(&pwdkey).expect("decrypt with key");
148        let hexkey: String = key.iter().map(|b| format!("{b:02x}")).collect();
149        eprintln!("[dpapi] guid = {}", mkf.guid);
150        eprintln!("[dpapi] recovered masterkey: {hexkey}");
151        if let Ok(expected) = std::env::var("DPAPI_MK_EXPECTED") {
152            assert_eq!(
153                hexkey,
154                expected.trim_start_matches("0x").to_lowercase(),
155                "masterkey mismatch vs oracle"
156            );
157        }
158    }
159}