Skip to main content

odf_crypto/
decrypt.rs

1//! Password decryption for LO-encrypted ODF packages.
2
3use std::io::Read;
4
5use pbkdf2::pbkdf2_hmac;
6use secure_gate::{RevealSecret, RevealSecretMut};
7use sha1::Sha1;
8use zip::ZipArchive;
9
10use quick_xml::events::{BytesStart, Event};
11use quick_xml::{Reader, Writer};
12
13fn is_manifest_size_attr(key: &[u8]) -> bool {
14    key.ends_with(b":size") || key == b"size"
15}
16
17use crate::bad_parameter::{wide, BadParameter, ManifestField, MemberFault, Primitive};
18use crate::classify::{member_matches_path, zip_entry_name};
19use crate::kdf::KdfError;
20use crate::limits::{
21    AES_BLOCK_LEN, AES_CBC_IV_LEN, AES_GCM_IV_LEN, AES_GCM_TAG_LEN, ARGON2_MAX_M_COST_KIB_READ,
22    ARGON2_MAX_P_COST_READ, ARGON2_MAX_T_COST_READ, BLOWFISH_IV_LEN, DERIVED_KEY_MAX_LEN,
23    DERIVED_KEY_MIN_LEN, INFLATE_CEILING, MAX_ENCRYPTED_ENTRIES, MAX_OUTPUT_BYTES, PBKDF2_MAX_ITER,
24    PBKDF2_MIN_ITER,
25};
26use crate::sensitive::{DerivedKey, PasswordDigest};
27use crate::types::{Cipher, EntryEncryption, Kdf, Mode};
28use crate::zip_err;
29use crate::DetectError;
30
31/// Failures from [`decrypt`].
32#[derive(Debug, thiserror::Error)]
33#[non_exhaustive]
34pub enum DecryptError {
35    /// [`classify`](crate::classify) refused the package before decryption began.
36    #[error("classification failed: {0}")]
37    Classify(#[from] DetectError),
38    /// The package classified as [`Mode::Plain`] — there is nothing to decrypt.
39    ///
40    /// A malformed `META-INF/manifest.xml` also arrives here rather than as a
41    /// parse error: LibreOffice discards every row on an XML failure and still
42    /// opens the package, so this crate classifies it plain.
43    #[error("package is not encrypted")]
44    NotEncrypted,
45    /// The password was empty. Checked before [`classify`](crate::classify) runs, so it implies
46    /// nothing about whether `bytes` is a valid or encrypted package.
47    #[error("password is empty")]
48    EmptyPassword,
49    /// The package is PGP-wrapped. Screened across every encrypted row, not
50    /// only the latch row. The wrapped key material is available from
51    /// [`crate::Classification::pgp_keys`] for handing to an OpenPGP implementation.
52    ///
53    /// **Not "a later arc".** The plans said that for a while and it was the
54    /// wrong reason, because it implies the work is merely unscheduled. Two
55    /// things make it infeasible in *this* function rather than unscheduled:
56    ///
57    /// - **There is no surface to pass a key through.** The signature is
58    ///   `decrypt(bytes: &[u8], password: &str)`. A PGP-wrapped package is
59    ///   opened with a private key, which arrives as a keyring path, a
60    ///   passphrase over that key, an agent socket, or a smartcard PIN
61    ///   prompt -- none of which a `&str` password can carry, and none of
62    ///   which a library should invent a side channel for.
63    /// - **The cost is the crate's whole premise.** Detection-only is about
64    ///   two dozen crates and the point of the default; an OpenPGP implementation is a
65    ///   dependency tree of a different order, for a path `classify` already
66    ///   reports without it.
67    ///
68    /// So the honest scope statement is *this API shape cannot express it*,
69    /// and the honest offer is the one above: `classify` surfaces the wrapped
70    /// key material, and a caller who has an OpenPGP stack does the unwrap.
71    #[error("PGP-encrypted packages are not supported")]
72    UnsupportedPgp,
73    /// LibreOffice `LookForUnexpectedODF12Streams` plus a root version `>= 1.2`.
74    /// `classify` reports the flag without failing; decrypt refuses so it does
75    /// not return a zip LO would not open.
76    #[error("LibreOffice would refuse this package: unexpected ODF 1.2 streams")]
77    Odf12Fatal,
78    /// The key did not open the package.
79    ///
80    /// Cannot distinguish a wrong password from corrupted ciphertext. On
81    /// AES-CBC and Blowfish it is decided by a checksum over only the first
82    /// 1 KiB of the decrypted stream, so damage past that window surfaces as
83    /// [`DecryptError::Inflate`] instead.
84    #[error("wrong password")]
85    WrongPassword,
86    /// The package's own encryption settings were refused: which setting, the
87    /// value the file declares, and what was allowed ([`BadParameter`]). It
88    /// carries no text from the file, so a caller may match on it and quote
89    /// its numbers. Changed in `0.1.0-rc.13` from a `String`, which could
90    /// carry a row's `manifest:full-path` unbounded.
91    ///
92    /// A verdict on the manifest, and the same verdict on every machine. A cost
93    /// this crate accepted and the host then could not meet is
94    /// [`DecryptError::HostCannotAllocate`], not a bad parameter.
95    #[error("invalid encryption parameters: {0}")]
96    BadParameters(crate::BadParameter),
97    /// Deliberately NOT the `BadParameters` analogue: that reports a hostile
98    /// value read out of the manifest, and this reports an invariant of our own
99    /// that something upstream was supposed to have enforced. Reaching it means
100    /// a guard moved, not that the input was bad.
101    ///
102    /// It exists for the same reason `EncryptError::Internal` does: a library
103    /// must not abort its caller's process to report a condition it could
104    /// return.
105    #[error("internal invariant violated: {0}")]
106    Internal(String),
107    /// This host could not allocate the working memory key derivation needs.
108    ///
109    /// **Not a statement about the package.** The manifest may be entirely
110    /// legal, and the same bytes may decrypt on a machine with more free memory
111    /// — so retrying, or retrying elsewhere, is meaningful, and re-downloading
112    /// the file is not. Deliberately not [`DecryptError::BadParameters`], which
113    /// reports a manifest field this crate refuses to act on at all, and
114    /// deliberately not [`DecryptError::Internal`], which reports an invariant
115    /// of ours; how much memory this machine had free at this moment is
116    /// neither.
117    ///
118    /// The shortfall is returned rather than aborted on because an abort skips
119    /// unwinding, and `Drop` is this crate's only zeroizing primitive — the
120    /// allocation happens with the password digest and the derived key both
121    /// live.
122    ///
123    /// Key derivation was the first allocation here to become fallible, and an
124    /// earlier version of this doc predicted that when the others followed, the
125    /// variant would want a field naming which one failed. They followed in
126    /// `0.1.0-rc.5`, and [`AllocationSite`] is that field. It was a breaking
127    /// change to the variant and was accepted.
128    ///
129    /// [`DecryptError`] itself is `#[non_exhaustive]`, but the variant is not,
130    /// deliberately: a variant nobody outside the crate can construct is a
131    /// variant nobody outside the crate can write a test against, and the
132    /// binary's own exit-code test needs to construct it.
133    #[error("host could not allocate {requested_bytes} bytes for {site}")]
134    HostCannotAllocate {
135        /// Which allocation could not be made.
136        site: AllocationSite,
137        /// The size that could not be obtained — in every case a number the
138        /// package itself supplied, not a ceiling of this crate's:
139        /// `manifest:argon2-memory` rounded to whole blocks, `manifest:size`,
140        /// `manifest:key-size`, or a member's own length.
141        requested_bytes: usize,
142    },
143    /// The decrypted stream was not valid DEFLATE, or did not inflate to the
144    /// length `manifest:size` promised.
145    ///
146    /// Never means "wrong password": it is reached only after a GCM tag or a
147    /// checksum has already accepted the key. It means the ciphertext is
148    /// damaged past the point those checks cover.
149    #[error("inflate failed: {0}")]
150    Inflate(String),
151    /// A zip failure, either reading the input or writing the rebuilt package
152    /// — plus the manifest rewrite's *parse* failure, which is the one thing
153    /// here that is not a zip error.
154    ///
155    /// The rewrite's *serialization* failures are no longer among them: they are
156    /// [`DecryptError::Internal`] as of `0.1.0-rc.5`, because they can only ever
157    /// report a broken invariant of ours, never anything about the package. The
158    /// doc used to say this variant carried *"every quick-xml failure"*, and
159    /// that sentence is what prompted the split — a name needing a disclaimer
160    /// is usually a name covering two things. The string is a diagnostic; do not
161    /// match on it.
162    ///
163    /// It may quote package-controlled text, so treat it as untrusted when
164    /// logging or displaying it. The zip half cannot: those are rendered by an
165    /// internal helper that quotes only text this crate chose, never the zip
166    /// crate's own `Display`. The quick-xml half can —
167    /// `IllFormedError::UnmatchedEndTag` carries an element name taken from the
168    /// manifest — and unlike [`crate::DetectError::Inconsistent`] it is **not**
169    /// elided to a bound.
170    ///
171    /// # Why it is not elided
172    ///
173    /// Because the path is unreachable, and an elision would imply a live threat
174    /// where there is none. The argument, since a claim of unreachability has to
175    /// carry one:
176    ///
177    /// `strip_manifest` can only return this from its *read* side — its writer
178    /// is a `Vec<u8>`, whose `write_all` cannot fail. So a `Zip` from the rewrite
179    /// means `read_event_into` errored. But `manifest::parse_manifest` maps
180    /// **any** read error to an empty row list, plus three more conditions
181    /// `strip_manifest` does not have, so `parse_manifest` returning rows means
182    /// no read error occurred. Empty rows means `classify` reports
183    /// [`Mode::Plain`], and `decrypt` refuses that with
184    /// [`DecryptError::NotEncrypted`] long before the rewrite runs.
185    ///
186    /// The two readers are configured differently — `parse_manifest` sets
187    /// `expand_empty_elements`, the rewrite leaves it at its default — which is
188    /// the only way they could disagree about what is ill-formed. They cannot:
189    /// in quick-xml 0.38.4 an expanded empty element pushes onto `opened_starts`
190    /// and is popped by the next read *without consuming input*, so the stack
191    /// every end-tag check consults is identical in both modes at every byte
192    /// boundary.
193    ///
194    /// **That argument is version-scoped to quick-xml 0.38.4**, which is why
195    /// `classify_accepting_a_manifest_implies_the_rewrite_accepts_it` pins it
196    /// rather than leaving it as prose a dependency bump could quietly falsify.
197    /// If that test ever fails, this variant needs the elision
198    /// [`crate::DetectError::Inconsistent`] already has.
199    #[error("zip error: {0}")]
200    Zip(String),
201    /// The plaintext inflated from encrypted members would exceed
202    /// [`DecryptLimits::max_output_bytes`].
203    ///
204    /// Raised before key derivation when `manifest:size` already says so, and
205    /// otherwise as the running count passes the limit. Members stored
206    /// unencrypted are copied, not inflated by this crate, and do not count:
207    /// they are bounded by the input.
208    ///
209    /// **A policy of this crate, not a rule of the format.** ODF bounds no
210    /// size; the limit exists because a few kilobytes of DEFLATE can claim
211    /// gigabytes, and a caller writing to disk wants that refused rather than
212    /// discovered. Raise it with [`DecryptLimits::with_max_output_bytes`].
213    #[error("decrypted output would exceed the {limit}-byte limit")]
214    OutputLimit {
215        /// The limit in force, from [`DecryptLimits::max_output_bytes`].
216        limit: u64,
217    },
218    /// The caller's reader or writer failed. Nothing is implied about the
219    /// package. The error is the caller's own value, so a cancellation can be
220    /// recognized in it.
221    #[error("I/O failed: {0}")]
222    Io(#[source] std::io::Error),
223}
224
225/// Which allocation a [`DecryptError::HostCannotAllocate`] refers to.
226///
227/// Diagnostic, not a decision: every site means the same thing to a caller —
228/// retrying, or retrying on a machine with more free memory, is meaningful, and
229/// re-downloading the file is not. It exists because the message was wrong
230/// without it. Until `0.1.0-rc.5` the variant's `Display` read *"for key
231/// derivation"* unconditionally, which was true while key derivation was the
232/// only fallible allocation here and became a false statement the moment the
233/// others followed.
234///
235/// Deliberately not shaped like [`ParamsReason`]. That type answers *whose rule
236/// refused this* — a policy bound of ours against a requirement of the cipher's
237/// — which a consumer renders differently and may act on. This answers *where*,
238/// which nobody acts on.
239///
240/// [`ParamsReason`]: crate::ParamsReason
241#[derive(Debug, Clone, Copy, PartialEq, Eq)]
242#[non_exhaustive]
243pub enum AllocationSite {
244    /// The KDF's own working memory: Argon2id's block buffer, sized from
245    /// `manifest:argon2-memory`.
246    KeyDerivation,
247    /// The derived-key buffer, sized from `manifest:key-size`.
248    ///
249    /// Bounded to `1..=64` before it is allocated, so on any host that can run
250    /// this crate at all it is unreachable — and it is allocated fallibly
251    /// anyway, because that bound is the thing under review. A ceiling that
252    /// happens to keep an infallible allocation from failing is not a reason
253    /// for the allocation to be infallible: widening it would make this
254    /// reachable again with no diff at this line to notice.
255    DerivedKey,
256    /// The inflate slot for one member of a per-entry package, sized from that
257    /// row's `manifest:size`.
258    ///
259    /// The one site where the **sum** matters rather than the individual
260    /// request: each row is bounded at 1 GiB, a package may hold up to
261    /// `MAX_ENCRYPTED_ENTRIES` of them, and every earlier member's plaintext is
262    /// still wrapped and live when a later one is allocated.
263    MemberPlaintext,
264    /// The inflate slot for a wholesome package's `encrypted-package` member,
265    /// sized from `manifest:size`.
266    PackagePlaintext,
267    /// The buffer a member's ciphertext is copied into so it can be decrypted
268    /// in place, sized from that member's own length.
269    CipherBuffer,
270    /// A fixed-size buffer of the streaming entry points (`decrypt_to`): a
271    /// chunk, the inflate window or the 1K hold-back. Never sized from the
272    /// package.
273    StreamBuffer,
274    /// A thread to run Argon2id's lanes on: the host could not spawn even one.
275    /// `requested_bytes` is that thread's stack. Added in `0.1.0-rc.15` with
276    /// parallel lanes; before it, the lanes ran on the caller's thread.
277    KdfThread,
278}
279
280impl core::fmt::Display for AllocationSite {
281    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
282        // Exhaustive on purpose, with no `_` arm, for the reason
283        // `Argon2Axis`'s Display gives: `#[non_exhaustive]` binds downstream
284        // crates and not this one, so a new site fails to compile here until it
285        // is given a name rather than rendering as something else.
286        f.write_str(match self {
287            Self::KeyDerivation => "key derivation",
288            Self::DerivedKey => "the derived-key buffer",
289            Self::MemberPlaintext => "a decrypted package member",
290            Self::PackagePlaintext => "the decrypted package",
291            Self::CipherBuffer => "a cipher buffer",
292            Self::StreamBuffer => "a streaming buffer",
293            Self::KdfThread => "an Argon2id lane thread's stack",
294        })
295    }
296}
297
298/// A zero-filled `Vec<u8>` of exactly `n` bytes, allocated **fallibly**.
299///
300/// `vec![0u8; n]` and `Vec::with_capacity(n)` route failure through
301/// `handle_alloc_error`, which *aborts* — whatever the panic strategy, because
302/// an abort is not a panic. Every caller of this function is inside at least one
303/// live `secure-gate` wrapper, and an abort skips unwinding, so `Drop` never
304/// runs and the crate's only zeroizing primitive does not happen. See
305/// `CLAUDE.md`, *The library does not panic*.
306///
307/// `n` comes from the package in every case, which is why a ceiling is not the
308/// fix: a guessed one refuses a host that could have coped and still aborts one
309/// that could not.
310pub(crate) fn try_zeroed(n: usize, site: AllocationSite) -> Result<Vec<u8>, DecryptError> {
311    let mut v = Vec::new();
312    v.try_reserve_exact(n)
313        .map_err(|_| DecryptError::HostCannotAllocate {
314            site,
315            requested_bytes: n,
316        })?;
317    // Load-bearing: `try_reserve_exact` has already secured the capacity, so
318    // this only sets the length. It cannot reallocate, so it cannot reach the
319    // infallible path this function exists to avoid.
320    v.resize(n, 0);
321    Ok(v)
322}
323
324/// Ceilings [`decrypt`] applies to cost parameters **a package chose**.
325///
326/// A manifest names how much work its key derivation takes, and `decrypt` must
327/// do that work before it can tell whether the password is even right. So the
328/// file, not the caller, picks the cost of an attempt. These are the defaults
329/// that bounds it, and [`decrypt_with_limits`] is how a caller who knows what
330/// they are opening raises them.
331///
332/// **The defaults refuse nothing any real producer writes.** LibreOffice's own
333/// output is `t = 3`, `m = 64 MiB`, `p = 4`, and at most 600,000 PBKDF2
334/// iterations — every one comfortably inside these.
335///
336/// | field | default | LibreOffice writes |
337/// | --- | --- | --- |
338/// | [`argon2_max_t`](Self::argon2_max_t) | 10 | 3 |
339/// | [`argon2_max_m_kib`](Self::argon2_max_m_kib) | 1 GiB | 64 MiB |
340/// | [`argon2_max_p`](Self::argon2_max_p) | 16 | 4 |
341/// | [`pbkdf2_max_iter`](Self::pbkdf2_max_iter) | 10,000,000 | 600,000 |
342///
343/// The Argon2 defaults are Bitwarden's published maxima. They are an
344/// application's limits on its own user's slider, adopted here for the one case
345/// where this crate is in the same position: a number arriving from outside.
346///
347/// # Why `t` and `m` are not independent
348///
349/// Argon2's cost is roughly `t × m`, and bounding each alone does not bound the
350/// product. Before `0.1.0-rc.6` this crate allowed `t ≤ 65536` with
351/// `m ≤ 1 GiB` — about **350,000× LibreOffice's own work**, extrapolating to
352/// ~33 hours from a measured 54.5 s at `t = 30, m = 1 GiB`. Neither ceiling
353/// looked wrong on its own. At `t = 10` the product is ~53×, which is seconds.
354///
355/// # Raising them
356///
357/// ```
358/// # #[cfg(feature = "crypto-ops")] {
359/// use odf_crypto::{decrypt_with_limits, DecryptLimits};
360///
361/// # fn demo(bytes: &[u8], pw: &str) -> Result<(), odf_crypto::DecryptError> {
362/// // A file from a tool that derives harder than LibreOffice does.
363/// let limits = DecryptLimits::default().with_argon2_max_t(64);
364/// let plain = decrypt_with_limits(bytes, pw, limits)?;
365///
366/// // Or: accept anything the format can express. Opt in knowingly --
367/// // on an untrusted file this is a decision to spend whatever it asks for.
368/// let plain = decrypt_with_limits(bytes, pw, DecryptLimits::PERMISSIVE)?;
369/// # let _ = plain;
370/// # Ok(())
371/// # }
372/// # }
373/// ```
374#[derive(Debug, Clone, Copy, PartialEq, Eq)]
375#[non_exhaustive]
376pub struct DecryptLimits {
377    /// Inclusive ceiling on `loext:argon2-iterations`.
378    pub argon2_max_t: u32,
379    /// Inclusive ceiling on `loext:argon2-memory`, in KiB.
380    pub argon2_max_m_kib: u32,
381    /// Inclusive ceiling on `loext:argon2-lanes`.
382    pub argon2_max_p: u32,
383    /// Inclusive ceiling on `manifest:iteration-count` for a PBKDF2 row.
384    pub pbkdf2_max_iter: u32,
385    /// Inclusive ceiling, in bytes, on the plaintext inflated from encrypted
386    /// members, summed across the package. Default 16 GiB. Exceeding it is
387    /// [`DecryptError::OutputLimit`].
388    ///
389    /// A policy of this crate, not of the format; see `OutputLimit`. The
390    /// whole-buffer [`decrypt`] is also held to 1 GiB per inflated buffer by
391    /// the memory it must allocate, whatever this says.
392    pub max_output_bytes: u64,
393}
394
395impl Default for DecryptLimits {
396    fn default() -> Self {
397        Self {
398            argon2_max_t: ARGON2_MAX_T_COST_READ,
399            argon2_max_m_kib: ARGON2_MAX_M_COST_KIB_READ,
400            argon2_max_p: ARGON2_MAX_P_COST_READ,
401            pbkdf2_max_iter: PBKDF2_MAX_ITER,
402            max_output_bytes: MAX_OUTPUT_BYTES,
403        }
404    }
405}
406
407impl DecryptLimits {
408    /// Everything the format can express: each field at the width of the
409    /// manifest attribute behind it.
410    ///
411    /// **This is not "no limits".** The cipher still refuses what it cannot run
412    /// (`m >= 8p`, `p <= argon2::Params::MAX_P_COST`) and the host still refuses
413    /// what it cannot allocate, as [`DecryptError::HostCannotAllocate`]. What it
414    /// removes is this crate's judgement about how much work a file may ask for.
415    ///
416    /// Measured on one laptop, with these: a single Argon2 row at
417    /// `t = 65536, m = 1 GiB` extrapolates to ~33 hours, and `decrypt` cannot be
418    /// interrupted. Reach for it when you know the producer, not to make a
419    /// stubborn file open.
420    pub const PERMISSIVE: Self = Self {
421        argon2_max_t: i32::MAX as u32,
422        argon2_max_m_kib: i32::MAX as u32,
423        argon2_max_p: i32::MAX as u32,
424        pbkdf2_max_iter: i32::MAX as u32,
425        // `manifest:size` is read as an `i64`, so this is wider than any size a
426        // package can declare.
427        max_output_bytes: u64::MAX,
428    };
429
430    /// Raise or lower the Argon2 `t` ceiling.
431    #[must_use]
432    pub fn with_argon2_max_t(mut self, t: u32) -> Self {
433        self.argon2_max_t = t;
434        self
435    }
436
437    /// Raise or lower the Argon2 `m` ceiling, in KiB.
438    #[must_use]
439    pub fn with_argon2_max_m_kib(mut self, m_kib: u32) -> Self {
440        self.argon2_max_m_kib = m_kib;
441        self
442    }
443
444    /// Raise or lower the Argon2 `p` ceiling.
445    #[must_use]
446    pub fn with_argon2_max_p(mut self, p: u32) -> Self {
447        self.argon2_max_p = p;
448        self
449    }
450
451    /// Raise or lower the PBKDF2 iteration ceiling.
452    #[must_use]
453    pub fn with_pbkdf2_max_iter(mut self, iter: u32) -> Self {
454        self.pbkdf2_max_iter = iter;
455        self
456    }
457
458    /// Raise or lower the ceiling on inflated plaintext, in bytes.
459    #[must_use]
460    pub fn with_max_output_bytes(mut self, bytes: u64) -> Self {
461        self.max_output_bytes = bytes;
462        self
463    }
464}
465
466/// Decrypt an LO-encrypted ODF package to the plaintext ODF zip LibreOffice
467/// would open after a correct password.
468///
469/// The two modes have different contracts:
470///
471/// - [`Mode::Wholesome`] — the inner `encrypted-package` member is decrypted and
472///   inflated, and returned verbatim. Nothing is stripped or recompressed.
473/// - [`Mode::PerEntry`] — the package is rebuilt: `encryption-data` elements are
474///   stripped from `META-INF/manifest.xml` and `manifest:size` is dropped from
475///   its `file-entry` elements. The rewritten manifest and each decrypted member
476///   are written DEFLATED; every other member is copied through with its
477///   original compression method, so a STORED member stays STORED.
478///
479/// # Errors
480///
481/// Refused before any key derivation, in this order, so no caller pays for
482/// PBKDF2 or a 64 MiB Argon2id to learn the input was never eligible:
483/// [`DecryptError::EmptyPassword`], [`DecryptError::Classify`],
484/// [`DecryptError::NotEncrypted`], [`DecryptError::Odf12Fatal`],
485/// [`DecryptError::UnsupportedPgp`], then [`DecryptError::BadParameters`] if the
486/// package declares more encrypted rows than will be processed, then
487/// [`DecryptError::OutputLimit`] if its `manifest:size` values sum past
488/// [`DecryptLimits::max_output_bytes`].
489///
490/// During derivation, and alone in this list in blaming neither the package nor
491/// this crate: [`DecryptError::HostCannotAllocate`], when the host cannot
492/// allocate Argon2id's working buffer. The same bytes may decrypt on a machine
493/// with more free memory.
494///
495/// After derivation: [`DecryptError::WrongPassword`],
496/// [`DecryptError::BadParameters`] for a hostile KDF or key-size field,
497/// [`DecryptError::Inflate`], [`DecryptError::Zip`], and
498/// [`DecryptError::Internal`].
499///
500/// [`DecryptError`] is `#[non_exhaustive]` and does not implement `PartialEq`;
501/// match with a `_` arm and [`matches!`].
502///
503/// # Examples
504///
505/// ```
506/// use odf_crypto::{classify, decrypt, Mode};
507///
508/// let sealed = include_bytes!("../tests/goldens/lo-wholesome-gcm-argon2.odt");
509/// assert_eq!(classify(sealed)?.mode, Mode::Wholesome);
510///
511/// let plain = decrypt(sealed, "password")?;
512/// assert_eq!(classify(&plain)?.mode, Mode::Plain);
513/// # Ok::<(), Box<dyn std::error::Error>>(())
514/// ```
515pub fn decrypt(bytes: &[u8], password: &str) -> Result<Vec<u8>, DecryptError> {
516    decrypt_with_limits(bytes, password, DecryptLimits::default())
517}
518
519/// [`decrypt`], with the ceilings on what a package may ask for under the
520/// caller's control. See [`DecryptLimits`].
521///
522/// # Errors
523///
524/// Identical to [`decrypt`]. A cost parameter outside `limits` is
525/// [`DecryptError::BadParameters`], which says *this crate declined*, not that
526/// the file is malformed — with `limits` raised, the same file may open.
527pub fn decrypt_with_limits(
528    bytes: &[u8],
529    password: &str,
530    limits: DecryptLimits,
531) -> Result<Vec<u8>, DecryptError> {
532    crate::decrypt_stream::decrypt_slice(bytes, password, &limits)
533}
534
535/// Every refusal that needs only the classification, in the order `decrypt`
536/// documents. Shared by the whole-buffer and streaming paths, so the two
537/// refuse the same packages for the same reasons.
538pub(crate) fn screen_class(
539    class: &crate::Classification,
540    limits: &DecryptLimits,
541) -> Result<(), DecryptError> {
542    if class.mode == Mode::Plain {
543        return Err(DecryptError::NotEncrypted);
544    }
545    if class.odf12_fatal {
546        return Err(DecryptError::Odf12Fatal);
547    }
548    if class
549        .encrypted_entries
550        .iter()
551        .any(|e| matches!(e.kdf, Kdf::PgpRsaOaepMgf1p))
552    {
553        return Err(DecryptError::UnsupportedPgp);
554    }
555    ensure_encrypted_entry_count(class.encrypted_entries.len(), MAX_ENCRYPTED_ENTRIES)?;
556    screen_output_limit(class, limits.max_output_bytes)
557}
558
559/// Refuse, before any key derivation, a package whose `manifest:size` values
560/// already promise more inflated plaintext than `limit`.
561///
562/// Sums only the rows `decrypt` will inflate: the wholesome row for a wholesome
563/// package, every encrypted row otherwise. A size `inflated_len` would refuse is
564/// skipped here rather than reported, so that refusal keeps the position in the
565/// error order it had before this screen existed; only `OutputLimit` is new.
566fn screen_output_limit(class: &crate::Classification, limit: u64) -> Result<(), DecryptError> {
567    let declared = |row: &EntryEncryption| u64::try_from(row.size).unwrap_or(0);
568    let total = match class.mode {
569        Mode::Wholesome => class.wholesome_row().map_or(0, declared),
570        _ => class
571            .encrypted_entries
572            .iter()
573            .fold(0u64, |sum, row| sum.saturating_add(declared(row))),
574    };
575    if total > limit {
576        return Err(DecryptError::OutputLimit { limit });
577    }
578    Ok(())
579}
580
581fn ensure_encrypted_entry_count(n: usize, cap: usize) -> Result<(), DecryptError> {
582    if n > cap {
583        return Err(DecryptError::BadParameters(BadParameter::OutOfRange {
584            field: ManifestField::EncryptedEntries,
585            got: wide(n),
586            min: 0,
587            max: wide(cap),
588        }));
589    }
590    Ok(())
591}
592
593/// First member whose raw or slash-collapsed name matches - the rule `classify`
594/// itself uses, because a row path is a folder-tree path, not a namelist key.
595/// `missing` is the refusal when none does: a row's
596/// [`BadParameter::NoMember`], by its index and never its path (#105), or an
597/// invariant of ours for a member `classify` already read.
598pub(crate) fn member_for_archive<R: Read + std::io::Seek>(
599    archive: &mut ZipArchive<R>,
600    path: &str,
601    missing: impl FnOnce() -> DecryptError,
602) -> Result<(usize, String), DecryptError> {
603    for i in 0..archive.len() {
604        let file = archive
605            .by_index(i)
606            .map_err(|e| DecryptError::Zip(zip_err::message(&e)))?;
607        let name = zip_entry_name(file.name_raw());
608        if member_matches_path(&name, path) {
609            return Ok((i, name));
610        }
611    }
612    Err(missing())
613}
614
615/// The refusal for encrypted row `row` naming no zip member.
616pub(crate) fn no_member(row: usize) -> impl FnOnce() -> DecryptError {
617    move || DecryptError::BadParameters(BadParameter::NoMember { row })
618}
619
620/// The index among `class`'s encrypted rows of its wholesome row, which
621/// `classify` puts there whenever it reports [`Mode::Wholesome`].
622pub(crate) fn wholesome_row(
623    class: &crate::Classification,
624) -> Result<(usize, &EntryEncryption), DecryptError> {
625    class
626        .encrypted_entries
627        .iter()
628        .enumerate()
629        .find(|(_, e)| class.mode == Mode::Wholesome && e.path == "encrypted-package")
630        .ok_or_else(|| {
631            DecryptError::Internal(
632                "a wholesome classification without its encrypted-package row".into(),
633            )
634        })
635}
636
637/// Give a [`KdfError`] its verdict on this side.
638///
639/// The two arms land in opposite halves of [`DecryptError`] — the package's
640/// fault and nobody's — so the match is exhaustive with no `_` arm, for the
641/// reason `impl Display for Argon2Axis` has none either: a third `KdfError`
642/// must be given a deliberate verdict here rather than inheriting whichever of
643/// these two it happens to be declared next to.
644///
645/// [`KdfError::Params`] is a manifest field — `t`, `m`, `p` or the key size
646/// this crate or `argon2` will not run — so it is a [`DecryptError::BadParameters`]
647/// here even though `encrypt`, which chose its own tuple, calls the identical
648/// error an invariant of its own. Both are right; the package author picked
649/// these numbers and this side is reading them.
650fn kdf_error(e: KdfError) -> DecryptError {
651    match e {
652        KdfError::Params(b) => DecryptError::BadParameters(b),
653        KdfError::Internal(s) => DecryptError::Internal(s.into()),
654        KdfError::HostCannotAllocate { requested_bytes } => DecryptError::HostCannotAllocate {
655            site: AllocationSite::KeyDerivation,
656            requested_bytes,
657        },
658        KdfError::HostCannotSpawn { requested_bytes } => DecryptError::HostCannotAllocate {
659            site: AllocationSite::KdfThread,
660            requested_bytes,
661        },
662    }
663}
664
665pub(crate) fn derive_key(
666    row: &EntryEncryption,
667    sk: PasswordDigest,
668    limits: &DecryptLimits,
669) -> Result<DerivedKey, DecryptError> {
670    let n = row.derived_key_len;
671    // Unreachable from the only current caller, and kept deliberately. Since #79
672    // `decrypt_member` screens this same field against the row's cipher, and every
673    // length that screen admits -- 16/24/32, or Blowfish's 4..=56 -- already sits
674    // inside this range, so nothing gets here to fail it.
675    //
676    // It stays because it is *this function's* precondition rather than that one's:
677    // `try_zeroed(n)` below allocates from `n`, and a second caller added later
678    // would otherwise inherit an unguarded `i32` straight from a manifest. Said
679    // out loud rather than left to be rediscovered, because an unreachable guard
680    // that reads as live is how the next person concludes the length is checked
681    // here and removes the screen.
682    //
683    // So reaching it is an invariant of ours breaking, not a verdict on the
684    // file (#105): `Internal`, not `BadParameters`.
685    if !(DERIVED_KEY_MIN_LEN..=DERIVED_KEY_MAX_LEN).contains(&n) {
686        return Err(DecryptError::Internal(
687            "derive_key reached with a derived key length screen_shape refuses".into(),
688        ));
689    }
690    let n = n as usize;
691    let mut derived = DerivedKey::new(try_zeroed(n, AllocationSite::DerivedKey)?);
692    sk.with_secret(|sk_bytes| {
693        derived.with_secret_mut(|derived_bytes| -> Result<(), DecryptError> {
694            match &row.kdf {
695                Kdf::Pbkdf2 { iterations, salt } => {
696                    // A negative count is outside the range too, with its sign.
697                    let out_of_range = |got: i64| {
698                        DecryptError::BadParameters(BadParameter::OutOfRange {
699                            field: ManifestField::IterationCount,
700                            got,
701                            min: PBKDF2_MIN_ITER.into(),
702                            max: limits.pbkdf2_max_iter.into(),
703                        })
704                    };
705                    let iters = u32::try_from(*iterations)
706                        .map_err(|_| out_of_range((*iterations).into()))?;
707                    if !(PBKDF2_MIN_ITER..=limits.pbkdf2_max_iter).contains(&iters) {
708                        return Err(out_of_range(iters.into()));
709                    }
710                    pbkdf2_hmac::<Sha1>(sk_bytes, salt, iters, derived_bytes);
711                    Ok(())
712                }
713                Kdf::Argon2id { t, m, p, salt } => {
714                    // Shared with `encrypt`, which chooses the same tuple rather
715                    // than reading it: `crate::kdf` is where the manifest's
716                    // hostile-parameter guards live, so both directions get them.
717                    crate::kdf::derive_argon2id(sk_bytes, salt, *t, *m, *p, limits, derived_bytes)
718                        .map_err(kdf_error)
719                }
720                // Screened out at the top of `decrypt`, ~140 lines and one
721                // function away. That distance is the whole argument for a
722                // returned error over a panic: nothing local keeps the two in
723                // step, so a future edit to the screen turns an `unreachable!`
724                // into an abort inside somebody else's library call.
725                Kdf::PgpRsaOaepMgf1p => Err(DecryptError::Internal(
726                    "PGP row reached derive_key; decrypt screens PGP before deriving".into(),
727                )),
728            }
729        })
730    })?;
731    Ok(derived)
732}
733
734/// Can `cipher` take a derived key of `n` bytes?
735///
736/// Knowable from the manifest alone, which is the whole point: the cipher's own
737/// refusal arrives *after* the key derivation that produced the key it refuses,
738/// and a row is free to make that derivation expensive. PBKDF2 emits
739/// `ceil(dkLen / 20)` HMAC-SHA1 blocks, so `manifest:key-size="64"` against an
740/// AES row costs twice what 32 does and is then thrown away -- a multiplier the
741/// file was never entitled to spend. See issue #79.
742///
743/// **This is a cost screen, not a fidelity change.** It accepts and refuses
744/// exactly the set the cipher does, so no package's outcome moves; only the
745/// moment of the refusal does. LibreOffice derives first too -- `StaticGetCipher`
746/// tests `m_nDerivedKeySize < 0` and nothing else before deriving
747/// (`ZipFile.cxx:154-157`) -- and that is not a reason to keep the ordering,
748/// because what its behaviour binds is which packages are accepted, and the
749/// timing of an error inside this function is not something a package can
750/// observe.
751///
752/// Kept in step with the cipher by `screen_matches_what_the_cipher_accepts`,
753/// which constructs every variant at every length rather than trusting this
754/// list. A hand-maintained copy of another crate's constraint is a proxy, and
755/// proxies here drift silently.
756fn cipher_accepts_key_len(cipher: Cipher, n: i32) -> bool {
757    match cipher {
758        // NSS picks AES-128/192/256 from the derived key length, so these are the
759        // three the dispatch below can name -- see `decrypt_aes_gcm`.
760        Cipher::AesGcmW3c | Cipher::AesCbcW3c => matches!(n, 16 | 24 | 32),
761        // Blowfish takes a variable key. Measured against `blowfish` 0.9 rather
762        // than read off the algorithm: `4..=56`, which is what
763        // `DERIVED_KEY_MAX_LEN`'s own doc means by "56 is Blowfish's maximum key;
764        // 64 rounds it up".
765        Cipher::BlowfishCfb8 => (4..=56).contains(&n),
766    }
767}
768
769/// Everything a row can be refused for **without deriving a key**.
770///
771/// `decrypt` must derive before it can tell whether the password is even right,
772/// so a manifest names the cost of its own rejection. Any check whose inputs are
773/// already in hand therefore belongs in front of the KDF, not behind it — and all
774/// of these were behind it: the cipher's key length (issue #79), the IV length,
775/// and the two member-shape tests. Each cost a full derivation to report
776/// something knowable from an integer comparison.
777///
778/// Only the moment of the refusal moved when these came forward. Since #105
779/// each carries a structured [`BadParameter`] rather than a message.
780///
781/// The cipher functions still carry these checks. They are unreachable through
782/// this path and kept anyway, because `decrypt_aes_gcm` indexes `blob` by a
783/// length one of them establishes — a non-local invariant is a poor thing to hang
784/// "the library does not panic" on. Each is labelled where it sits.
785#[cfg(test)]
786fn screen_before_deriving(row: &EntryEncryption, blob: &[u8]) -> Result<(), DecryptError> {
787    let head = &blob[..blob.len().min(AES_GCM_IV_LEN)];
788    screen_shape(row, blob.len() as u64, head)
789}
790
791/// [`screen_before_deriving`] for a member that is not in memory: its length,
792/// and its first bytes (at most `AES_GCM_IV_LEN` are looked at). The streaming
793/// path calls this; the whole-buffer one reaches it through the function above,
794/// so both refuse the same members with the same messages.
795pub(crate) fn screen_shape(
796    row: &EntryEncryption,
797    len: u64,
798    head: &[u8],
799) -> Result<(), DecryptError> {
800    if !cipher_accepts_key_len(row.cipher, row.derived_key_len) {
801        return Err(DecryptError::BadParameters(
802            BadParameter::KeySizeForCipher {
803                got: row.derived_key_len,
804                cipher: row.cipher,
805            },
806        ));
807    }
808    // A cipher's IV length is the cipher's own requirement, exactly one value.
809    let iv_len = |by: Primitive, want: usize| {
810        if row.iv.len() == want {
811            Ok(())
812        } else {
813            Err(DecryptError::BadParameters(BadParameter::CipherRejects {
814                field: ManifestField::IvLen,
815                by,
816                got: wide(row.iv.len()),
817                min: wide(want),
818                max: wide(want),
819            }))
820        }
821    };
822    let member = |fault| Err(DecryptError::BadParameters(BadParameter::Member(fault)));
823    match row.cipher {
824        Cipher::AesGcmW3c => {
825            iv_len(Primitive::AesGcm, AES_GCM_IV_LEN)?;
826            if len < (AES_GCM_IV_LEN + AES_GCM_TAG_LEN) as u64 || head.len() < AES_GCM_IV_LEN {
827                return member(MemberFault::ShorterThanIvAndTag);
828            }
829            if head[..AES_GCM_IV_LEN] != row.iv[..] {
830                return member(MemberFault::IvMismatch);
831            }
832        }
833        Cipher::AesCbcW3c => {
834            iv_len(Primitive::AesCbc, AES_CBC_IV_LEN)?;
835            if len == 0 || !len.is_multiple_of(AES_BLOCK_LEN as u64) {
836                return member(MemberFault::NotBlockMultiple);
837            }
838        }
839        Cipher::BlowfishCfb8 => iv_len(Primitive::Blowfish, BLOWFISH_IV_LEN)?,
840    }
841    Ok(())
842}
843
844/// Bound `manifest:size` before it becomes an allocation length.
845///
846/// **Its original reason is gone, and the same thing happened here as to
847/// `ARGON2_MAX_M_COST_KIB_READ`.** This doc used to argue the ceiling like this: a
848/// sized slot moves the allocation ahead of the decode, `size` is an `i64` the
849/// manifest controls, and `vec![0u8; huge]` aborts the caller's process rather
850/// than returning an error. The first two clauses still hold. The third does
851/// not: the slot is allocated by [`try_zeroed`] now, so an unaffordable `size`
852/// returns [`DecryptError::HostCannotAllocate`] and the abort it was guarding
853/// against cannot happen.
854///
855/// What the check still does, and it is not nothing:
856///
857/// - **`size < 0` and the `i64` -> `usize` cast.** A negative `manifest:size`
858///   has no meaning and a 64-bit value cast on a 32-bit host truncates. That
859///   half is a correctness bound and is not up for review.
860/// - **Refusing absurd sizes before any work.** A row claiming a petabyte is
861///   answered by a comparison rather than by an allocation attempt and a KDF.
862///
863/// What it no longer does is prevent an abort, so `INFLATE_CEILING` itself is
864/// now a **policy** cap in exactly the sense `src/limits.rs` means, with the
865/// same open question over it: it refuses a host that could have coped, and no
866/// longer saves one that could not. Not widened here -- that is the same
867/// decision, and it belongs with the others rather than being taken quietly in
868/// a doc comment.
869pub(crate) fn inflated_len(size: i64) -> Result<usize, DecryptError> {
870    if !(0..=INFLATE_CEILING as i64).contains(&size) {
871        return Err(DecryptError::BadParameters(BadParameter::OutOfRange {
872            field: ManifestField::Size,
873            got: size,
874            min: 0,
875            max: wide(INFLATE_CEILING),
876        }));
877    }
878    // Bounded above by INFLATE_CEILING, itself a `usize`, so this cannot truncate.
879    Ok(size as usize)
880}
881
882/// Rebuild a start tag without `manifest:size`, which an LO plaintext save never writes.
883fn without_size(e: &BytesStart<'_>) -> BytesStart<'static> {
884    let name = String::from_utf8_lossy(e.name().as_ref()).into_owned();
885    let mut out = BytesStart::new(name);
886    let strip_size = e.local_name().as_ref() == b"file-entry";
887    for attr in e.attributes().flatten() {
888        if strip_size && is_manifest_size_attr(attr.key.as_ref()) {
889            continue;
890        }
891        out.push_attribute((attr.key.as_ref(), attr.value.as_ref()));
892    }
893    out.into_owned()
894}
895
896pub(crate) fn strip_manifest(xml: &[u8]) -> Result<Vec<u8>, DecryptError> {
897    let mut reader = Reader::from_reader(xml);
898    reader.config_mut().trim_text(false);
899    // `io::Write for Vec<u8>` is infallible -- its `write_all` is
900    // `extend_from_slice` then `Ok(())` -- so the four `write_event` calls below
901    // cannot fail today. quick-xml's signature says they can (`writer.rs:193`
902    // returns `io::Result<()>`), and an `.expect()` here would abort a caller's
903    // process to report that quick-xml had changed its mind.
904    //
905    // `Internal`, not `Zip`: no manifest byte can make `extend_from_slice` fail,
906    // so a failure here would blame the package for a broken invariant of ours
907    // -- and the CLI would print exit 6, "malformed or hostile package", for it.
908    // Deliberately the same mapping, message and reasoning as
909    // `encrypt::build_manifest`, which had it right; two files making one call
910    // and giving two answers was the defect.
911    let mut writer = Writer::new(Vec::new());
912    let mut buf = Vec::new();
913    let mut skip_depth = 0u32;
914
915    loop {
916        buf.clear();
917        match reader.read_event_into(&mut buf) {
918            Ok(Event::Eof) => break,
919            Ok(Event::Start(e)) => {
920                if skip_depth > 0 {
921                    skip_depth += 1;
922                    continue;
923                }
924                if e.local_name().as_ref() == b"encryption-data" {
925                    skip_depth = 1;
926                    continue;
927                }
928                writer
929                    .write_event(Event::Start(without_size(&e)))
930                    .map_err(|e| DecryptError::Internal(format!("manifest XML write: {e}")))?;
931            }
932            Ok(Event::End(e)) => {
933                if skip_depth > 0 {
934                    skip_depth -= 1;
935                    continue;
936                }
937                writer
938                    .write_event(Event::End(e.into_owned()))
939                    .map_err(|e| DecryptError::Internal(format!("manifest XML write: {e}")))?;
940            }
941            Ok(Event::Empty(e)) => {
942                if skip_depth > 0 {
943                    continue;
944                }
945                if e.local_name().as_ref() == b"encryption-data" {
946                    continue;
947                }
948                // A file-entry with no children is an Empty event, and it can still
949                // carry manifest:size. Filtering only Start would leave those behind.
950                writer
951                    .write_event(Event::Empty(without_size(&e)))
952                    .map_err(|e| DecryptError::Internal(format!("manifest XML write: {e}")))?;
953            }
954            Ok(other) => {
955                if skip_depth > 0 {
956                    continue;
957                }
958                writer
959                    .write_event(other)
960                    .map_err(|e| DecryptError::Internal(format!("manifest XML write: {e}")))?;
961            }
962            // Stays `Zip`, and stays un-elided. This is the READ side: its
963            // payload is document-derived, and it is the half #48 was about.
964            // The path is unreachable -- see `DecryptError::Zip`'s rustdoc for
965            // the argument and the test that keeps it honest.
966            Err(e) => return Err(DecryptError::Zip(e.to_string())),
967        }
968    }
969    Ok(writer.into_inner())
970}
971
972/// Compare metadata that must survive per-entry decrypt (for tests).
973#[cfg(test)]
974pub(crate) fn classification_metadata_unchanged(
975    before: &crate::Classification,
976    after: &crate::Classification,
977) -> bool {
978    before.odf_version == after.odf_version
979        && before.media_type == after.media_type
980        && before.zip_has_encrypted_package == after.zip_has_encrypted_package
981}
982
983#[cfg(test)]
984#[path = "decrypt_tests.rs"]
985mod tests;