1#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25#[non_exhaustive]
26pub enum FileField {
27 AgileReserved,
30 SpinCount,
32 KeyDataKeyBits,
34 EncryptedKeyKeyBits,
36 KeyDataBlockSize,
38 EncryptedKeyBlockSize,
40 KeyDataHashSize,
42 EncryptedKeyHashSize,
44 KeyDataSaltSize,
46 EncryptedKeySaltSize,
48 KeyDataSaltValue,
50 EncryptedKeySaltValue,
52 KeyDataHashAlgorithm,
54 EncryptedKeyHashAlgorithm,
56 KeyDataCipherAlgorithm,
58 EncryptedKeyCipherAlgorithm,
60 KeyDataCipherChaining,
62 EncryptedKeyCipherChaining,
64 EncryptedKeyValue,
66 EncryptedVerifierHashInput,
68 EncryptedVerifierHashValue,
70 PasswordKeyEncryptor,
72 DataIntegrity,
74 EncryptedHmacKey,
76 EncryptedHmacValue,
78 SessionKey,
80
81 EncryptionInfo,
84 EncryptionHeaderSize,
86 EncryptionHeader,
88 EncryptionHeaderFlags,
90 EncryptionHeaderKeySize,
92 EncryptionHeaderAlgId,
94 EncryptionVerifier,
96 VerifierSaltSize,
98 VerifierHashSize,
100 EncryptedPackageSize,
102 Rc4Office97Header,
104
105 FibWIdent,
108 FibLKey,
110 EncryptionVersionInfo,
112
113 BiffRecord,
116 WorkbookBof,
118 Filepass,
120 FilepassEncryptionType,
122
123 UserEditAtom,
126 OffsetLastEdit,
128 PersistDirectory,
130 EncryptSessionPersistIdRef,
132 CryptSession10Container,
134 PersistObject,
136 PicturesRecord,
138
139 SummaryStream,
142 SummaryDescriptorArray,
144 SummaryDescriptorCount,
146 SummaryDescriptor,
148 SummaryStreamName,
150 SummaryStreamExtent,
152}
153
154impl FileField {
155 pub fn spelling(self) -> &'static str {
157 match self {
160 Self::AgileReserved => "agile EncryptionInfo Reserved",
161 Self::SpinCount => "p:encryptedKey/@spinCount",
162 Self::KeyDataKeyBits => "keyData/@keyBits",
163 Self::EncryptedKeyKeyBits => "p:encryptedKey/@keyBits",
164 Self::KeyDataBlockSize => "keyData/@blockSize",
165 Self::EncryptedKeyBlockSize => "p:encryptedKey/@blockSize",
166 Self::KeyDataHashSize => "keyData/@hashSize",
167 Self::EncryptedKeyHashSize => "p:encryptedKey/@hashSize",
168 Self::KeyDataSaltSize => "keyData/@saltSize",
169 Self::EncryptedKeySaltSize => "p:encryptedKey/@saltSize",
170 Self::KeyDataSaltValue => "keyData/@saltValue",
171 Self::EncryptedKeySaltValue => "p:encryptedKey/@saltValue",
172 Self::KeyDataHashAlgorithm => "keyData/@hashAlgorithm",
173 Self::EncryptedKeyHashAlgorithm => "p:encryptedKey/@hashAlgorithm",
174 Self::KeyDataCipherAlgorithm => "keyData/@cipherAlgorithm",
175 Self::EncryptedKeyCipherAlgorithm => "p:encryptedKey/@cipherAlgorithm",
176 Self::KeyDataCipherChaining => "keyData/@cipherChaining",
177 Self::EncryptedKeyCipherChaining => "p:encryptedKey/@cipherChaining",
178 Self::EncryptedKeyValue => "p:encryptedKey/@encryptedKeyValue",
179 Self::EncryptedVerifierHashInput => "p:encryptedKey/@encryptedVerifierHashInput",
180 Self::EncryptedVerifierHashValue => "p:encryptedKey/@encryptedVerifierHashValue",
181 Self::PasswordKeyEncryptor => "keyEncryptor (password)",
182 Self::DataIntegrity => "dataIntegrity",
183 Self::EncryptedHmacKey => "dataIntegrity/@encryptedHmacKey",
184 Self::EncryptedHmacValue => "dataIntegrity/@encryptedHmacValue",
185 Self::SessionKey => "the recovered session key",
186 Self::EncryptionInfo => "EncryptionInfo",
187 Self::EncryptionHeaderSize => "EncryptionHeaderSize",
188 Self::EncryptionHeader => "EncryptionHeader",
189 Self::EncryptionHeaderFlags => "EncryptionHeader.Flags",
190 Self::EncryptionHeaderKeySize => "EncryptionHeader.KeySize",
191 Self::EncryptionHeaderAlgId => "EncryptionHeader.AlgID",
192 Self::EncryptionVerifier => "EncryptionVerifier",
193 Self::VerifierSaltSize => "EncryptionVerifier.SaltSize",
194 Self::VerifierHashSize => "EncryptionVerifier.VerifierHashSize",
195 Self::EncryptedPackageSize => "EncryptedPackage StreamSize",
196 Self::Rc4Office97Header => "the RC4 (Office 97) header",
197 Self::FibWIdent => "FibBase.wIdent",
198 Self::FibLKey => "FibBase.lKey",
199 Self::EncryptionVersionInfo => "EncryptionVersionInfo",
200 Self::BiffRecord => "a BIFF record",
201 Self::WorkbookBof => "the Workbook BOF record",
202 Self::Filepass => "the FILEPASS record",
203 Self::FilepassEncryptionType => "FILEPASS.wEncryptionType",
204 Self::UserEditAtom => "the UserEditAtom",
205 Self::OffsetLastEdit => "UserEditAtom.offsetLastEdit",
206 Self::PersistDirectory => "the PersistDirectoryAtom",
207 Self::EncryptSessionPersistIdRef => "UserEditAtom.encryptSessionPersistIdRef",
208 Self::CryptSession10Container => "the CryptSession10Container",
209 Self::PersistObject => "a persist object",
210 Self::PicturesRecord => "a Pictures record",
211 Self::SummaryStream => "the encrypted summary stream",
212 Self::SummaryDescriptorArray => "the EncryptedStreamDescriptor array",
213 Self::SummaryDescriptorCount => "EncryptedStreamDescriptorCount",
214 Self::SummaryDescriptor => "an EncryptedStreamDescriptor",
215 Self::SummaryStreamName => "an EncryptedStreamDescriptor's stream name",
216 Self::SummaryStreamExtent => "an encrypted stream's extent",
217 }
218 }
219}
220
221impl core::fmt::Display for FileField {
222 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
223 f.write_str(self.spelling())
224 }
225}
226
227#[derive(Debug, Clone, Copy, PartialEq, Eq)]
230#[non_exhaustive]
231pub enum Bound {
232 Spec,
235 Cipher,
237 Margin,
239 Crate,
242}
243
244impl core::fmt::Display for Bound {
245 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
246 f.write_str(match self {
247 Self::Spec => "the specification's",
248 Self::Cipher => "the cipher's",
249 Self::Margin => "this crate's margin",
250 Self::Crate => "this crate's",
251 })
252 }
253}
254
255#[derive(Debug, Clone, Copy, PartialEq, Eq)]
257#[non_exhaustive]
258pub enum AllowedSet {
259 AesKeyBits,
261 XorOrRc4,
263 Rc4KeyBits,
265 PicturesRecordTypes,
267}
268
269impl core::fmt::Display for AllowedSet {
270 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
271 f.write_str(match self {
272 Self::AesKeyBits => "128, 192 or 256",
273 Self::XorOrRc4 => "0 (XOR) or 1 (RC4)",
274 Self::Rc4KeyBits => "40 to 128 in steps of 8",
275 Self::PicturesRecordTypes => "a blip or a file-block entry",
276 })
277 }
278}
279
280#[derive(Debug, Clone, Copy, PartialEq, Eq)]
282#[non_exhaustive]
283pub enum FileProblem {
284 OutOfRange {
286 got: u64,
288 min: u64,
290 max: u64,
292 bound: Bound,
294 },
295 NotInSet {
297 got: u64,
299 allowed: AllowedSet,
301 bound: Bound,
303 },
304 NotRequiredValue {
306 got: u64,
308 required: u64,
310 bound: Bound,
312 },
313 Disagrees {
315 got: u64,
317 expected: u64,
319 with: FileField,
321 },
322 DigestMismatch {
324 got: u64,
326 hash: crate::HashAlgorithm,
328 },
329 Truncated {
331 have: u64,
333 need: u64,
335 },
336 OutOfBounds {
338 offset: u64,
340 len: u64,
342 end: u64,
344 },
345 Unreadable {
347 offset: u64,
349 },
350 Missing,
352 Duplicate,
354 Overlaps,
356 Unterminated,
358 FlagClear,
360 BadSignature,
362 OutOfOrder {
364 after_record: u16,
366 },
367 Unrecognized {
369 got: u64,
371 },
372}
373
374impl core::fmt::Display for FileProblem {
375 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
376 match self {
377 Self::OutOfRange {
378 got,
379 min,
380 max,
381 bound,
382 } => write!(f, "is {got}, outside {min}..={max} ({bound} range)"),
383 Self::NotInSet {
384 got,
385 allowed,
386 bound,
387 } => write!(f, "is {got}, not {allowed} ({bound} set)"),
388 Self::NotRequiredValue {
389 got,
390 required,
391 bound,
392 } => write!(f, "is {got}, not {required} ({bound} requirement)"),
393 Self::Disagrees {
394 got,
395 expected,
396 with,
397 } => write!(f, "is {got}, but {with} requires {expected}"),
398 Self::DigestMismatch { got, hash } => {
399 write!(f, "is {got}, which {} cannot produce", hash.name())
400 }
401 Self::Truncated { have, need } => write!(f, "is {have} bytes, needs {need}"),
402 Self::OutOfBounds { offset, len, end } => {
403 write!(f, "runs from {offset} for {len} bytes, past {end}")
404 }
405 Self::Unreadable { offset } => write!(f, "cannot be read at offset {offset}"),
406 Self::Missing => f.write_str("is missing"),
407 Self::Duplicate => f.write_str("appears more than once"),
408 Self::Overlaps => f.write_str("overlaps another"),
409 Self::Unterminated => f.write_str("is not terminated"),
410 Self::FlagClear => f.write_str("has a required flag clear"),
411 Self::BadSignature => f.write_str("does not carry the format's signature"),
412 Self::OutOfOrder { after_record } => {
413 write!(f, "follows record 0x{after_record:04X}")
414 }
415 Self::Unrecognized { got } => write!(f, "is {got}, a value the format does not define"),
416 }
417 }
418}
419
420#[derive(Debug, Clone, Copy, PartialEq, Eq)]
424#[non_exhaustive]
425pub enum Invariant {
426 AesKeyLength,
428 AesIvLength,
430 BlockSizeOverDigest,
432 CounterOverflow,
434 RewriteLength,
436 PlaceholderLength,
438 SerializedLength,
440 IntegrityPadding,
442 Rc4KeyLength,
444 Rc4BlockSize,
446 KeyLadderLength,
448 Unrepresentable,
450 InternalSlice,
452}
453
454impl core::fmt::Display for Invariant {
455 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
456 f.write_str(match self {
457 Self::AesKeyLength => "an AES key length the screen passed",
458 Self::AesIvLength => "an AES IV length the screen passed",
459 Self::BlockSizeOverDigest => "a block size longer than its digest",
460 Self::CounterOverflow => "more blocks than a 32-bit counter numbers",
461 Self::RewriteLength => "an in-place rewrite changed a stream's length",
462 Self::PlaceholderLength => "the EncryptionInfo placeholder changed length",
463 Self::SerializedLength => "a serialized blob has the wrong length",
464 Self::IntegrityPadding => "integrity padding arithmetic overflowed",
465 Self::Rc4KeyLength => "an RC4 key length outside 5..=16 bytes",
466 Self::Rc4BlockSize => "an RC4 block size of zero",
467 Self::KeyLadderLength => "a key size the SHA-1 ladder cannot yield",
468 Self::Unrepresentable => "a value that does not fit this host's usize",
469 Self::InternalSlice => "a slice outside its buffer",
470 })
471 }
472}
473
474#[derive(Debug, Clone, Copy, PartialEq, Eq)]
480#[non_exhaustive]
481pub enum AlgorithmName {
482 Known(KnownAlgorithm),
484 Unknown {
486 len: u32,
488 },
489 AlgId(u32),
491 Fixed(&'static str),
493}
494
495impl core::fmt::Display for AlgorithmName {
496 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
497 match self {
498 Self::Known(k) => write!(f, "{k}"),
499 Self::Unknown { len } => {
500 write!(f, "a name the format does not define ({len} characters)")
501 }
502 Self::AlgId(id) => write!(f, "{id:#010x}"),
503 Self::Fixed(s) => f.write_str(s),
504 }
505 }
506}
507
508#[derive(Debug, Clone, Copy, PartialEq, Eq)]
512#[non_exhaustive]
513pub enum KnownAlgorithm {
514 Md5,
516 Md4,
518 Md2,
520 Ripemd128,
522 Ripemd160,
524 Whirlpool,
526 Rc2,
528 Rc4,
530 Des,
532 Desx,
534 TripleDes,
536 TripleDes112,
538 ChainingModeCfb,
540}
541
542impl KnownAlgorithm {
543 const ALL: [KnownAlgorithm; 13] = [
544 Self::Md5,
545 Self::Md4,
546 Self::Md2,
547 Self::Ripemd128,
548 Self::Ripemd160,
549 Self::Whirlpool,
550 Self::Rc2,
551 Self::Rc4,
552 Self::Des,
553 Self::Desx,
554 Self::TripleDes,
555 Self::TripleDes112,
556 Self::ChainingModeCfb,
557 ];
558
559 pub fn spelling(self) -> &'static str {
561 match self {
562 Self::Md5 => "MD5",
563 Self::Md4 => "MD4",
564 Self::Md2 => "MD2",
565 Self::Ripemd128 => "RIPEMD-128",
566 Self::Ripemd160 => "RIPEMD-160",
567 Self::Whirlpool => "WHIRLPOOL",
568 Self::Rc2 => "RC2",
569 Self::Rc4 => "RC4",
570 Self::Des => "DES",
571 Self::Desx => "DESX",
572 Self::TripleDes => "3DES",
573 Self::TripleDes112 => "3DES_112",
574 Self::ChainingModeCfb => "ChainingModeCFB",
575 }
576 }
577}
578
579impl core::fmt::Display for KnownAlgorithm {
580 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
581 f.write_str(self.spelling())
582 }
583}
584
585pub(crate) fn algorithm_name(spelled: &str) -> AlgorithmName {
589 KnownAlgorithm::ALL
590 .into_iter()
591 .find(|k| k.spelling() == spelled)
592 .map_or_else(
593 || AlgorithmName::Unknown {
594 len: u32::try_from(spelled.chars().count()).unwrap_or(u32::MAX),
595 },
596 AlgorithmName::Known,
597 )
598}
599
600pub(crate) fn wide<T: TryInto<u64>>(n: T) -> u64 {
603 n.try_into().unwrap_or(u64::MAX)
604}
605
606pub(crate) fn bad(field: FileField, problem: FileProblem) -> crate::Error {
608 crate::Error::BadParameters { field, problem }
609}