Skip to main content

dpapi_offline/
crypto.rs

1//! DPAPI crypto primitives. These are the parts validated against **published RFC
2//! known-answer vectors** (see the tests) — PBKDF2-HMAC-SHA1 (RFC 6070) and HMAC (RFC 2202 /
3//! 4231). The DPAPI-specific derivation that *uses* them lives in `masterkey`/`blob`.
4
5use aes::Aes256;
6use cbc::cipher::{block_padding::NoPadding, BlockDecryptMut, KeyIvInit};
7use des::TdesEde3;
8use hmac::{Hmac, Mac};
9use md4::{Digest as Md4Digest, Md4};
10use sha1::Sha1;
11use sha2::{Sha256, Sha512};
12
13pub type HmacSha1 = Hmac<Sha1>;
14pub type HmacSha512 = Hmac<Sha512>;
15
16pub fn hmac_sha1(key: &[u8], msg: &[u8]) -> [u8; 20] {
17    let mut m = <HmacSha1 as Mac>::new_from_slice(key).expect("hmac key");
18    m.update(msg);
19    m.finalize().into_bytes().into()
20}
21
22pub fn hmac_sha512(key: &[u8], msg: &[u8]) -> [u8; 64] {
23    let mut m = <HmacSha512 as Mac>::new_from_slice(key).expect("hmac key");
24    m.update(msg);
25    m.finalize().into_bytes().into()
26}
27
28/// MD4 — the NT-hash primitive (`nt_hash = MD4(UTF16LE(password))`). Cryptographically broken,
29/// kept because Windows domain-user DPAPI prekey derivation is defined on it (MS-DPAPI has no
30/// migration path off MD4 for the NT-hash input).
31pub fn md4(data: &[u8]) -> [u8; 16] {
32    let mut h = Md4::new();
33    h.update(data);
34    h.finalize().into()
35}
36
37/// Standard RFC 8018 PBKDF2 with HMAC-SHA256 as the PRF. Used by DPAPI's
38/// Protected-Users derivation stage.
39pub fn pbkdf2_sha256(password: &[u8], salt: &[u8], rounds: u32, dklen: usize) -> Vec<u8> {
40    let mut out = vec![0u8; dklen];
41    let rounds = rounds.max(1);
42    pbkdf2::pbkdf2_hmac::<Sha256>(password, salt, rounds, &mut out);
43    out
44}
45
46/// **Microsoft's non-standard DPAPI key-derivation loop** — the one Windows actually uses
47/// inside `CryptDeriveKey` for the masterkey subfield. Structurally similar to RFC 8018
48/// PBKDF2 but differs in one load-bearing way: instead of accumulating
49/// `T = U1 ⊕ U2 ⊕ … ⊕ Uc` and always feeding `U_{i-1}` into the PRF, MS feeds the running-XOR
50/// value itself back into the PRF at each round. Concretely:
51///
52/// ```text
53///   derived = PRF(P, salt || counter_be32)      // U1
54///   repeat count-1 times:
55///       actual  = PRF(P, derived)               // NOT U_{i-1} — the running XOR
56///       derived = derived ⊕ actual
57///   emit derived                                 // one output block
58/// ```
59///
60/// So `derived` after round 1 equals `U1 ⊕ U2`, after round 2 equals `(U1⊕U2) ⊕ PRF(P, U1⊕U2)`,
61/// and so on — a strictly different sequence from standard PBKDF2 despite the same inputs.
62///
63/// Byte-oracle: impacket 0.14 `dpapi.py MasterKey.deriveKey`. Every masterkey `decrypt_with_key`
64/// path in this crate routes through here — using `pbkdf2::pbkdf2_hmac` fails HMAC verification
65/// on every real Windows masterkey.
66pub fn ms_derive_key(hash: HashAlgo, passphrase: &[u8], salt: &[u8], count: u32, dklen: usize) -> Vec<u8> {
67    let count = count.max(1);
68    let mut out = Vec::with_capacity(dklen);
69    let mut counter: u32 = 1;
70    while out.len() < dklen {
71        let mut buf = Vec::with_capacity(salt.len() + 4);
72        buf.extend_from_slice(salt);
73        buf.extend_from_slice(&counter.to_be_bytes());
74        counter += 1;
75        let mut derived = hash.hmac(passphrase, &buf);
76        for _ in 0..(count - 1) {
77            let actual = hash.hmac(passphrase, &derived);
78            for (d, a) in derived.iter_mut().zip(actual.iter()) {
79                *d ^= *a;
80            }
81        }
82        out.extend_from_slice(&derived);
83    }
84    out.truncate(dklen);
85    out
86}
87
88/// Which hash a DPAPI structure selected (from its ALG_ID). Carries the digest and HMAC
89/// block sizes the key-derivation needs.
90#[derive(Clone, Copy, Debug, PartialEq, Eq)]
91pub enum HashAlgo {
92    Sha1,
93    Sha512,
94}
95
96impl HashAlgo {
97    /// CALG_SHA1 = 0x8004, CALG_SHA_512 = 0x800e.
98    pub fn from_alg_id(id: u32) -> Option<Self> {
99        match id {
100            0x8004 => Some(HashAlgo::Sha1),
101            0x800e => Some(HashAlgo::Sha512),
102            _ => None,
103        }
104    }
105    pub fn digest_len(self) -> usize {
106        match self {
107            HashAlgo::Sha1 => 20,
108            HashAlgo::Sha512 => 64,
109        }
110    }
111    pub fn block_size(self) -> usize {
112        match self {
113            HashAlgo::Sha1 => 64,
114            HashAlgo::Sha512 => 128,
115        }
116    }
117    pub fn hmac(self, key: &[u8], msg: &[u8]) -> Vec<u8> {
118        match self {
119            HashAlgo::Sha1 => hmac_sha1(key, msg).to_vec(),
120            HashAlgo::Sha512 => hmac_sha512(key, msg).to_vec(),
121        }
122    }
123    /// PBKDF2 with this hash as the PRF.
124    pub fn pbkdf2(self, password: &[u8], salt: &[u8], rounds: u32, dklen: usize) -> Vec<u8> {
125        let mut out = vec![0u8; dklen];
126        let rounds = rounds.max(1);
127        match self {
128            HashAlgo::Sha1 => pbkdf2::pbkdf2_hmac::<Sha1>(password, salt, rounds, &mut out),
129            HashAlgo::Sha512 => pbkdf2::pbkdf2_hmac::<Sha512>(password, salt, rounds, &mut out),
130        }
131        out
132    }
133}
134
135/// Which block cipher a DPAPI structure selected (from its ALG_ID).
136#[derive(Clone, Copy, Debug, PartialEq, Eq)]
137pub enum CipherAlgo {
138    Aes256,
139    TripleDes,
140}
141
142impl CipherAlgo {
143    /// CALG_AES_256 = 0x6610, CALG_3DES = 0x6603.
144    pub fn from_alg_id(id: u32) -> Option<Self> {
145        match id {
146            0x6610 => Some(CipherAlgo::Aes256),
147            0x6603 => Some(CipherAlgo::TripleDes),
148            _ => None,
149        }
150    }
151    pub fn key_len(self) -> usize {
152        match self {
153            CipherAlgo::Aes256 => 32,
154            CipherAlgo::TripleDes => 24,
155        }
156    }
157    pub fn iv_len(self) -> usize {
158        match self {
159            CipherAlgo::Aes256 => 16,
160            CipherAlgo::TripleDes => 8,
161        }
162    }
163    /// CBC decrypt with no padding removal (masterkey path — length is a block multiple).
164    pub fn cbc_decrypt_nopad(self, key: &[u8], iv: &[u8], ct: &[u8]) -> Option<Vec<u8>> {
165        if ct.is_empty() || ct.len() % 8 != 0 {
166            return None;
167        }
168        let mut buf = ct.to_vec();
169        match self {
170            CipherAlgo::Aes256 => {
171                let d = cbc::Decryptor::<Aes256>::new_from_slices(key, iv).ok()?;
172                d.decrypt_padded_mut::<NoPadding>(&mut buf).ok()?;
173            }
174            CipherAlgo::TripleDes => {
175                let d = cbc::Decryptor::<TdesEde3>::new_from_slices(key, iv).ok()?;
176                d.decrypt_padded_mut::<NoPadding>(&mut buf).ok()?;
177            }
178        }
179        Some(buf)
180    }
181}
182
183/// Strip PKCS#7 padding (data-blob path). Returns None on an invalid pad.
184pub fn unpad_pkcs7(data: &[u8]) -> Option<Vec<u8>> {
185    let &pad = data.last()?;
186    let pad = pad as usize;
187    if pad == 0 || pad > data.len() || pad > 16 {
188        return None;
189    }
190    if data[data.len() - pad..].iter().all(|&b| b as usize == pad) {
191        Some(data[..data.len() - pad].to_vec())
192    } else {
193        None
194    }
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200
201    // RFC 6070 — PBKDF2-HMAC-SHA1 known-answer vectors. A genuine external oracle for the PBKDF2
202    // wiring (not a self-round-trip).
203    #[test]
204    fn pbkdf2_hmac_sha1_rfc6070() {
205        let dk = HashAlgo::Sha1.pbkdf2(b"password", b"salt", 1, 20);
206        assert_eq!(hex(&dk), "0c60c80f961f0e71f3a9b524af6012062fe037a6");
207        let dk = HashAlgo::Sha1.pbkdf2(b"password", b"salt", 2, 20);
208        assert_eq!(hex(&dk), "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957");
209        let dk = HashAlgo::Sha1.pbkdf2(b"password", b"salt", 4096, 20);
210        assert_eq!(hex(&dk), "4b007901b765489abead49d926f721d065a429c1");
211    }
212
213    // RFC 2202 — HMAC-SHA1 test case 2 (key="Jefe", data="what do ya want for nothing?").
214    #[test]
215    fn hmac_sha1_rfc2202() {
216        let mac = hmac_sha1(b"Jefe", b"what do ya want for nothing?");
217        assert_eq!(hex(&mac), "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79");
218    }
219
220    // RFC 4231 — HMAC-SHA512 test case 2.
221    #[test]
222    fn hmac_sha512_rfc4231() {
223        let mac = hmac_sha512(b"Jefe", b"what do ya want for nothing?");
224        assert_eq!(
225            hex(&mac),
226            "164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea250554\
2279758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737"
228        );
229    }
230
231    #[test]
232    fn pkcs7_unpad_roundtrip() {
233        assert_eq!(unpad_pkcs7(&[b'a', b'b', 2, 2]).unwrap(), b"ab");
234        assert_eq!(unpad_pkcs7(&[1]).unwrap(), b"");
235        assert!(unpad_pkcs7(&[b'a', 2, 3]).is_none()); // inconsistent pad
236        assert!(unpad_pkcs7(&[]).is_none());
237    }
238
239    fn hex(b: &[u8]) -> String {
240        b.iter().map(|x| format!("{x:02x}")).collect()
241    }
242}