Skip to main content

msoffice_crypto/
classify.rs

1#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
2//! Answer what encryption a byte stream declares, without decrypting anything.
3//!
4//! [`classify()`] is the first thing a caller runs on a file it has not vetted, so it is
5//! built to the one property that matters in that position: **it cannot panic and it
6//! cannot fail**. Every unreadable shape — a truncated container, a corrupt directory
7//! tree, XML that does not parse, an attribute that is not a number — collapses into
8//! `Unknown` rather than an error or an unwind. A caller gets a verdict for every input.
9//!
10//! It also needs **no cryptographic dependency**: reading `EncryptionInfo` is a CFB open
11//! plus an XML or binary-header parse. That is why the crate's `crypto-ops` feature is
12//! off by default — `cargo add msoffice-crypto` installs detection, and only a consumer
13//! that actually decrypts pays for `aes`, `cbc`, `ecb`, `sha1`, `sha2` and `hmac`.
14//!
15//! # Design commitment D1 — classify carries the integrity claim
16//!
17//! The sibling crate `odf-crypto`'s `classify` answers "encrypted? which algorithm
18//! tuple?". This one answers a third question: **does the file declare a
19//! `<dataIntegrity>` element?** ([`IntegrityDeclaration`]). That is what lets a caller
20//! choose `IntegrityPolicy::Require` knowingly instead of discovering after the
21//! fact that there was nothing to verify. See the foundation plan's D1.
22//!
23//! # The two agile parameter sets are reported separately
24//!
25//! `<keyData>` and `<p:encryptedKey>` each carry their own `cipherAlgorithm`,
26//! `hashAlgorithm`, `keyBits`, `blockSize` and `saltSize`. [MS-OFFCRYPTO] §2.3.4.10
27//! constrains two of those five: a writer's `PasswordKeyEncryptor` `hashAlgorithm` and
28//! `cipherAlgorithm` "MUST be the same as" `Encryption.keyData`'s. The other three —
29//! `keyBits`, `blockSize`, `saltSize` — carry no such rule and legitimately differ.
30//!
31//! A *reader* gets no guarantee from a writer's MUST, and Office writes all five
32//! identically, which is exactly what hides a crossed-parameter bug in any round trip
33//! against your own writer — this crate shipped exactly that bug once, where the package
34//! IVs were derived from the wrong element's parameters and every round trip still
35//! passed. So [`Classification::key_data`] and
36//! [`Classification::password_key`] are two fields, not one merged tuple, and a caller
37//! can see when a file disagrees with itself.
38
39use quick_xml::{events::Event, Reader};
40
41use crate::binary_office;
42use crate::cfb_reader;
43use crate::data_space_map;
44use std::io::{Cursor, Read, Seek, SeekFrom};
45
46/// The container [`classify()`] found the bytes wrapped in.
47///
48/// An Office file encrypted with a password is a CFB container whose `EncryptedPackage`
49/// stream holds the original ZIP; an unencrypted `.docx`/`.xlsx`/`.pptx` is the ZIP
50/// itself. Anything else is [`Container::Unknown`]. Both containers are decided on their
51/// magic alone, so a CFB or ZIP whose header is present is reported as that container
52/// even when nothing inside it can be read — what could not be read shows up in
53/// [`Classification::family`], not here.
54///
55/// # Examples
56///
57/// ```
58/// use msoffice_crypto::{classify, Container};
59///
60/// assert_eq!(
61///     classify(include_bytes!("../tests/fixtures/agile_encrypted.docx")).container,
62///     Container::Cfb
63/// );
64/// assert_eq!(
65///     classify(include_bytes!("../tests/fixtures/plain.docx")).container,
66///     Container::Zip
67/// );
68/// assert_eq!(classify(b"not a file").container, Container::Unknown);
69/// ```
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71#[non_exhaustive]
72pub enum Container {
73    /// Compound Binary File — magic `D0 CF 11 E0 A1 B1 1A E1`. What Office produces
74    /// when a document is encrypted with a password.
75    Cfb,
76    /// A ZIP archive — magic `PK\x03\x04` (also `PK\x05\x06` for an empty archive and
77    /// `PK\x07\x08` for a spanned one). An unencrypted OOXML package looks like this.
78    Zip,
79    /// Neither, or too short to tell.
80    Unknown,
81}
82
83/// Which application format a container holds.
84///
85/// Orthogonal to [`Container`] and to [`Family`]: an encrypted `.docx` and an encrypted
86/// `.doc` are both [`Container::Cfb`], and both can carry RC4 CryptoAPI, but they are
87/// entirely different formats inside and only one of them this crate can read. Without
88/// this a caller cannot tell those two apart, which is the difference between
89/// "encrypted Word 97-2003 document, unsupported" and "unknown".
90///
91/// # Examples
92///
93/// ```
94/// use msoffice_crypto::{classify, Document};
95///
96/// // A plain package is a ZIP this crate did not open, and says so.
97/// assert_eq!(
98///     classify(include_bytes!("../tests/fixtures/plain.docx")).document,
99///     Document::ZipArchive
100/// );
101/// // Inside an ECMA-376 container the claim is the format's, so it is made.
102/// assert_eq!(
103///     classify(include_bytes!("../tests/fixtures/agile_encrypted.docx")).document,
104///     Document::OoxmlPackage
105/// );
106/// assert_eq!(classify(b"????").document, Document::Unknown);
107/// ```
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109#[non_exhaustive]
110pub enum Document {
111    /// An OOXML package — `.docx` / `.xlsx` / `.pptx` and their macro-enabled and binary
112    /// (`.xlsb`) siblings — wrapped in a CFB by ECMA-376 encryption.
113    ///
114    /// **Only ever reported for a CFB container**, where the container was opened and an
115    /// `EncryptionInfo` stream read: ECMA-376 encryption wraps a package by definition, so
116    /// the claim is the format's rather than this crate's guess. A plain archive is
117    /// [`Document::ZipArchive`] — see that variant for why the two are not the same fact.
118    OoxmlPackage,
119    /// A ZIP archive whose contents were **not examined**.
120    ///
121    /// Reported for every plain `PK` signature this crate knows, and it is deliberately
122    /// not [`Document::OoxmlPackage`]: the decision is four bytes of magic, no entry is
123    /// read, and no content type is looked at. A `.docx`, a `.vsdx`, an `.odt`, a `.jar`
124    /// and a backup archive are indistinguishable here, which is the honest report of
125    /// what was checked.
126    ///
127    /// This crate holds [`Classification::is_encrypted`] to "nothing determined is not a
128    /// claim the file is plain"; naming a plain ZIP an OOXML package would have been the
129    /// same principle abandoned on the other side — an affirmative claim about a format
130    /// from a test that never looked at one. A caller that needs "is this really a Word
131    /// document" must read `[Content_Types].xml` or the root relationship itself; there is
132    /// no shortcut here, and pretending otherwise is what this variant exists to stop.
133    ZipArchive,
134    /// Word 97-2003 binary (`.doc`).
135    WordBinary,
136    /// Excel 97-2003 binary (`.xls`).
137    ExcelBinary,
138    /// PowerPoint 97-2003 binary (`.ppt`).
139    PowerPointBinary,
140    /// Word 6.0/95 binary (`.doc`): a `WordDocument` stream whose FIB's `nFib` is 0x0065
141    /// to 0x0069. Word 97 and later write 0x00C1; Word 6.0 wrote 0x0065 to 0x0068 and
142    /// Word 95 0x0069 (LibreOffice's reader, `sw/source/filter/ww8/ww8scan.cxx:5862-5876`,
143    /// MPL, behaviour only). Its layout and its encryption are not the ones [MS-DOC]
144    /// describes, and `decrypt_binary_office` refuses it by name.
145    ///
146    /// Until 0.1.0-rc.6 such a file was [`Document::WordBinary`].
147    Word95Binary,
148    /// Excel 5.0/95 binary (`.xls`): a BIFF5 workbook, in a `Book` stream rather than
149    /// BIFF8's `Workbook`. Refused by `decrypt_binary_office` by name.
150    ///
151    /// Until 0.1.0-rc.6 such a file was [`Document::ExcelBinary`].
152    Excel95Binary,
153    /// Not recognised.
154    Unknown,
155}
156
157/// Which MS-OFFCRYPTO encryption family the `EncryptionInfo` version pair names.
158///
159/// The pair alone does not always settle it: `vMinor = 2` covers **both** ECMA-376
160/// standard (AES) encryption and RC4 CryptoAPI, and the discriminator is the
161/// `fAES` bit of `EncryptionHeader.Flags` ([MS-OFFCRYPTO] §2.3.1).
162///
163/// # Examples
164///
165/// ```
166/// use msoffice_crypto::{classify, Family};
167///
168/// assert_eq!(
169///     classify(include_bytes!("../tests/fixtures/agile_encrypted.docx")).family,
170///     Family::Agile
171/// );
172/// assert_eq!(
173///     classify(include_bytes!("../tests/fixtures/plain.docx")).family,
174///     Family::Unencrypted
175/// );
176/// ```
177///
178/// # See Also
179///
180/// [`Classification::is_encrypted`] and [`Classification::is_supported`] are the
181/// predicates built on this enum.
182#[derive(Debug, Clone, Copy, PartialEq, Eq)]
183#[non_exhaustive]
184pub enum Family {
185    /// Not Office-encrypted: a plain ZIP package, or a container whose own records
186    /// *prove* there is no password — a `.doc` with `fEncrypted` clear, a workbook that
187    /// reads a must-be-encrypted record in the clear, a presentation whose `UserEditAtom`
188    /// is the unencrypted shape.
189    ///
190    /// A container this crate recognises but cannot read to a verdict is
191    /// [`Family::Unknown`], never this: saying "unencrypted" without the proof would be a
192    /// guess in the attacker's favour.
193    Unencrypted,
194    /// ECMA-376 agile encryption, `vMajor = 4`, `vMinor = 4`. Office 2010 and later.
195    Agile,
196    /// ECMA-376 standard encryption, `vMajor` 2/3/4 with `vMinor = 2` and `fAES` set.
197    /// Office 2007.
198    Standard,
199    /// RC4 CryptoAPI — the same `vMinor = 2` version pair with `fAES` **clear**
200    /// ([MS-OFFCRYPTO] §2.3.5). Office XP/2003's password-to-open for the binary
201    /// formats, and what Office 16 still writes into a `.doc`, `.xls` or `.ppt`.
202    /// Decrypted by `decrypt_binary_office` under the `legacy-binary` feature when the
203    /// document is one of those three; an `EncryptionInfo` container declaring it is
204    /// recognised and refused.
205    Rc4CryptoApi,
206    /// Office binary document RC4 encryption — version `1.1`, MD5, "Office 97/2000
207    /// Compatible" ([MS-OFFCRYPTO] §2.3.6). Binary documents only; decrypted under
208    /// `legacy-binary`.
209    Rc4,
210    /// XOR obfuscation ([MS-OFFCRYPTO] §2.3.7): a `.xls` whose `FILEPASS` declares
211    /// `wEncryptionType = 0`, or a `.doc` with `fObfuscated` set. A distinct scheme, not a
212    /// weak RC4. The Excel form is decrypted under `legacy-binary`; the Word form
213    /// (Method 2) is named and refused.
214    XorObfuscation,
215    /// The file **is** encrypted and this crate will not open it. Four unrelated
216    /// conditions arrive here, and they do not share a remedy.
217    ///
218    /// Reached by: an `EncryptionInfo` whose version pair names a family this crate does
219    /// not implement — extensible encryption, and equally any pair the spec never
220    /// defined; a `vMinor = 2` stream whose `AlgID` names no cipher this crate
221    /// recognises with `fAES` clear, or whose `EncryptionHeader` is too short to read;
222    /// and a binary document that declares encryption without a header this crate can
223    /// read.
224    ///
225    /// # What [`Classification::version`] does and does not tell you
226    ///
227    /// Written as properties of the field rather than as a list of cases, because a
228    /// fifth condition would invalidate a list and these three survive it.
229    ///
230    /// **Presence carries no information about readability.** It is tempting to read
231    /// `version.is_none()` as "the header could not be read", and it is wrong in both
232    /// directions. An unrecognised `AlgID` is reached *after* a well-formed header has
233    /// been parsed, so `version` is reliably `Some` there — the very case that reading
234    /// would be looking for. And a binary document that declares encryption reaches this
235    /// variant through a catch-all that takes `Some(pair)` as readily as `None`, so a
236    /// `FILEPASS` naming `(5, 5)` arrives with a version present.
237    ///
238    /// **The agile/standard path's catch-all swallows every pair but two.** Anything that
239    /// is not `(4, 4)` or `(2..=4, 2)` lands here, so extensible encryption and a
240    /// corrupted version field are *indistinguishable by having reached this variant*.
241    /// They are distinguishable by the pair itself.
242    ///
243    /// **Extensible encryption is `(3, 3)` and `(4, 3)`, both halves pinned.**
244    /// [MS-OFFCRYPTO] §2.3.4.6: "Version.vMajor MUST be 0x0003 or 0x0004 and
245    /// Version.vMinor MUST be 0x0003." Match the pairs, not `minor == 3` — a file
246    /// declaring `(7, 3)` is non-conforming, and calling it rights-managed tells its
247    /// holder that no tool will ever open it, which is a confident claim about a
248    /// malformed header. This matters because the remedy differs more than the cause
249    /// does: extensible encryption keeps its key on a rights server, so *no* offline
250    /// implementation opens it, ever, and that is a property of the format rather than a
251    /// gap here.
252    ///
253    /// **An unrecognised `AlgID` has no marker of its own.** Its signature is this
254    /// variant, a recognised version pair, and `key_data`'s `cipher` being `None` — an
255    /// inference across two fields rather than a discriminator. Stated as a limitation
256    /// rather than dressed up: if telling it apart matters to a caller, the honest fix is
257    /// a distinction in this enum, and that case should be made rather than worked
258    /// around.
259    ///
260    /// Written because two readers have now needed this decomposition and derived it from
261    /// the source: this crate's own CLI, and a downstream consumer writing refusal copy
262    /// who reached for `version.is_none()` and would have shipped two wrong sentences.
263    Unsupported,
264    /// Information Rights Management ([MS-OFFCRYPTO] §2.2): the content is encrypted
265    /// under a rights-management policy whose key a rights-management server holds. No
266    /// password opens it, so no offline implementation does, and that is the format's
267    /// property rather than a gap here.
268    ///
269    /// Reported for an OOXML package under the `DRMEncryptedDataSpace` data space, and for
270    /// a `.doc`, `.xls` or `.ppt` whose real content is in a `\x09DRMContent` stream. The
271    /// second kind carries an **unencrypted placeholder document** beside it, so before
272    /// 0.1.0-rc.6 it classified as [`Family::Unencrypted`] — the claim this variant
273    /// exists to stop. Neither decrypt function opens either kind; both refuse by name.
274    Irm,
275    /// Nothing could be determined — not a container this crate reads, or one whose
276    /// `EncryptionInfo` stream is missing, truncated or unparsable.
277    Unknown,
278}
279
280/// The cipher a file names for its payload.
281///
282/// Reported as `Option<CipherAlgorithm>`: `None` means the attribute or field was
283/// absent, or named something this crate does not recognise. A classifier that
284/// invented a value for either case would be worse than one that says "I could not
285/// tell".
286///
287/// # Examples
288///
289/// ```
290/// use msoffice_crypto::{classify, CipherAlgorithm};
291///
292/// let class = classify(include_bytes!("../tests/fixtures/agile_encrypted.docx"));
293/// assert_eq!(class.key_data.unwrap().cipher, Some(CipherAlgorithm::Aes));
294/// ```
295#[derive(Debug, Clone, Copy, PartialEq, Eq)]
296#[non_exhaustive]
297pub enum CipherAlgorithm {
298    /// Agile `cipherAlgorithm="AES"`, or a standard-encryption header with `fAES` set
299    /// or an `AlgID` in the AES range.
300    Aes,
301    /// RC4 — `AlgID = 0x00006801` with `fAES` clear ([MS-OFFCRYPTO] §2.3.2).
302    Rc4,
303}
304
305/// The hash a file names.
306///
307/// This is the same enum the decrypt path runs on (`hash.rs` adds the digest, HMAC and
308/// IV-derivation operations to it under the `crypto-ops` feature), so there is one
309/// spelling table rather than a reporting copy that can drift from an operational one.
310///
311/// Reported as `Option<HashAlgorithm>`, with `None` meaning absent **or** not one of the
312/// four this crate implements.
313///
314/// # Examples
315///
316/// ```
317/// use msoffice_crypto::{classify, HashAlgorithm};
318///
319/// let class = classify(include_bytes!("../tests/fixtures/agile_encrypted.docx"));
320/// assert_eq!(class.key_data.unwrap().hash, Some(HashAlgorithm::Sha512));
321/// ```
322#[derive(Debug, Clone, Copy, PartialEq, Eq)]
323#[non_exhaustive]
324pub enum HashAlgorithm {
325    /// SHA-1, 20-byte digest.
326    Sha1,
327    /// SHA-256, 32-byte digest.
328    Sha256,
329    /// SHA-384, 48-byte digest.
330    Sha384,
331    /// SHA-512, 64-byte digest. What Office 16 writes for agile.
332    Sha512,
333}
334
335impl HashAlgorithm {
336    /// Office writes `SHA512`; the hyphenated spelling is accepted defensively.
337    pub(crate) fn parse(name: &str) -> Option<Self> {
338        match name {
339            "SHA1" | "SHA-1" => Some(Self::Sha1),
340            "SHA256" | "SHA-256" => Some(Self::Sha256),
341            "SHA384" | "SHA-384" => Some(Self::Sha384),
342            "SHA512" | "SHA-512" => Some(Self::Sha512),
343            _ => None,
344        }
345    }
346}
347
348/// One parameter set, as the file declares it.
349///
350/// Every field is `Option` because every one of them is optional in at least one of the
351/// two formats: agile writes all six on `<p:encryptedKey>` and five on `<keyData>`
352/// (no `spinCount`), while standard encryption declares a cipher, a hash, a key length
353/// and a salt size, and fixes the remaining two by spec — AES-ECB has no `blockSize`, and
354/// [MS-OFFCRYPTO] §2.3.4.7 fixes the spin count at 50 000 rather than carrying it in the
355/// file.
356///
357/// The numbers are reported **unbounded and unvalidated** — `spin_count` may be
358/// `u32::MAX`, `key_bits` may be 7. Bounding them is `decrypt`'s job
359/// (`crate::limits`); a classifier that refused to report a hostile value would leave
360/// its caller unable to see what it was refusing.
361///
362/// # Examples
363///
364/// ```
365/// use msoffice_crypto::classify;
366///
367/// let class = classify(include_bytes!("../tests/fixtures/agile_encrypted.docx"));
368/// let password = class.password_key.expect("agile files declare a password encryptor");
369/// assert_eq!(password.spin_count, Some(100_000));
370/// assert_eq!(password.key_bits, Some(256));
371/// ```
372#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
373#[non_exhaustive]
374pub struct AlgorithmParams {
375    /// `cipherAlgorithm`, or standard encryption's `AlgID` + `fAES`.
376    pub cipher: Option<CipherAlgorithm>,
377    /// `hashAlgorithm`, or standard encryption's `AlgIDHash`.
378    pub hash: Option<HashAlgorithm>,
379    /// `keyBits`, or standard encryption's `EncryptionHeader.KeySize`.
380    pub key_bits: Option<u32>,
381    /// `blockSize` — the cipher block / IV truncation length. Agile only: standard
382    /// encryption is AES-ECB and declares no block size field.
383    pub block_size: Option<u32>,
384    /// `saltSize`, or standard encryption's `EncryptionVerifier.SaltSize`.
385    pub salt_size: Option<u32>,
386    /// `spinCount` — the password KDF iteration count. Agile `<p:encryptedKey>` only:
387    /// `<keyData>` has no such attribute, and standard encryption fixes it at 50 000 by
388    /// spec rather than declaring it.
389    pub spin_count: Option<u32>,
390}
391
392/// Whether the file declares a `dataIntegrity` element (design commitment D1).
393///
394/// This is the pre-flight answer to "will `IntegrityPolicy::Require` work on
395/// this file?" — the after-the-fact answer is `IntegrityOutcome`, which reports
396/// what actually happened during a decrypt. Those two names exist only under
397/// `crypto-ops`, so they are not linked from this page.
398///
399/// # Examples
400///
401/// ```
402/// use msoffice_crypto::{classify, IntegrityDeclaration};
403///
404/// assert_eq!(
405///     classify(include_bytes!("../tests/fixtures/agile_encrypted.docx")).data_integrity,
406///     IntegrityDeclaration::Declared
407/// );
408/// assert_eq!(
409///     classify(include_bytes!("../tests/fixtures/plain.docx")).data_integrity,
410///     IntegrityDeclaration::NotApplicable
411/// );
412/// ```
413#[derive(Debug, Clone, Copy, PartialEq, Eq)]
414#[non_exhaustive]
415pub enum IntegrityDeclaration {
416    /// `<dataIntegrity>` is present and carries both `encryptedHmacKey` and
417    /// `encryptedHmacValue`. `Require` will verify it.
418    Declared,
419    /// `<dataIntegrity>` is present but one of the two blobs is missing. `decrypt`
420    /// refuses this with `Error::BadParameters` (a `crypto-ops` type, so not linked from this doc, which renders in every build): a half-written
421    /// element is malformed, not absent. Collapsing the two would report a corrupt tag
422    /// as a *stripped* one under the default policy, and under the explicitly chosen
423    /// `VerifyIfPresent` and `Skip` policies would decrypt the file and call it
424    /// `NotDeclared`.
425    Incomplete,
426    /// An agile file that declares no `<dataIntegrity>` element.
427    ///
428    /// **`decrypt` refuses this under the default policy** (GH #12). No agile writer
429    /// surveyed omits the element and no file in any local corpus lacks it, so absence
430    /// reads as a stripped or malformed file rather than an old one — accepting it by
431    /// default would let an attacker disable tamper detection by deleting the thing that
432    /// detects tampering. Only the explicitly chosen `VerifyIfPresent` and `Skip`
433    /// policies decrypt it, and this variant is the pre-flight warning that one of them
434    /// will be needed.
435    Absent,
436    /// The format defines no integrity element at all — ECMA-376 standard encryption
437    /// ([MS-OFFCRYPTO] §2.3.4.5), RC4 CryptoAPI (§2.3.5), Office 97/2000 RC4 (§2.3.6),
438    /// XOR obfuscation (§2.3.7) — or the file is not encrypted. Absence here is the spec,
439    /// not a defect.
440    NotApplicable,
441    /// Could not be determined, because nothing about the encryption could be.
442    Unknown,
443}
444
445/// Whether the container's own directory could be read from the bytes supplied.
446///
447/// The fact this crate can establish, and no more. A CFB container names its directory
448/// and FAT by sector offset, so a caller handed the first few kilobytes of a file has a
449/// recognisable signature and an unreachable directory — and every field downstream of it
450/// then reports `Unknown`, which is indistinguishable from a genuinely unrecognisable
451/// file unless something says which happened.
452///
453/// **This is the difference between "I looked and found nothing" and "I could not
454/// look."** A dispatcher that matches [`Family::Agile`] and falls through on anything else
455/// takes no arm in both cases, silently, and for a prefix that is the wrong answer rather
456/// than a missing one.
457///
458/// Named for what was observed rather than what caused it: a directory outside the
459/// supplied bytes is equally a truncation, a prefix, and a corrupt header that points
460/// past the end. This crate cannot tell those apart and does not claim to.
461///
462/// # Examples
463///
464/// ```
465/// use msoffice_crypto::{classify, ContainerRead, Family};
466///
467/// let whole = include_bytes!("../tests/fixtures/agile_encrypted.docx");
468/// assert_eq!(classify(whole).container_read, ContainerRead::Opened);
469///
470/// // The same file's first 128 bytes: still recognisably a CFB, nothing readable in it.
471/// let prefix = classify(&whole[..128]);
472/// assert_eq!(prefix.family, Family::Unknown);
473/// assert_eq!(prefix.container_read, ContainerRead::Unreadable);
474///
475/// // A ZIP is identified by signature alone, so nothing was opened to begin with.
476/// assert_eq!(
477///     classify(include_bytes!("../tests/fixtures/plain.docx")).container_read,
478///     ContainerRead::NotAttempted
479/// );
480/// ```
481#[derive(Debug, Clone, Copy, PartialEq, Eq)]
482#[non_exhaustive]
483pub enum ContainerRead {
484    /// The container was opened and its directory read. Every other field of the
485    /// [`Classification`] describes bytes this crate actually reached.
486    Opened,
487    /// The container's signature matched but it could not be opened from these bytes:
488    /// its directory or FAT lies outside them, or contradicts them.
489    ///
490    /// **A prefix of a longer file reaches this**, and so does a corrupt or truncated
491    /// container. Re-read with the whole file before believing any other field.
492    Unreadable,
493    /// Nothing was opened, so nothing failed. Either no container was recognised at all
494    /// ([`Container::Unknown`]), or the container is identified by signature alone and
495    /// this crate does not open it ([`Container::Zip`], whose entries it never reads —
496    /// see [`Document::ZipArchive`]).
497    NotAttempted,
498}
499
500/// What [`classify()`] found. Never an error: an unreadable file is `Unknown`, not a
501/// failure.
502///
503/// # Examples
504///
505/// ```
506/// use msoffice_crypto::{classify, Container, Family, IntegrityDeclaration};
507///
508/// let class = classify(b"not an office file at all");
509/// assert_eq!(class.container, Container::Unknown);
510/// assert_eq!(class.family, Family::Unknown);
511/// assert_eq!(class.data_integrity, IntegrityDeclaration::Unknown);
512/// assert!(!class.is_encrypted());
513/// ```
514#[derive(Debug, Clone, Copy, PartialEq, Eq)]
515#[non_exhaustive]
516pub struct Classification {
517    /// The container shape.
518    pub container: Container,
519    /// The application format inside the container.
520    pub document: Document,
521    /// `EncryptionVersionInfo` as `(vMajor, vMinor)`: from the `EncryptionInfo` stream
522    /// when one is present and at least 8 bytes long, and from the binary formats' own
523    /// CryptoAPI `EncryptionHeader` for a `.doc` / `.xls` / `.ppt`, which carry no such
524    /// stream. `None` when neither could be read, and for the schemes that predate the
525    /// header — XOR obfuscation names no version.
526    pub version: Option<(u16, u16)>,
527    /// The encryption family the version pair — and, for `vMinor = 2`, the `fAES` flag —
528    /// names.
529    pub family: Family,
530    /// Parameters governing the **payload**: agile `<keyData>`, standard encryption's
531    /// `EncryptionHeader` plus `EncryptionVerifier.SaltSize`, or — for a 97-2003 binary
532    /// document — the `keyBits` its CryptoAPI `EncryptionHeader` exposes, which is the
533    /// only member of the tuple those formats give up without decrypting. The rest stay
534    /// `None` rather than being invented.
535    pub key_data: Option<AlgorithmParams>,
536    /// Parameters governing the **password key encryptor**: agile `<p:encryptedKey>`.
537    /// `None` for standard encryption, which has a single parameter set.
538    pub password_key: Option<AlgorithmParams>,
539    /// Whether a `dataIntegrity` element is declared (D1).
540    pub data_integrity: IntegrityDeclaration,
541    /// Whether the container's directory could be read from the bytes supplied.
542    ///
543    /// Read this before trusting a `Unknown` in any field above it:
544    /// [`ContainerRead::Unreadable`] means the bytes were too few or too damaged to look
545    /// inside, which is a different fact from having looked and found nothing.
546    pub container_read: ContainerRead,
547}
548
549impl Classification {
550    /// `true` when the file declares a password-to-open — an `EncryptionInfo` stream, or
551    /// a 97-2003 binary document's own encryption marker — including a family this crate
552    /// cannot decrypt.
553    ///
554    /// `false` also covers "nothing could be determined": an `EncryptionInfo` too short to
555    /// hold a version pair leaves [`Family::Unknown`], which is not a claim that the file
556    /// is plain.
557    ///
558    /// Deliberately not "can I decrypt this": see [`Classification::is_supported`].
559    ///
560    /// # Examples
561    ///
562    /// ```
563    /// use msoffice_crypto::classify;
564    ///
565    /// assert!(classify(include_bytes!("../tests/fixtures/agile_encrypted.docx")).is_encrypted());
566    /// assert!(!classify(include_bytes!("../tests/fixtures/plain.docx")).is_encrypted());
567    /// ```
568    #[must_use]
569    pub fn is_encrypted(&self) -> bool {
570        matches!(
571            self.family,
572            Family::Agile
573                | Family::Standard
574                | Family::Rc4CryptoApi
575                | Family::Rc4
576                | Family::XorObfuscation
577                | Family::Unsupported
578                | Family::Irm
579        )
580    }
581
582    /// `true` when a decrypt path of this crate implements the (document, family) pair —
583    /// `decrypt_ooxml` for an OOXML package under `crypto-ops`, `decrypt_binary_office`
584    /// for a `.doc`, `.xls` or `.ppt` under `legacy-binary`. In a build without the
585    /// feature this still answers, and describes what enabling it would open.
586    ///
587    /// Says nothing about whether the *parameters* are ones this crate accepts:
588    /// a legal agile file with a `spinCount` over the ceiling classifies as
589    /// [`Family::Agile`], reports `true` here, and is refused at decrypt. Family-level,
590    /// not tuple-level, by design — the tuple is in [`Classification::key_data`]. The
591    /// document matters because the same family means different things in different
592    /// containers: an `EncryptionInfo` stream naming RC4 CryptoAPI is refused, a `.doc`
593    /// carrying it is read, and XOR obfuscation is read in a `.xls` and refused in a
594    /// `.doc`.
595    ///
596    /// # Examples
597    ///
598    /// ```
599    /// use msoffice_crypto::classify;
600    ///
601    /// assert!(classify(include_bytes!("../tests/fixtures/agile_encrypted.docx")).is_supported());
602    /// assert!(!classify(include_bytes!("../tests/fixtures/plain.docx")).is_supported());
603    /// ```
604    #[must_use]
605    pub fn is_supported(&self) -> bool {
606        matches!(
607            (self.document, self.family),
608            (Document::OoxmlPackage, Family::Agile | Family::Standard)
609                | (
610                    Document::WordBinary | Document::ExcelBinary | Document::PowerPointBinary,
611                    Family::Rc4CryptoApi | Family::Rc4,
612                )
613                | (Document::ExcelBinary, Family::XorObfuscation)
614        )
615    }
616}
617
618/// Report what encryption `data` declares, without decrypting it.
619///
620/// Reads the `EncryptionInfo` stream (capped at `limits::ENCRYPTION_INFO_READ_CAP`) and,
621/// for a CFB that carries none, the 97-2003 binary streams the probe needs —
622/// `/WordDocument` and its table stream at `limits::BINARY_HEADER_READ_CAP`, the workbook
623/// at `limits::BIFF_SCAN_CAP`, `/Current User` at `limits::CURRENT_USER_READ_CAP`, and a
624/// bounded walk of `/PowerPoint Document`. Every read is capped and the `EncryptedPackage`
625/// payload is never touched. Needs no cryptographic dependency and is available in the
626/// default build.
627///
628/// **This function does not panic and does not fail.** Truncated, corrupt, hostile and
629/// empty inputs all produce a [`Classification`] whose unreadable parts are `Unknown` or
630/// `None`. That is the single property that makes it safe as the first thing a caller
631/// runs on a file from outside.
632///
633/// # Examples
634///
635/// A real agile-encrypted document:
636///
637/// ```
638/// use msoffice_crypto::{classify, CipherAlgorithm, Container, Family,
639///                       HashAlgorithm, IntegrityDeclaration};
640///
641/// let bytes = include_bytes!("../tests/fixtures/agile_encrypted.docx");
642/// let class = classify(bytes);
643///
644/// assert_eq!(class.container, Container::Cfb);
645/// assert_eq!(class.version, Some((4, 4)));
646/// assert_eq!(class.family, Family::Agile);
647/// assert_eq!(class.data_integrity, IntegrityDeclaration::Declared);
648///
649/// let key_data = class.key_data.expect("agile files declare <keyData>");
650/// assert_eq!(key_data.cipher, Some(CipherAlgorithm::Aes));
651/// assert_eq!(key_data.hash, Some(HashAlgorithm::Sha512));
652/// assert_eq!(key_data.key_bits, Some(256));
653///
654/// let password = class.password_key.expect("…and a password key encryptor");
655/// assert_eq!(password.spin_count, Some(100_000));
656/// ```
657///
658/// An unencrypted package:
659///
660/// ```
661/// use msoffice_crypto::{classify, Container, Family, IntegrityDeclaration};
662///
663/// let class = classify(include_bytes!("../tests/fixtures/plain.docx"));
664/// assert_eq!(class.container, Container::Zip);
665/// assert_eq!(class.family, Family::Unencrypted);
666/// assert_eq!(class.data_integrity, IntegrityDeclaration::NotApplicable);
667/// assert!(!class.is_encrypted());
668/// ```
669///
670/// # See Also
671///
672/// [`crate::is_cfb_office`] is the cheaper magic-byte check.
673/// [`Classification::is_supported`] is whether a decrypt path of this crate implements
674/// the pair; that is not a promise the parameters will be accepted.
675#[must_use]
676pub fn classify(data: &[u8]) -> Classification {
677    classify_from(Cursor::new(data))
678}
679
680/// [`classify()`] from a reader, reading only what classification needs.
681///
682/// For a ZIP that is four bytes. For a CFB container it is the header, the FAT and
683/// directory, and the few streams the verdict rests on (`EncryptionInfo`, the
684/// `\x06DataSpaces\DataSpaceMap`, a binary format's header records), each under the read
685/// cap `classify` already applies, and never `\EncryptedPackage`. So a caller classifying
686/// a large file before deciding what to do with it no longer has to read the whole file
687/// into memory first, which `classify(&[u8])` made it do. The answer is identical to
688/// `classify()` on the same bytes, because `classify()` *is* this over a `Cursor`.
689///
690/// **Never fails loudly**, like `classify()`. A reader that errors part-way is reported
691/// the way an unreadable file is, [`ContainerRead::Unreadable`] with
692/// [`Document::Unknown`], because "could not look" is what it is. Where the reader is left
693/// positioned is unspecified.
694///
695/// ```
696/// use msoffice_crypto::{classify, classify_from, Family};
697/// use std::io::Cursor;
698///
699/// let bytes = include_bytes!("../tests/fixtures/agile_encrypted.docx");
700/// let class = classify_from(Cursor::new(&bytes[..]));
701/// assert_eq!(class.family, Family::Agile);
702/// assert_eq!(class, classify(bytes));
703/// ```
704#[must_use]
705pub fn classify_from<R: Read + Seek>(mut reader: R) -> Classification {
706    let mut magic = [0u8; 8];
707    let Ok(n) = reader
708        .seek(SeekFrom::Start(0))
709        .and_then(|_| cfb_reader::read_full(&mut reader, &mut magic))
710    else {
711        return unknown(Container::Unknown, ContainerRead::NotAttempted);
712    };
713    let head = magic.get(..n).unwrap_or_default();
714    if crate::is_cfb_office(head) {
715        if reader.seek(SeekFrom::Start(0)).is_err() {
716            return unknown(Container::Cfb, ContainerRead::Unreadable);
717        }
718        let Ok(reader) = cfb_reader::SeekBufReader::new(reader) else {
719            return unknown(Container::Cfb, ContainerRead::Unreadable);
720        };
721        return match cfb::CompoundFile::open(reader) {
722            Ok(mut cfb) => classify_cfb(&mut cfb),
723            Err(_) => unknown(Container::Cfb, ContainerRead::Unreadable),
724        };
725    }
726    if is_zip(head) {
727        return Classification {
728            container: Container::Zip,
729            // Four bytes of signature, and nothing inside the archive is read. See
730            // `Document::ZipArchive` for why this is not `OoxmlPackage`.
731            document: Document::ZipArchive,
732            version: None,
733            family: Family::Unencrypted,
734            key_data: None,
735            password_key: None,
736            data_integrity: IntegrityDeclaration::NotApplicable,
737            container_read: ContainerRead::NotAttempted,
738        };
739    }
740    unknown(Container::Unknown, ContainerRead::NotAttempted)
741}
742
743/// Everything-unreadable result for a container we could name but not read.
744fn unknown(container: Container, container_read: ContainerRead) -> Classification {
745    unknown_document(container, Document::Unknown, container_read)
746}
747
748/// `unknown`, for a container whose *format* was recognised even though its encryption
749/// was not. A legacy binary document reaches this: we know it is a `.doc`, which is
750/// strictly more than we knew before.
751fn unknown_document(
752    container: Container,
753    document: Document,
754    container_read: ContainerRead,
755) -> Classification {
756    Classification {
757        container,
758        document,
759        version: None,
760        family: Family::Unknown,
761        key_data: None,
762        password_key: None,
763        data_integrity: IntegrityDeclaration::Unknown,
764        container_read,
765    }
766}
767
768fn is_zip(data: &[u8]) -> bool {
769    data.len() >= 4
770        && data[0] == b'P'
771        && data[1] == b'K'
772        && matches!((data[2], data[3]), (3, 4) | (5, 6) | (7, 8))
773}
774
775fn classify_cfb<F: Read + Seek>(cfb: &mut cfb::CompoundFile<F>) -> Classification {
776    // Rights management first: neither kind is what the rest of this function would
777    // call it. An IRM package has no `EncryptionInfo`, and an IRM binary document carries
778    // a placeholder whose own markers say "unencrypted".
779    if let Some(kind) = data_space_map::rights_management_in(cfb) {
780        return classify_irm(cfb, kind);
781    }
782    // No `EncryptionInfo` does not mean "unreadable". The 97-2003 binary formats are CFB
783    // containers too and carry their encryption inside their own records, so ask them
784    // before giving up -- otherwise an encrypted `.doc` classifies identically to a
785    // corrupt file, which is the failure this crate made in GH #11 and LibreOffice makes
786    // on `.ppt` to this day.
787    // "The container would not open" and "it opened and the stream is missing or
788    // oversized" are different verdicts, and a 128-byte prefix of an agile file must not
789    // classify the same as sixteen bytes of junk. That distinction is made once, where
790    // `classify_from` opens the container and returns `Unreadable` if it cannot; by the
791    // time this runs the container is open, so any failure here means the stream, and
792    // the binary formats are the next thing to ask.
793    let Ok(info) = cfb_reader::read_encryption_info_in(cfb) else {
794        return classify_binary(cfb);
795    };
796    if info.len() < 8 {
797        return classify_binary(cfb);
798    }
799
800    let v_major = u16::from_le_bytes([info[0], info[1]]);
801    let v_minor = u16::from_le_bytes([info[2], info[3]]);
802    let version = Some((v_major, v_minor));
803
804    match (v_major, v_minor) {
805        (4, 4) => classify_agile(&info[8..], version),
806        (2..=4, 2) => classify_standard(&info[8..], version),
807        // Everything else carries an EncryptionInfo — so it *is* encrypted — but names a
808        // family this crate does not implement. Extensible encryption (vMajor 3 or 4 with
809        // vMinor = 3, [MS-OFFCRYPTO] §2.3.4.6) is the case that reaches this in the wild; its
810        // parameters live in a provider-defined blob rather than in fields this crate
811        // could report, so no tuple comes back with it.
812        _ => Classification {
813            container: Container::Cfb,
814            document: Document::OoxmlPackage,
815            version,
816            family: Family::Unsupported,
817            key_data: None,
818            password_key: None,
819            data_integrity: IntegrityDeclaration::Unknown,
820            container_read: ContainerRead::Opened,
821        },
822    }
823}
824
825/// A rights-managed container. The document is the format's claim for an ECMA-376 one,
826/// and whatever the placeholder beside the protected content is for a binary one.
827fn classify_irm<F: Read + Seek>(
828    cfb: &mut cfb::CompoundFile<F>,
829    kind: data_space_map::RightsManagement,
830) -> Classification {
831    let document = match kind {
832        data_space_map::RightsManagement::Ecma376 => Document::OoxmlPackage,
833        data_space_map::RightsManagement::Binary => binary_office::probe_in(cfb)
834            .map_or(Document::Unknown, |v| binary_document(v.format, v.pre_97)),
835    };
836    Classification {
837        container: Container::Cfb,
838        document,
839        version: None,
840        family: Family::Irm,
841        key_data: None,
842        password_key: None,
843        // The rights-management transform's integrity is not one this crate can see.
844        data_integrity: IntegrityDeclaration::Unknown,
845        container_read: ContainerRead::Opened,
846    }
847}
848
849/// The [`Document`] a binary format and edition are.
850fn binary_document(format: binary_office::BinaryFormat, pre_97: bool) -> Document {
851    match (format, pre_97) {
852        (binary_office::BinaryFormat::Word, false) => Document::WordBinary,
853        (binary_office::BinaryFormat::Word, true) => Document::Word95Binary,
854        (binary_office::BinaryFormat::Excel, false) => Document::ExcelBinary,
855        (binary_office::BinaryFormat::Excel, true) => Document::Excel95Binary,
856        (binary_office::BinaryFormat::PowerPoint, _) => Document::PowerPointBinary,
857    }
858}
859
860/// Classify a CFB container that carries no `EncryptionInfo`: a 97-2003 binary document,
861/// or something this crate does not recognise at all.
862///
863/// The families here are named for the *scheme*, and the `document` field for the
864/// *format*, because they vary independently: ECMA-376 standard encryption can also carry
865/// an RC4 AlgID, so `Family::Rc4CryptoApi` alone would not tell a `.doc` from a `.docx`.
866fn classify_binary<F: Read + Seek>(cfb: &mut cfb::CompoundFile<F>) -> Classification {
867    let Some(v) = binary_office::probe_in(cfb) else {
868        // The container opened -- `classify_cfb` returned above when it would not -- so
869        // this is "looked inside, recognised no format", not "could not look".
870        return unknown(Container::Cfb, ContainerRead::Opened);
871    };
872
873    let document = binary_document(v.format, v.pre_97);
874
875    let family = match (v.encrypted, v.xor_obfuscated, v.version) {
876        // Recognised the format, could not reach its encryption marker. Saying
877        // "unencrypted" here would be a guess in the attacker's favour.
878        (None, _, _) => Family::Unknown,
879        (Some(false), _, _) => Family::Unencrypted,
880        // XOR obfuscation is a distinct scheme, not a weak RC4.
881        (Some(true), true, _) => Family::XorObfuscation,
882        (Some(true), false, Some((2..=4, 2))) => Family::Rc4CryptoApi,
883        // Office 97/2000 RC4, version 1.1.
884        (Some(true), false, Some((1, 1))) => Family::Rc4,
885        // Anything else that claims to be encrypted without a version pair this crate
886        // can name -- including a PowerPoint file whose CryptSession10Container could
887        // not be reached, and a BIFF5 workbook whose FILEPASS has no version at all.
888        (Some(true), false, _) => Family::Unsupported,
889    };
890
891    Classification {
892        container: Container::Cfb,
893        document,
894        version: v.version,
895        // `key_bits` is the only parameter these formats expose without decrypting, and
896        // only the CryptoAPI-era header carries it. The rest of `AlgorithmParams` stays
897        // `None` rather than being invented.
898        key_data: v.key_bits.map(|bits| AlgorithmParams {
899            cipher: None,
900            hash: None,
901            key_bits: Some(bits),
902            block_size: None,
903            salt_size: None,
904            spin_count: None,
905        }),
906        family,
907        password_key: None,
908        // None of the binary formats defines an integrity element.
909        data_integrity: IntegrityDeclaration::NotApplicable,
910        container_read: ContainerRead::Opened,
911    }
912}
913
914// ---- agile ---------------------------------------------------------------------------
915
916/// Parse the agile `EncryptionInfo` XML for reporting only.
917///
918/// Deliberately far more forgiving than `agile::parse_encryption_info`: a missing
919/// attribute is a `None` field, a non-numeric one is a `None` field, and an XML error
920/// stops the scan and keeps whatever was already read. Nothing here can reject a file —
921/// rejecting is `decrypt`'s job, and a classifier that refused to describe a malformed
922/// file would be useless in exactly the case a caller most needs a description.
923fn classify_agile(xml: &[u8], version: Option<(u16, u16)>) -> Classification {
924    let mut key_data = AlgorithmParams::default();
925    let mut password_key = AlgorithmParams::default();
926    let mut saw_key_data = false;
927    let mut saw_password_key = false;
928    let mut saw_data_integrity = false;
929    let mut saw_hmac_key = false;
930    let mut saw_hmac_value = false;
931
932    let mut reader = Reader::from_reader(xml);
933    reader.config_mut().trim_text(true);
934    let mut buf = Vec::new();
935    loop {
936        match reader.read_event_into(&mut buf) {
937            Ok(Event::Start(ref e)) | Ok(Event::Empty(ref e)) => {
938                let name = e.name().as_ref().to_vec();
939                match local_name(&name) {
940                    b"keyData" => {
941                        saw_key_data = true;
942                        read_params(e, &mut key_data);
943                    }
944                    // Matched on the local name, so `<p:encryptedKey>` and a bare
945                    // `<encryptedKey>` both land here — as does a *certificate* key
946                    // encryptor's `<c:encryptedKey>`, which this crate cannot use. That
947                    // is a known looseness shared with `agile::parse_encryption_info`
948                    // and is recorded rather than fixed here: making the two parsers
949                    // disagree about which element they mean would be worse than the
950                    // looseness itself.
951                    b"encryptedKey" => {
952                        saw_password_key = true;
953                        read_params(e, &mut password_key);
954                    }
955                    b"dataIntegrity" => {
956                        saw_data_integrity = true;
957                        for attr in e.attributes().flatten() {
958                            match attr.key.as_ref() {
959                                b"encryptedHmacKey" => saw_hmac_key = true,
960                                b"encryptedHmacValue" => saw_hmac_value = true,
961                                _ => {}
962                            }
963                        }
964                    }
965                    _ => {}
966                }
967            }
968            // Stop on EOF *and* on a parse error, keeping whatever was read before it.
969            Ok(Event::Eof) | Err(_) => break,
970            _ => {}
971        }
972        buf.clear();
973    }
974
975    let data_integrity = match (saw_data_integrity, saw_hmac_key && saw_hmac_value) {
976        (true, true) => IntegrityDeclaration::Declared,
977        (true, false) => IntegrityDeclaration::Incomplete,
978        (false, _) => IntegrityDeclaration::Absent,
979    };
980
981    Classification {
982        container: Container::Cfb,
983        document: Document::OoxmlPackage,
984        version,
985        family: Family::Agile,
986        key_data: saw_key_data.then_some(key_data),
987        password_key: saw_password_key.then_some(password_key),
988        data_integrity,
989        container_read: ContainerRead::Opened,
990    }
991}
992
993fn read_params(e: &quick_xml::events::BytesStart<'_>, into: &mut AlgorithmParams) {
994    for attr in e.attributes().flatten() {
995        match attr.key.as_ref() {
996            b"cipherAlgorithm" => {
997                into.cipher = attr_str(&attr).and_then(|v| match v.as_str() {
998                    "AES" => Some(CipherAlgorithm::Aes),
999                    "RC4" => Some(CipherAlgorithm::Rc4),
1000                    _ => None,
1001                });
1002            }
1003            b"hashAlgorithm" => {
1004                into.hash = attr_str(&attr).as_deref().and_then(HashAlgorithm::parse);
1005            }
1006            b"keyBits" => into.key_bits = attr_u32(&attr),
1007            b"blockSize" => into.block_size = attr_u32(&attr),
1008            b"saltSize" => into.salt_size = attr_u32(&attr),
1009            b"spinCount" => into.spin_count = attr_u32(&attr),
1010            _ => {}
1011        }
1012    }
1013}
1014
1015// `normalized_value(Implicit1_0)` rather than the deprecated `unescape_value()`, which
1016// quick-xml 0.41 removed from the non-deprecated surface. This is not an equivalent call,
1017// it is the *same* call: 0.41's `unescape_value` is defined as
1018// `normalized_value_with(XmlVersion::Implicit1_0, 1, resolve_predefined_entity)`
1019// (quick-xml-0.41.0/src/events/attributes.rs:299) and `normalized_value(v)` as
1020// `normalized_value_with(v, 1, resolve_predefined_entity)` (:84). So the behaviour of this
1021// parser on every input, hostile ones included, is unchanged by the rename.
1022//
1023// `Implicit1_0` is also the correct version to assert independently of the deprecation.
1024// It means "no XML declaration was parsed, so 1.0 is assumed" -- and this crate reads
1025// EncryptionInfo with a plain `Reader` that never inspects the declaration. The only
1026// thing the choice controls is whether `…` and ` 28` normalise to a space, which
1027// they do in 1.1 and not in 1.0; no value this parser reads (an algorithm token, a
1028// base64 blob, a decimal integer) may legally contain either.
1029fn attr_str(attr: &quick_xml::events::attributes::Attribute<'_>) -> Option<String> {
1030    attr.normalized_value(quick_xml::XmlVersion::Implicit1_0)
1031        .ok()
1032        .map(|v| v.into_owned())
1033}
1034
1035fn attr_u32(attr: &quick_xml::events::attributes::Attribute<'_>) -> Option<u32> {
1036    attr_str(attr).and_then(|v| v.parse::<u32>().ok())
1037}
1038
1039/// Strip a namespace prefix from an element name (`p:encryptedKey` → `encryptedKey`).
1040///
1041/// Shared with `agile::parse_encryption_info` so the two cannot disagree about which
1042/// elements they are looking at.
1043pub(crate) fn local_name(name: &[u8]) -> &[u8] {
1044    match name.iter().position(|&b| b == b':') {
1045        Some(pos) => &name[pos + 1..],
1046        None => name,
1047    }
1048}
1049
1050// ---- standard / RC4 CryptoAPI --------------------------------------------------------
1051
1052/// `EncryptionHeaderFlags.fAES` — [MS-OFFCRYPTO] §2.3.1.
1053///
1054/// This bit, not the version pair, is what separates ECMA-376 standard (AES) encryption
1055/// from RC4 CryptoAPI: both are written with `vMinor = 2`.
1056const FLAG_AES: u32 = 0x0000_0020;
1057
1058/// `AlgID` values — [MS-OFFCRYPTO] §2.3.2, the `wincrypt.h` `CALG_*` constants.
1059const ALG_ID_RC4: u32 = 0x0000_6801;
1060const ALG_ID_AES_128: u32 = 0x0000_660E;
1061const ALG_ID_AES_192: u32 = 0x0000_660F;
1062const ALG_ID_AES_256: u32 = 0x0000_6610;
1063
1064/// `AlgIDHash` values — [MS-OFFCRYPTO] §2.3.2, the `wincrypt.h` `CALG_*` hash constants.
1065const ALG_ID_HASH_SHA1: u32 = 0x0000_8004;
1066const ALG_ID_HASH_SHA256: u32 = 0x0000_800C;
1067const ALG_ID_HASH_SHA384: u32 = 0x0000_800D;
1068const ALG_ID_HASH_SHA512: u32 = 0x0000_800E;
1069
1070/// Offsets within `EncryptionHeader` — [MS-OFFCRYPTO] §2.3.2. `standard::decrypt` reads
1071/// the same layout; these names exist so the offsets are stated once in prose.
1072const HDR_FLAGS: usize = 0;
1073const HDR_ALG_ID: usize = 8;
1074const HDR_ALG_ID_HASH: usize = 12;
1075const HDR_KEY_SIZE: usize = 16;
1076/// `CSPName`, a null-terminated UTF-16LE string, starts here and runs to the
1077/// `EncryptionVerifier`.
1078const HDR_CSP_NAME: usize = 32;
1079
1080/// Parse the binary `EncryptionInfo` body of a `vMinor = 2` file, for reporting only.
1081///
1082/// `body` is the stream with the 8-byte `EncryptionVersionInfo` + `EncryptionHeaderFlags`
1083/// prefix already removed, so it begins at `EncryptionHeaderSize`.
1084///
1085/// Two fields are absent by construction rather than by omission and are reported as
1086/// `None`: `block_size` (this is AES-**ECB**, which has no chaining block to declare) and
1087/// `spin_count` ([MS-OFFCRYPTO] §2.3.4.7 fixes it at 50 000; the file does not carry it).
1088fn classify_standard(body: &[u8], version: Option<(u16, u16)>) -> Classification {
1089    let mut params = AlgorithmParams::default();
1090    let mut family = Family::Unsupported;
1091
1092    // `EncryptionHeaderSize`, then the header itself. The size is not read here and does
1093    // not need to be: every field this function reports lives in the header's 32 fixed
1094    // bytes, which start immediately after it whatever it says. `standard::decrypt` does
1095    // read it — it is where the `EncryptionVerifier` begins ([MS-OFFCRYPTO] §2.3.4.5) —
1096    // and the two still agree about these offsets, which is all that matters for a
1097    // function whose contract is to report and never to refuse.
1098    if body.len() >= 4 + HDR_CSP_NAME {
1099        let header = &body[4..];
1100        let flags = read_u32(header, HDR_FLAGS);
1101        let alg_id = read_u32(header, HDR_ALG_ID);
1102        let alg_id_hash = read_u32(header, HDR_ALG_ID_HASH);
1103        let key_size = read_u32(header, HDR_KEY_SIZE);
1104
1105        // fAES first, AlgID second. [MS-OFFCRYPTO] §2.3.1: "If the fAES encryption bit is
1106        // set, a block cipher that supports ECB mode MUST be used" — RC4 is a stream
1107        // cipher, so with the bit set the AlgID does not get to name RC4, and §2.3.2's
1108        // combination table has no `fAES` + `0x00006801` row to fall back on. Which is
1109        // what the `standard_encrypted.docx` fixture needs: it declares `fAES` **and**
1110        // `AlgID = 0x6801`, a combination the spec forbids, and it is AES-128 in fact (it
1111        // decrypts as such). Reading fAES first is both the spec's own precedence and the
1112        // reading that matches the corpus.
1113        let aes = flags & FLAG_AES != 0;
1114        params.cipher = if aes {
1115            Some(CipherAlgorithm::Aes)
1116        } else {
1117            match alg_id {
1118                ALG_ID_RC4 => Some(CipherAlgorithm::Rc4),
1119                ALG_ID_AES_128 | ALG_ID_AES_192 | ALG_ID_AES_256 => Some(CipherAlgorithm::Aes),
1120                _ => None,
1121            }
1122        };
1123        params.hash = match alg_id_hash {
1124            // 0x00000000 means "determined by Flags", which for every family here is
1125            // SHA-1: agile is the only MS-OFFCRYPTO format with a choice of hash.
1126            0 | ALG_ID_HASH_SHA1 => Some(HashAlgorithm::Sha1),
1127            ALG_ID_HASH_SHA256 => Some(HashAlgorithm::Sha256),
1128            ALG_ID_HASH_SHA384 => Some(HashAlgorithm::Sha384),
1129            ALG_ID_HASH_SHA512 => Some(HashAlgorithm::Sha512),
1130            _ => None,
1131        };
1132        params.key_bits = (key_size != 0).then_some(key_size);
1133        params.salt_size = verifier_salt_size(header);
1134
1135        family = match params.cipher {
1136            Some(CipherAlgorithm::Aes) => Family::Standard,
1137            Some(CipherAlgorithm::Rc4) => Family::Rc4CryptoApi,
1138            None => Family::Unsupported,
1139        };
1140    }
1141
1142    Classification {
1143        container: Container::Cfb,
1144        document: Document::OoxmlPackage,
1145        version,
1146        family,
1147        key_data: Some(params),
1148        password_key: None,
1149        // [MS-OFFCRYPTO] §2.3.4.5 defines no integrity element for this format, and the
1150        // RC4 families define none either. Absence is the spec, not a defect.
1151        data_integrity: IntegrityDeclaration::NotApplicable,
1152        container_read: ContainerRead::Opened,
1153    }
1154}
1155
1156/// `EncryptionVerifier.SaltSize`, found by walking `CSPName` to its UTF-16 terminator.
1157///
1158/// **Not** how `standard::decrypt` finds the verifier: that reader takes it at the
1159/// declared `EncryptionHeaderSize` ([MS-OFFCRYPTO] §2.3.4.5), because the scan lands in
1160/// the header's own padding on any file that puts bytes after `CSPName`. The two agree on
1161/// every conforming file, and the scan is kept here for the one property this function
1162/// needs and that one does not: it cannot fail. `classify` must answer on a header whose
1163/// size field is a lie, so it reads what is there and answers `None` for anything it
1164/// cannot reach, rather than refusing the file.
1165fn verifier_salt_size(header: &[u8]) -> Option<u32> {
1166    let mut pos = HDR_CSP_NAME;
1167    while pos + 1 < header.len() {
1168        if header[pos] == 0 && header[pos + 1] == 0 {
1169            pos += 2;
1170            break;
1171        }
1172        pos += 2;
1173    }
1174    let verifier = header.get(pos..)?;
1175    if verifier.len() < 4 {
1176        return None;
1177    }
1178    Some(read_u32(verifier, 0))
1179}
1180
1181/// Little-endian `u32` at `offset`, or `0` when the slice is too short.
1182///
1183/// The zero default is what makes every caller above bound-free: `standard.rs`'s own
1184/// `read_u32` panics out of range and relies on a length guard forty lines away, which
1185/// is the shape this function exists not to have.
1186fn read_u32(data: &[u8], offset: usize) -> u32 {
1187    match data.get(offset..offset + 4) {
1188        Some(bytes) => u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]),
1189        None => 0,
1190    }
1191}
1192
1193#[cfg(test)]
1194#[path = "classify_tests.rs"]
1195mod tests;