Skip to main content

odf_crypto/
lib.rs

1//! LibreOffice-faithful ODF package encryption detection, decryption and encryption.
2//!
3//! [`classify`] answers whether a file is an ODF package, whether it is encrypted,
4//! in which zip-shape [`Mode`], and with which algorithm tuple. It follows
5//! LibreOffice `package/` accept predicates, not the origin-detection approach of
6//! [Horsmann/odfdecrypt](https://github.com/Horsmann/odfdecrypt).
7//!
8//! ```
9//! use odf_crypto::{classify, Mode};
10//!
11//! let bytes = include_bytes!("../tests/goldens/lo-unencrypted.odt");
12//! let class = classify(bytes)?;
13//! assert_eq!(class.mode, Mode::Plain);
14//! # Ok::<(), odf_crypto::DetectError>(())
15//! ```
16//!
17//! Detection is the default build: [`classify`] needs no cryptographic
18//! dependency. Everything past it is behind the `crypto-ops` feature.
19//!
20//! With `crypto-ops` enabled, [`decrypt`] turns an LO-encrypted package into the
21//! plaintext ODF zip LibreOffice would open after a correct password. Packages
22//! `classify` reports as `odf12_fatal` are refused: LO would not open them, so
23//! neither does this crate.
24//!
25//! [`encrypt`] is the reverse: it turns a plaintext ([`Mode::Plain`]) ODF package
26//! into what current LibreOffice writes for that input under a password.
27//!
28//! # Scope
29//!
30//! [`encrypt`] writes one profile: a single `encrypted-package` member, Argon2id
31//! `t=3, m=65536, p=4`, AES-256-GCM, a SHA-256 start key, no checksum, and
32//! `manifest:version="1.4"`. Per-entry writing and PGP wrapping are out of scope,
33//! and the two are out for different reasons worth stating on the surface rather
34//! than only in the plans:
35//!
36//! - **Per-entry write** is unbuilt, not impossible. `decrypt` reads AES-CBC and
37//!   Blowfish-CFB packages and this crate ships goldens of both, so the crate
38//!   can read three profiles and write one. That asymmetry is an effort gap.
39//! - **PGP wrapping** cannot be expressed by this API at all: a private key does
40//!   not arrive through `password: &str`. See [`DecryptError::UnsupportedPgp`].
41//!
42//! The Argon2id cost is the one part of that profile a caller may change, with
43//! [`encrypt_with_params`] and [`Argon2Params`] — `m=65536` is 64 MiB of working
44//! memory per call, which some hardware cannot spend. A weaker tuple is accepted
45//! rather than refused: the cost is the caller's decision, and this crate reports
46//! it instead of overruling it. But it is stored *in the file*, so it binds every
47//! future reader on every device, and real LibreOffice honours whatever is
48//! written — verified against 26.2.1.2 down to `(1, 1024, 1)`.
49//!
50//! [`decrypt`] reads all three algorithm families LibreOffice and Apache
51//! OpenOffice produce — AES-GCM + Argon2id, AES-CBC + PBKDF2, and Blowfish-CFB +
52//! PBKDF2. PGP-wrapped packages are classified, and their wrapped material is
53//! reported in [`Classification::pgp_keys`], but decryption refuses them.
54//!
55//! # Untrusted input
56//!
57//! Every bound a hostile package could push on is capped before any allocation
58//! or key derivation: the manifest is read at most 8 MiB, at most 4096 complete
59//! `encryption-data` rows get a KDF run, and `iteration-count`, Argon2
60//! `t`/`m`/`p` and `key-size` each carry a floor and a ceiling. The whole-buffer
61//! [`decrypt`] and [`encrypt`] also hold each inflated member and the input to
62//! 1 GiB, because they hold them in memory; the streaming entry points do not,
63//! and bound inflated output by [`DecryptLimits::max_output_bytes`] instead.
64//!
65//! # Streaming
66//!
67//! [`decrypt_to`], [`encrypt_to`] and [`reencrypt_to`] read from any
68//! `Read + Seek` and write to a writer a chunk at a time, so peak memory does
69//! not grow with the package. Nothing is written before a member has been
70//! accepted -- an AES-GCM tag checked in a first pass, or an AES-CBC/Blowfish
71//! member's checked first 1 KiB -- and on any error the writer's contents must
72//! be discarded. The whole-buffer functions run the same code.
73//!
74//! At the API boundary: `password` is a `&str` and [`decrypt`] returns plaintext
75//! as a plain `Vec<u8>`. Key material derived inside the crate is zeroized on
76//! drop; the password you pass and the plaintext you receive are yours to wipe.
77//!
78//! # Stability
79//!
80//! Pre-1.0 — the API may change between releases. Requires Rust 1.88.
81
82// Scoped to the one config where `decrypt`/`encrypt` genuinely are not compiled.
83#![cfg_attr(not(feature = "crypto-ops"), allow(rustdoc::broken_intra_doc_links))]
84// doc_auto_cfg merged into doc_cfg in 1.92; docs.rs sets `docsrs` for us.
85#![cfg_attr(docsrs, feature(doc_cfg))]
86
87mod classify;
88mod io_latch;
89mod limits;
90mod manifest;
91mod types;
92mod uris;
93mod zip_err;
94mod zip_tree;
95
96#[cfg(test)]
97mod test_support;
98
99#[cfg(feature = "crypto-ops")]
100mod bad_parameter;
101#[cfg(feature = "crypto-ops")]
102mod decrypt;
103#[cfg(feature = "crypto-ops")]
104mod decrypt_entries;
105#[cfg(feature = "crypto-ops")]
106mod decrypt_stream;
107#[cfg(feature = "crypto-ops")]
108mod encrypt;
109#[cfg(feature = "crypto-ops")]
110mod encrypt_stream;
111#[cfg(feature = "crypto-ops")]
112mod kdf;
113#[cfg(feature = "crypto-ops")]
114mod ms1252;
115#[cfg(feature = "crypto-ops")]
116mod reencrypt;
117#[cfg(feature = "crypto-ops")]
118mod sensitive;
119#[cfg(feature = "crypto-ops")]
120mod stream;
121#[cfg(feature = "crypto-ops")]
122mod zip_stream;
123
124// A doc-only module: `//!` docs, no items, no runtime cost. Gated on
125// `crypto-ops` because five of its six symptoms are about `decrypt` and
126// `encrypt`, whose types do not exist in a detection-only build -- an
127// intra-doc link to `DecryptError` there would not resolve. docs.rs builds
128// `--all-features`, so it is on the published page regardless.
129#[cfg(feature = "crypto-ops")]
130#[cfg_attr(docsrs, doc(cfg(feature = "crypto-ops")))]
131pub mod troubleshooting;
132
133pub use classify::{classify, classify_reader};
134pub use types::{
135    Checksum, Cipher, Classification, DetectError, EncryptedKey, EntryEncryption, Kdf, Mode,
136    StartKeyAlg,
137};
138
139#[cfg(feature = "crypto-ops")]
140pub use bad_parameter::{BadParameter, ManifestField, MemberFault, Primitive};
141#[cfg(feature = "crypto-ops")]
142pub use decrypt::{decrypt, decrypt_with_limits, AllocationSite, DecryptError, DecryptLimits};
143#[cfg(feature = "crypto-ops")]
144pub use decrypt_stream::{decrypt_to, decrypt_with_limits_to, DecryptOutcome, IntegrityOutcome};
145#[cfg(feature = "crypto-ops")]
146pub use encrypt::{
147    encrypt, encrypt_with_params, Argon2Axis, Argon2Params, EncryptError, ParamsReason,
148};
149#[cfg(feature = "crypto-ops")]
150pub use encrypt_stream::{encrypt_to, encrypt_with_params_to};
151#[cfg(feature = "crypto-ops")]
152pub use reencrypt::{reencrypt_to, ReencryptError};
153
154// Compiles every ```rust block in README.md, and renders none of it.
155//
156// `cfg(doctest)` is set only while rustdoc COLLECTS doctests, never while it
157// BUILDS documentation -- so `cargo test --doc` checks the examples and no part
158// of README.md reaches the rendered API pages. `cfg(test)` would be wrong: it is
159// not set during collection, so the examples would never run.
160//
161// Precisely: the struct is absent from every page under `doc/odf_crypto/`, but
162// the NAME appears once in `doc/src/odf_crypto/lib.rs.html`, because rustdoc's
163// source viewer renders the file verbatim including items it compiled out. That
164// is expected and harmless -- the README's prose is what must not escape, and it
165// appears nowhere. So verify by grepping a README-only SENTENCE, not this
166// identifier: grepping the identifier reports a correct setup as broken.
167//
168// Gated on `crypto-ops` because that is the smallest feature set under which
169// all four examples compile: one needs only `classify`, the other three need
170// `decrypt`, `encrypt` and `encrypt_with_params`. CI's `test (crypto-ops)` and
171// `test (cli)` jobs both reach it, which matters -- an inert check reads
172// exactly like a passing one.
173//
174// The examples are `no_run`: they are complete `fn main()` programs that read
175// `document.odt`, so collecting them without running them is the point. A
176// doctest that opens a file no machine has fails everywhere.
177//
178// A fence with NO language tag is Rust to rustdoc, and is not `no_run` --
179// README.md:195's sample terminal output ran as a doctest and failed until it
180// was tagged ```text. Tag every new fence; an untagged one is a live test.
181//
182// Proved by breaking it: `odf12_fatal` -> `odf12_fatl` in the README gave
183//     test src\lib.rs - ReadmeDoctests (line 180) - compile ... FAILED
184//     error[E0609]: no field `odf12_fatl` on type `Classification`
185// which is the defect class this catches -- a README naming a field that moved.
186#[cfg(all(doctest, feature = "crypto-ops"))]
187#[doc = include_str!("../README.md")]
188pub struct ReadmeDoctests;