1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
//! Troubleshooting, organised by symptom.
//!
//! The typed errors elsewhere in this crate tell a caller *which* case they
//! hit. They do not say what to do about it. This page does, and it is indexed
//! by **how a stuck developer actually arrives** rather than by API — arriving
//! by API only works if you already know what is wrong.
//!
//! It is documentation and nothing else: no items, no runtime cost. The
//! examples compile as doctests, so the advice cannot rot into describing
//! behaviour the code no longer has.
//!
//! **Deliberately no `file:line` citations.** They drift, and this repository
//! has repaired the same citation table three times. Functions and types are
//! named instead; `grep` finds them.
//!
//! - [`decrypt` returned `BadParameters`](#decrypt-returned-badparameters)
//! - [`WrongPassword`, but the password is right](#wrongpassword-but-the-password-is-right)
//! - [LibreOffice will not open what `encrypt` wrote](#libreoffice-will-not-open-what-encrypt-wrote)
//! - [Which Argon2 cost should I pick?](#which-argon2-cost-should-i-pick)
//! - [The error contains text I did not write](#the-error-contains-text-i-did-not-write)
//! - [`encrypt` refused a file LibreOffice does not ask a password for](#encrypt-refused-a-file-libreoffice-does-not-ask-a-password-for)
//! - [`decrypt_to` wrote output, then returned an error](#decrypt_to-wrote-output-then-returned-an-error)
//! - [`reencrypt_to` refused a file `decrypt` opens](#reencrypt_to-refused-a-file-decrypt-opens)
//!
//! # `decrypt` returned `BadParameters`
//!
//! **Whose fault is it?** Four different answers meet here. Since `0.1.0-rc.13`
//! the variant carries a [`BadParameter`](crate::BadParameter) that says which:
//! the setting, the value the file declares, the range allowed, and whose rule
//! the range is. It carries no text from the file.
//!
//! | case | means | what it carries |
//! | --- | --- | --- |
//! | 1. the format forbids it | a negative or zero cost, a negative size | `OutOfRange`, below the format's floor |
//! | 2. the cipher or KDF cannot run it | an IV length, `argon2`'s own `m >= 8p`, a salt under 8 bytes | `CipherRejects`, naming the [`Primitive`](crate::Primitive); `KeySizeForCipher`; `Member` |
//! | 3. **this host** cannot afford it | not this variant at all | [`crate::DecryptError::HostCannotAllocate`] |
//! | 4. spec-legal, runnable, **and this crate declined** | a policy cap of ours | `OutOfRange`, above a [`crate::DecryptLimits`] or `limits.rs` ceiling — and see below |
//!
//! **Case 4 is the one worth knowing about**, because reporting a policy cap as
//! case 1 tells a user their file is invalid when it is not. These are ours,
//! and the format permits more: `PBKDF2_MAX_ITER`, `ARGON2_MAX_T_COST`,
//! `MAX_ENCRYPTED_ENTRIES`, and the payload ceilings. A file refused by one of
//! them may open perfectly in LibreOffice.
//!
//! **Case 4 is the one you can do something about.** Since `0.1.0-rc.6` the
//! policy caps that apply to a package's own cost parameters are values on
//! [`crate::DecryptLimits`], not constants you cannot reach:
//!
//! ```
//! # #[cfg(feature = "crypto-ops")] {
//! use odf_crypto::{decrypt_with_limits, DecryptLimits};
//!
//! # fn demo(bytes: &[u8], pw: &str) -> Result<(), odf_crypto::DecryptError> {
//! // Raise one ceiling, having decided this file is worth it.
//! let plain = decrypt_with_limits(bytes, pw, DecryptLimits::default().with_argon2_max_t(64))?;
//! # let _ = plain;
//! # Ok(())
//! # }
//! # }
//! ```
//!
//! The defaults refuse nothing LibreOffice writes — `t = 3`, `m = 64 MiB`,
//! `p = 4`, at most 600,000 PBKDF2 iterations, all comfortably inside them — so
//! a file that trips one came from somewhere else. `DecryptLimits::PERMISSIVE`
//! accepts everything the format can express, and is a decision to spend
//! whatever an unknown file asks for: a single Argon2 row at the format's
//! widths extrapolates to about **33 hours**, and `decrypt` cannot be
//! interrupted.
//!
//! Argon2 memory split in two in `0.1.0-rc.6` and is on the list only for the
//! direction you are reading about here. A manifest's `m` is still capped at
//! 1 GiB by policy, because `decrypt` must run the KDF before it can check a
//! password, so the file chooses the cost of the attempt. A cost **you** pass to
//! `encrypt_with_params` is not capped by us at all — at 1 GiB that refused RFC
//! 9106's own first recommended tuple — and an unaffordable one there is case 3
//! rather than case 4.
//!
//! **Case 3 is a separate variant on purpose.** It blames neither the package
//! nor this crate — the manifest may be entirely legal and the same bytes may
//! decrypt on a machine with more free memory. So retrying, or retrying
//! elsewhere, is meaningful; re-downloading the file is not. Its
//! [`AllocationSite`](crate::AllocationSite) names which buffer could not be
//! obtained.
//!
//! ```
//! use odf_crypto::{decrypt, BadParameter, DecryptError};
//!
//! fn explain(bytes: &[u8], password: &str) -> String {
//! match decrypt(bytes, password) {
//! Ok(_) => "decrypted".into(),
//! // Structured, with no text from the file: quote its numbers in
//! // your own words. Case 2 is the cipher's rule, not this crate's.
//! Err(DecryptError::BadParameters(BadParameter::CipherRejects { field, by, got, .. })) => {
//! format!("the file declares {field} = {got}, which {by} cannot run")
//! }
//! // Cases 1 and 4: a file the format and LibreOffice allow can land
//! // here, so never call it damaged.
//! Err(DecryptError::BadParameters(BadParameter::OutOfRange { field, got, max, .. })) => {
//! format!("the file declares {field} = {got}; the most this app acts on is {max}")
//! }
//! Err(DecryptError::BadParameters(other)) => format!("not opened: {other}"),
//! // Case 3. Say "try again, or try on a bigger machine" -- never
//! // "your file is damaged", which is what exit 6 used to imply.
//! Err(DecryptError::HostCannotAllocate { site, requested_bytes }) => {
//! format!("this machine could not spare {requested_bytes} bytes for {site}")
//! }
//! Err(other) => other.to_string(),
//! }
//! }
//! # let _ = explain(&[], "");
//! ```
//!
//! # `WrongPassword`, but the password is right
//!
//! [`crate::DecryptError::WrongPassword`] **cannot distinguish a wrong password from
//! damaged or tampered ciphertext**, and how much it covers depends on the
//! cipher — which is the part that surprises people.
//!
//! **AES-GCM**: the verdict is the AEAD tag, over the *whole* ciphertext. Any
//! altered byte anywhere fails it. `manifest:checksum` is not consulted at all.
//! So here `WrongPassword` is a strong statement about the entire stream.
//!
//! **AES-CBC and Blowfish-CFB**: the key is never authenticated. The verdict is
//! a checksum over the **first `CHECKSUM_WINDOW` bytes** of the *compressed*
//! plaintext — 1024, which is LibreOffice's `n_ConstDigestLength`. A wrong key
//! almost always corrupts that first kilobyte too, so the error still fires
//! reliably. But **damage past that window, with the correct password, does not
//! surface here**: it surfaces as [`crate::DecryptError::Inflate`], when the corrupted
//! DEFLATE stream fails to decode or does not inflate to `manifest:size`.
//!
//! So a caller seeing `Inflate` after a *successful* password should not treat
//! it as a password problem, and a caller seeing `WrongPassword` should not
//! promise the user it is one.
//!
//! **Write the user-facing copy so it survives being wrong.** Not *"incorrect
//! password"* but something closer to: *"This file could not be opened with that
//! password. Either the password is wrong or the file has been damaged — try
//! the password once more, and if it still fails, get a fresh copy."* That
//! sentence is true in both worlds, and the shorter one is false in one of them.
//!
//! **Old files and non-ASCII passwords.** Before `0.1.0-rc.9`, files from
//! OpenOffice.org 1.x, StarOffice and LibreOffice before 3.5 could report
//! `WrongPassword` with the right password, because those writers derived the
//! start key with a knowingly broken SHA-1 or from the MS-1252 bytes. Since rc.9
//! `decrypt` walks LibreOffice's own retry ladder for any SHA-1 row, so such a
//! file opens here exactly when it opens in LibreOffice. If one still fails,
//! LibreOffice refuses it too.
//!
//! # LibreOffice will not open what `encrypt` wrote
//!
//! **`encrypt` writes one profile, whatever the input was.** One
//! `encrypted-package` member, AES-256-GCM, Argon2id, a SHA-256 start key, no
//! checksum, `manifest:version="1.4"`. It does not read a cipher off the input,
//! because a `Mode::Plain` input does not have one.
//!
//! The consequence catches people: **`decrypt` then `encrypt` is not
//! format-preserving.** Feed it an ODF 1.1 Blowfish document and you get the
//! modern profile back. The crate reads three profiles and writes one — that
//! asymmetry is an effort gap rather than a judgement, and it is tracked.
//!
//! **What is actually verified, stated precisely because the gap matters:** the
//! `tests/goldens/*.odt` corpus is real LibreOffice output, and one golden is
//! write-side evidence. It was produced by a script driving LibreOffice over
//! UNO with the password handed across as a property — **which is not what a
//! double-click does.** No password dialog, no wrong-password retry, no recovery
//! bar. A file can satisfy that harness and still be one a person cannot open,
//! which is why `tests/artifacts/` exists and why its verdict is recorded by
//! hand.
//!
//! If `encrypt` refused *before* writing anything, see
//! [`crate::EncryptError::Odf12Fatal`]: the **plaintext input** has streams its
//! manifest does not account for and declares ODF `>= 1.2`, which is the shape
//! LibreOffice itself refuses to open. Refusing early beats sealing a document
//! nothing can read.
//!
//! # Which Argon2 cost should I pick?
//!
//! **If you have no opinion, express none** — call [`encrypt`](crate::encrypt),
//! which uses LibreOffice's own tuple.
//!
//! The one sentence that matters: **the cost is written into the file and binds
//! every future reader on every device.** It is not a local performance knob.
//! Lowering it to suit today's hardware weakens that document permanently, and
//! it cannot be raised again without decrypting and re-encrypting.
//!
//! **A weak tuple is accepted, not refused.** The cost is the caller's decision
//! and this crate does not overrule it. It also does not *warn* on its own —
//! [`crate::Argon2Params::is_weaker_than_libreoffice`] is a predicate you must ask.
//! The CLI asks it and prints to stderr; a library has no terminal, so nothing
//! happens unless your code makes it happen.
//!
//! What *is* refused is a different axis entirely, and
//! [`ParamsReason`](crate::ParamsReason) names whose rule it was:
//! `OutOfRange` is **our** policy bound, `CipherRejects` is `argon2`'s own
//! requirement. Neither means "too weak". A third axis,
//! [`crate::EncryptError::HostCannotAllocate`], means the tuple was fine and this
//! machine was not.
//!
//! ```
//! use odf_crypto::{encrypt, encrypt_with_params, Argon2Params};
//!
//! # fn demo(plain: &[u8], pw: &str) -> Result<(), odf_crypto::EncryptError> {
//! // GOOD -- expresses no opinion, gets LibreOffice's profile.
//! let sealed = encrypt(plain, pw)?;
//!
//! // GOOD -- a constrained device, traded knowingly and recorded.
//! let p = Argon2Params::new(2, 8192, 2)?; // ~8 MiB instead of 64
//! if p.is_weaker_than_libreoffice() {
//! eprintln!("sealing at a reduced cost: {} {} {}", p.t(), p.m_kib(), p.p());
//! }
//! let sealed_cheaply = encrypt_with_params(plain, pw, p)?;
//!
//! // POOR -- legal, runnable, and about as cheap to attack as the format
//! // allows. Nothing refuses it. The document is weak for every future
//! // reader, on hardware that could have afforded more.
//! let weak = Argon2Params::new(1, 8, 1)?;
//! assert!(weak.is_weaker_than_libreoffice());
//! # let _ = (sealed, sealed_cheaply);
//! # Ok(())
//! # }
//! # let _ = demo;
//! ```
//!
//! # The error contains text I did not write
//!
//! Some payloads quote bytes the package chose. Rendering one as though it were
//! this library's own words hands an attacker your log line or your dialog.
//!
//! **Ask what was interpolated, not what the type is.** That is the trap: the
//! variants are `thiserror` enums with fixed format strings, which looks
//! reassuring and tells you nothing — the hazard is in the `{0}`.
//!
//! | payload | carries package text? |
//! | --- | --- |
//! | [`DetectError::Inconsistent`](crate::DetectError::Inconsistent) | **yes**, bounded to `DIAGNOSTIC_ELISION` (96 bytes) |
//! | the zip half of any `Zip` variant | no — rendered from `&'static str` this crate chose, never the zip crate's `Display` |
//! | the quick-xml half of [`crate::DecryptError::Zip`] | **yes**, and un-elided — see its own docs for why that is safe |
//! | [`crate::DecryptError::BadParameters`] | no — enums and integers only, since `0.1.0-rc.13`; before that it quoted manifest values, a row's `manifest:full-path` among them, unbounded |
//! | `Internal` on either error | no — our own text about our own invariant |
//!
//! **Elision bounds volume, not trust.** 96 bytes of attacker-chosen text is
//! still attacker-chosen: nothing distinguishes a hostile media type from a
//! real one by shape. So the rule is not "short enough to print" — it is *do
//! not interpolate these into a sentence that reads as yours*. Show them quoted,
//! attributed to the file, and truncated for display.
//!
//! # `encrypt` refused a file LibreOffice does not ask a password for
//!
//! That is [`crate::EncryptError::PartiallyEncrypted`], and the surprise is real rather
//! than a bug in your reasoning.
//!
//! [`Mode::PerEntry`](crate::Mode::PerEntry) means *complete `encryption-data`
//! rows exist*. [`Classification::package_encrypted`](crate::Classification::package_encrypted)
//! means something narrower — it is LibreOffice's `HasEncryptedEntries` latch,
//! and only a row resolving to `content.xml` or `encrypted-package` sets it.
//! **A package can be `PerEntry` with the latch false**, and LibreOffice never
//! asks for its password, because the prompt is gated on the latch.
//!
//! It does not open it either, at least when Writer has to read one of the
//! encrypted members: measured in rc.9 (`tools/probe_unlatched.py`), it raises
//! `ERRCODE_SFX_WRONGPASSWORD` without having asked, and opens the file only
//! when the password is supplied programmatically. [`crate::decrypt`] does the
//! same: given the password, it decrypts the rows, so it recovers a file a
//! LibreOffice user cannot open from the GUI.
//!
//! So the old single `AlreadyEncrypted` was telling a caller something the
//! specifying implementation contradicts. It is still refused, for a reason
//! worth stating: `encrypt` deflates the **whole input** and wraps it in one new
//! member. Wrapping a package whose members are already ciphertext buries them
//! a layer deeper, readable by nobody.
//!
//! **Do not test `!package_encrypted` to decide whether a package is
//! plaintext.** That is exactly the confusion the split exists to stop. The
//! plaintext test is `mode == Mode::Plain`.
//!
//! ```
//! use odf_crypto::{classify, Mode};
//!
//! # fn is_sealable(bytes: &[u8]) -> Result<bool, odf_crypto::DetectError> {
//! let class = classify(bytes)?;
//! // Right. `package_encrypted` is a narrower question than this one.
//! Ok(class.mode == Mode::Plain)
//! # }
//! # let _ = is_sealable;
//! ```
//!
//! To reproduce LibreOffice's *other* verdict on such packages, read
//! [`Classification::has_non_encrypted_entries`](crate::Classification::has_non_encrypted_entries),
//! its `HasNonEncryptedEntries`. With **both** flags set on ODF `>= 1.2`,
//! LibreOffice raises `ERRCODE_SFX_INCOMPLETE_ENCRYPTION` and disables macro
//! execution (`sfx2/source/doc/objmisc.cxx:1028-1063`). Until `0.1.0-rc.9`
//! only half of that predicate was visible here.
//!
//! # `decrypt_to` wrote output, then returned an error
//!
//! **Discard the output. It is not a document.** The streaming functions write
//! as they go, so a failure found late in a member arrives after earlier bytes
//! were written. What they never do is write a member before it was accepted:
//!
//! - an AES-GCM member's tag is checked in a first pass that writes nothing,
//! so a wrong password -- or a tampered member -- writes none of it;
//! - an AES-CBC or Blowfish member is held back until its first 1 KiB matches
//! the manifest's checksum. Past that window nothing is authenticated, here
//! or in LibreOffice, so damage there surfaces later as
//! [`DecryptError::Inflate`](crate::DecryptError::Inflate) or `Zip`, with
//! output already written. [`IntegrityOutcome::PasswordCheckOnly`](crate::IntegrityOutcome::PasswordCheckOnly)
//! is the success-side name for the same fact.
//!
//! So write to somewhere you can throw away -- a temporary file, renamed into
//! place on `Ok`, is what the `odf-crypto` binary does -- and treat every `Err`
//! as "delete it".
//!
//! [`DecryptError::Io`](crate::DecryptError::Io) of kind `InvalidData` has one
//! extra meaning: the input changed between the two passes over an AES-GCM
//! member. Check what else is writing to that file.
//!
//! # `reencrypt_to` refused a file `decrypt` opens
//!
//! **That is policy, and it is this crate's, not LibreOffice's.** A per-entry
//! package -- the older AES-CBC and Blowfish profiles -- is refused when any
//! listed part of it is not encrypted
//! ([`ReencryptError::PartiallyEncrypted`](crate::ReencryptError::PartiallyEncrypted))
//! or when it holds parts its manifest does not list
//! ([`ReencryptError::UnexpectedStreams`](crate::ReencryptError::UnexpectedStreams)).
//!
//! The reason is what the re-key would do. Those parts were never protected by
//! the old password, and the new file is AES-GCM: its tag would vouch for them.
//! A part someone slipped into an old file would come out looking as
//! trustworthy as the rest. LibreOffice opens such a file, after warning that
//! it has unencrypted parts and with macros disabled, which is why
//! [`decrypt_to`](crate::decrypt_to) opens it too.
//!
//! To re-key it anyway, decide what to do with those parts first: decrypt it,
//! inspect or drop them, and [`encrypt_to`](crate::encrypt_to) the result
//! under the new password.
// No items. This module is a page.