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 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 sha1::Sha1;
use sha2::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()
}

/// 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()
    }
}