1use crate::Error;
33use aes::Aes256;
34use cbc::cipher::{block_padding::NoPadding, BlockDecryptMut, KeyIvInit};
35use md5::{Digest as _, Md5};
36use rc4::{consts::U16, KeyInit, Rc4, StreamCipher};
37use sha2::Sha256;
38
39type Aes256CbcDec = cbc::Decryptor<Aes256>;
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub struct PekKey {
46 bytes: [u8; 16],
47}
48
49impl PekKey {
50 pub fn new(bytes: [u8; 16]) -> Self {
52 PekKey { bytes }
53 }
54 pub fn bytes(&self) -> &[u8; 16] {
56 &self.bytes
57 }
58}
59
60#[derive(Debug, Clone)]
62#[non_exhaustive]
63pub struct PekList {
64 pub version: u8,
66 pub keys: Vec<PekKey>,
68}
69
70impl PekList {
71 pub fn key_for(&self, index: u32) -> Option<PekKey> {
73 self.keys.get(index as usize).copied()
74 }
75}
76
77pub fn unwrap_peklist(bootkey: &[u8; 16], peklist_bytes: &[u8]) -> Result<PekList, Error> {
86 if peklist_bytes.len() < 8 + 16 + 1 {
87 return Err(Error::Crypto(format!(
88 "PEKLIST too short ({} bytes)",
89 peklist_bytes.len()
90 )));
91 }
92
93 let version = peklist_bytes[0];
94 let key_material: &[u8; 16] = peklist_bytes[8..24]
95 .try_into()
96 .expect("length checked above");
97 let ciphertext = &peklist_bytes[24..];
98
99 let plaintext = match version {
100 3 => decrypt_rev3(bootkey, key_material, ciphertext)?,
101 2 => decrypt_rev2(bootkey, key_material, ciphertext),
102 other => return Err(Error::Crypto(format!("unknown PEK version {other:#04x}"))),
103 };
104
105 PekList::parse_plaintext(&plaintext).map(|mut l| {
106 l.version = version;
107 l
108 })
109}
110
111fn decrypt_rev3(
113 bootkey: &[u8; 16],
114 key_material: &[u8; 16],
115 ciphertext: &[u8],
116) -> Result<Vec<u8>, Error> {
117 if ciphertext.is_empty() || ciphertext.len() % 16 != 0 {
118 return Err(Error::Crypto(format!(
119 "revision-3 ciphertext length {} is not a multiple of 16",
120 ciphertext.len()
121 )));
122 }
123 let mut hasher = Sha256::new();
124 hasher.update(bootkey);
125 for _ in 0..1000 {
126 hasher.update(key_material);
127 }
128 let tmp_key = hasher.finalize();
129
130 let mut buf = ciphertext.to_vec();
131 Aes256CbcDec::new(tmp_key.as_slice().into(), key_material.into())
132 .decrypt_padded_mut::<NoPadding>(&mut buf)
133 .map_err(|e| Error::Crypto(format!("AES-256-CBC decrypt failed: {e}")))?;
134 Ok(buf)
135}
136
137fn decrypt_rev2(bootkey: &[u8; 16], key_material: &[u8; 16], ciphertext: &[u8]) -> Vec<u8> {
139 let mut hasher = Md5::new();
140 hasher.update(bootkey);
141 for _ in 0..1000 {
142 hasher.update(key_material);
143 }
144 let tmp_key = hasher.finalize();
145
146 let mut buf = ciphertext.to_vec();
147 let mut cipher: Rc4<U16> = Rc4::new(tmp_key.as_slice().into());
148 cipher.apply_keystream(&mut buf);
149 buf
150}
151
152impl PekList {
153 pub fn parse_plaintext(plaintext: &[u8]) -> Result<Self, Error> {
158 if plaintext.len() < 32 + 20 {
159 return Err(Error::Crypto(format!(
160 "PEK plaintext too short ({} bytes, need at least 52)",
161 plaintext.len()
162 )));
163 }
164 let body_len = plaintext.len() - 32;
168 let count = body_len / 20;
169 let consumed = count * 20;
170 if plaintext[32 + consumed..].iter().any(|&b| b != 0) {
171 return Err(Error::Crypto(format!(
172 "PEK plaintext has {} non-zero trailing bytes past the last entry — likely wrong unwrap or torn buffer",
173 body_len - consumed
174 )));
175 }
176 let mut keys = Vec::with_capacity(count);
177 for i in 0..count {
178 let off = 32 + i * 20;
179 let mut k = [0u8; 16];
180 k.copy_from_slice(&plaintext[off + 4..off + 20]);
181 keys.push(PekKey::new(k));
182 }
183 Ok(PekList { version: 0, keys })
184 }
185}
186
187#[cfg(test)]
188mod tests {
189 use super::*;
190 use aes::cipher::{block_padding::NoPadding, BlockEncryptMut, KeyIvInit};
191 type Aes256CbcEnc = cbc::Encryptor<Aes256>;
192
193 #[test]
194 fn parse_plaintext_reads_two_keys() {
195 let mut pt = vec![0u8; 32];
196 for i in 0..2u32 {
197 pt.extend_from_slice(&i.to_le_bytes());
198 pt.extend_from_slice(&[i as u8; 16]);
199 }
200 let list = PekList::parse_plaintext(&pt).unwrap();
201 assert_eq!(list.keys.len(), 2);
202 assert_eq!(list.keys[0].bytes(), &[0u8; 16]);
203 assert_eq!(list.keys[1].bytes(), &[1u8; 16]);
204 assert_eq!(list.key_for(1), Some(PekKey::new([1u8; 16])));
205 assert_eq!(list.key_for(2), None);
206 }
207
208 #[test]
209 fn parse_plaintext_rejects_short() {
210 assert!(matches!(
211 PekList::parse_plaintext(&[0u8; 30]).unwrap_err(),
212 Error::Crypto(_)
213 ));
214 }
215
216 #[test]
217 fn parse_plaintext_accepts_zero_padded_tail() {
218 let mut pt = vec![0u8; 32];
221 pt.extend_from_slice(&0u32.to_le_bytes());
222 pt.extend_from_slice(&[0xEE; 16]);
223 pt.extend_from_slice(&[0u8; 12]); let list = PekList::parse_plaintext(&pt).unwrap();
225 assert_eq!(list.keys.len(), 1);
226 assert_eq!(list.keys[0].bytes(), &[0xEE; 16]);
227 }
228
229 #[test]
230 fn parse_plaintext_rejects_nonzero_ragged_tail() {
231 let mut pt = vec![0u8; 32];
233 pt.extend_from_slice(&0u32.to_le_bytes());
234 pt.extend_from_slice(&[0xEE; 16]);
235 pt.push(0x42); assert!(matches!(
237 PekList::parse_plaintext(&pt).unwrap_err(),
238 Error::Crypto(_)
239 ));
240 }
241
242 #[test]
243 fn unwrap_peklist_reports_unknown_revision() {
244 let mut blob = vec![0u8; 32];
245 blob[0] = 42;
246 let err = unwrap_peklist(&[0u8; 16], &blob).unwrap_err();
247 assert!(format!("{err}").contains("unknown PEK version"));
248 }
249
250 #[test]
253 fn unwrap_peklist_rev3_roundtrip() {
254 let bootkey = [0xABu8; 16];
255 let salt = [0x11u8; 16];
256
257 let mut plaintext = vec![0u8; 32];
259 for i in 0..2u32 {
260 plaintext.extend_from_slice(&i.to_le_bytes());
261 plaintext.extend_from_slice(&[0xC0u8 + i as u8; 16]);
262 }
263 while plaintext.len() % 16 != 0 {
265 plaintext.push(0);
266 }
267
268 let mut hasher = Sha256::new();
270 hasher.update(bootkey);
271 for _ in 0..1000 {
272 hasher.update(salt);
273 }
274 let key = hasher.finalize();
275
276 let mut ct = plaintext.clone();
278 let ct_len = ct.len();
279 Aes256CbcEnc::new(key.as_slice().into(), &salt.into())
280 .encrypt_padded_mut::<NoPadding>(&mut ct, ct_len)
281 .unwrap();
282
283 let mut blob = vec![0u8; 8];
285 blob[0] = 3;
286 blob.extend_from_slice(&salt);
287 blob.extend_from_slice(&ct);
288
289 let list = unwrap_peklist(&bootkey, &blob).unwrap();
291 assert_eq!(list.version, 3);
292 assert_eq!(list.keys.len(), 2);
293 assert_eq!(list.keys[0].bytes(), &[0xC0u8; 16]);
294 assert_eq!(list.keys[1].bytes(), &[0xC1u8; 16]);
295 }
296
297 #[test]
299 fn unwrap_peklist_rev2_roundtrip() {
300 use md5::{Digest, Md5};
301 let bootkey = [0x33u8; 16];
302 let salt = [0x77u8; 16];
303
304 let mut plaintext = vec![0u8; 32];
305 plaintext.extend_from_slice(&0u32.to_le_bytes());
306 plaintext.extend_from_slice(&[0xEFu8; 16]);
307
308 let mut hasher = Md5::new();
309 hasher.update(bootkey);
310 for _ in 0..1000 {
311 hasher.update(salt);
312 }
313 let key = hasher.finalize();
314
315 let mut ct = plaintext.clone();
317 let mut cipher: Rc4<U16> = Rc4::new(key.as_slice().into());
318 cipher.apply_keystream(&mut ct);
319
320 let mut blob = vec![0u8; 8];
321 blob[0] = 2;
322 blob.extend_from_slice(&salt);
323 blob.extend_from_slice(&ct);
324
325 let list = unwrap_peklist(&bootkey, &blob).unwrap();
326 assert_eq!(list.version, 2);
327 assert_eq!(list.keys.len(), 1);
328 assert_eq!(list.keys[0].bytes(), &[0xEFu8; 16]);
329 }
330}