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