1pub mod cms;
22mod cursor;
23pub mod der;
24pub mod gkdi;
25pub mod kdf;
26
27use aes_gcm::aead::Aead;
28use aes_gcm::{Aes256Gcm, KeyInit, Nonce};
29use aes_kw::KekAes256;
30
31use cms::ProtectedBlob;
32use gkdi::GroupKeyEnvelope;
33use kdf::{kdf, kds_service_label};
34
35#[derive(Debug, thiserror::Error, PartialEq, Eq)]
36pub enum DpapiError {
37 #[error("truncated: {0}")]
38 Truncated(&'static str),
39 #[error("bad {what} magic: {got:#010x}")]
40 BadMagic { what: &'static str, got: u32 },
41 #[error("malformed DER: {0}")]
42 Der(&'static str),
43 #[error("DER {what}: expected tag {expected:#04x}, got {got:#04x}")]
44 DerTag {
45 what: &'static str,
46 expected: u8,
47 got: u8,
48 },
49 #[error("not a CMS EnvelopedData (contentType {0})")]
50 NotEnvelopedData(String),
51 #[error("no MS-GKDI key identifier in the KEK recipient info")]
52 NoKeyIdentifier,
53 #[error("unsupported algorithm: {0}")]
54 UnsupportedAlgorithm(String),
55 #[error("the envelope carries a public key, not seed keys — ask the DC for the private half")]
56 PublicKeyEnvelope,
57 #[error("the envelope has no {0} seed key")]
58 MissingSeedKey(&'static str),
59 #[error("tree index out of range: l1={l1} l2={l2}")]
60 BadTreeIndex { l1: i32, l2: i32 },
61 #[error("the envelope is for root key {envelope}, the blob wants {blob}")]
62 RootKeyMismatch { envelope: String, blob: String },
63 #[error("the envelope is at L0 {envelope}, the blob wants {blob} — ask the DC for that L0")]
64 L0Mismatch { envelope: i32, blob: i32 },
65 #[error("key unwrap failed — wrong KEK")]
66 KeyUnwrap,
67 #[error("content decryption failed — wrong content key or corrupt blob")]
68 Decrypt,
69 #[error("msLAPS-EncryptedPassword blob is too short")]
70 ShortLapsBlob,
71}
72
73pub type Result<T> = std::result::Result<T, DpapiError>;
74
75#[derive(Clone, Debug)]
78pub struct LapsBlob {
79 pub update_timestamp: u64,
81 pub blob: Vec<u8>,
83}
84
85impl LapsBlob {
86 pub fn parse(b: &[u8]) -> Result<LapsBlob> {
88 if b.len() < 16 {
89 return Err(DpapiError::ShortLapsBlob);
90 }
91 let upper = u32::from_le_bytes(b[0..4].try_into().unwrap()) as u64;
93 let lower = u32::from_le_bytes(b[4..8].try_into().unwrap()) as u64;
94 let len = u32::from_le_bytes(b[8..12].try_into().unwrap()) as usize;
95 let rest = &b[16..];
96 let blob = rest
97 .get(..len.min(rest.len()))
98 .ok_or(DpapiError::ShortLapsBlob)?;
99 Ok(LapsBlob {
100 update_timestamp: (upper << 32) | lower,
101 blob: blob.to_vec(),
102 })
103 }
104
105 pub fn protected(&self) -> Result<ProtectedBlob> {
107 ProtectedBlob::parse(&self.blob)
108 }
109}
110
111pub fn laps_password_from_json(utf16le: &[u8]) -> Option<String> {
115 let json = gkdi::utf16_lossy(utf16le);
116 let at = json.find("\"p\"")?;
117 let rest = &json[at + 3..];
118 let start = rest.find('"')? + 1;
119 let tail = &rest[start..];
120 let end = tail.find('"')?;
121 Some(tail[..end].to_string())
122}
123
124pub fn decrypt_with_seed_key(blob: &ProtectedBlob, l2_key: &[u8]) -> Result<Vec<u8>> {
131 let hash = blob.key_identifier.hash()?;
132 let ctx = gkdi::kdf_context(
133 blob.key_identifier.root_key_id,
134 blob.key_identifier.l0,
135 blob.key_identifier.l1,
136 blob.key_identifier.l2,
137 );
138 let label = kds_service_label();
139
140 let mut candidates: Vec<Vec<u8>> = Vec::new();
141 if l2_key.len() >= 32 {
142 candidates.push(l2_key[..32].to_vec());
143 }
144 candidates.push(kdf(hash, l2_key, &label, &ctx, 32));
145 candidates.push(kdf(hash, l2_key, &label, &[], 32));
146
147 let mut last = DpapiError::KeyUnwrap;
148 for kek in candidates {
149 match decrypt_with_kek(blob, &kek) {
150 Ok(v) => return Ok(v),
151 Err(e) => last = e,
152 }
153 }
154 Err(last)
155}
156
157pub fn decrypt_with_kek(blob: &ProtectedBlob, kek: &[u8]) -> Result<Vec<u8>> {
160 let kek: [u8; 32] = kek.try_into().map_err(|_| DpapiError::KeyUnwrap)?;
161 let unwrapper = KekAes256::from(kek);
162 let mut cek = vec![0u8; blob.encrypted_key.len().saturating_sub(8)];
163 unwrapper
164 .unwrap(&blob.encrypted_key, &mut cek)
165 .map_err(|_| DpapiError::KeyUnwrap)?;
166 decrypt_content(blob, &cek)
167}
168
169pub fn decrypt_content(blob: &ProtectedBlob, cek: &[u8]) -> Result<Vec<u8>> {
171 let cipher = Aes256Gcm::new_from_slice(cek).map_err(|_| DpapiError::Decrypt)?;
172 let nonce = Nonce::from_slice(&blob.nonce);
173 cipher
174 .decrypt(nonce, blob.encrypted_content.as_ref())
175 .map_err(|_| DpapiError::Decrypt)
176}
177
178pub fn decrypt(blob: &ProtectedBlob, envelope: &GroupKeyEnvelope) -> Result<Vec<u8>> {
183 let id = &blob.key_identifier;
184 if envelope.root_key_id != id.root_key_id {
185 return Err(DpapiError::RootKeyMismatch {
186 envelope: envelope.root_key_id.to_string(),
187 blob: id.root_key_id.to_string(),
188 });
189 }
190 if envelope.l0 != id.l0 {
191 return Err(DpapiError::L0Mismatch {
192 envelope: envelope.l0,
193 blob: id.l0,
194 });
195 }
196 let l2_key = gkdi::compute_l2_key(envelope, id.l1, id.l2)?;
197 decrypt_with_seed_key(blob, &l2_key)
198}