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
//! DPAPI crypto primitives. These are the parts validated against **published RFC
//! known-answer vectors** (see the tests) — PBKDF2-HMAC-SHA1 (RFC 6070) and HMAC (RFC 2202 /
//! 4231). The DPAPI-specific derivation that *uses* them lives in `masterkey`/`blob`.

use aes::Aes256;
use cbc::cipher::{block_padding::NoPadding, BlockDecryptMut, KeyIvInit};
use des::TdesEde3;
use hmac::{Hmac, Mac};
use md4::{Digest as Md4Digest, Md4};
use sha1::Sha1;
use sha2::{Sha256, Sha512};

pub type HmacSha1 = Hmac<Sha1>;
pub type HmacSha512 = Hmac<Sha512>;

pub fn hmac_sha1(key: &[u8], msg: &[u8]) -> [u8; 20] {
    let mut m = <HmacSha1 as Mac>::new_from_slice(key).expect("hmac key");
    m.update(msg);
    m.finalize().into_bytes().into()
}

pub fn hmac_sha512(key: &[u8], msg: &[u8]) -> [u8; 64] {
    let mut m = <HmacSha512 as Mac>::new_from_slice(key).expect("hmac key");
    m.update(msg);
    m.finalize().into_bytes().into()
}

/// MD4 — the NT-hash primitive (`nt_hash = MD4(UTF16LE(password))`). Cryptographically broken,
/// kept because Windows domain-user DPAPI prekey derivation is defined on it (MS-DPAPI has no
/// migration path off MD4 for the NT-hash input).
pub fn md4(data: &[u8]) -> [u8; 16] {
    let mut h = Md4::new();
    h.update(data);
    h.finalize().into()
}

/// Standard RFC 8018 PBKDF2 with HMAC-SHA256 as the PRF. Used by DPAPI's
/// Protected-Users derivation stage.
pub fn pbkdf2_sha256(password: &[u8], salt: &[u8], rounds: u32, dklen: usize) -> Vec<u8> {
    let mut out = vec![0u8; dklen];
    let rounds = rounds.max(1);
    pbkdf2::pbkdf2_hmac::<Sha256>(password, salt, rounds, &mut out);
    out
}

/// **Microsoft's non-standard DPAPI key-derivation loop** — the one Windows actually uses
/// inside `CryptDeriveKey` for the masterkey subfield. Structurally similar to RFC 8018
/// PBKDF2 but differs in one load-bearing way: instead of accumulating
/// `T = U1 ⊕ U2 ⊕ … ⊕ Uc` and always feeding `U_{i-1}` into the PRF, MS feeds the running-XOR
/// value itself back into the PRF at each round. Concretely:
///
/// ```text
///   derived = PRF(P, salt || counter_be32)      // U1
///   repeat count-1 times:
///       actual  = PRF(P, derived)               // NOT U_{i-1} — the running XOR
///       derived = derived ⊕ actual
///   emit derived                                 // one output block
/// ```
///
/// So `derived` after round 1 equals `U1 ⊕ U2`, after round 2 equals `(U1⊕U2) ⊕ PRF(P, U1⊕U2)`,
/// and so on — a strictly different sequence from standard PBKDF2 despite the same inputs.
///
/// Byte-oracle: impacket 0.14 `dpapi.py MasterKey.deriveKey`. Every masterkey `decrypt_with_key`
/// path in this crate routes through here — using `pbkdf2::pbkdf2_hmac` fails HMAC verification
/// on every real Windows masterkey.
pub fn ms_derive_key(hash: HashAlgo, passphrase: &[u8], salt: &[u8], count: u32, dklen: usize) -> Vec<u8> {
    let count = count.max(1);
    let mut out = Vec::with_capacity(dklen);
    let mut counter: u32 = 1;
    while out.len() < dklen {
        let mut buf = Vec::with_capacity(salt.len() + 4);
        buf.extend_from_slice(salt);
        buf.extend_from_slice(&counter.to_be_bytes());
        counter += 1;
        let mut derived = hash.hmac(passphrase, &buf);
        for _ in 0..(count - 1) {
            let actual = hash.hmac(passphrase, &derived);
            for (d, a) in derived.iter_mut().zip(actual.iter()) {
                *d ^= *a;
            }
        }
        out.extend_from_slice(&derived);
    }
    out.truncate(dklen);
    out
}

/// Which hash a DPAPI structure selected (from its ALG_ID). Carries the digest and HMAC
/// block sizes the key-derivation needs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum HashAlgo {
    Sha1,
    Sha512,
}

