dpapi_offline/
masterkey.rs1use crate::crypto::{CipherAlgo, HashAlgo};
14use crate::DpapiError;
15
16fn u32le(b: &[u8], o: usize) -> Option<u32> {
17 Some(u32::from_le_bytes(b.get(o..o + 4)?.try_into().ok()?))
18}
19fn u64le(b: &[u8], o: usize) -> Option<u64> {
20 Some(u64::from_le_bytes(b.get(o..o + 8)?.try_into().ok()?))
21}
22
23#[derive(Debug, Clone)]
25pub struct MasterKeyFile {
26 pub guid: String,
28 pub master_key: Option<MasterKey>,
30}
31
32impl MasterKeyFile {
33 pub fn parse(data: &[u8]) -> Result<Self, DpapiError> {
53 if data.len() < 128 {
54 return Err(DpapiError::Parse("masterkey file too short".into()));
55 }
56 let guid_units: Vec<u16> = data[12..12 + 72]
58 .chunks_exact(2)
59 .map(|c| u16::from_le_bytes([c[0], c[1]]))
60 .collect();
61 let guid = String::from_utf16_lossy(&guid_units)
62 .trim_end_matches('\0')
63 .to_string();
64 let mk_len = u64le(data, 96).ok_or_else(|| DpapiError::Parse("mk len".into()))? as usize;
65 let master_key = if mk_len > 0 {
66 let start = 128usize;
67 let end = start
68 .checked_add(mk_len)
69 .filter(|&e| e <= data.len())
70 .ok_or_else(|| DpapiError::Parse("mk subfield out of bounds".into()))?;
71 Some(MasterKey::parse(&data[start..end])?)
72 } else {
73 None
74 };
75 Ok(MasterKeyFile { guid, master_key })
76 }
77}
78
79#[derive(Debug, Clone)]
81pub struct MasterKey {
82 pub salt: [u8; 16],
83 pub rounds: u32,
84 pub hash_algo: HashAlgo,
85 pub cipher_algo: CipherAlgo,
86 pub ciphertext: Vec<u8>,
87}
88
89impl MasterKey {
90 pub fn parse(data: &[u8]) -> Result<Self, DpapiError> {
91 if data.len() < 32 {
92 return Err(DpapiError::Parse("masterkey subfield too short".into()));
93 }
94 let salt: [u8; 16] = data[4..20].try_into().unwrap();
95 let rounds = u32le(data, 20).unwrap();
96 let hash_id = u32le(data, 24).unwrap();
97 let crypt_id = u32le(data, 28).unwrap();
98 let hash_algo = HashAlgo::from_alg_id(hash_id)
99 .ok_or_else(|| DpapiError::Unsupported(format!("hash alg 0x{hash_id:04x}")))?;
100 let cipher_algo = CipherAlgo::from_alg_id(crypt_id)
101 .ok_or_else(|| DpapiError::Unsupported(format!("cipher alg 0x{crypt_id:04x}")))?;
102 Ok(MasterKey {
103 salt,
104 rounds,
105 hash_algo,
106 cipher_algo,
107 ciphertext: data[32..].to_vec(),
108 })
109 }
110
111 pub fn decrypt_with_key(&self, pwdkey: &[u8]) -> Result<[u8; 64], DpapiError> {
114 let key_len = self.cipher_algo.key_len();
115 let iv_len = self.cipher_algo.iv_len();
116 let derived = self
117 .hash_algo
118 .pbkdf2(pwdkey, &self.salt, self.rounds, key_len + iv_len);
119 let clear = self
120 .cipher_algo
121 .cbc_decrypt_nopad(&derived[..key_len], &derived[key_len..], &self.ciphertext)
122 .ok_or(DpapiError::Decrypt)?;
123
124 let dlen = self.hash_algo.digest_len();
126 if clear.len() < 16 + dlen + 64 {
127 return Err(DpapiError::Decrypt);
128 }
129 let hmac_salt = &clear[..16];
130 let stored = &clear[16..16 + dlen];
131 let masterkey: [u8; 64] = clear[clear.len() - 64..].try_into().unwrap();
132
133 let hmac1 = self.hash_algo.hmac(pwdkey, hmac_salt);
134 let computed = self.hash_algo.hmac(&hmac1, &masterkey);
135 if computed == stored {
136 Ok(masterkey)
137 } else {
138 Err(DpapiError::HmacMismatch)
139 }
140 }
141
142 pub fn decrypt_with_password(&self, password: &str, sid: &str) -> Result<[u8; 64], DpapiError> {
145 let pwdkey = derive_local_prekey(password, sid);
146 self.decrypt_with_key(&pwdkey)
147 }
148}
149
150pub fn derive_local_prekey(password: &str, sid: &str) -> [u8; 20] {
152 use sha1::{Digest, Sha1};
153 let pw16: Vec<u8> = password.encode_utf16().flat_map(u16::to_le_bytes).collect();
154 let pwdhash = Sha1::digest(&pw16);
155 let mut sid16: Vec<u8> = sid.encode_utf16().flat_map(u16::to_le_bytes).collect();
156 sid16.extend_from_slice(&[0, 0]); crate::crypto::hmac_sha1(&pwdhash, &sid16)
158}
159
160#[cfg(test)]
161mod tests {
162 use super::*;
163
164 #[test]
167 fn parses_header_guid_and_subfield_lengths() {
168 let mut f = vec![0u8; 128];
169 f[0] = 2; let guid = "{DEADBEEF-0000-0000-0000-000000000000}";
171 let g16: Vec<u8> = guid.encode_utf16().flat_map(u16::to_le_bytes).collect();
172 f[12..12 + g16.len()].copy_from_slice(&g16);
173 f[96..104].copy_from_slice(&48u64.to_le_bytes());
175 let mut mk = vec![0u8; 32];
177 mk[0] = 2;
178 mk[20..24].copy_from_slice(&8000u32.to_le_bytes());
179 mk[24..28].copy_from_slice(&0x800eu32.to_le_bytes()); mk[28..32].copy_from_slice(&0x6610u32.to_le_bytes()); mk.extend_from_slice(&[0xAB; 16]);
182 f.extend_from_slice(&mk);
183
184 let parsed = MasterKeyFile::parse(&f).unwrap();
185 assert!(parsed.guid.starts_with("{DEADBEEF"));
186 let k = parsed.master_key.unwrap();
187 assert_eq!(k.rounds, 8000);
188 assert_eq!(k.hash_algo, HashAlgo::Sha512);
189 assert_eq!(k.cipher_algo, CipherAlgo::Aes256);
190 assert_eq!(k.ciphertext, vec![0xAB; 16]);
191 }
192
193 #[test]
194 fn prekey_is_deterministic_and_20_bytes() {
195 let a = derive_local_prekey("Passw0rd!", "S-1-5-21-1-2-3-1001");
196 let b = derive_local_prekey("Passw0rd!", "S-1-5-21-1-2-3-1001");
197 assert_eq!(a, b);
198 assert_ne!(a, derive_local_prekey("Passw0rd!", "S-1-5-21-1-2-3-1002"));
199 }
200
201 #[test]
202 fn rejects_short_and_bad_alg() {
203 assert!(MasterKeyFile::parse(&[0u8; 10]).is_err());
204 let mut mk = vec![0u8; 32];
205 mk[24..28].copy_from_slice(&0xDEADu32.to_le_bytes()); assert!(matches!(
207 MasterKey::parse(&mk),
208 Err(DpapiError::Unsupported(_))
209 ));
210 }
211}