Skip to main content

odf_crypto/
encrypt.rs

1//! Password encryption for ODF packages.
2//!
3//! `encrypt` turns a plaintext ODF package (`classify` reports [`Mode::Plain`])
4//! into what current LibreOffice writes for that same input under that password:
5//! one `encrypted-package` member, Argon2id-derived AES-256-GCM, no checksum,
6//! `manifest:version="1.4"`. Modern (wholesome) only -- per-entry write and PGP
7//! wrap are later, out-of-scope arcs. See
8//! `docs/plans/odf-encryption-encrypt-2026-09-03.md`.
9
10use std::io::Read;
11
12use quick_xml::events::{BytesDecl, BytesEnd, BytesStart, Event};
13use quick_xml::Writer;
14use secure_gate::{RevealSecret, RevealSecretMut};
15use zip::ZipArchive;
16
17use crate::limits::{
18    AES_GCM_IV_LEN, ARGON2_MAX_M_COST_KIB_WRITE, ARGON2_MAX_T_COST_WRITE, ARGON2_MIN_M_COST_KIB,
19    ARGON2_MIN_P_COST, ARGON2_MIN_T_COST, DEFLATE_CEILING, MIMETYPE_CEILING,
20};
21use crate::sensitive::DerivedKey;
22use crate::types::{Mode, StartKeyAlg};
23use crate::uris;
24use crate::DetectError;
25
26/// The one profile this arc writes (plan §1's last row, §2's emit table).
27///
28/// Spelled once and consumed by both the KDF call and the manifest emit, so
29/// the two cannot drift: a key derived under one `m` while the manifest
30/// promises another is a bug no round-trip test would catch if the two were
31/// separate literals, because `decrypt` reads the manifest's copy.
32pub(crate) struct Profile {
33    /// Argon2 `(t, m, p)` in the manifest's own `sal_Int32` type, in the
34    /// order `manifest:` writes them -- *not* `Params::new`'s `(m, t, p)`.
35    argon2_t: i32,
36    argon2_m_kib: i32,
37    argon2_p: i32,
38    derived_key_len: usize,
39    pub(crate) salt_len: usize,
40    pub(crate) iv_len: usize,
41    odf_version: &'static str,
42}
43
44/// `SetupStorage`'s wholesome row: Argon2id `(3, 65536, 4)`, AES-256-GCM,
45/// SHA-256 start key, no checksum (`objstor.cxx:349-399`); salt 16 bytes and
46/// IV 12 bytes per `ZipPackageStream.cxx:587-607`.
47pub(crate) const WHOLESOME: Profile = Profile {
48    argon2_t: 3,
49    argon2_m_kib: 65536,
50    argon2_p: 4,
51    derived_key_len: 32,
52    salt_len: 16,
53    iv_len: 12,
54    odf_version: "1.4",
55};
56
57// The invariants that make this arc's Argon2id and AES-GCM calls reject
58// nothing about their PARAMETERS, checked at compile time rather than
59// asserted in a comment: argon2 requires `m >= 8p` and a salt of at least 8
60// bytes, AES-256 needs a 32-byte key, and GCM's nonce is 96 bits.
61// `uris::AESGCM256_URL` in `build_manifest` is keyed to `derived_key_len ==
62// 32`; the assert below is what ties them together. Not a claim that the
63// Argon2id call cannot fail at all -- it can still fail on the host's
64// available memory; see `EncryptError::HostCannotAllocate`, which is about
65// the machine, not the tuple these asserts cover.
66//
67// The Argon2 `m >= 8p` assert still covers the DEFAULT tuple, but it is no
68// longer the whole story: `encrypt_with_params` takes `(t, m, p)` from a
69// caller, and a value that arrives at run time cannot be checked at compile
70// time. `Argon2Params::new` carries that same invariant to the constructor,
71// which is why it returns a `Result` and why `encrypt_with_params` cannot
72// fail on its parameters' VALIDITY. Their COST is a different axis: however
73// small the tuple, no `(t, m, p)` can guarantee in advance that this host has
74// the memory to run it.
75const _: () = assert!(WHOLESOME.argon2_m_kib >= 8 * WHOLESOME.argon2_p);
76const _: () = assert!(WHOLESOME.salt_len >= 8);
77const _: () = assert!(WHOLESOME.derived_key_len == 32);
78const _: () = assert!(WHOLESOME.iv_len == AES_GCM_IV_LEN);
79
80/// Which axis of an Argon2id tuple a [`ParamsReason`] is about.
81///
82/// Named rather than positional for the same reason [`Argon2Params`] has named
83/// fields: the manifest orders these `(t, m, p)` and `argon2::Params` orders
84/// them `(m, t, p)`, so an index would be a transposition waiting to happen.
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86#[non_exhaustive]
87pub enum Argon2Axis {
88    /// Time cost, `manifest:argon2-iterations`.
89    T,
90    /// Memory cost in KiB, `manifest:argon2-memory`.
91    MKib,
92    /// Parallelism, `manifest:argon2-lanes`.
93    P,
94}
95
96impl core::fmt::Display for Argon2Axis {
97    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
98        // Exhaustive on purpose, with no `_` arm: `#[non_exhaustive]` binds
99        // downstream crates, not this one, so adding an axis fails to compile
100        // here until it is given a name. A wildcard would silently render it
101        // as something else.
102        f.write_str(match self {
103            Self::T => "t",
104            Self::MKib => "m",
105            Self::P => "p",
106        })
107    }
108}
109
110/// Why an [`Argon2Params`] tuple was refused — specifically, **whose rule it
111/// broke**.
112///
113/// That distinction is the reason this is a type rather than a string. A
114/// consumer telling a user "the format does not allow this" when the truth is
115/// "this crate declined" has said something false with a straight face, and a
116/// free-text message gives them no way to tell the two apart. Each variant
117/// names the authority.
118///
119/// Neither variant means *weak*. A cheap-but-runnable tuple is accepted; see
120/// [`Argon2Params`].
121///
122/// `#[non_exhaustive]`: more reasons may be added, so match with a `_` arm.
123///
124/// A host that cannot allocate the requested memory is deliberately **not**
125/// one of them -- see [`EncryptError::HostCannotAllocate`], a top-level
126/// variant rather than a `ParamsReason`. `ParamsReason` is raised by
127/// [`Argon2Params::new`], before `encrypt_with_params` -- let alone the
128/// package -- is ever touched; it is `Copy + Eq`, a reproducible verdict on
129/// three integers that gives the same answer on every machine; and the CLI
130/// pins it to exit 1, usage. A host-capacity failure has none of those
131/// properties: it surfaces mid-`encrypt_with_params`, the same tuple can
132/// succeed on a machine with more free memory, and reporting it as exit 1
133/// would send someone to fix a command line that was never wrong.
134#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
135#[non_exhaustive]
136pub enum ParamsReason {
137    /// The value is outside the range `odf-crypto` acts on.
138    ///
139    /// **What that range is changed in `0.1.0-rc.6`, and this doc used to say
140    /// the opposite.** It read *"this is a policy bound of ours — do not report
141    /// it as a format violation"*, which was true when
142    /// [`Argon2Params::new`] capped `t` at `1 << 16` and `m` at 1 GiB. Both
143    /// policy caps are gone from the write path: a cost you choose for your own
144    /// machine is yours to choose. What is left here is the **format's** own
145    /// rule — `positiveInteger`, so `0` and negatives are refused, and the
146    /// manifest attribute's `i32` width above.
147    ///
148    /// So on this side a refusal now means the tuple **cannot be written into a
149    /// manifest at all**, which is the opposite of the old caveat. The policy
150    /// caps still exist where a number arrives from outside: see
151    /// [`crate::DecryptLimits`], which bounds what `decrypt` will act on and is
152    /// overridable per call.
153    #[error("{axis} = {got} is outside {min}..={max}, the range this crate acts on")]
154    OutOfRange {
155        /// Which axis was out of range.
156        axis: Argon2Axis,
157        /// The value supplied.
158        got: i32,
159        /// Inclusive floor.
160        min: u32,
161        /// Inclusive ceiling.
162        max: u32,
163    },
164    /// **`argon2` cannot run it.** Not this crate's decision, and widening our
165    /// own bounds would not help.
166    ///
167    /// Today this is `m >= 8 * p` (argon2 cannot allocate fewer than 8 KiB per
168    /// lane) and `p <= argon2::Params::MAX_P_COST`.
169    #[error("{axis} = {got} is outside {min}..={max}, which argon2 itself requires")]
170    CipherRejects {
171        /// Which axis was rejected.
172        axis: Argon2Axis,
173        /// The value supplied.
174        got: i32,
175        /// Inclusive floor `argon2` requires.
176        min: u32,
177        /// Inclusive ceiling `argon2` requires.
178        max: u32,
179    },
180}
181
182/// Argon2id cost parameters for [`encrypt_with_params`].
183///
184/// # These are a property of the file, not of the machine that wrote it
185///
186/// The three values are written into `META-INF/manifest.xml` and travel with
187/// the document. Choosing a low cost to suit a constrained device therefore
188/// weakens that document **permanently, for every future reader on every
189/// device** — the file cannot be re-derived at a higher cost without being
190/// decrypted and re-encrypted. It is a deliberate, irreversible trade and this
191/// crate does not make it for you: nothing here refuses a weak-but-valid
192/// tuple, and nothing silently substitutes a stronger one.
193///
194/// [`Argon2Params::LIBREOFFICE_DEFAULT`] is what current LibreOffice writes.
195/// Prefer it unless you have a reason you could defend to the person whose
196/// document it is.
197///
198/// # Why a struct rather than three integers
199///
200/// Two orderings of the same three `i32`s are already in play: the manifest
201/// writes `(t, m, p)` and `argon2::Params` orders them `(m, t, p)`. A tuple or
202/// array makes transposing them type-check, look plausible and still produce a
203/// file. Named fields make the mistake unrepresentable.
204///
205/// Fields are private and reached through [`t`](Self::t), [`m_kib`](Self::m_kib)
206/// and [`p`](Self::p), so a value of this type has always been validated.
207///
208/// # Examples
209///
210/// ```
211/// use odf_crypto::Argon2Params;
212///
213/// let default = Argon2Params::LIBREOFFICE_DEFAULT;
214/// assert_eq!((default.t(), default.m_kib(), default.p()), (3, 65536, 4));
215///
216/// // An eighth of the default memory: weaker, allowed, and yours to justify.
217/// let low = Argon2Params::new(2, 8192, 2)?;
218/// assert_eq!(low.m_kib(), 8192);
219///
220/// // Refused because argon2 cannot run it, not because it is weak.
221/// assert!(Argon2Params::new(3, 8, 4).is_err());
222/// # Ok::<(), odf_crypto::EncryptError>(())
223/// ```
224#[derive(Debug, Clone, Copy, PartialEq, Eq)]
225pub struct Argon2Params {
226    t: i32,
227    m_kib: i32,
228    p: i32,
229}
230
231impl Argon2Params {
232    /// What current LibreOffice writes: `t = 3`, `m = 65536` KiB (64 MiB),
233    /// `p = 4` — `oArgon2Args.emplace(3, (1<<16), 4)` in
234    /// `package/source/zippackage/ZipPackage.cxx`, on the branch taken when the
235    /// KDF is Argon2id. The tuple [`encrypt`] uses.
236    ///
237    /// This used to cite `objstor.cxx:349-399`, which is where LibreOffice
238    /// chooses Argon2id *over PBKDF2* and never names a tuple at all. The
239    /// numbers were right and the citation was not, which is the failure mode
240    /// `CLAUDE.md` means by *check the code, not the doc* — a reader following
241    /// it to confirm `65536` would not have found it.
242    pub const LIBREOFFICE_DEFAULT: Self = Self {
243        t: WHOLESOME.argon2_t,
244        m_kib: WHOLESOME.argon2_m_kib,
245        p: WHOLESOME.argon2_p,
246    };
247
248    /// Validate a `(t, m, p)` tuple, in the manifest's own order.
249    ///
250    /// `m_kib` is **kibibytes**, matching `manifest:argon2-memory` — 65536 is
251    /// 64 MiB, not 64 KiB.
252    ///
253    /// # Errors
254    ///
255    /// [`EncryptError::Params`] when the tuple cannot be run, never when it is
256    /// merely weak. Two reasons, and the distinction is the point:
257    ///
258    /// - a value outside the range this crate acts on at all, which is the
259    ///   same range `decrypt` accepts off a manifest, so anything `encrypt`
260    ///   writes can be read back;
261    /// - `m_kib < 8 * p`, which `argon2` itself rejects — the invariant the
262    ///   default tuple checks with a `const` assert.
263    pub fn new(t: i32, m_kib: i32, p: i32) -> Result<Self, EncryptError> {
264        // Ours. The schema and LibreOffice both permit more; see
265        // `ParamsReason::OutOfRange`.
266        let ours = |axis, got, min, max| {
267            EncryptError::Params(ParamsReason::OutOfRange {
268                axis,
269                got,
270                min,
271                max,
272            })
273        };
274        if !(ARGON2_MIN_T_COST..=ARGON2_MAX_T_COST_WRITE).contains(&u32::try_from(t).unwrap_or(0)) {
275            return Err(ours(
276                Argon2Axis::T,
277                t,
278                ARGON2_MIN_T_COST,
279                ARGON2_MAX_T_COST_WRITE,
280            ));
281        }
282        if !(ARGON2_MIN_M_COST_KIB..=ARGON2_MAX_M_COST_KIB_WRITE)
283            .contains(&u32::try_from(m_kib).unwrap_or(0))
284        {
285            return Err(ours(
286                Argon2Axis::MKib,
287                m_kib,
288                ARGON2_MIN_M_COST_KIB,
289                ARGON2_MAX_M_COST_KIB_WRITE,
290            ));
291        }
292        // `argon2::Params::MAX_P_COST`, not a bound of ours -- the same
293        // ceiling `kdf::derive_argon2id` applies on the read side, so the two
294        // directions cannot disagree about which tuples exist. Reported as
295        // `CipherRejects` for that reason: widening our own range would not
296        // make this tuple runnable.
297        if !(ARGON2_MIN_P_COST..=argon2::Params::MAX_P_COST)
298            .contains(&u32::try_from(p).unwrap_or(0))
299        {
300            return Err(EncryptError::Params(ParamsReason::CipherRejects {
301                axis: Argon2Axis::P,
302                got: p,
303                min: ARGON2_MIN_P_COST,
304                max: argon2::Params::MAX_P_COST,
305            }));
306        }
307        // argon2's own requirement, not a policy of ours: it cannot allocate
308        // fewer than 8 KiB per lane. Checked here because a caller-supplied
309        // tuple cannot be checked by the `const` assert above. `p` is already
310        // bounded by MAX_P_COST above, so `8 * p` cannot overflow `i32`.
311        if m_kib < 8 * p {
312            return Err(EncryptError::Params(ParamsReason::CipherRejects {
313                axis: Argon2Axis::MKib,
314                got: m_kib,
315                min: u32::try_from(8 * p).unwrap_or(u32::MAX),
316                max: ARGON2_MAX_M_COST_KIB_WRITE,
317            }));
318        }
319        Ok(Self { t, m_kib, p })
320    }
321
322    /// Time cost, `manifest:argon2-iterations`.
323    #[must_use]
324    pub fn t(&self) -> i32 {
325        self.t
326    }
327
328    /// Memory cost in **KiB**, `manifest:argon2-memory`.
329    #[must_use]
330    pub fn m_kib(&self) -> i32 {
331        self.m_kib
332    }
333
334    /// Parallelism, `manifest:argon2-lanes`.
335    #[must_use]
336    pub fn p(&self) -> i32 {
337        self.p
338    }
339
340    /// Whether **any** axis is below what LibreOffice writes.
341    ///
342    /// Reported, never enforced — [`encrypt_with_params`] accepts a tuple for
343    /// which this is `true`. It exists so a front end can say so: the CLI
344    /// prints a warning on this, and a library consumer can do the same
345    /// rather than re-deriving the comparison.
346    ///
347    /// # It is a warning trigger, not a strength ordering
348    ///
349    /// "Any axis below" is the right question for *should I warn about this*
350    /// and the wrong one for *is this cryptographically weaker*, because the
351    /// three axes do not trade off linearly and this collapses them to a bool.
352    /// A tuple can be below on one axis and well above on another:
353    ///
354    /// ```
355    /// use odf_crypto::Argon2Params;
356    ///
357    /// // One fewer pass, but twice LibreOffice's memory. Reported weaker.
358    /// let mixed = Argon2Params::new(2, 131_072, 4)?;
359    /// assert!(mixed.is_weaker_than_libreoffice());
360    ///
361    /// // Stronger on t, identical elsewhere. Not reported weaker.
362    /// let stronger = Argon2Params::new(4, 65536, 4)?;
363    /// assert!(!stronger.is_weaker_than_libreoffice());
364    /// # Ok::<(), odf_crypto::EncryptError>(())
365    /// ```
366    ///
367    /// Warning on the first is deliberate — it is below the reference on an
368    /// axis, and a caller deserves to be told before that is frozen into a
369    /// document — but do not read it as "this file is weaker overall". If you
370    /// need a per-axis decision, compare [`t`](Self::t), [`m_kib`](Self::m_kib)
371    /// and [`p`](Self::p) against [`Self::LIBREOFFICE_DEFAULT`] yourself;
372    /// `m_kib` is usually the axis a memory-constrained device cares about.
373    #[must_use]
374    pub fn is_weaker_than_libreoffice(&self) -> bool {
375        let d = Self::LIBREOFFICE_DEFAULT;
376        self.t < d.t || self.m_kib < d.m_kib || self.p < d.p
377    }
378}
379
380/// Failures from [`encrypt`].
381#[derive(Debug, thiserror::Error)]
382#[non_exhaustive]
383pub enum EncryptError {
384    /// `classify()` itself rejected the input (not a zip, no manifest, ...).
385    #[error("classification failed: {0}")]
386    Classify(#[from] DetectError),
387    /// The package is encrypted and LibreOffice would prompt for a password:
388    /// `classify` set [`crate::Classification::package_encrypted`], the latch
389    /// LibreOffice calls `HasEncryptedEntries`. Covers `Wholesome`, `PerEntry`
390    /// with a latch row, and PGP rows alike.
391    ///
392    /// Split from [`EncryptError::PartiallyEncrypted`] in `0.1.0-rc.5`, because
393    /// one variant was making a claim about the file that LibreOffice does not
394    /// make -- see that variant.
395    #[error("package is already encrypted")]
396    AlreadyEncrypted,
397    /// The package holds complete `encryption-data` rows but **no latch row**,
398    /// so `classify` reports [`crate::Mode::PerEntry`] with
399    /// `package_encrypted == false`.
400    ///
401    /// **LibreOffice never asks for this file's password.** The latch is set
402    /// only by a row resolving to `content.xml` or `encrypted-package`
403    /// (`ZipPackage.cxx:435-446`), and the password prompt is gated on the
404    /// latch, so a package whose only complete rows sit on other members is
405    /// not, to LibreOffice, an encrypted document.
406    ///
407    /// What happens instead was **measured in rc.9** (`tools/probe_unlatched.py`,
408    /// both orders): with `styles.xml`, `settings.xml`, `meta.xml` and
409    /// `manifest.rdf` encrypted and `content.xml` plain, LibreOffice raises
410    /// `ERRCODE_SFX_WRONGPASSWORD` without ever having asked, and refuses to
411    /// open. Supplied the password programmatically it opens normally. Writer's
412    /// import (`sw/source/filter/xml/swxml.cxx`) maps an encrypted stream it
413    /// cannot read to that error, so a package whose encrypted members are ones
414    /// the load never reads may open; that variant was not measured.
415    ///
416    /// Before rc.9 this doc said LibreOffice *opens* the file without
417    /// prompting. That was inferred from the latch alone and is wrong for the
418    /// measured shape; the "no prompt" half was right.
419    ///
420    /// Reporting this as *"package is already encrypted"* would still tell a
421    /// caller something the specifying implementation contradicts: to
422    /// LibreOffice this is not an encrypted document.
423    ///
424    /// Still refused, and the refusal is the same one: wrapping a package whose
425    /// members are already ciphertext produces a file whose inner members
426    /// nothing can open. What changed is the name of what was detected, not the
427    /// decision. Both map to CLI exit 5.
428    ///
429    /// LibreOffice's own answer to this shape is worth knowing, because this
430    /// crate cannot give it: on ODF >= 1.2 with the latch *also* set, it raises
431    /// `ERRCODE_SFX_INCOMPLETE_ENCRYPTION` and disables macro execution
432    /// (`sfx2/source/doc/objmisc.cxx:1028-1063`).
433    #[error(
434        "package has encrypted entries but no latch row: LibreOffice never prompts for its password"
435    )]
436    PartiallyEncrypted,
437    /// LibreOffice would not open this plaintext package (`odf12_fatal`):
438    /// unexpected streams and a root version `>= 1.2`. Refuse before Argon2id
439    /// rather than wrapping a document LO rejects.
440    #[error("LibreOffice would refuse this package: unexpected ODF 1.2 streams")]
441    Odf12Fatal,
442    /// Mirrors [`crate::DecryptError::EmptyPassword`] /
443    /// `CreatePackageEncryptionData`'s empty sequence.
444    #[error("password is empty")]
445    EmptyPassword,
446    /// CSPRNG failure -- vanishingly rare, but a library must not panic for it.
447    #[error("random number generation failed: {0}")]
448    Random(String),
449    /// An [`Argon2Params`] tuple that cannot be used, carrying **whose rule**
450    /// it broke — see [`ParamsReason`].
451    ///
452    /// **Never returned for a tuple that is merely weak.** Cost is the
453    /// caller's decision and this crate does not overrule it; see
454    /// [`Argon2Params`].
455    ///
456    /// Deliberately distinct from [`EncryptError::Internal`]: this reports a
457    /// value that came from the caller, which they can correct, where
458    /// `Internal` reports an invariant of ours. It quotes only the caller's own
459    /// numbers and this crate's bounds, never anything read out of a package.
460    ///
461    /// # Do not render this as a problem with the document
462    ///
463    /// It is a **usage** error: the tuple was wrong, the input package was
464    /// never examined. It is raised by [`Argon2Params::new`] before
465    /// [`encrypt_with_params`] is even called, so it says nothing about the
466    /// bytes a caller passed. A consumer that renders it as "this file is
467    /// damaged" tells the user the one thing it does not mean, and sends them
468    /// looking at the wrong thing. The `odf-crypto` binary maps it to exit 1
469    /// (usage), not 6 (malformed), for the same reason.
470    #[error("invalid Argon2 parameters: {0}")]
471    Params(ParamsReason),
472    /// This host could not allocate the working memory Argon2id needs.
473    ///
474    /// **Not an invalid tuple.** `params` was validated when it was
475    /// constructed; this is the machine declining, and the same call may
476    /// succeed on a machine with more free memory. Lowering
477    /// [`Argon2Params::m_kib`] is a legitimate response, but read
478    /// [`Argon2Params`] first: the cost is stored in the file and binds
479    /// every future reader on every device, so trading it away to fit
480    /// today's host is irreversible.
481    #[error("host could not allocate {requested_bytes} bytes for key derivation")]
482    HostCannotAllocate {
483        /// The size, in bytes, of the working buffer Argon2id could not
484        /// obtain: `params.m_kib` rounded up to whole blocks.
485        requested_bytes: usize,
486    },
487    /// The input buffer cannot be deflated. `compress_to_vec` itself is
488    /// infallible, so in practice this is the 1 GiB input-size rejection.
489    #[error("deflate failed: {0}")]
490    Deflate(String),
491    /// The input's own `mimetype` member cannot be carried into the output.
492    /// Four reasons, all of which `classify` itself tolerates (its check is
493    /// `starts_with("application/vnd.")` over the first 1024 bytes):
494    ///
495    /// - over 1 KiB, which is all `classify` ever looked at;
496    /// - not valid UTF-8;
497    /// - containing a character outside XML 1.0's `Char` production, which
498    ///   would emit a `manifest.xml` real LibreOffice's expat rejects;
499    /// - containing a tab, LF or CR. Those are legal `Char`s, but XML
500    ///   attribute-value normalization rewrites each to a space on the way
501    ///   back in, so the verbatim `mimetype` zip member and the parsed
502    ///   `manifest:media-type` would then disagree.
503    ///
504    /// All four fail closed rather than writing a package that classifies but
505    /// will not open.
506    #[error("unusable mimetype member: {0}")]
507    Mimetype(String),
508    /// A zip failure on either side: reading the input's own `mimetype`
509    /// member, or building the outer container `encrypt` writes. The string
510    /// is a diagnostic; do not match on its content.
511    #[error("zip error: {0}")]
512    Zip(String),
513    /// A crypto primitive rejected parameters `encrypt` chose *itself* -- the
514    /// wholesome profile's Argon2id tuple, its 32-byte key, its 12-byte nonce.
515    /// Unreachable today: every one of those is a compile-time constant
516    /// guarded by `const` asserts beside the profile, which is why this
517    /// carries no recovery advice.
518    ///
519    /// **Not** where a host's inability to allocate Argon2id's working memory
520    /// lands: that is [`EncryptError::HostCannotAllocate`], a distinct
521    /// variant because it blames the machine, not a parameter a crypto
522    /// primitive refused.
523    ///
524    /// Also covers a supposedly infallible write failing: `io::Write for
525    /// Vec<u8>` through quick-xml, when building the manifest.
526    ///
527    /// It exists because the alternative is a panic in a library. This is
528    /// deliberately not a `BadParameters` analogue: that variant would report
529    /// an *untrusted manifest field*, which `encrypt` never reads. This
530    /// reports an internal invariant a dependency bump could invalidate under
531    /// us -- if `argon2` or `aes-gcm` ever narrows what it accepts, the
532    /// failure surfaces as an `Err` a caller can handle rather than an abort
533    /// it cannot.
534    #[error("internal invariant violated: {0}")]
535    Internal(String),
536    /// The caller's reader or writer failed. Nothing is implied about the
537    /// package. The error is the caller's own value, so a cancellation can be
538    /// recognized in it.
539    #[error("I/O failed: {0}")]
540    Io(#[source] std::io::Error),
541}
542
543/// Encrypt a plaintext ODF package with `password`, producing what current
544/// LibreOffice writes for that input under that password.
545///
546/// One profile only: wholesome Argon2id-derived AES-256-GCM, a single
547/// `encrypted-package` member, no checksum. The salt and IV are fresh per call,
548/// so two calls on the same input never produce the same bytes — assert on a
549/// round trip, never on the output.
550///
551/// # Errors
552///
553/// Refused before any crypto runs, in this order, so no caller pays for a
554/// 64 MiB Argon2id before learning the input was never eligible:
555/// [`EncryptError::EmptyPassword`] (mirroring [`crate::decrypt`]'s own ordering),
556/// [`EncryptError::AlreadyEncrypted`] for anything [`classify`](crate::classify) does not report
557/// as [`Mode::Plain`], [`EncryptError::Classify`] if classification itself
558/// fails, [`EncryptError::Odf12Fatal`] for a package LibreOffice would refuse,
559/// and [`EncryptError::Mimetype`] for a `mimetype` member that cannot be
560/// carried into the output.
561///
562/// [`EncryptError::HostCannotAllocate`] is different from every entry above:
563/// it is not a pre-crypto screen. It surfaces mid-derivation, after the
564/// whole-input deflate has already run, if the host cannot supply Argon2id's
565/// working memory.
566///
567/// Then [`EncryptError::Deflate`] (in practice, an input over 1 GiB),
568/// [`EncryptError::Random`], [`EncryptError::Zip`] and
569/// [`EncryptError::Internal`].
570///
571/// [`EncryptError`] is `#[non_exhaustive]` and does not implement `PartialEq`;
572/// match with a `_` arm and [`matches!`].
573///
574/// # Examples
575///
576/// ```
577/// use odf_crypto::{classify, decrypt, encrypt, Mode};
578///
579/// let plain = include_bytes!("../tests/goldens/lo-unencrypted.odt");
580/// assert_eq!(classify(plain)?.mode, Mode::Plain);
581///
582/// let sealed = encrypt(plain, "correct horse battery staple")?;
583/// assert_eq!(classify(&sealed)?.mode, Mode::Wholesome);
584///
585/// // Round trips byte for byte.
586/// let back = decrypt(&sealed, "correct horse battery staple")?;
587/// assert_eq!(back, plain.as_slice());
588/// # Ok::<(), Box<dyn std::error::Error>>(())
589/// ```
590pub fn encrypt(bytes: &[u8], password: &str) -> Result<Vec<u8>, EncryptError> {
591    encrypt_with_params(bytes, password, Argon2Params::LIBREOFFICE_DEFAULT)
592}
593
594/// [`encrypt`] with the Argon2id cost chosen by the caller.
595///
596/// Identical in every other respect: one `encrypted-package` member,
597/// AES-256-GCM, a SHA-256 start key, no checksum, `manifest:version="1.4"`.
598/// Only `(t, m, p)` moves, and it moves into both the key derivation and the
599/// `loext:argon2-*` attributes, so the file describes how it was actually
600/// derived.
601///
602/// # This can produce a deliberately weak file, and will not stop you
603///
604/// `params` is accepted whenever `argon2` can run it — see [`Argon2Params`]
605/// for what is refused and why. A cost below
606/// [`Argon2Params::LIBREOFFICE_DEFAULT`] is not an error here, and this
607/// function does not warn: a library has no terminal to warn on. Call
608/// [`Argon2Params::is_weaker_than_libreoffice`] if you want to tell someone.
609///
610/// The cost travels **with the document**, so it is not a local performance
611/// setting. A file written at a low cost stays that weak for every future
612/// reader, including on hardware that could have afforded more.
613///
614/// # Real LibreOffice reads these back
615///
616/// Verified against LibreOffice 26.2.1.2 rather than inferred from the format:
617/// packages written at `(3, 65536, 4)`, `(2, 8192, 2)` and `(1, 1024, 1)` all
618/// open with the correct text recovered.
619///
620/// Its source bounds every tuple, not just those three. `ManifestImport.cxx:257`
621/// checks the attributes for positivity and nothing else — no floor, no ceiling,
622/// no clamp — and `ZipFile.cxx:184-186` passes the file's own values straight
623/// into `argon2_context`, with `:192` saying why there is no range check there
624/// either: *"libargon2 validates all the arguments so don't need to do it
625/// here."* What this crate will write is a strict subset of what libargon2
626/// accepts, so no tuple it produces is refusable by LibreOffice on parameter
627/// grounds.
628///
629/// # Errors
630///
631/// Exactly [`encrypt`]'s. `params`' *validity* was checked when it was
632/// constructed, so this still cannot fail on that: [`EncryptError::Params`]
633/// comes from [`Argon2Params::new`], not from here.
634///
635/// `params`' *cost* is a different question, and construction cannot have
636/// checked it: [`EncryptError::HostCannotAllocate`] can still occur here,
637/// scaling with `params.m_kib()` -- the one axis of the tuple a caller
638/// chooses and the one no validation can guarantee a given host can afford.
639///
640/// # Examples
641///
642/// ```
643/// use odf_crypto::{classify, decrypt, encrypt_with_params, Argon2Params, Kdf};
644///
645/// let plain = include_bytes!("../tests/goldens/lo-unencrypted.odt");
646/// let cheap = Argon2Params::new(2, 8192, 2)?;
647/// assert!(cheap.is_weaker_than_libreoffice());
648///
649/// let sealed = encrypt_with_params(plain, "hunter2", cheap)?;
650///
651/// // The file records the cost it was actually derived at.
652/// let row = classify(&sealed)?.common.expect("wholesome carries a latch row");
653/// assert!(matches!(row.kdf, Kdf::Argon2id { t: 2, m: 8192, p: 2, .. }));
654/// assert_eq!(decrypt(&sealed, "hunter2")?, plain.as_slice());
655/// # Ok::<(), Box<dyn std::error::Error>>(())
656/// ```
657pub fn encrypt_with_params(
658    bytes: &[u8],
659    password: &str,
660    params: Argon2Params,
661) -> Result<Vec<u8>, EncryptError> {
662    crate::encrypt_stream::encrypt_slice(bytes, password, params, DEFLATE_CEILING as u64)
663}
664
665/// Plan §6 step 4/6: the SHA-256 start key, then Argon2id over it with `salt`
666/// -- `crate::kdf`'s helpers, shared verbatim with `decrypt`, so the two
667/// directions cannot derive keys differently. Shared by [`encrypt`] and
668/// `encrypt_to`.
669pub(crate) fn derive_write_key(
670    password: &str,
671    salt: &[u8],
672    params: Argon2Params,
673) -> Result<DerivedKey, EncryptError> {
674    let start_key = crate::kdf::start_key(password, StartKeyAlg::Sha256);
675    let mut derived_key = DerivedKey::new(vec![0u8; WHOLESOME.derived_key_len]);
676    start_key.with_secret(|sk| {
677        derived_key.with_secret_mut(|key| {
678            crate::kdf::derive_argon2id(
679                sk,
680                salt,
681                params.t,
682                params.m_kib,
683                params.p,
684                // The write path's own ceilings, not `DecryptLimits::default()`:
685                // these are the caller's numbers about their own machine, so
686                // only the field widths and the cipher bound them. Same
687                // reasoning as `ARGON2_MAX_M_COST_KIB_WRITE`'s own doc.
688                &crate::DecryptLimits::PERMISSIVE
689                    .with_argon2_max_t(ARGON2_MAX_T_COST_WRITE)
690                    .with_argon2_max_m_kib(ARGON2_MAX_M_COST_KIB_WRITE),
691                key,
692            )
693            .map_err(
694                // Exhaustive, no `_` arm: the next `KdfError` variant must be
695                // given a deliberate mapping here rather than silently
696                // inheriting one -- the same discipline `Argon2Axis`'s
697                // `Display` impl follows at its own match, above.
698                |e| match e {
699                    crate::kdf::KdfError::Params(b) => EncryptError::Internal(b.to_string()),
700                    crate::kdf::KdfError::Internal(s) => EncryptError::Internal(s.into()),
701                    crate::kdf::KdfError::HostCannotAllocate { requested_bytes }
702                    | crate::kdf::KdfError::HostCannotSpawn { requested_bytes } => {
703                        EncryptError::HostCannotAllocate { requested_bytes }
704                    }
705                },
706            )
707        })
708    })?;
709
710    Ok(derived_key)
711}
712
713/// The refusals `encrypt` makes from the classification alone. Shared with
714/// `encrypt_to`, so the two refuse the same inputs for the same reasons.
715pub(crate) fn screen_input(class: &crate::Classification) -> Result<(), EncryptError> {
716    if class.mode != Mode::Plain {
717        // The latch, not the row count. `package_encrypted` is LibreOffice's
718        // `HasEncryptedEntries`, and it is what decides whether LO prompts --
719        // so it is what decides which refusal is true of this file.
720        return Err(if class.package_encrypted {
721            EncryptError::AlreadyEncrypted
722        } else {
723            EncryptError::PartiallyEncrypted
724        });
725    }
726    if class.odf12_fatal {
727        return Err(EncryptError::Odf12Fatal);
728    }
729    Ok(())
730}
731
732/// `len` random bytes via a CSPRNG (`ZipPackageStream.cxx:590,594` -- LO's
733/// `rtl_random_getBytes`, here `getrandom::fill`, the OS generator `zip`
734/// already depends on; plan OQ2 chose `aes_gcm`'s `OsRng`, which wrapped the
735/// same source, until rc.15 dropped aes-gcm from the runtime graph). Fallible:
736/// a library must not panic for an ordinary CSPRNG failure (plan §4).
737pub(crate) fn random_bytes(len: usize) -> Result<Vec<u8>, EncryptError> {
738    let mut buf = vec![0u8; len];
739    getrandom::fill(&mut buf).map_err(|e| EncryptError::Random(e.to_string()))?;
740    Ok(buf)
741}
742
743/// Plan §3's mimetype fallback chain, shared by the `mimetype` zip member's
744/// bytes and the manifest `media-type` attribute: the input's own `mimetype`
745/// member, read verbatim (never re-derived from `classify`'s recovered
746/// string, since the two can diverge on a trailing newline or encoding
747/// nuance); else `classify`'s `media_type` as raw UTF-8 with no trailing
748/// newline; else `None`, and the attribute is omitted entirely.
749///
750/// Verbatim, but not unconditionally: a member over [`MIMETYPE_CEILING`], or
751/// carrying bytes that cannot go into an XML attribute, is
752/// [`EncryptError::Mimetype`] rather than a package that classifies and then
753/// fails to open. Every real producer's `mimetype` is a short ASCII media
754/// type, so the §3 ruling still governs every file that exists.
755/// Returns a `String`, not the raw bytes, so the UTF-8 validity established
756/// here is carried in the type rather than re-derived downstream: the manifest
757/// writer takes `&str` and has nothing left to unwrap. Copying stays verbatim
758/// -- `String::from_utf8` does not transform the bytes, and `as_bytes()` hands
759/// back exactly what the input member held.
760pub(crate) fn resolve_mimetype<R: Read + std::io::Seek>(
761    archive: &mut ZipArchive<R>,
762    classify_media_type: Option<&str>,
763) -> Result<Option<String>, EncryptError> {
764    if let Some(raw) = read_input_mimetype_member(archive)? {
765        return Ok(Some(validate_media_type(raw)?));
766    }
767    Ok(classify_media_type.map(str::to_owned))
768}
769
770/// Reject anything that cannot be written into `manifest:media-type` and read
771/// back unchanged. Two separate reasons:
772///
773/// 1. **Invalid UTF-8, or a character outside XML 1.0's `Char` production**
774///    (`#x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] |
775///    [#x10000-#x10FFFF]`). quick-xml escapes the five markup characters but
776///    emits a C0 control byte as-is, and expat -- LO's own `ManifestReader` --
777///    rejects the result, discarding every row.
778/// 2. **Tab, LF or CR**, which *are* legal `Char`s but are not attribute
779///    stable: XML 1.0 §3.3.3 attribute-value normalization replaces each with
780///    a space on the way back in (this crate's own `manifest::normalize_attr_value`
781///    implements exactly that). The `mimetype` zip member is copied verbatim,
782///    so the member bytes and the parsed attribute would then disagree --
783///    two things we write that are supposed to say the same thing.
784///
785/// Measured, not assumed: a package whose `mimetype` ends in a newline
786/// reaches `encrypt` only if its manifest declares no root media type (with
787/// one, `classify` already refuses the input as inconsistent), and real
788/// LibreOffice cannot open such a document *before* encryption either. So no
789/// loadable input is affected, and refusing costs nothing real -- every
790/// producer writes a bare ASCII media type. It closes the divergence rather
791/// than leaving it to be discovered from the other side.
792fn validate_media_type(raw: Vec<u8>) -> Result<String, EncryptError> {
793    let text = String::from_utf8(raw)
794        .map_err(|e| EncryptError::Mimetype(format!("not valid UTF-8: {e}")))?;
795    if let Some(c) = text.chars().find(|&c| !is_xml_char(c)) {
796        return Err(EncryptError::Mimetype(format!(
797            "contains U+{:04X}, not an XML 1.0 Char",
798            c as u32
799        )));
800    }
801    if let Some(c) = text.chars().find(|&c| matches!(c, '\t' | '\n' | '\r')) {
802        return Err(EncryptError::Mimetype(format!(
803            "contains U+{:04X}, which XML attribute-value normalization would \
804             turn into a space, making the manifest attribute disagree with the \
805             verbatim mimetype member",
806            c as u32
807        )));
808    }
809    Ok(text)
810}
811
812fn is_xml_char(c: char) -> bool {
813    matches!(c, '\t' | '\n' | '\r' | ' '..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..='\u{10FFFF}')
814}
815
816/// Read the input zip's own `mimetype` member, verbatim, straight off the
817/// archive -- not through `Classification` (plan §3). Bounded by
818/// [`MIMETYPE_CEILING`]: `zip` bounds only the *compressed* size, so an
819/// unguarded `read_to_end` here would inflate whatever a crafted member
820/// claims, although `classify` admitted the package on its first 1024 bytes.
821///
822/// A root `mimetype` member is exactly `"mimetype"` -- `collapse_slashes`
823/// cannot turn any other name into it -- so this is `zip`'s own O(1)
824/// name lookup rather than decrypt's `member_matches_path` scan.
825fn read_input_mimetype_member<R: Read + std::io::Seek>(
826    archive: &mut ZipArchive<R>,
827) -> Result<Option<Vec<u8>>, EncryptError> {
828    let Ok(mut file) = archive.by_name("mimetype") else {
829        return Ok(None);
830    };
831    let mut buf = Vec::new();
832    file.by_ref()
833        .take(MIMETYPE_CEILING as u64 + 1)
834        .read_to_end(&mut buf)
835        .map_err(|e| EncryptError::Zip(e.to_string()))?;
836    if buf.len() > MIMETYPE_CEILING {
837        return Err(EncryptError::Mimetype(format!(
838            "member exceeds ceiling {MIMETYPE_CEILING}, which is all classify itself read"
839        )));
840    }
841    Ok(Some(buf))
842}
843
844/// Build `META-INF/manifest.xml` exactly per plan §2's emit table: one
845/// `file-entry` for `encrypted-package`, no checksum attributes at all
846/// (`SetupStorage`'s `Value.clear()` for GCM), `manifest:version` fixed at
847/// [`WHOLESOME`]`.odf_version`, and no root `/` file-entry
848/// (`ManifestExport.cxx:297` -- wholesome `continue`s past the per-entry
849/// write loop for that sequence). Child order inside `encryption-data`:
850/// algorithm, start-key-generation, key-derivation.
851///
852/// Every parameter it writes comes from [`WHOLESOME`] or from this call's own
853/// salt/IV, so the manifest cannot promise a tuple the key was not derived
854/// under.
855pub(crate) fn build_manifest(
856    size: i64,
857    iv: &[u8],
858    salt: &[u8],
859    media_type: Option<&str>,
860    params: Argon2Params,
861) -> Result<Vec<u8>, EncryptError> {
862    // `ManifestExport.cxx:145-153`: `xmlns:loext` and `manifest:version` are
863    // both written together, gated on the same ODF >= 1.2 check -- always
864    // true for wholesome, which only exists at ODFSVER_LATEST_EXTENDED.
865    let mut root = BytesStart::new(uris::ELEMENT_MANIFEST);
866    root.push_attribute(("xmlns:manifest", uris::MANIFEST_NS_OASIS));
867    root.push_attribute(("xmlns:loext", uris::MANIFEST_NS_LOEXT));
868    root.push_attribute((uris::ATTR_VERSION, WHOLESOME.odf_version));
869
870    let size_str = size.to_string();
871    let mut file_entry = BytesStart::new(uris::ELEMENT_FILE_ENTRY);
872    file_entry.push_attribute((uris::ATTR_FULL_PATH, "encrypted-package"));
873    file_entry.push_attribute((uris::ATTR_SIZE, size_str.as_str()));
874    if let Some(mt) = media_type {
875        file_entry.push_attribute((uris::ATTR_MEDIA_TYPE, mt));
876    }
877
878    let iv_b64 = crate::manifest::encode_b64(iv);
879    let mut algorithm = BytesStart::new(uris::ELEMENT_ALGORITHM);
880    algorithm.push_attribute((uris::ATTR_ALGORITHM_NAME, uris::AESGCM256_URL));
881    algorithm.push_attribute((uris::ATTR_IV, iv_b64.as_str()));
882
883    // `ManifestExport.cxx:437-475`: GCM picks the W3C SHA-256 URL
884    // (`SHA256_URL`), not the "bad ODF URL" (`SHA256_URL_ODF12`) CBC keeps for
885    // ODF <= 1.4 interop -- "new encryption is incompatible anyway, use W3C URL".
886    let key_size = WHOLESOME.derived_key_len.to_string();
887    let mut start_key_gen = BytesStart::new(uris::ELEMENT_START_KEY_GENERATION);
888    start_key_gen.push_attribute((uris::ATTR_START_KEY_NAME, uris::SHA256_URL));
889    start_key_gen.push_attribute((uris::ATTR_KEY_SIZE, key_size.as_str()));
890
891    let (t, m, p) = (
892        params.t.to_string(),
893        params.m_kib.to_string(),
894        params.p.to_string(),
895    );
896    let salt_b64 = crate::manifest::encode_b64(salt);
897    let mut key_derivation = BytesStart::new(uris::ELEMENT_KEY_DERIVATION);
898    key_derivation.push_attribute((uris::ATTR_KEY_DERIVATION_NAME, uris::ARGON2ID_URL_LO));
899    key_derivation.push_attribute((uris::ATTR_ARGON2_T_LO, t.as_str()));
900    key_derivation.push_attribute((uris::ATTR_ARGON2_M_LO, m.as_str()));
901    key_derivation.push_attribute((uris::ATTR_ARGON2_P_LO, p.as_str()));
902    key_derivation.push_attribute((uris::ATTR_SALT, salt_b64.as_str()));
903    // `ManifestExport.cxx:517-522`: key-derivation's own `key-size` is written
904    // only when `bStoreStartKeyGeneration` -- always true here.
905    key_derivation.push_attribute((uris::ATTR_KEY_SIZE, key_size.as_str()));
906
907    let events = [
908        Event::Decl(BytesDecl::new("1.0", Some("UTF-8"), None)),
909        Event::Start(root),
910        Event::Start(file_entry),
911        Event::Start(BytesStart::new(uris::ELEMENT_ENCRYPTION_DATA)),
912        Event::Empty(algorithm),
913        Event::Empty(start_key_gen),
914        Event::Empty(key_derivation),
915        Event::End(BytesEnd::new(uris::ELEMENT_ENCRYPTION_DATA)),
916        Event::End(BytesEnd::new(uris::ELEMENT_FILE_ENTRY)),
917        Event::End(BytesEnd::new(uris::ELEMENT_MANIFEST)),
918    ];
919
920    let mut writer = Writer::new(Vec::new());
921    for event in events {
922        // `io::Write for Vec<u8>` is infallible, so this cannot fail today --
923        // but quick-xml's signature says it can, and an `.expect()` here would
924        // abort a caller's process to report that quick-xml had changed its
925        // mind. Same reasoning as every other Internal in this file.
926        writer
927            .write_event(event)
928            .map_err(|e| EncryptError::Internal(format!("manifest XML write: {e}")))?;
929    }
930    Ok(writer.into_inner())
931}
932
933#[cfg(test)]
934#[path = "encrypt_tests.rs"]
935mod tests;