dpapi-offline 0.1.2

Pure-Rust offline Windows DPAPI decryption (DonPAPI/dploot-class): parse and decrypt user masterkey files (password/SID-derived) and DPAPI data blobs. No FFI, no live host.
Documentation
//! Offline Windows **DPAPI** decryption — a DonPAPI/dploot-class core in pure Rust. No FFI, no
//! live host: point it at files copied off disk.
//!
//! - [`masterkey`] — parse a user masterkey file and decrypt it from the user's password + SID.
//! - [`blob`] — parse a `DPAPI_BLOB` (`CryptProtectData` output) and decrypt it with a masterkey.
//! - [`crypto`] — the underlying primitives.
//!
//! # VALIDATION STATUS (read this)
//!
//! This is the one crate in the ADhammer set that is a **from-scratch crypto build**, not an
//! extraction of already-live code. Its honesty bar is therefore explicit:
//!
//! * **Primitives — VALIDATED.** PBKDF2-HMAC-SHA1 (RFC 6070), HMAC-SHA1 (RFC 2202) and
//!   HMAC-SHA512 (RFC 4231) are checked against published known-answer vectors in
//!   `crypto`'s tests — a genuine external oracle, not a self-round-trip.
//! * **Parsers — VALIDATED (structure).** Deterministic layout tests for the masterkey file,
//!   masterkey subfield, and `DPAPI_BLOB`, plus truncation-safety.
//! * **Masterkey decrypt chain — VALIDATED (0.1.2, 2026-08-31).** The full parser +
//!   `ms_derive_key` + AES256-CBC + HMAC-verify chain is exercised on every test run
//!   against a deterministic KAT (`KAT_MK_SUBFIELD` in `masterkey::tests`). 0.1.2 rebuilt
//!   the KAT from **synthetic** throwaway credentials via `docs/synthetic_kat.py` — earlier
//!   0.1.1 embedded values derived from a real lab masterkey (Administrator on the icedracon
//!   testlab) and was yanked to stop the credential-material distribution; the synthetic
//!   KAT still exercises byte-oracle equivalence with impacket 0.14 `dpapi.py` because it
//!   uses the same algorithm that impacket implements — but nothing in the fixture maps
//!   back to a real account.
//!
//!   The masterkey chain itself was proved correct against a real Windows Server 2025 domain
//!   Administrator masterkey during the 0.1.1 development cycle; that experiment is what
//!   discovered 0.1.0's PBKDF2 used the RFC 8018 formulation, while Windows DPAPI uses a
//!   non-standard variant that feeds the running XOR back into the PRF at every round
//!   (`ms_derive_key`). 0.1.1+ routes every masterkey decrypt through that variant, adds MD4
//!   + Protected-Users pre-key derivations, and `unlock_masterkey` handles standalone,
//!   pre-2019 domain-joined, and 2019+ domain-joined / Protected-Users accounts
//!   transparently. Operators can re-run the live byte-oracle themselves via the ignored
//!   `test_real_masterkey` / `test_real_masterkey_with_pwdkey` tests + `DPAPI_MK_FILE=…`
//!   / `DPAPI_MK_PWDKEY=…` env vars.
//! * **Blob decrypt chain — NOT YET VALIDATED end-to-end.** The `blob` derivation follows
//!   MS-DPAPI and impacket, but has **not** been run against a real Windows-generated blob
//!   yet — validate the same way: run impacket `dpapi.py credential`/`vault` against the
//!   same bytes as the byte-oracle.

pub mod blob;
pub mod crypto;
pub mod masterkey;

pub use blob::DpapiBlob;
pub use masterkey::{MasterKey, MasterKeyFile};

/// Errors from parsing or decrypting DPAPI structures.
#[derive(Debug, thiserror::Error)]
pub enum DpapiError {
    #[error("parse: {0}")]
    Parse(String),
    #[error("unsupported algorithm: {0}")]
    Unsupported(String),
    #[error("CBC decryption failed")]
    Decrypt,
    #[error("masterkey HMAC verification failed (wrong password/SID?)")]
    HmacMismatch,
}

