dpapi-offline 0.1.0

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
//! DPAPI user **masterkey file** parsing and decryption.
//!
//! On disk at `%APPDATA%\Microsoft\Protect\<SID>\<GUID>`. The file wraps an encrypted 64-byte
//! masterkey; recovering it from the user's password + SID follows MS-DPAPI (structures and the
//! derivation match impacket's `dpapi.py`, the intended byte-oracle for validation):
//!
//! 1. `pwdhash  = SHA1(UTF16LE(password))`                    (local/standalone user)
//! 2. `pwdkey   = HMAC-SHA1(pwdhash, UTF16LE(SID + "\0"))`
//! 3. `derived  = PBKDF2(HMAC-<hash>, pwdkey, salt, rounds, keyLen+ivLen)`
//! 4. `cleartext = CBC-decrypt(derived[..keyLen], derived[keyLen..], encryptedKey)`  (no padding)
//! 5. verify: `HMAC(HMAC(pwdkey, hmacSalt), masterkey) == storedHmac`; masterkey = last 64 bytes.

use crate::crypto::{CipherAlgo, HashAlgo};
use crate::DpapiError;

fn u32le(b: &[u8], o: usize) -> Option<u32> {
    Some(u32::from_le_bytes(b.get(o..o + 4)?.try_into().ok()?))
}
fn u64le(b: &[u8], o: usize) -> Option<u64> {
    Some(u64::from_le_bytes(b.get(o..o + 8)?.try_into().ok()?))
}

/// The parsed masterkey-file header plus the embedded encrypted masterkey.
#[derive(Debug, Clone)]
pub struct MasterKeyFile {
    /// The `{guid}` this file is named after (identifies which key a blob needs).
    pub guid: String,
    /// The encrypted masterkey subfield, if present (MasterKeyLen > 0).
    pub master_key: Option<MasterKey>,
}

impl MasterKeyFile {
    /// Parse the 128-byte header + subfields. Only the MasterKey subfield is decoded;
    /// BackupKey/CredHist/DomainKey are skipped.
    ///
    /// Header layout (verified byte-for-byte against real Windows Server 2025 masterkey
    /// files at `C:\Users\<u>\AppData\Roaming\Microsoft\Protect\<SID>\<GUID>`):
    /// ```text
    ///   0..4    Version   (u32 = 2 on modern Windows)
    ///   4..8    Unk1
    ///   8..12   Unk2
    ///  12..84   Guid      (72 bytes UTF-16LE, the file's own {guid} name)
    ///  84..88   Unk3
    ///  88..92   Policy
    ///  92..96   Flags     (u32 — impacket had this as u64 in older versions; MODERN is u32)
    ///  96..104  MasterKeyLen  (u64)
    /// 104..112  BackupKeyLen  (u64)
    /// 112..120  CredHistLen   (u64)
    /// 120..128  DomainKeyLen  (u64)
    /// 128..     [ MasterKey ][ BackupKey ][ CredHist ][ DomainKey ]  concatenated
    /// ```
    pub fn parse(data: &[u8]) -> Result<Self, DpapiError> {
        if data.len() < 128 {
            return Err(DpapiError::Parse("masterkey file too short".into()));
        }
        // Guid: 72 bytes UTF-16LE at offset 12.
        let guid_units: Vec<u16> = data[12..12 + 72]
            .chunks_exact(2)
            .map(|c| u16::from_le_bytes([c[0], c[1]]))
            .collect();
        let guid = String::from_utf16_lossy(&guid_units)
            .trim_end_matches('\0')
            .to_string();
        let mk_len = u64le(data, 96).ok_or_else(|| DpapiError::Parse("mk len".into()))? as usize;
        let master_key = if mk_len > 0 {
            let start = 128usize;
            let end = start
                .checked_add(mk_len)
                .filter(|&e| e <= data.len())
                .ok_or_else(|| DpapiError::Parse("mk subfield out of bounds".into()))?;
            Some(MasterKey::parse(&data[start..end])?)
        } else {
            None
        };
        Ok(MasterKeyFile { guid, master_key })
    }
}

/// The encrypted masterkey subfield: Version(4) Salt(16) Rounds(4) HashAlgo(4) CryptAlgo(4) data.
#[derive(Debug, Clone)]
pub struct MasterKey {
    pub salt: [u8; 16],
    pub rounds: u32,
    pub hash_algo: HashAlgo,
    pub cipher_algo: CipherAlgo,
    pub ciphertext: Vec<u8>,
}

impl MasterKey {
    pub fn parse(data: &[u8]) -> Result<Self, DpapiError> {
        if data.len() < 32 {
            return Err(DpapiError::Parse("masterkey subfield too short".into()));
        }
        let salt: [u8; 16] = data[4..20].try_into().unwrap();
        let rounds = u32le(data, 20).unwrap();
        let hash_id = u32le(data, 24).unwrap();
        let crypt_id = u32le(data, 28).unwrap();
        let hash_algo = HashAlgo::from_alg_id(hash_id)
            .ok_or_else(|| DpapiError::Unsupported(format!("hash alg 0x{hash_id:04x}")))?;
        let cipher_algo = CipherAlgo::from_alg_id(crypt_id)
            .ok_or_else(|| DpapiError::Unsupported(format!("cipher alg 0x{crypt_id:04x}")))?;
        Ok(MasterKey {
            salt,
            rounds,
            hash_algo,
            cipher_algo,
            ciphertext: data[32..].to_vec(),
        })
    }

