odf-crypto 0.1.1

LibreOffice-faithful encryption for ODF packages (.odt, .ods, .odp): detect it, decrypt it, write it
Documentation
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
//! Stage B (`ZipPackage::parseManifest`) plus zip-shape `classify`.

use std::collections::HashSet;
use std::io::{Cursor, Read, Seek};

use zip::read::HasZipMetadata;
use zip::read::{ArchiveOffset, Config};
use zip::result::ZipResult;
use zip::CompressionMethod;
use zip::ZipArchive;

use crate::io_latch::{Latch, Latched};
use crate::limits::{DIAGNOSTIC_ELISION, MANIFEST_READ_CAP, MIMETYPE_CEILING};
use crate::manifest::parse_manifest;
use crate::types::{
    Checksum, ChecksumAlg, Classification, EncryptedKey, EntryEncryption, Kdf, KdfId, PropertyBag,
    StartKeyAlg,
};
use crate::uris;
use crate::zip_err;
use crate::zip_tree::{FolderTree, ResolvedKind, StreamAsFolder};
use crate::{Cipher, DetectError, Mode};

struct ZipMember {
    name: String,
    index: usize,
    stored: bool,
    data_descriptor: bool,
}

/// Classify an ODF package's encryption. Does not derive keys or decrypt.
///
/// Answers whether `bytes` is an ODF package, whether it is encrypted, in which
/// zip shape, and with which algorithm tuple — by running LibreOffice's own two
/// stages, `ManifestImport` then `ZipPackage::parseManifest`, rather than
/// evaluating manifest rows independently. State leaks across rows upstream in
/// ways a per-row implementation gets wrong on constructible input.
///
/// Needs no cryptographic dependency, and is available in the default build.
///
/// # Errors
///
/// [`DetectError::NotZip`] if the bytes are not a zip archive;
/// [`DetectError::MissingManifest`] if they are a zip with no
/// `META-INF/manifest.xml`; [`DetectError::Zip`] if an entry cannot be read;
/// and [`DetectError::Inconsistent`] for an archive LibreOffice itself would
/// refuse to open — a duplicate or invalid entry name, or a stream/folder
/// collision.
///
/// A malformed `META-INF/manifest.xml` is **not** an error: LibreOffice
/// discards every row and still opens the package, so the result is
/// [`Mode::Plain`].
///
/// [`DetectError`] is `#[non_exhaustive]` and does not implement `PartialEq`;
/// match with a `_` arm and [`matches!`].
///
/// # Examples
///
/// ```
/// use odf_crypto::{classify, DetectError};
///
/// let err = classify(b"this is not a zip file").unwrap_err();
/// assert!(matches!(err, DetectError::NotZip));
/// ```
///
/// A real LibreOffice document, encrypted with AES-GCM and Argon2id:
///
/// ```
/// use odf_crypto::{classify, Cipher, Kdf, Mode};
///
/// let bytes = include_bytes!("../tests/goldens/lo-wholesome-gcm-argon2.odt");
/// let class = classify(bytes)?;
///
/// assert_eq!(class.mode, Mode::Wholesome);
/// assert!(class.package_encrypted);
///
/// let row = class.common.as_ref().expect("wholesome packages carry a latch row");
/// assert_eq!(row.cipher, Cipher::AesGcmW3c);
/// assert!(matches!(row.kdf, Kdf::Argon2id { .. }));
/// # Ok::<(), odf_crypto::DetectError>(())
/// ```
pub fn classify(bytes: &[u8]) -> Result<Classification, DetectError> {
    classify_reader(Cursor::new(bytes))
}

/// [`classify`], reading the package from `reader` instead of a slice.
///
/// It runs the same two LibreOffice machines over the same zip reads, so a
/// package classifies identically either way. Only the central directory, the
/// manifest (at most 8 MiB) and the `mimetype` member are read; member bodies
/// are not, so the cost does not grow with the document.
///
/// `R` must seek because a zip is read from its central directory at the end.
///
/// # Errors
///
/// Those of [`classify`], plus [`DetectError::Io`] when `reader` itself fails a
/// read or a seek. That takes precedence over whatever the zip layer made of
/// the failure, so a cancelling reader is reported as a cancel, never as
/// [`DetectError::NotZip`].
///
/// # Examples
///
/// ```
/// use std::fs::File;
/// use odf_crypto::{classify, classify_reader};
///
/// let path = "tests/goldens/lo-wholesome-gcm-argon2.odt";
/// let from_reader = classify_reader(File::open(path)?)?;
/// assert_eq!(from_reader, classify(&std::fs::read(path)?)?);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn classify_reader<R: Read + Seek>(reader: R) -> Result<Classification, DetectError> {
    let latch = Latch::default();
    let result = classify_latched(Latched::new(reader, &latch));
    match latch.take() {
        Some(err) => Err(DetectError::Io(err)),
        None => result,
    }
}