impl HashAlgo {
    /// CALG_SHA1 = 0x8004, CALG_SHA_512 = 0x800e.
    pub fn from_alg_id(id: u32) -> Option<Self> {
        match id {
            0x8004 => Some(HashAlgo::Sha1),
            0x800e => Some(HashAlgo::Sha512),
            _ => None,
        }
    }
    pub fn digest_len(self) -> usize {
        match self {
            HashAlgo::Sha1 => 20,
            HashAlgo::Sha512 => 64,
        }
    }
    pub fn block_size(self) -> usize {
        match self {
            HashAlgo::Sha1 => 64,
            HashAlgo::Sha512 => 128,
        }
    }
    pub fn hmac(self, key: &[u8], msg: &[u8]) -> Vec<u8> {
        match self {
            HashAlgo::Sha1 => hmac_sha1(key, msg).to_vec(),
            HashAlgo::Sha512 => hmac_sha512(key, msg).to_vec(),
        }
    }
    /// PBKDF2 with this hash as the PRF.
    pub fn pbkdf2(self, password: &[u8], salt: &[u8], rounds: u32, dklen: usize) -> Vec<u8> {
        let mut out = vec![0u8; dklen];
        let rounds = rounds.max(1);
        match self {
            HashAlgo::Sha1 => pbkdf2::pbkdf2_hmac::<Sha1>(password, salt, rounds, &mut out),
            HashAlgo::Sha512 => pbkdf2::pbkdf2_hmac::<Sha512>(password, salt, rounds, &mut out),
        }
        out
    }
}

/// Which block cipher a DPAPI structure selected (from its ALG_ID).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CipherAlgo {
    Aes256,
    TripleDes,
}

impl CipherAlgo {
    /// CALG_AES_256 = 0x6610, CALG_3DES = 0x6603.
    pub fn from_alg_id(id: u32) -> Option<Self> {
        match id {
            0x6610 => Some(CipherAlgo::Aes256),
            0x6603 => Some(CipherAlgo::TripleDes),
            _ => None,
        }
    }
    pub fn key_len(self) -> usize {
        match self {
            CipherAlgo::Aes256 => 32,
            CipherAlgo::TripleDes => 24,
        }
    }
    pub fn iv_len(self) -> usize {
        match self {
            CipherAlgo::Aes256 => 16,
            CipherAlgo::TripleDes => 8,
        }
    }
    /// CBC decrypt with no padding removal (masterkey path — length is a block multiple).
    pub fn cbc_decrypt_nopad(self, key: &[u8], iv: &[u8], ct: &[u8]) -> Option<Vec<u8>> {
        if ct.is_empty() || ct.len() % 8 != 0 {
            return None;
        }
        let mut buf = ct.to_vec();
        match self {
            CipherAlgo::Aes256 => {
                let d = cbc::Decryptor::<Aes256>::new_from_slices(key, iv).ok()?;
                d.decrypt_padded_mut::<NoPadding>(&mut buf).ok()?;
            }
            CipherAlgo::TripleDes => {
                let d = cbc::Decryptor::<TdesEde3>::new_from_slices(key, iv).ok()?;
                d.decrypt_padded_mut::<NoPadding>(&mut buf).ok()?;
            }
        }
        Some(buf)
    }
}

/// Strip PKCS#7 padding (data-blob path). Returns None on an invalid pad.
pub fn unpad_pkcs7(data: &[u8]) -> Option<Vec<u8>> {
    let &pad = data.last()?;
    let pad = pad as usize;
    if pad == 0 || pad > data.len() || pad > 16 {
        return None;
    }
    if data[data.len() - pad..].iter().all(|&b| b as usize == pad) {
        Some(data[..data.len() - pad].to_vec())
    } else {
        None
    }
}

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

    // RFC 6070 — PBKDF2-HMAC-SHA1 known-answer vectors. A genuine external oracle for the PBKDF2
    // wiring (not a self-round-trip).
    #[test]
    fn pbkdf2_hmac_sha1_rfc6070() {
        let dk = HashAlgo::Sha1.pbkdf2(b"password", b"salt", 1, 20);
        assert_eq!(hex(&dk), "0c60c80f961f0e71f3a9b524af6012062fe037a6");
        let dk = HashAlgo::Sha1.pbkdf2(b"password", b"salt", 2, 20);
        assert_eq!(hex(&dk), "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957");
        let dk = HashAlgo::Sha1.pbkdf2(b"password", b"salt", 4096, 20);
        assert_eq!(hex(&dk), "4b007901b765489abead49d926f721d065a429c1");
    }

    // RFC 2202 — HMAC-SHA1 test case 2 (key="Jefe", data="what do ya want for nothing?").
    #[test]
    fn hmac_sha1_rfc2202() {
        let mac = hmac_sha1(b"Jefe", b"what do ya want for nothing?");
        assert_eq!(hex(&mac), "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79");
    }

    // RFC 4231 — HMAC-SHA512 test case 2.
    #[test]
    fn hmac_sha512_rfc4231() {
        let mac = hmac_sha512(b"Jefe", b"what do ya want for nothing?");
        assert_eq!(
            hex(&mac),
            "164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea250554\
9758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737"
        );
    }

    #[test]
    fn pkcs7_unpad_roundtrip() {
        assert_eq!(unpad_pkcs7(&[b'a', b'b', 2, 2]).unwrap(), b"ab");
        assert_eq!(unpad_pkcs7(&[1]).unwrap(), b"");
        assert!(unpad_pkcs7(&[b'a', 2, 3]).is_none()); // inconsistent pad
        assert!(unpad_pkcs7(&[]).is_none());
    }

    fn hex(b: &[u8]) -> String {
        b.iter().map(|x| format!("{x:02x}")).collect()
    }
}