1pub mod cms;
28pub mod der;
29pub mod gkdi;
30pub mod kdf;
31
32#[cfg(feature = "rpc")]
35pub mod rpc;
36
37use aes_gcm::aead::Aead;
38use aes_gcm::{Aes256Gcm, KeyInit, Nonce};
39use aes_kw::KekAes256;
40
41use cms::ProtectedBlob;
42use ms_gkdi::gkdi::{self as gkdi_impl, GroupKeyEnvelope};
43use ms_gkdi::kdf::{kdf, kds_service_label};
44
45#[derive(Debug, thiserror::Error, PartialEq, Eq)]
46pub enum DpapiError {
47 #[error("truncated: {0}")]
48 Truncated(&'static str),
49 #[error("bad {what} magic: {got:#010x}")]
50 BadMagic { what: &'static str, got: u32 },
51 #[error("malformed DER: {0}")]
52 Der(&'static str),
53 #[error("DER {what}: expected tag {expected:#04x}, got {got:#04x}")]
54 DerTag {
55 what: &'static str,
56 expected: u8,
57 got: u8,
58 },
59 #[error("not a CMS EnvelopedData (contentType {0})")]
60 NotEnvelopedData(String),
61 #[error("no MS-GKDI key identifier in the KEK recipient info")]
62 NoKeyIdentifier,
63 #[error("unsupported algorithm: {0}")]
64 UnsupportedAlgorithm(String),
65 #[error("the envelope carries a public key, not seed keys — ask the DC for the private half")]
66 PublicKeyEnvelope,
67 #[error("the envelope has no {0} seed key")]
68 MissingSeedKey(&'static str),
69 #[error("tree index out of range: l1={l1} l2={l2}")]
70 BadTreeIndex { l1: i32, l2: i32 },
71 #[error("the envelope is for root key {envelope}, the blob wants {blob}")]
72 RootKeyMismatch { envelope: String, blob: String },
73 #[error("the envelope is at L0 {envelope}, the blob wants {blob} — ask the DC for that L0")]
74 L0Mismatch { envelope: i32, blob: i32 },
75 #[error("key unwrap failed — wrong KEK")]
76 KeyUnwrap,
77 #[error("content decryption failed — wrong content key or corrupt blob")]
78 Decrypt,
79 #[error("msLAPS-EncryptedPassword blob is too short")]
80 ShortLapsBlob,
81}
82
83pub type Result<T> = std::result::Result<T, DpapiError>;
84
85impl From<ms_gkdi::GkdiError> for DpapiError {
88 fn from(e: ms_gkdi::GkdiError) -> Self {
89 match e {
90 ms_gkdi::GkdiError::Truncated(w) => DpapiError::Truncated(w),
91 ms_gkdi::GkdiError::BadMagic { what, got } => DpapiError::BadMagic { what, got },
92 ms_gkdi::GkdiError::UnsupportedAlgorithm(a) => DpapiError::UnsupportedAlgorithm(a),
93 ms_gkdi::GkdiError::PublicKeyEnvelope => DpapiError::PublicKeyEnvelope,
94 ms_gkdi::GkdiError::MissingSeedKey(w) => DpapiError::MissingSeedKey(w),
95 ms_gkdi::GkdiError::BadTreeIndex { l1, l2 } => DpapiError::BadTreeIndex { l1, l2 },
96 }
97 }
98}
99
100#[derive(Clone, Debug)]
103pub struct LapsBlob {
104 pub update_timestamp: u64,
106 pub blob: Vec<u8>,
108}
109
110impl LapsBlob {
111 pub fn parse(b: &[u8]) -> Result<LapsBlob> {
113 if b.len() < 16 {
114 return Err(DpapiError::ShortLapsBlob);
115 }
116 let upper = u32::from_le_bytes(b[0..4].try_into().unwrap()) as u64;
118 let lower = u32::from_le_bytes(b[4..8].try_into().unwrap()) as u64;
119 let len = u32::from_le_bytes(b[8..12].try_into().unwrap()) as usize;
120 let rest = &b[16..];
121 let blob = rest
122 .get(..len.min(rest.len()))
123 .ok_or(DpapiError::ShortLapsBlob)?;
124 Ok(LapsBlob {
125 update_timestamp: (upper << 32) | lower,
126 blob: blob.to_vec(),
127 })
128 }
129
130 pub fn protected(&self) -> Result<ProtectedBlob> {
132 ProtectedBlob::parse(&self.blob)
133 }
134}
135
136pub fn laps_password_from_json(utf16le: &[u8]) -> Option<String> {
140 let json = utf16le_lossy(utf16le);
141 let at = json.find("\"p\"")?;
142 let rest = &json[at + 3..];
143 let start = rest.find('"')? + 1;
144 let tail = &rest[start..];
145 let end = tail.find('"')?;
146 Some(tail[..end].to_string())
147}
148
149fn utf16le_lossy(b: &[u8]) -> String {
152 let units: Vec<u16> = b
153 .chunks_exact(2)
154 .map(|c| u16::from_le_bytes([c[0], c[1]]))
155 .collect();
156 let trimmed = match units.iter().rposition(|&u| u != 0) {
157 Some(i) => &units[..=i],
158 None => &[][..],
159 };
160 String::from_utf16_lossy(trimmed)
161}
162
163pub fn decrypt_with_seed_key(blob: &ProtectedBlob, l2_key: &[u8]) -> Result<Vec<u8>> {
170 let hash = blob.key_identifier.hash()?;
171 let ctx = gkdi_impl::kdf_context(
172 blob.key_identifier.root_key_id,
173 blob.key_identifier.l0,
174 blob.key_identifier.l1,
175 blob.key_identifier.l2,
176 );
177 let label = kds_service_label();
178
179 let mut candidates: Vec<Vec<u8>> = Vec::new();
180 if l2_key.len() >= 32 {
181 candidates.push(l2_key[..32].to_vec());
182 }
183 candidates.push(kdf(hash, l2_key, &label, &ctx, 32));
184 candidates.push(kdf(hash, l2_key, &label, &[], 32));
185
186 let mut last = DpapiError::KeyUnwrap;
187 for kek in candidates {
188 match decrypt_with_kek(blob, &kek) {
189 Ok(v) => return Ok(v),
190 Err(e) => last = e,
191 }
192 }
193 Err(last)
194}
195
196pub fn decrypt_with_kek(blob: &ProtectedBlob, kek: &[u8]) -> Result<Vec<u8>> {
199 let kek: [u8; 32] = kek.try_into().map_err(|_| DpapiError::KeyUnwrap)?;
200 let unwrapper = KekAes256::from(kek);
201 let mut cek = vec![0u8; blob.encrypted_key.len().saturating_sub(8)];
202 unwrapper
203 .unwrap(&blob.encrypted_key, &mut cek)
204 .map_err(|_| DpapiError::KeyUnwrap)?;
205 decrypt_content(blob, &cek)
206}
207
208pub fn decrypt_content(blob: &ProtectedBlob, cek: &[u8]) -> Result<Vec<u8>> {
210 let cipher = Aes256Gcm::new_from_slice(cek).map_err(|_| DpapiError::Decrypt)?;
211 let nonce = Nonce::from_slice(&blob.nonce);
212 cipher
213 .decrypt(nonce, blob.encrypted_content.as_ref())
214 .map_err(|_| DpapiError::Decrypt)
215}
216
217pub fn decrypt(blob: &ProtectedBlob, envelope: &GroupKeyEnvelope) -> Result<Vec<u8>> {
222 let id = &blob.key_identifier;
223 if envelope.root_key_id != id.root_key_id {
224 return Err(DpapiError::RootKeyMismatch {
225 envelope: envelope.root_key_id.to_string(),
226 blob: id.root_key_id.to_string(),
227 });
228 }
229 if envelope.l0 != id.l0 {
230 return Err(DpapiError::L0Mismatch {
231 envelope: envelope.l0,
232 blob: id.l0,
233 });
234 }
235 let l2_key = gkdi_impl::compute_l2_key(envelope, id.l1, id.l2)?;
236 decrypt_with_seed_key(blob, &l2_key)
237}