/// Opens `reader` as a zip whose first byte is the archive's first byte, as
/// `ZipFile::readCEN` does: `nCenPos = nCenOff; // data before start of zip is
/// not supported` (`ZipFile.cxx:1336`). The central directory is read where
/// the end record says it is, and nowhere else.
///
/// `ZipArchive::new` is `ArchiveOffset::Detect`, which differs in two ways
/// LibreOffice does not share. It accepts bytes prepended to the archive by
/// shifting every offset. When the end record's directory offset and size
/// disagree, it prefers the directory that abuts the end record. Either
/// way it can read a package LibreOffice reports as corrupt, so `classify`
/// would call encrypted a file LibreOffice never prompts for. An ODF package
/// starts with its `mimetype` member, so offset 0 costs no real file.
///
/// Every archive this crate reads is opened here. #112 also measured the open
/// for speed; the fidelity reason above is why it is `Known(0)`.
pub(crate) fn open_archive<R: Read + Seek>(reader: R) -> ZipResult<ZipArchive<R>> {
    ZipArchive::with_config(
        Config {
            archive_offset: ArchiveOffset::Known(0),
        },
        reader,
    )
}

pub(crate) fn classify_latched<R: Read + Seek>(reader: R) -> Result<Classification, DetectError> {
    let mut archive = open_archive(reader).map_err(|_| DetectError::NotZip)?;
    let members = collect_members(&mut archive)?;
    let mut tree = FolderTree::from_zip_names(members.iter().map(|m| m.name.as_str()))
        .map_err(|_| DetectError::Zip("Bad Zip File, stream as folder".into()))?;
    let zip_has_encrypted_package = tree.root_has_entry("encrypted-package");

    let manifest_xml = read_named_member(&mut archive, &members, "META-INF/manifest.xml")?
        .ok_or(DetectError::MissingManifest)?;
    let bags = parse_manifest(&manifest_xml);
    let mimetype = read_mimetype(&mut archive, &members, &tree)?;
    let class = stage_b(bags, &mut tree, zip_has_encrypted_package, mimetype)?;
    check_stored_data_descriptors(&members, &class)?;
    Ok(class)
}

fn collect_members<R: Read + Seek>(
    archive: &mut ZipArchive<R>,
) -> Result<Vec<ZipMember>, DetectError> {
    let mut members = Vec::new();
    let mut seen = HashSet::new();
    let mut seen_lower = HashSet::new();
    for i in 0..archive.len() {
        let file = archive
            .by_index(i)
            .map_err(|err| DetectError::Zip(zip_err::message(&err)))?;
        let meta = file.get_metadata();
        if meta.uncompressed_size == 0
            && u8::from(meta.system) == 0
            && meta.external_attributes & 0x10 != 0
        {
            continue;
        }
        let name = zip_entry_name(file.name_raw());
        if !is_valid_zip_entry_file_name(&name) {
            return Err(DetectError::Zip("Zip entry has an invalid name.".into()));
        }
        if !seen.insert(name.clone()) {
            return Err(DetectError::Zip("Duplicate CEN entry".into()));
        }
        if !seen_lower.insert(name.to_ascii_lowercase()) {
            return Err(DetectError::Zip(
                "Duplicate CEN entry (case insensitive)".into(),
            ));
        }
        members.push(ZipMember {
            name,
            index: i,
            stored: file.compression() == CompressionMethod::Stored,
            data_descriptor: meta.is_using_data_descriptor(),
        });
    }
    Ok(members)
}

