Skip to main content

odf_crypto/
reencrypt.rs

1//! `reencrypt_to`: change an encrypted package's password without its plaintext
2//! ever being written anywhere -- decrypt and encrypt joined into one stream.
3//!
4//! The output is what [`crate::encrypt`] writes (wholesome AES-256-GCM under
5//! Argon2id), whatever the source's profile. See
6//! `docs/plans/odf-streaming-2026-10-15.md`, §2 and §4.
7
8use std::io::{self, Read, Seek, SeekFrom, Write};
9
10use secure_gate::{RevealSecret, RevealSecretMut};
11use zip::{CompressionMethod, ZipArchive, ZipWriter};
12
13use crate::classify::{classify_latched, open_archive};
14use crate::decrypt::{
15    member_for_archive, no_member, screen_class, screen_shape, DecryptError, DecryptLimits,
16};
17use crate::decrypt_stream::{
18    declared_size, fault_error, gcm_key, member_shape, open_after_iv, DecryptOutcome,
19    IntegrityOutcome, Sizes,
20};
21use crate::encrypt::{
22    build_manifest, derive_write_key, random_bytes, resolve_mimetype, Argon2Params, EncryptError,
23    WHOLESOME,
24};
25use crate::io_latch::{Latch, Latched};
26use crate::limits::{AES_GCM_IV_LEN, AES_GCM_TAG_LEN};
27use crate::sensitive::DerivedKey;
28use crate::stream::{
29    chunk_buffer, DeflateWriter, Fault, GcmDecryptReader, GcmEncryptWriter, GcmStream,
30    InflateReader, CHUNK,
31};
32use crate::zip_err;
33use crate::zip_stream::{self, deflate_bound, ZipStreamWriter};
34use crate::{Classification, Mode};
35
36const MANIFEST_PATH: &str = "META-INF/manifest.xml";
37
38/// Failures from [`reencrypt_to`].
39#[derive(Debug, thiserror::Error)]
40#[non_exhaustive]
41pub enum ReencryptError {
42    /// The source could not be decrypted with the old password: every
43    /// [`DecryptError`] it can be, except [`DecryptError::Io`], which is
44    /// reported as [`ReencryptError::Io`].
45    #[error("decrypting the source failed: {0}")]
46    Decrypt(DecryptError),
47    /// The output could not be encrypted with the new password -- an empty one,
48    /// say, or an unaffordable Argon2id cost. [`EncryptError::Io`] is reported
49    /// as [`ReencryptError::Io`].
50    #[error("encrypting the result failed: {0}")]
51    Encrypt(EncryptError),
52    /// A per-entry source in which some listed content is not encrypted: a
53    /// manifest row with no complete `encryption-data`
54    /// ([`crate::Classification::has_non_encrypted_entries`]), or encrypted
55    /// rows with no row on `content.xml` to latch the package as encrypted.
56    ///
57    /// Re-encrypting would carry that plaintext into a container whose AEAD
58    /// tag then vouches for it. **This crate's policy, not LibreOffice's**:
59    /// [`crate::decrypt_to`] still decrypts the package, as LibreOffice opens
60    /// it, after a warning (`ERRCODE_SFX_INCOMPLETE_ENCRYPTION`).
61    #[error("refused: the source has listed content that is not encrypted")]
62    PartiallyEncrypted,
63    /// A per-entry source with zip members its manifest does not list. Not
64    /// fatal to LibreOffice below ODF 1.2, but carried into the output they
65    /// would be authenticated by its tag. Policy, as above.
66    #[error("refused: the source has members its manifest does not list")]
67    UnexpectedStreams,
68    /// The caller's reader or writer failed. A reader failure is the reader's
69    /// own error and takes precedence, so a cancel is reported as a cancel.
70    #[error("I/O failed: {0}")]
71    Io(#[source] io::Error),
72}
73
74impl From<DecryptError> for ReencryptError {
75    fn from(e: DecryptError) -> Self {
76        match e {
77            DecryptError::Io(e) => ReencryptError::Io(e),
78            other => ReencryptError::Decrypt(other),
79        }
80    }
81}
82
83impl From<EncryptError> for ReencryptError {
84    fn from(e: EncryptError) -> Self {
85        match e {
86            EncryptError::Io(e) => ReencryptError::Io(e),
87            other => ReencryptError::Encrypt(other),
88        }
89    }
90}
91
92/// Decrypt `reader` with `old` and write it to `writer` encrypted with `new`,
93/// in bounded memory and with no plaintext written anywhere.
94///
95/// - **A wholesome source** is re-keyed without recompressing: its tag is
96///   checked first, as [`crate::decrypt_to`] checks it, then its deflated
97///   stream is decrypted and re-encrypted chunk by chunk, while a side inflate
98///   confirms it still inflates to its `manifest:size`. The inner package is
99///   carried over byte for byte.
100/// - **A per-entry source** is refused if it has listed content that is not
101///   encrypted, or unlisted members (see [`ReencryptError`]). Otherwise it is
102///   rebuilt as [`crate::decrypt_to`] rebuilds it, and the rebuilt package is
103///   encrypted as [`crate::encrypt`] would, all in one stream.
104///
105/// The outcome reports what the **source** was checked with, as
106/// [`crate::decrypt_to`]'s does. The output is AES-256-GCM, so the new
107/// package will verify fully, whatever the old one did.
108///
109/// **On any `Err`, `writer`'s contents are unspecified and must be
110/// discarded.**
111///
112/// # Errors
113///
114/// [`ReencryptError::Decrypt`] for what [`crate::decrypt_to`] would refuse,
115/// in its order; the two refusals above; [`ReencryptError::Encrypt`] for what
116/// [`crate::encrypt_to`] would refuse of the new password and cost; and
117/// [`ReencryptError::Io`].
118///
119/// # Examples
120///
121/// ```
122/// use std::fs::File;
123/// use std::io::Cursor;
124/// use odf_crypto::{decrypt, reencrypt_to, Argon2Params, DecryptLimits};
125///
126/// let path = "tests/goldens/lo-wholesome-gcm-argon2.odt";
127/// let mut rekeyed = Cursor::new(Vec::new());
128/// reencrypt_to(
129///     File::open(path)?,
130///     &mut rekeyed,
131///     "password",
132///     "a new one",
133///     DecryptLimits::default(),
134///     Argon2Params::LIBREOFFICE_DEFAULT,
135/// )?;
136///
137/// let rekeyed = rekeyed.into_inner();
138/// assert_eq!(decrypt(&rekeyed, "a new one")?, decrypt(&std::fs::read(path)?, "password")?);
139/// assert!(decrypt(&rekeyed, "password").is_err());
140/// # Ok::<(), Box<dyn std::error::Error>>(())
141/// ```
142pub fn reencrypt_to<R: Read + Seek, W: Write + Seek>(
143    reader: R,
144    writer: W,
145    old: &str,
146    new: &str,
147    limits: DecryptLimits,
148    params: Argon2Params,
149) -> Result<DecryptOutcome, ReencryptError> {
150    if old.is_empty() {
151        return Err(DecryptError::EmptyPassword.into());
152    }
153    if new.is_empty() {
154        return Err(EncryptError::EmptyPassword.into());
155    }
156    let latch = Latch::default();
157    let mut src = Latched::new(reader, &latch);
158    let result = run(&mut src, writer, old, new, &limits, params);
159    match latch.take() {
160        Some(err) => Err(ReencryptError::Io(err)),
161        None => result,
162    }
163}
164
165fn run<R: Read + Seek, W: Write + Seek>(
166    src: &mut R,
167    writer: W,
168    old: &str,
169    new: &str,
170    limits: &DecryptLimits,
171    params: Argon2Params,
172) -> Result<DecryptOutcome, ReencryptError> {
173    let class = classify_latched(&mut *src).map_err(DecryptError::from)?;
174    screen_class(&class, limits)?;
175    if class.mode == Mode::PerEntry {
176        screen_per_entry(&class)?;
177    }
178    src.seek(SeekFrom::Start(0)).map_err(ReencryptError::Io)?;
179    let mut archive =
180        open_archive(&mut *src).map_err(|e| DecryptError::Zip(zip_err::message(&e)))?;
181    let mimetype = resolve_mimetype(&mut archive, class.media_type.as_deref())?;
182    match class.mode {
183        Mode::Wholesome => wholesome(
184            &mut archive,
185            &class,
186            writer,
187            old,
188            new,
189            limits,
190            params,
191            mimetype,
192        ),
193        _ => per_entry(
194            &mut archive,
195            &class,
196            writer,
197            old,
198            new,
199            limits,
200            params,
201            mimetype,
202        ),
203    }
204}
205
206/// The plan's §4 refusals, all read from the classification, before any key
207/// is derived or any byte written.
208fn screen_per_entry(class: &Classification) -> Result<(), ReencryptError> {
209    if class.has_non_encrypted_entries {
210        return Err(ReencryptError::PartiallyEncrypted);
211    }
212    if class.has_unexpected_streams {
213        return Err(ReencryptError::UnexpectedStreams);
214    }
215    if !class.package_encrypted {
216        return Err(ReencryptError::PartiallyEncrypted);
217    }
218    Ok(())
219}
220
221/// The new package's three members around `payload`, which writes the
222/// `encrypted-package` body after its IV and returns the inner package's
223/// length for `manifest:size`.
224#[allow(clippy::too_many_arguments)]
225fn write_package<W: Write + Seek>(
226    writer: W,
227    new: &str,
228    params: Argon2Params,
229    mimetype: Option<String>,
230    could_reach: u64,
231    payload: impl FnOnce(&mut dyn Write, &[u8]) -> Result<u64, ReencryptError>,
232) -> Result<(), ReencryptError> {
233    let salt = random_bytes(WHOLESOME.salt_len)?;
234    let iv = random_bytes(WHOLESOME.iv_len)?;
235    let key = derive_write_key(new, &salt, params)?;
236
237    let to_zip = |e: zip::result::ZipError| -> ReencryptError {
238        match e {
239            zip::result::ZipError::Io(e) => ReencryptError::Io(e),
240            other => EncryptError::Zip(zip_err::message(&other)).into(),
241        }
242    };
243    let stored = zip_stream::file_options(CompressionMethod::Stored);
244    let mut out = ZipWriter::new(writer);
245    out.start_file("mimetype", stored).map_err(to_zip)?;
246    out.write_all(mimetype.as_deref().map(str::as_bytes).unwrap_or(&[]))
247        .map_err(ReencryptError::Io)?;
248    let worst = (AES_GCM_IV_LEN + AES_GCM_TAG_LEN) as u64 + could_reach;
249    out.start_file(
250        "encrypted-package",
251        stored.large_file(worst >= u64::from(u32::MAX)),
252    )
253    .map_err(to_zip)?;
254    out.write_all(&iv).map_err(ReencryptError::Io)?;
255    let size = key.with_secret(|k| -> Result<u64, ReencryptError> {
256        let gcm = GcmStream::new(k, &iv)
257            .ok_or_else(|| EncryptError::Internal("AES-256-GCM key".into()))?;
258        let mut sealer = GcmEncryptWriter::new(&mut out, gcm).map_err(alloc)?;
259        let size = payload(&mut sealer, k)?;
260        sealer.finish().map_err(ReencryptError::Io)?;
261        Ok(size)
262    })?;
263    let size = i64::try_from(size)
264        .map_err(|_| EncryptError::Internal(format!("inner package of {size} bytes")))?;
265    let manifest = build_manifest(size, &iv, &salt, mimetype.as_deref(), params)?;
266    let deflated = zip_stream::file_options(CompressionMethod::Deflated);
267    out.start_file(MANIFEST_PATH, deflated).map_err(to_zip)?;
268    out.write_all(&manifest).map_err(ReencryptError::Io)?;
269    out.finish().map_err(to_zip)?;
270    Ok(())
271}
272
273fn alloc(f: Fault) -> ReencryptError {
274    match f {
275        Fault::Alloc(n) => EncryptError::HostCannotAllocate { requested_bytes: n }.into(),
276        other => EncryptError::Internal(other.to_string()).into(),
277    }
278}
279
280/// Reads `src` and writes every byte it yields to `dst` as well: the old
281/// stream's deflated plaintext goes on to the new cipher while the inflater
282/// beside it checks it. The bytes pass through the reader's own buffer, which
283/// the inflater owns and wipes.
284struct Tee<R, W> {
285    src: R,
286    dst: W,
287}
288
289/// A failure of the tee's output, marked so [`read_error`] reports it as the
290/// caller's writer rather than as the source.
291#[derive(Debug)]
292struct OutputFailed(io::Error);
293
294impl std::fmt::Display for OutputFailed {
295    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
296        write!(f, "writing the output failed: {}", self.0)
297    }
298}
299
300impl std::error::Error for OutputFailed {}
301
302impl<R: Read, W: Write> Read for Tee<R, W> {
303    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
304        let n = self.src.read(buf)?;
305        self.dst
306            .write_all(&buf[..n])
307            .map_err(|e| io::Error::other(OutputFailed(e)))?;
308        Ok(n)
309    }
310}
311
312#[allow(clippy::too_many_arguments)]
313fn wholesome<R: Read + Seek, W: Write + Seek>(
314    archive: &mut ZipArchive<R>,
315    class: &Classification,
316    writer: W,
317    old: &str,
318    new: &str,
319    limits: &DecryptLimits,
320    params: Argon2Params,
321    mimetype: Option<String>,
322) -> Result<DecryptOutcome, ReencryptError> {
323    let (row_index, row) = crate::decrypt::wholesome_row(class)?;
324    let expected = declared_size(row.size)?;
325    let (index, _) = member_for_archive(archive, &row.path, no_member(row_index))?;
326    let (len, head) = member_shape(archive, index)?;
327    screen_shape(row, len, &head)?;
328    // The verify pass, under the old key, before anything is derived for the
329    // new one or written.
330    let old_key: DerivedKey = gcm_key(archive, index, row, len, old, limits)?;
331    let ct_len = len - (AES_GCM_IV_LEN + AES_GCM_TAG_LEN) as u64;
332
333    write_package(writer, new, params, mimetype, len, |sealer, _| {
334        let mut file = open_after_iv(archive, index)?;
335        old_key.with_secret(|k| -> Result<u64, ReencryptError> {
336            let gcm = GcmStream::new(k, &row.iv).ok_or_else(|| {
337                DecryptError::Internal("an AES-GCM key length screen_shape passed".into())
338            })?;
339            let plain = GcmDecryptReader::new(&mut file, gcm, ct_len);
340            let mut tee = Tee {
341                src: plain,
342                dst: sealer,
343            };
344            {
345                let mut check = InflateReader::new(&mut tee, expected, limits.max_output_bytes)
346                    .map_err(fault_error(limits))?;
347                drain(&mut check, limits)?;
348            }
349            // Past the DEFLATE end marker: still part of the member, so still
350            // re-encrypted, and the old tag is still checked at its end.
351            drain(&mut tee, limits)?;
352            Ok(expected)
353        })
354    })?;
355    Ok(DecryptOutcome {
356        integrity: IntegrityOutcome::Verified,
357    })
358}
359
360#[allow(clippy::too_many_arguments)]
361fn per_entry<R: Read + Seek, W: Write + Seek>(
362    archive: &mut ZipArchive<R>,
363    class: &Classification,
364    writer: W,
365    old: &str,
366    new: &str,
367    limits: &DecryptLimits,
368    params: Argon2Params,
369    mimetype: Option<String>,
370) -> Result<DecryptOutcome, ReencryptError> {
371    // The rebuilt package is at most every member inflated, plus headers; the
372    // bound only decides whether the outer member needs Zip64.
373    let mut could_reach = 1 << 20;
374    for i in 0..archive.len() {
375        let f = archive
376            .by_index_raw(i)
377            .map_err(|e| DecryptError::Zip(zip_err::message(&e)))?;
378        could_reach += f.size().max(f.compressed_size()) + 1024;
379    }
380    for row in &class.encrypted_entries {
381        could_reach += declared_size(row.size)?;
382    }
383    let mut outcome = None;
384    write_package(
385        writer,
386        new,
387        params,
388        mimetype,
389        deflate_bound(could_reach),
390        |sealer, _| {
391            let mut deflate = DeflateWriter::adaptive(sealer).map_err(alloc)?;
392            let mut zip = ZipStreamWriter::new(&mut deflate);
393            outcome = Some(crate::decrypt_entries::per_entry(
394                archive,
395                class,
396                &mut zip,
397                old,
398                limits,
399                Sizes::Streamed,
400            )?);
401            zip.finish()
402                .map_err(crate::decrypt_entries::zip_stream_error(limits))?;
403            let size = deflate.consumed();
404            deflate.finish().map_err(write_error)?;
405            Ok(size)
406        },
407    )?;
408    outcome.ok_or_else(|| {
409        EncryptError::Internal("per-entry rebuild produced no outcome".into()).into()
410    })
411}
412
413fn write_error(e: io::Error) -> ReencryptError {
414    match Fault::take(e) {
415        Ok(Fault::Deflate(s)) => EncryptError::Deflate(s).into(),
416        Ok(other) => alloc(other),
417        Err(e) => ReencryptError::Io(e),
418    }
419}
420
421/// Read `r` to its end through a wiped buffer, discarding what it yields.
422fn drain(r: &mut dyn Read, limits: &DecryptLimits) -> Result<(), ReencryptError> {
423    let mut buf = chunk_buffer(CHUNK).map_err(alloc)?;
424    loop {
425        let n = buf
426            .with_secret_mut(|b| r.read(b))
427            .map_err(|e| read_error(e, limits))?;
428        if n == 0 {
429            return Ok(());
430        }
431    }
432}
433
434/// A read failed somewhere along decrypt, tee and inflate. A [`Fault`] is
435/// about the source; a failure of the new cipher's writer (the tee's `dst`) is
436/// the caller's output, and anything else is the zip layer.
437fn read_error(e: io::Error, limits: &DecryptLimits) -> ReencryptError {
438    let e = match Fault::take(e) {
439        Ok(f) => return fault_error(limits)(f).into(),
440        Err(e) => e,
441    };
442    if !e.get_ref().is_some_and(|inner| inner.is::<OutputFailed>()) {
443        return DecryptError::Zip(e.to_string()).into();
444    }
445    match e.into_inner().map(|inner| inner.downcast::<OutputFailed>()) {
446        Some(Ok(failed)) => ReencryptError::Io(failed.0),
447        Some(Err(other)) => ReencryptError::Io(io::Error::other(other)),
448        None => DecryptError::Zip("reading the source failed".into()).into(),
449    }
450}
451
452#[cfg(test)]
453#[path = "reencrypt_tests.rs"]
454mod tests;