Skip to main content

odf_crypto/
types.rs

1//! Classification types: the public result surface of [`crate::classify`], plus
2//! the `pub(crate)` Stage A / Stage B intermediates it is built from.
3
4/// Zip-shape outcome. PGP is a [`Kdf`], not a mode.
5///
6/// ```
7/// use odf_crypto::{classify, Mode};
8///
9/// let bytes = include_bytes!("../tests/goldens/lo-unencrypted.odt");
10/// let class = classify(bytes)?;
11///
12/// match class.mode {
13///     Mode::Plain => println!("not encrypted"),
14///     Mode::PerEntry => println!("{} encrypted members", class.encrypted_entries.len()),
15///     Mode::Wholesome => println!("one encrypted-package member"),
16/// }
17/// assert_eq!(class.mode, Mode::Plain);
18/// # Ok::<(), odf_crypto::DetectError>(())
19/// ```
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum Mode {
22    /// No stream in the zip resolved to a complete `encryption-data` row — the
23    /// state `encrypt` requires and `decrypt` refuses.
24    Plain,
25    /// Ordinary members carry complete `encryption-data`, and no root
26    /// `encrypted-package` entry does. Also reached when an `encrypted-package`
27    /// row is complete but exists only as an XML path, with no such zip entry.
28    PerEntry,
29    /// A root `encrypted-package` zip member whose `encryption-data` is
30    /// complete. The whole document is one encrypted stream.
31    Wholesome,
32}
33
34/// Start-key digest. Omitted `start-key-generation` defaults to SHA-1 on the
35/// password path. PGP clamps to SHA-256 (`ZipPackage.cxx` 339).
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum StartKeyAlg {
38    /// SHA-1, and the default when the row omits `start-key-generation`.
39    Sha1,
40    /// SHA-256, written explicitly by every modern LibreOffice row.
41    Sha256,
42}
43
44/// LibreOffice `CipherID`: three values. 128/192/256 survives only as
45/// [`EntryEncryption::derived_key_len`] (`sal_Int32`).
46///
47/// ```
48/// use odf_crypto::{classify, Cipher, Kdf, Mode};
49///
50/// let bytes = include_bytes!("../tests/goldens/aoo-blowfish-pbkdf2.odt");
51/// let class = classify(bytes)?;
52///
53/// assert_eq!(class.mode, Mode::PerEntry);
54/// let row = &class.encrypted_entries[0];
55/// assert_eq!(row.cipher, Cipher::BlowfishCfb8);
56/// assert!(matches!(row.kdf, Kdf::Pbkdf2 { .. }));
57/// # Ok::<(), odf_crypto::DetectError>(())
58/// ```
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum Cipher {
61    /// Blowfish in CFB. The name mirrors LibreOffice's
62    /// `CipherID::BLOWFISH_CFB_8`, but the wire mode is 64-bit-segment CFB
63    /// (`BF_updateCFB` / `EVP_bf_cfb`), not CFB-8.
64    BlowfishCfb8,
65    /// AES-CBC. All three `xmlenc#aes{128,192,256}-cbc` URIs collapse here —
66    /// only [`EntryEncryption::derived_key_len`] says which AES.
67    AesCbcW3c,
68    /// AES-GCM, the W3C URI current LibreOffice writes.
69    AesGcmW3c,
70}
71
72/// Key-derivation function recorded on a complete row.
73///
74/// ```
75/// use odf_crypto::Kdf;
76///
77/// fn describe(kdf: &Kdf) -> String {
78///     match kdf {
79///         Kdf::Pbkdf2 { iterations, .. } => format!("PBKDF2, {iterations} iterations"),
80///         Kdf::Argon2id { t, m, p, .. } => format!("Argon2id t={t} m={m}KiB p={p}"),
81///         Kdf::PgpRsaOaepMgf1p => "PGP".to_string(),
82///     }
83/// }
84/// ```
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub enum Kdf {
87    /// PBKDF2. Its HMAC is SHA-1 whatever [`StartKeyAlg`] the row asked for —
88    /// the start-key digest and the PBKDF2 PRF are separate choices.
89    Pbkdf2 {
90        /// `manifest:iteration-count`, an `sal_Int32` the file controls.
91        iterations: i32,
92        /// `manifest:salt`, base64-decoded.
93        salt: Vec<u8>,
94    },
95    /// Argon2id, written by current LibreOffice.
96    Argon2id {
97        /// Time cost (`manifest:argon2-t`), an `sal_Int32` the file controls.
98        t: i32,
99        /// Memory cost in **KiB** (`manifest:argon2-m`), not bytes.
100        m: i32,
101        /// Parallelism (`manifest:argon2-p`), an `sal_Int32` the file controls.
102        p: i32,
103        /// `manifest:salt`, base64-decoded.
104        salt: Vec<u8>,
105    },
106    /// PGP key wrapping. Reported by `classify`, refused by `decrypt`; the
107    /// wrapped material is in [`Classification::pgp_keys`].
108    PgpRsaOaepMgf1p,
109}
110
111/// Checksum on a complete row. GCM (and PGP+GCM) may omit it.
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub enum Checksum {
114    /// No checksum. The AEAD tag is the only integrity check.
115    None,
116    /// SHA-1 over the first 1 KiB of the decrypted but **still-deflated** bytes.
117    Sha1_1K(Vec<u8>),
118    /// SHA-256 over the first 1 KiB of the decrypted but **still-deflated** bytes.
119    Sha256_1K(Vec<u8>),
120}
121
122/// One complete encryption-data tuple after Stage B.
123#[derive(Debug, Clone, PartialEq, Eq)]
124pub struct EntryEncryption {
125    /// The **resolved** tree path, which is not necessarily the row's
126    /// `manifest:full-path`: LibreOffice's own lookup can land a row on a
127    /// stream its path does not name.
128    pub path: String,
129    /// Cipher the row declares.
130    pub cipher: Cipher,
131    /// Key-derivation function and its parameters.
132    pub kdf: Kdf,
133    /// Digest applied to the password before the KDF runs.
134    pub start_key: StartKeyAlg,
135    /// Integrity check, if the row carries one.
136    pub checksum: Checksum,
137    /// `manifest:size` (`sal_Int64`): the **uncompressed plaintext** length,
138    /// which `decrypt` enforces after inflating.
139    pub size: i64,
140    /// Initialisation vector or nonce, base64-decoded.
141    pub iv: Vec<u8>,
142    /// `manifest:key-size` in bytes (`sal_Int32`), and the only thing that says
143    /// which AES a [`Cipher::AesCbcW3c`] row means. PGP uses
144    /// `GetDefaultDerivedKeySize`.
145    pub derived_key_len: i32,
146}
147
148/// Result of [`crate::classify`].
149#[derive(Debug, Clone, PartialEq, Eq)]
150pub struct Classification {
151    /// Which zip shape the package is in.
152    pub mode: Mode,
153    /// LibreOffice `HasEncryptedEntries` — the latch, not “any encryption-data”.
154    pub package_encrypted: bool,
155    /// LibreOffice `HasNonEncryptedEntries`: some manifest row resolves to a
156    /// stream **without** a complete `encryption-data` tuple
157    /// (`ZipPackage.cxx:446`, the `else` of the test that admits a row to
158    /// [`Classification::encrypted_entries`]).
159    ///
160    /// It is the other half of a predicate LibreOffice acts on.
161    /// `SfxObjectShell::CheckEncryption_Impl` (`sfx2/source/doc/objmisc.cxx:1028-1063`)
162    /// reads both flags, and on a package whose root version is ODF 1.2 or later
163    /// with `HasEncryptedEntries && HasNonEncryptedEntries` it raises
164    /// `ERRCODE_SFX_INCOMPLETE_ENCRYPTION` -- *"this is an encrypted document with
165    /// nonencrypted streams inside, show the warning"* -- and **disables macro
166    /// execution**. So a consumer reproduces LibreOffice's behavior with:
167    ///
168    /// ```text
169    /// package_encrypted && has_non_encrypted_entries && odf_version >= "1.2"
170    /// ```
171    ///
172    /// the version compared byte-lexicographically, as
173    /// [`Classification::odf_version`] describes.
174    ///
175    /// Only manifest-listed streams count. A zip member the manifest never
176    /// names -- `mimetype`, `META-INF/manifest.xml` -- is not a row upstream
177    /// and sets nothing.
178    pub has_non_encrypted_entries: bool,
179    /// The package's ODF version, from the root folder — the first non-empty
180    /// `manifest:version` in the manifest, falling back to the one implied by
181    /// the `mimetype` member.
182    ///
183    /// `None` when no row declares one, which is normal for older packages.
184    /// Compared **byte-lexicographically**, not numerically, when deciding
185    /// [`Classification::odf12_fatal`] — so `"1.10"` sorts below `"1.2"`, as it
186    /// does in LibreOffice.
187    pub odf_version: Option<String>,
188    /// Root **entry** named `encrypted-package` in the zip's folder tree, not an
189    /// XML-only path — a member path such as `encrypted-package/x` synthesizes
190    /// that entry as a folder and also sets this. Feeds the unexpected-streams
191    /// test and root media-type selection, so it is not inert.
192    pub zip_has_encrypted_package: bool,
193    /// Root-folder `manifest:media-type`, the document's MIME type.
194    pub media_type: Option<String>,
195    /// The row that decided the package is encrypted, and the one to read when
196    /// you want the package's encryption parameters without walking
197    /// [`Classification::encrypted_entries`].
198    ///
199    /// It is the first accepted row resolving to `content.xml` or
200    /// `encrypted-package` — the same row that sets
201    /// [`Classification::package_encrypted`], so the two are `Some`/`true`
202    /// together. A clone, not a borrow: the same entry also appears in
203    /// `encrypted_entries`.
204    ///
205    /// **For a [`Mode::Wholesome`] package this is not necessarily the row
206    /// `decrypt` acts on** — use [`Classification::wholesome_row`] if what you
207    /// want is the payload's cipher or KDF. The latch is first-wins, so a
208    /// manifest carrying a complete `content.xml` row *and* a complete
209    /// `encrypted-package` row takes `common` from the first and its
210    /// `Wholesome` verdict from the second. That doc has the worked case.
211    ///
212    /// `None` for a [`Mode::Plain`] package, and also for one whose only
213    /// complete rows sit on other members — encrypted entries can exist with no
214    /// latch row, which is why `package_encrypted` is not
215    /// `!encrypted_entries.is_empty()`. That shape -- `!package_encrypted &&
216    /// !encrypted_entries.is_empty()` -- is the one
217    /// `EncryptError::PartiallyEncrypted` names: LibreOffice opens it without
218    /// asking for a password.
219    pub common: Option<EntryEncryption>,
220    /// Every member that resolved to a complete `encryption-data` row, in
221    /// manifest order.
222    pub encrypted_entries: Vec<EntryEncryption>,
223    /// `LookForUnexpectedODF12Streams`. Always computed.
224    pub has_unexpected_streams: bool,
225    /// `has_unexpected_streams && root version >= "1.2"` (byte-lexicographic).
226    /// LibreOffice throws rather than opening; `decrypt` and `encrypt` refuse
227    /// the same packages so they do not unwrap or wrap something LO would reject.
228    pub odf12_fatal: bool,
229    /// PGP `encrypted-key` material from the first file-entry's key info, if any.
230    /// Present so a caller can hand it to an OpenPGP implementation; this crate
231    /// refuses such packages.
232    pub pgp_keys: Vec<EncryptedKey>,
233}
234
235impl Classification {
236    /// The row [`decrypt`](crate::decrypt) acts on for a [`Mode::Wholesome`]
237    /// package — the one resolving to `encrypted-package`.
238    ///
239    /// `None` for [`Mode::Plain`], and `None` for [`Mode::PerEntry`], where
240    /// there is no single payload row: `decrypt` acts on every entry in
241    /// [`Classification::encrypted_entries`].
242    ///
243    /// # Why this is not [`Classification::common`]
244    ///
245    /// **They can be different rows, and the difference is constructible.**
246    /// `common` is the *latch* row — the first accepted row resolving to
247    /// `content.xml` **or** `encrypted-package`, reproducing LibreOffice's
248    /// `HasEncryptedEntries` (`ZipPackage.cxx`), which is first-wins. Whether
249    /// the package is `Wholesome` is decided separately, by whether a complete
250    /// `encrypted-package` row exists at all.
251    ///
252    /// So a manifest carrying a complete `content.xml` row **and** a complete
253    /// `encrypted-package` row is `Wholesome` because of the second while
254    /// `common` came from the first:
255    ///
256    /// | row | cipher | kdf |
257    /// | --- | --- | --- |
258    /// | `content.xml` *(first, so it is `common`)* | AES-256-GCM | Argon2id |
259    /// | `encrypted-package` *(what `decrypt` uses)* | AES-256-CBC | PBKDF2 |
260    ///
261    /// Reading `common` there reports the modern profile for a package whose
262    /// payload is neither. LibreOffice does not write such a file; an attacker
263    /// can. **If you are asking what cipher or KDF the payload actually uses,
264    /// this method is the question you meant.**
265    ///
266    /// `decrypt` calls this, so the two cannot drift.
267    ///
268    /// # Examples
269    ///
270    /// ```
271    /// # #[cfg(feature = "crypto-ops")] {
272    /// use odf_crypto::{classify, Cipher, Mode};
273    ///
274    /// # fn demo(bytes: &[u8]) -> Result<(), odf_crypto::DetectError> {
275    /// let class = classify(bytes)?;
276    /// if class.mode == Mode::Wholesome {
277    ///     // Right: the row the payload is actually sealed with.
278    ///     let row = class.wholesome_row().expect("Wholesome implies this row");
279    ///     let modern = row.cipher == Cipher::AesGcmW3c;
280    ///     let _ = modern;
281    /// }
282    /// # Ok(())
283    /// # }
284    /// # }
285    /// ```
286    #[must_use]
287    pub fn wholesome_row(&self) -> Option<&EntryEncryption> {
288        if self.mode != Mode::Wholesome {
289            return None;
290        }
291        self.encrypted_entries
292            .iter()
293            .find(|e| e.path == "encrypted-package")
294    }
295}
296
297/// Failures that stop `classify` before a [`Classification`].
298///
299/// Does not implement `PartialEq` — match with [`matches!`] rather than
300/// comparing, or compare the `Display` output.
301///
302/// ```
303/// use odf_crypto::{classify, DetectError};
304///
305/// let err = classify(b"this is not a zip file").unwrap_err();
306/// assert!(matches!(err, DetectError::NotZip));
307/// ```
308#[derive(Debug, thiserror::Error)]
309#[non_exhaustive]
310pub enum DetectError {
311    /// The bytes are not a zip archive at all.
312    #[error("not a zip archive")]
313    NotZip,
314    /// A zip, but with no `META-INF/manifest.xml`, so not an ODF package.
315    #[error("not an ODF package: META-INF/manifest.xml is missing")]
316    MissingManifest,
317    /// A zip entry could not be read. The string is a diagnostic; do not match
318    /// on its content.
319    #[error("failed to read zip entry: {0}")]
320    Zip(String),
321    /// The package is one LibreOffice itself would not open — a duplicate or
322    /// invalid entry name, or a stream/folder collision.
323    ///
324    /// The string is a diagnostic; do not match on its content. It may quote
325    /// package-controlled text — the `mimetype` member and `manifest:media-type`
326    /// both appear in the mimetype-conflict case — so treat it as untrusted
327    /// when logging or displaying it. Each quoted value is elided to 96 bytes,
328    /// which bounds the message but does not make its content trustworthy.
329    #[error("inconsistent package: {0}")]
330    Inconsistent(String),
331    /// The caller's reader failed a read or a seek, so nothing can be said
332    /// about the package. Only [`crate::classify_reader`] returns it: a slice
333    /// cannot fail a read.
334    ///
335    /// The error is the reader's own value, so a caller can recognize its own
336    /// cancellation in it. It wins over the zip layer's interpretation of the
337    /// same failure; see `classify_reader`.
338    #[error("reading the package failed: {0}")]
339    Io(#[source] std::io::Error),
340}
341
342/// Internal checksum-type after Stage A (digest bytes live on the bag).
343#[derive(Debug, Clone, Copy, PartialEq, Eq)]
344pub(crate) enum ChecksumAlg {
345    Sha1_1K,
346    Sha256_1K,
347}
348
349/// Internal KDF id after Stage A, before accept predicates.
350#[derive(Debug, Clone, Copy, PartialEq, Eq)]
351pub(crate) enum KdfId {
352    Pbkdf2,
353    Argon2id,
354    PgpRsaOaepMgf1p,
355}
356
357/// One `encrypted-key` collected by Stage A.
358#[derive(Debug, Clone, Default, PartialEq, Eq)]
359pub struct EncryptedKey {
360    /// OpenPGP key id the packet is addressed to, base64-decoded.
361    pub key_id: Vec<u8>,
362    /// The `PGPKeyPacket` bytes, base64-decoded.
363    pub key_packet: Vec<u8>,
364    /// The RSA-wrapped session key (`CipherValue`), base64-decoded.
365    pub cipher_value: Vec<u8>,
366}
367
368/// `KeyInfo` attached only to the first file-entry bag (`ManifestImport.cxx` 468).
369#[derive(Debug, Clone, PartialEq, Eq)]
370pub(crate) struct KeyInfo {
371    pub keys: Vec<EncryptedKey>,
372}
373
374/// Stage A property bag. Fields are present only when ManifestImport wrote them.
375#[derive(Debug, Clone, Default, PartialEq, Eq)]
376pub(crate) struct PropertyBag {
377    pub full_path: String,
378    pub media_type: Option<String>,
379    pub version: Option<String>,
380    pub size: Option<i64>,
381    pub salt: Option<Vec<u8>>,
382    pub iv: Option<Vec<u8>>,
383    pub iteration_count: Option<i32>,
384    pub derived_key_size: Option<i32>,
385    pub digest: Option<Vec<u8>>,
386    pub digest_alg: Option<ChecksumAlg>,
387    pub enc_alg: Option<Cipher>,
388    pub start_key_alg: Option<StartKeyAlg>,
389    pub kdf: Option<KdfId>,
390    pub argon2_args: Option<(i32, i32, i32)>,
391    pub key_info: Option<KeyInfo>,
392}