/// `OStorageHelper::IsValidZipEntryFileName` with slashes allowed.
fn is_valid_zip_entry_file_name(name: &str) -> bool {
    let mut dots: i32 = 0;
    for (i, c) in name.chars().enumerate() {
        match c {
            '.' => {
                if dots != -1 {
                    dots += 1;
                }
            }
            '\\' | '?' | '<' | '>' | '"' | '|' | ':' => return false,
            '/' => {
                if dots == 1 || dots == 2 || i == 0 {
                    return false;
                }
                dots = 0;
            }
            _ => {
                dots = -1;
                let u = c as u32;
                if u < 32 || (0xD800..=0xDFFF).contains(&u) {
                    return false;
                }
            }
        }
    }
    dots != 1 && dots != 2
}

fn read_named_member<R: Read + Seek>(
    archive: &mut ZipArchive<R>,
    members: &[ZipMember],
    want: &str,
) -> Result<Option<Vec<u8>>, DetectError> {
    let Some(member) = members.iter().find(|m| member_matches_path(&m.name, want)) else {
        return Ok(None);
    };
    let mut file = archive
        .by_index(member.index)
        .map_err(|err| DetectError::Zip(zip_err::message(&err)))?;
    let mut buf = Vec::new();
    file.by_ref()
        .take(MANIFEST_READ_CAP as u64 + 1)
        .read_to_end(&mut buf)
        .map_err(|err| DetectError::Zip(err.to_string()))?;
    if buf.len() > MANIFEST_READ_CAP {
        return Err(DetectError::Zip("zip entry too large".into()));
    }
    Ok(Some(buf))
}

/// Namelist key `classify` uses: UTF-8 lossy raw CEN bytes, not `ZipFile::name()`'s
/// CP437 decode when the general-purpose UTF-8 flag is unset.
pub(crate) fn zip_entry_name(raw: &[u8]) -> String {
    String::from_utf8_lossy(raw).into_owned()
}

pub(crate) fn member_matches_path(zip_name: &str, want: &str) -> bool {
    if zip_name == want {
        return true;
    }
    // `META-INF//manifest.xml` inserts as `META-INF/manifest.xml`.
    collapse_slashes(zip_name) == want
}

pub(crate) fn collapse_slashes(name: &str) -> String {
    let mut out = String::with_capacity(name.len());
    let mut prev_slash = false;
    for c in name.chars() {
        if c == '/' {
            if !prev_slash {
                out.push(c);
            }
            prev_slash = true;
        } else {
            prev_slash = false;
            out.push(c);
        }
    }
    out
}

fn read_mimetype<R: Read + Seek>(
    archive: &mut ZipArchive<R>,
    members: &[ZipMember],
    tree: &FolderTree,
) -> Result<Option<String>, DetectError> {
    if !tree.root_has_entry("mimetype") {
        return Ok(None);
    }
    if !tree.root_has_stream("mimetype") {
        // Root folder named `mimetype`: LO reads an empty media-type.
        return Ok(Some(String::new()));
    }
    let Some(member) = members.iter().find(|m| m.name == "mimetype") else {
        return Ok(Some(String::new()));
    };
    let mut file = archive
        .by_index(member.index)
        .map_err(|err| DetectError::Zip(zip_err::message(&err)))?;
    let mut buf = [0u8; MIMETYPE_CEILING];
    let n = file
        .read(&mut buf)
        .map_err(|err| DetectError::Zip(err.to_string()))?;
    Ok(Some(String::from_utf8_lossy(&buf[..n]).into_owned()))
}

fn nonempty(value: Option<&String>) -> bool {
    value.map(|s| !s.is_empty()).unwrap_or(false)
}

fn version_ge_12(version: Option<&str>) -> bool {
    version.map(|v| v >= "1.2").unwrap_or(false)
}