/// Convenience: decrypt a masterkey file's masterkey from a password + SID. Tries all three
/// pre-key derivations in this order — standalone SHA1, domain MD4, Protected-Users PBKDF2-
/// SHA256 — and returns the first that HMAC-verifies. On a Server 2019+ domain admin the
/// Protected-Users variant is what wins; on an old Server 2012 standalone box it's the SHA1
/// variant. Caller doesn't have to know which category the account is in.
pub fn unlock_masterkey(
    masterkey_file: &[u8],
    password: &str,
    sid: &str,
) -> Result<[u8; 64], DpapiError> {
    let mkf = MasterKeyFile::parse(masterkey_file)?;
    let mk = mkf
        .master_key
        .ok_or_else(|| DpapiError::Parse("file has no masterkey subfield".into()))?;
    let candidates: [&[u8]; 3] = [
        &masterkey::derive_local_prekey(password, sid),
        &masterkey::derive_domain_prekey_md4(password, sid),
        &masterkey::derive_domain_prekey_protected(password, sid),
    ];
    let mut last_err = DpapiError::HmacMismatch;
    for pwdkey in candidates {
        match mk.decrypt_with_key(pwdkey) {
            Ok(k) => return Ok(k),
            Err(e) => last_err = e,
        }
    }
    Err(last_err)
}

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

    /// The one test that actually proves the crypto chain. It stays `#[ignore]` until you point it
    /// at a REAL masterkey file (copied from `%APPDATA%\Microsoft\Protect\<SID>\<guid>`) whose
    /// password/SID you know. Run it, then cross-check with impacket on Kali:
    ///   `dpapi.py masterkey -file <guid> -sid <SID> -password <pw>`
    /// and confirm the 64-byte key matches.
    ///
    /// Env: DPAPI_MK_FILE (path), DPAPI_MK_PASSWORD, DPAPI_MK_SID, optional DPAPI_MK_EXPECTED (hex).
    #[test]
    #[ignore = "needs a real masterkey file (see VALIDATION STATUS)"]
    fn test_real_masterkey() {
        let Ok(path) = std::env::var("DPAPI_MK_FILE") else {
            return;
        };
        let pw = std::env::var("DPAPI_MK_PASSWORD").expect("DPAPI_MK_PASSWORD");
        let sid = std::env::var("DPAPI_MK_SID").expect("DPAPI_MK_SID");
        let bytes = std::fs::read(&path).expect("read masterkey file");
        let key = unlock_masterkey(&bytes, &pw, &sid).expect("decrypt masterkey");
        let hexkey: String = key.iter().map(|b| format!("{b:02x}")).collect();
        eprintln!("[dpapi] recovered masterkey: {hexkey}");
        if let Ok(expected) = std::env::var("DPAPI_MK_EXPECTED") {
            assert_eq!(
                hexkey,
                expected.to_lowercase(),
                "masterkey mismatch vs oracle"
            );
        }
    }

    /// Byte-oracle variant: pwdkey pre-derived externally, so this exercises
    /// only the parser + `ms_derive_key` + CBC + HMAC-verify without any
    /// pre-key-derivation ambiguity. Useful when validating a masterkey file
    /// whose account type (standalone / domain / Protected-Users) isn't
    /// known — grep the winning pwdkey out of `dpapi.py` on Kali, feed it
    /// straight in, and confirm this crate returns the same 64 bytes.
    ///
    /// Env: DPAPI_MK_FILE, DPAPI_MK_PWDKEY (40-char hex = 20 bytes), optional
    /// DPAPI_MK_EXPECTED (hex).
    #[test]
    #[ignore = "needs a real masterkey file + externally derived pwdkey"]
    fn test_real_masterkey_with_pwdkey() {
        let Ok(path) = std::env::var("DPAPI_MK_FILE") else {
            return;
        };
        let key_hex = std::env::var("DPAPI_MK_PWDKEY").expect("DPAPI_MK_PWDKEY");
        let pwdkey: Vec<u8> = (0..key_hex.len())
            .step_by(2)
            .map(|i| u8::from_str_radix(&key_hex[i..i + 2], 16).unwrap())
            .collect();
        let bytes = std::fs::read(&path).expect("read masterkey file");
        let mkf = MasterKeyFile::parse(&bytes).expect("parse mk file");
        let mk = mkf.master_key.expect("mk file has no MasterKey subfield");
        let key = mk.decrypt_with_key(&pwdkey).expect("decrypt with key");
        let hexkey: String = key.iter().map(|b| format!("{b:02x}")).collect();
        eprintln!("[dpapi] guid = {}", mkf.guid);
        eprintln!("[dpapi] recovered masterkey: {hexkey}");
        if let Ok(expected) = std::env::var("DPAPI_MK_EXPECTED") {
            assert_eq!(
                hexkey,
                expected.trim_start_matches("0x").to_lowercase(),
                "masterkey mismatch vs oracle"
            );
        }
    }
}