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()?))
}
#[derive(Debug, Clone)]
pub struct MasterKeyFile {
pub guid: String,
pub master_key: Option<MasterKey>,
}
impl MasterKeyFile {
pub fn parse(data: &[u8]) -> Result<Self, DpapiError> {
if data.len() < 128 {
return Err(DpapiError::Parse("masterkey file too short".into()));
}
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 })
}
}
#[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(),
})
}
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 = crate::crypto::ms_derive_key(
self.hash_algo,
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)?;
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)
}
}
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)
}
}
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]); crate::crypto::hmac_sha1(&pwdhash, &sid16)
}
pub fn derive_domain_prekey_md4(password: &str, sid: &str) -> [u8; 20] {
let pw16: Vec<u8> = password.encode_utf16().flat_map(u16::to_le_bytes).collect();
let nt = crate::crypto::md4(&pw16);
let mut sid16: Vec<u8> = sid.encode_utf16().flat_map(u16::to_le_bytes).collect();
sid16.extend_from_slice(&[0, 0]);
crate::crypto::hmac_sha1(&nt, &sid16)
}
pub fn derive_domain_prekey_protected(password: &str, sid: &str) -> [u8; 20] {
let pw16: Vec<u8> = password.encode_utf16().flat_map(u16::to_le_bytes).collect();
let nt = crate::crypto::md4(&pw16);
let sid16: Vec<u8> = sid.encode_utf16().flat_map(u16::to_le_bytes).collect();
let tmp1 = crate::crypto::pbkdf2_sha256(&nt, &sid16, 10000, 32);
let tmp2 = crate::crypto::pbkdf2_sha256(&tmp1, &sid16, 1, 32);
let mut sid16_nul: Vec<u8> = sid.encode_utf16().flat_map(u16::to_le_bytes).collect();
sid16_nul.extend_from_slice(&[0, 0]);
crate::crypto::hmac_sha1(&tmp2[..16], &sid16_nul)
}
#[cfg(test)]
mod tests {
use super::*;
fn hex(b: &[u8]) -> String {
b.iter().fold(String::with_capacity(b.len() * 2), |mut s, x| {
use std::fmt::Write;
write!(s, "{x:02x}").unwrap();
s
})
}
fn hex_decode(s: &str) -> Vec<u8> {
(0..s.len())
.step_by(2)
.map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
.collect()
}
const KAT_MK_SUBFIELD: [u8; 176] = [
0x02, 0x00, 0x00, 0x00, 0x4c, 0x94, 0xf7, 0x33, 0x72, 0x11, 0x7a, 0x67, 0x73, 0x9b, 0xd2,
0x13, 0x6b, 0x79, 0xef, 0x9a, 0x40, 0x1f, 0x00, 0x00, 0x0e, 0x80, 0x00, 0x00, 0x10, 0x66,
0x00, 0x00, 0x2f, 0xc5, 0xd6, 0xec, 0xbd, 0x9a, 0x03, 0x33, 0x29, 0x61, 0x2c, 0x93, 0x3d,
0x5e, 0xa7, 0xd8, 0x33, 0x6e, 0x73, 0xce, 0xcb, 0xf7, 0xad, 0x68, 0x4d, 0x95, 0x41, 0x54,
0x1e, 0x6f, 0x7d, 0x0b, 0x48, 0x8c, 0x3f, 0x51, 0xf6, 0x71, 0x2e, 0xa3, 0x89, 0x1b, 0xe5,
0xea, 0x5d, 0xc6, 0x9d, 0x90, 0xb7, 0xbf, 0x23, 0x37, 0xc8, 0x9e, 0xec, 0x77, 0xbc, 0xd9,
0x71, 0xe2, 0xf3, 0x91, 0x16, 0xeb, 0x05, 0x90, 0x1c, 0x46, 0xb9, 0xaa, 0x39, 0xa6, 0x12,
0x7d, 0x20, 0xf1, 0x32, 0x60, 0x64, 0xa6, 0x13, 0x2c, 0xea, 0x07, 0xa4, 0x92, 0xed, 0x16,
0xdf, 0xf1, 0xfa, 0x3d, 0xbe, 0x56, 0x62, 0x86, 0xb1, 0x58, 0x49, 0xc9, 0x20, 0xfb, 0x81,
0x53, 0x46, 0x9a, 0x0d, 0xfe, 0x05, 0xf3, 0x12, 0x94, 0x8f, 0x3c, 0x5b, 0x64, 0x1d, 0x4c,
0x84, 0xf2, 0xe7, 0x6a, 0x84, 0x04, 0x40, 0xd5, 0xa0, 0x53, 0x95, 0x3b, 0x77, 0x55, 0x76,
0xad, 0x5c, 0x0a, 0x77, 0x25, 0x8f, 0xb9, 0xab, 0xe6, 0x1d, 0xac,
];
const KAT_PASSWORD: &str = "Zikurat2003$";
const KAT_SID: &str = "S-1-5-21-4202935557-1141836847-2435275103-500";
const KAT_PWDKEY_MD4: &str = "a4cee3971e4a7acc05a5b384f380c76ba86d8c2d";
const KAT_PWDKEY_PROTECTED: &str = "3d7d82260a3a2c39039f28e9cede2a4775f89e92";
const KAT_MASTERKEY: &str = "93a18bf11f58cf2c9dd7b1db2e9fd7f68838cb16c9f0f71d9ff174d97da415e67841c7b8597fbdb633ce2eac3910a426829723ef3772ff630109bdc8de662259";
#[test]
fn derive_domain_prekey_matches_impacket() {
assert_eq!(
hex(&derive_domain_prekey_md4(KAT_PASSWORD, KAT_SID)),
KAT_PWDKEY_MD4
);
assert_eq!(
hex(&derive_domain_prekey_protected(KAT_PASSWORD, KAT_SID)),
KAT_PWDKEY_PROTECTED
);
}
#[test]
fn decrypt_with_key_end_to_end_server_2025() {
let mk = MasterKey::parse(&KAT_MK_SUBFIELD).expect("parse mk subfield");
let pwdkey = hex_decode(KAT_PWDKEY_PROTECTED);
let out = mk.decrypt_with_key(&pwdkey).expect("decrypt with key");
assert_eq!(hex(&out), KAT_MASTERKEY);
}
#[test]
fn parses_header_guid_and_subfield_lengths() {
let mut f = vec![0u8; 128];
f[0] = 2; 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);
f[96..104].copy_from_slice(&48u64.to_le_bytes());
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()); mk[28..32].copy_from_slice(&0x6610u32.to_le_bytes()); 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()); assert!(matches!(
MasterKey::parse(&mk),
Err(DpapiError::Unsupported(_))
));
}
}