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//! * **The DPAPI chain — NOT YET VALIDATED end-to-end.** The masterkey/blob *derivation* follows
19//!   MS-DPAPI and impacket's `dpapi.py`, but has **not** been run against a real masterkey. Do
20//!   **not** treat masterkey/blob decryption as proven until [`test_real_masterkey`] passes.
21//!   Validate the same way ADhammer validated WMI/DCSync: on Kali, run impacket
22//!   `dpapi.py masterkey`/`credential` against the *same* files as the byte-oracle.
23
24pub mod blob;
25pub mod crypto;
26pub mod masterkey;
27
28pub use blob::DpapiBlob;
29pub use masterkey::{MasterKey, MasterKeyFile};
30
31/// Errors from parsing or decrypting DPAPI structures.
32#[derive(Debug, thiserror::Error)]
33pub enum DpapiError {
34    #[error("parse: {0}")]
35    Parse(String),
36    #[error("unsupported algorithm: {0}")]
37    Unsupported(String),
38    #[error("CBC decryption failed")]
39    Decrypt,
40    #[error("masterkey HMAC verification failed (wrong password/SID?)")]
41    HmacMismatch,
42}
43
44/// Convenience: decrypt a masterkey file's masterkey from a password + SID.
45pub fn unlock_masterkey(
46    masterkey_file: &[u8],
47    password: &str,
48    sid: &str,
49) -> Result<[u8; 64], DpapiError> {
50    let mkf = MasterKeyFile::parse(masterkey_file)?;
51    let mk = mkf
52        .master_key
53        .ok_or_else(|| DpapiError::Parse("file has no masterkey subfield".into()))?;
54    mk.decrypt_with_password(password, sid)
55}
56
57#[cfg(test)]
58mod integration {
59    use super::*;
60
61    /// The one test that actually proves the crypto chain. It stays `#[ignore]` until you point it
62    /// at a REAL masterkey file (copied from `%APPDATA%\Microsoft\Protect\<SID>\<guid>`) whose
63    /// password/SID you know. Run it, then cross-check with impacket on Kali:
64    ///   `dpapi.py masterkey -file <guid> -sid <SID> -password <pw>`
65    /// and confirm the 64-byte key matches.
66    ///
67    /// Env: DPAPI_MK_FILE (path), DPAPI_MK_PASSWORD, DPAPI_MK_SID, optional DPAPI_MK_EXPECTED (hex).
68    #[test]
69    #[ignore = "needs a real masterkey file (see VALIDATION STATUS)"]
70    fn test_real_masterkey() {
71        let Ok(path) = std::env::var("DPAPI_MK_FILE") else {
72            return;
73        };
74        let pw = std::env::var("DPAPI_MK_PASSWORD").expect("DPAPI_MK_PASSWORD");
75        let sid = std::env::var("DPAPI_MK_SID").expect("DPAPI_MK_SID");
76        let bytes = std::fs::read(&path).expect("read masterkey file");
77        let key = unlock_masterkey(&bytes, &pw, &sid).expect("decrypt masterkey");
78        let hexkey: String = key.iter().map(|b| format!("{b:02x}")).collect();
79        eprintln!("[dpapi] recovered masterkey: {hexkey}");
80        if let Ok(expected) = std::env::var("DPAPI_MK_EXPECTED") {
81            assert_eq!(
82                hexkey,
83                expected.to_lowercase(),
84                "masterkey mismatch vs oracle"
85            );
86        }
87    }
88}