fn stage_b(
    bags: Vec<PropertyBag>,
    tree: &mut FolderTree,
    zip_has_encrypted_package: bool,
    mimetype: Option<String>,
) -> Result<Classification, DetectError> {
    let mut key_info = false;
    let mut pgp_keys: Vec<EncryptedKey> = Vec::new();
    let mut o_first_version = None;
    let mut package_encrypted = false;
    let mut has_non_encrypted_entries = false;
    let mut common = None;
    let mut encrypted_entries = Vec::new();
    let mut encrypted_package_complete = false;

    for bag in bags {
        if o_first_version.is_none() {
            if let Some(v) = bag.version.as_ref().filter(|s| !s.is_empty()) {
                o_first_version = Some(v.clone());
            }
        }
        if let Some(ki) = &bag.key_info {
            key_info = true;
            if pgp_keys.is_empty() {
                pgp_keys = ki.keys.clone();
            }
        }
        if bag.full_path.is_empty() {
            continue;
        }
        let resolved = match tree.resolve(&bag.full_path) {
            Ok(r) => r,
            Err(StreamAsFolder) => {
                return Err(DetectError::Inconsistent(
                    "stream used as folder in manifest path".into(),
                ));
            }
        };
        let Some(resolved) = resolved else {
            continue;
        };

        match resolved.kind {
            ResolvedKind::Folder => {
                tree.set_folder_meta(
                    &resolved.tree_path,
                    bag.media_type.clone(),
                    bag.version.clone(),
                );
            }
            ResolvedKind::Stream => {
                tree.mark_from_manifest(&resolved.tree_path, bag.media_type.clone());
                if let Some(entry) = accept_row(&bag, key_info, resolved.tree_path.clone()) {
                    // Wholesome complete-check is the resolved root member,
                    // not the bag's `full-path`.
                    if resolved.tree_path == "encrypted-package" {
                        encrypted_package_complete = true;
                    }
                    let short = short_name(&entry.path);
                    if !package_encrypted
                        && (short == "content.xml" || short == "encrypted-package")
                    {
                        package_encrypted = true;
                        common = Some(entry.clone());
                    }
                    encrypted_entries.push(entry);
                } else {
                    // `ZipPackage.cxx:446`: the `else` of the same complete-row
                    // test, over the same streams. A manifest row on a folder,
                    // or naming no member, sets nothing upstream either.
                    has_non_encrypted_entries = true;
                }
            }
        }
    }

    let mode = if zip_has_encrypted_package && encrypted_package_complete {
        Mode::Wholesome
    } else if !encrypted_entries.is_empty() {
        Mode::PerEntry
    } else {
        Mode::Plain
    };

    let root_had_media = nonempty(tree.root_meta().media_type.as_ref());
    if let Some(ref mt) = mimetype {
        if !root_had_media {
            if mt.starts_with("application/vnd.") {
                let version = if !nonempty(tree.root_meta().version.as_ref()) {
                    o_first_version.clone()
                } else {
                    tree.root_meta().version.clone()
                };
                tree.set_folder_meta("/", Some(mt.clone()), version);
            }
        } else {
            let xml_mt = if zip_has_encrypted_package {
                tree.root_entry_media_type("encrypted-package")
                    .unwrap_or("")
            } else {
                tree.root_meta().media_type.as_deref().unwrap_or("")
            };
            if xml_mt != mt.as_str() {
                return Err(DetectError::Inconsistent(format!(
                    "mimetype conflicts with manifest.xml, \"{}\" vs. \"{}\"",
                    elide(xml_mt),
                    elide(mt)
                )));
            }
        }
    }

    let root = tree.root_meta();
    let has_unexpected_streams = tree.has_unexpected_odf12_streams(zip_has_encrypted_package);
    let odf12_fatal = has_unexpected_streams && version_ge_12(root.version.as_deref());

    Ok(Classification {
        mode,
        package_encrypted,
        has_non_encrypted_entries,
        odf_version: root.version.clone(),
        zip_has_encrypted_package,
        media_type: root.media_type.clone(),
        common,
        encrypted_entries,
        has_unexpected_streams,
        odf12_fatal,
        pgp_keys,
    })
}

fn check_stored_data_descriptors(
    members: &[ZipMember],
    class: &Classification,
) -> Result<(), DetectError> {
    let encrypted: HashSet<&str> = class
        .encrypted_entries
        .iter()
        .map(|e| e.path.as_str())
        .collect();
    for member in members {
        if member.stored && member.data_descriptor {
            let collapsed = collapse_slashes(&member.name);
            if !encrypted.contains(member.name.as_str()) && !encrypted.contains(collapsed.as_str())
            {
                return Err(DetectError::Zip(
                    "entry STORED with data descriptor but not encrypted".into(),
                ));
            }
        }
    }
    Ok(())
}