    /// Decrypt with an already-derived key (`HMAC-SHA1(SHA1(pw), SID)` or an NT-hash-derived
    /// equivalent). Returns the 64-byte masterkey on success; verifies the trailing HMAC.
    pub fn decrypt_with_key(&self, pwdkey: &[u8]) -> Result<[u8; 64], DpapiError> {
        let key_len = self.cipher_algo.key_len();
        let iv_len = self.cipher_algo.iv_len();
        let derived = self
            .hash_algo
            .pbkdf2(pwdkey, &self.salt, self.rounds, key_len + iv_len);
        let clear = self
            .cipher_algo
            .cbc_decrypt_nopad(&derived[..key_len], &derived[key_len..], &self.ciphertext)
            .ok_or(DpapiError::Decrypt)?;

        // cleartext = hmacSalt(16) || storedHmac(digestLen) || ... || masterkey(64)
        let dlen = self.hash_algo.digest_len();
        if clear.len() < 16 + dlen + 64 {
            return Err(DpapiError::Decrypt);
        }
        let hmac_salt = &clear[..16];
        let stored = &clear[16..16 + dlen];
        let masterkey: [u8; 64] = clear[clear.len() - 64..].try_into().unwrap();

        let hmac1 = self.hash_algo.hmac(pwdkey, hmac_salt);
        let computed = self.hash_algo.hmac(&hmac1, &masterkey);
        if computed == stored {
            Ok(masterkey)
        } else {
            Err(DpapiError::HmacMismatch)
        }
    }

    /// Decrypt a local/standalone user's masterkey from their cleartext password + SID string
    /// (e.g. `S-1-5-21-…-1001`).
    pub fn decrypt_with_password(&self, password: &str, sid: &str) -> Result<[u8; 64], DpapiError> {
        let pwdkey = derive_local_prekey(password, sid);
        self.decrypt_with_key(&pwdkey)
    }
}

/// `HMAC-SHA1(SHA1(UTF16LE(password)), UTF16LE(SID + "\0"))` — the local-user pre-key.
pub fn derive_local_prekey(password: &str, sid: &str) -> [u8; 20] {
    use sha1::{Digest, Sha1};
    let pw16: Vec<u8> = password.encode_utf16().flat_map(u16::to_le_bytes).collect();
    let pwdhash = Sha1::digest(&pw16);
    let mut sid16: Vec<u8> = sid.encode_utf16().flat_map(u16::to_le_bytes).collect();
    sid16.extend_from_slice(&[0, 0]); // trailing NUL, UTF-16LE
    crate::crypto::hmac_sha1(&pwdhash, &sid16)
}

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

    // Structure/parse tests (deterministic). NOTE: these do NOT validate the crypto chain — see
    // the crate-level VALIDATION STATUS. A real masterkey + impacket oracle is required for that.
    #[test]
    fn parses_header_guid_and_subfield_lengths() {
        let mut f = vec![0u8; 128];
        f[0] = 2; // Version
        let guid = "{DEADBEEF-0000-0000-0000-000000000000}";
        let g16: Vec<u8> = guid.encode_utf16().flat_map(u16::to_le_bytes).collect();
        f[12..12 + g16.len()].copy_from_slice(&g16);
        // MasterKeyLen (offset 96) = 32-byte header + 16-byte ciphertext.
        f[96..104].copy_from_slice(&48u64.to_le_bytes());
        // Append a MasterKey subfield: Version, Salt, Rounds, HashAlgo=SHA512, CryptAlgo=AES256, 16 ct.
        let mut mk = vec![0u8; 32];
        mk[0] = 2;
        mk[20..24].copy_from_slice(&8000u32.to_le_bytes());
        mk[24..28].copy_from_slice(&0x800eu32.to_le_bytes()); // SHA512
        mk[28..32].copy_from_slice(&0x6610u32.to_le_bytes()); // AES256
        mk.extend_from_slice(&[0xAB; 16]);
        f.extend_from_slice(&mk);

        let parsed = MasterKeyFile::parse(&f).unwrap();
        assert!(parsed.guid.starts_with("{DEADBEEF"));
        let k = parsed.master_key.unwrap();
        assert_eq!(k.rounds, 8000);
        assert_eq!(k.hash_algo, HashAlgo::Sha512);
        assert_eq!(k.cipher_algo, CipherAlgo::Aes256);
        assert_eq!(k.ciphertext, vec![0xAB; 16]);
    }

    #[test]
    fn prekey_is_deterministic_and_20_bytes() {
        let a = derive_local_prekey("Passw0rd!", "S-1-5-21-1-2-3-1001");
        let b = derive_local_prekey("Passw0rd!", "S-1-5-21-1-2-3-1001");
        assert_eq!(a, b);
        assert_ne!(a, derive_local_prekey("Passw0rd!", "S-1-5-21-1-2-3-1002"));
    }

    #[test]
    fn rejects_short_and_bad_alg() {
        assert!(MasterKeyFile::parse(&[0u8; 10]).is_err());
        let mut mk = vec![0u8; 32];
        mk[24..28].copy_from_slice(&0xDEADu32.to_le_bytes()); // bogus hash alg
        assert!(matches!(
            MasterKey::parse(&mk),
            Err(DpapiError::Unsupported(_))
        ));
    }
}