/// Render an untrusted manifest string into a diagnostic, bounded.
///
/// Both sides of the mimetype comparison are package-controlled, and before
/// this only one of them was bounded — see [`DIAGNOSTIC_ELISION`] for the
/// measurement that prompted it. The elided form reports how much was cut:
/// it is the part of an anomalous value actually worth reporting, and it is
/// ours rather than the package's.
///
/// The cut lands on a character boundary. Slicing a `&str` at an arbitrary
/// byte index panics, `manifest:media-type` is arbitrary UTF-8, and this
/// crate does not panic to describe its input.
fn elide(s: &str) -> String {
    if s.len() <= DIAGNOSTIC_ELISION {
        return s.to_string();
    }
    let cut = s
        .char_indices()
        .map(|(i, _)| i)
        .take_while(|&i| i <= DIAGNOSTIC_ELISION)
        .last()
        .unwrap_or(0);
    format!("{}… [+{} bytes elided]", &s[..cut], s.len() - cut)
}

fn short_name(path: &str) -> &str {
    path.rsplit('/')
        .next()
        .filter(|s| !s.is_empty())
        .unwrap_or(path)
}

fn accept_row(bag: &PropertyBag, key_info: bool, path: String) -> Option<EntryEncryption> {
    if key_info {
        if let Some(row) = pgp_entry(bag, &path) {
            return Some(row);
        }
    }
    password_entry(bag, &path)
}

/// Both builders were once a `*_complete(bag) -> bool` guard followed by a
/// builder that re-read the same fields with `.expect("*_complete")`. Extracting
/// with `?` here makes the completeness test and the extraction the same code,
/// so they cannot drift and there is nothing left to unwrap: an incomplete bag
/// is a rejected row, which is what the guard already meant.
///
/// The one condition that is a test rather than an extraction — GCM needs no
/// checksum, everything else does — stays an explicit `if`.
fn checksum_present_or_unneeded(bag: &PropertyBag, cipher: Cipher) -> bool {
    cipher == Cipher::AesGcmW3c || (bag.digest.is_some() && bag.digest_alg.is_some())
}

fn pgp_entry(bag: &PropertyBag, path: &str) -> Option<EntryEncryption> {
    if bag.kdf != Some(KdfId::PgpRsaOaepMgf1p) {
        return None;
    }
    let cipher = bag.enc_alg?;
    let size = bag.size?;
    let iv = bag.iv.clone()?;
    if !checksum_present_or_unneeded(bag, cipher) {
        return None;
    }
    Some(EntryEncryption {
        path: path.to_string(),
        cipher,
        kdf: Kdf::PgpRsaOaepMgf1p,
        start_key: StartKeyAlg::Sha256,
        checksum: checksum_of(bag),
        size,
        iv,
        derived_key_len: uris::default_derived_key_size(cipher),
    })
}

fn password_entry(bag: &PropertyBag, path: &str) -> Option<EntryEncryption> {
    let cipher = bag.enc_alg?;
    let size = bag.size?;
    let iv = bag.iv.clone()?;
    let salt = bag.salt.clone()?;
    let kdf = match bag.kdf {
        Some(KdfId::Pbkdf2) => Kdf::Pbkdf2 {
            iterations: bag.iteration_count.unwrap_or(0),
            salt,
        },
        Some(KdfId::Argon2id) => {
            let (t, m, p) = bag.argon2_args?;
            Kdf::Argon2id { t, m, p, salt }
        }
        _ => return None,
    };
    if !checksum_present_or_unneeded(bag, cipher) {
        return None;
    }
    Some(EntryEncryption {
        path: path.to_string(),
        cipher,
        kdf,
        start_key: bag.start_key_alg.unwrap_or(StartKeyAlg::Sha1),
        checksum: checksum_of(bag),
        size,
        iv,
        derived_key_len: bag.derived_key_size.unwrap_or(16),
    })
}

fn checksum_of(bag: &PropertyBag) -> Checksum {
    match (bag.digest_alg, bag.digest.as_ref()) {
        (Some(ChecksumAlg::Sha1_1K), Some(d)) => Checksum::Sha1_1K(d.clone()),
        (Some(ChecksumAlg::Sha256_1K), Some(d)) => Checksum::Sha256_1K(d.clone()),
        _ => Checksum::None,
    }
}

#[cfg(test)]
#[path = "classify_tests.rs"]
mod tests;