Skip to main content

openszigno_core/
decode.rs

1use std::io::{Cursor, Read};
2
3use base64::{Engine as _, engine::general_purpose::STANDARD};
4use serde::Serialize;
5use zip::ZipArchive;
6
7use crate::decrypt::{CmsOutcome, DecryptOptions, decrypt_cms};
8use crate::{Document, Error, ErrorCode, Limits};
9
10/// Why a document that parsed could not be turned back into its source bytes.
11///
12/// Every variant is a reason to skip one document, never to fail a run: a
13/// dossier addressed to somebody else is a perfectly valid dossier.
14#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
15#[serde(rename_all = "snake_case")]
16pub enum UnsupportedReason {
17    /// The document is encrypted and no decryption key was supplied.
18    Encrypted,
19    /// The transform chain is not one this crate reverses.
20    TransformChain,
21    /// The document is encrypted, a key was supplied, and no `RecipientInfo`
22    /// names that key's certificate.
23    NoMatchingRecipient,
24    /// The CMS message uses a key-transport or content-encryption algorithm
25    /// outside the supported subset. `oid` names it.
26    UnsupportedCipher { oid: String },
27    /// The content is encrypted with DES-EDE3-CBC and legacy ciphers were not
28    /// allowed. `oid` names it.
29    LegacyCipher { oid: String },
30}
31
32#[derive(Clone, Debug)]
33pub struct DecodedDocument {
34    pub bytes: Vec<u8>,
35    /// Whether an `encrypt` transform was reversed to produce `bytes`.
36    ///
37    /// This says a supplied key unwrapped the content encryption key, and
38    /// nothing at all about who produced the document or whether it is signed.
39    pub decrypted: bool,
40}
41
42#[derive(Clone, Debug)]
43pub enum DecodeOutcome {
44    Decoded(DecodedDocument),
45    Unsupported(UnsupportedReason),
46}
47
48/// Decode one document without any decryption key, the behaviour
49/// [`Dossier::decode_document`](crate::Dossier::decode_document) exposes.
50pub(crate) fn decode_document(
51    document: &Document,
52    limits: &Limits,
53) -> Result<DecodeOutcome, Error> {
54    decode_document_with_options(document, limits, &DecryptOptions::default())
55}
56
57fn decode_document_with_options(
58    document: &Document,
59    limits: &Limits,
60    decrypt: &DecryptOptions<'_>,
61) -> Result<DecodeOutcome, Error> {
62    // The specification fixes the forward order as `zip? -> encrypt? ->
63    // base64`, so reversing it is base64, then decryption, then expansion.
64    let (encrypted, compressed) = match document.transforms.as_slice() {
65        [base64] if base64 == "base64" => (false, false),
66        [zip, base64] if zip == "zip" && base64 == "base64" => (false, true),
67        [encrypt, base64] if encrypt == "encrypt" && base64 == "base64" => (true, false),
68        [zip, encrypt, base64] if zip == "zip" && encrypt == "encrypt" && base64 == "base64" => {
69            (true, true)
70        }
71        _ => {
72            return Ok(DecodeOutcome::Unsupported(
73                UnsupportedReason::TransformChain,
74            ));
75        }
76    };
77
78    let mut decoded = decode_base64(&document.payload, limits)?;
79    if encrypted {
80        let Some(key) = decrypt.key else {
81            return Ok(DecodeOutcome::Unsupported(UnsupportedReason::Encrypted));
82        };
83        decoded = match decrypt_cms(&decoded, key, decrypt.allow_legacy_ciphers, limits)? {
84            CmsOutcome::Plaintext(plaintext) => plaintext,
85            CmsOutcome::NoMatchingRecipient => {
86                return Ok(DecodeOutcome::Unsupported(
87                    UnsupportedReason::NoMatchingRecipient,
88                ));
89            }
90            CmsOutcome::UnsupportedAlgorithm(oid) => {
91                return Ok(DecodeOutcome::Unsupported(
92                    UnsupportedReason::UnsupportedCipher { oid },
93                ));
94            }
95            CmsOutcome::LegacyCipher(oid) => {
96                return Ok(DecodeOutcome::Unsupported(
97                    UnsupportedReason::LegacyCipher { oid },
98                ));
99            }
100        };
101    }
102    if compressed {
103        decoded = decode_zip(&decoded, limits)?;
104    }
105
106    // Without a declared size there is nothing to compare against; the
107    // omission is reported as a structural warning when the dossier is parsed.
108    if document
109        .source_size
110        .is_some_and(|declared| decoded.len() as u64 != declared)
111    {
112        return Err(Error::new(
113            ErrorCode::SourceSizeMismatch,
114            format!(
115                "document {} decoded size does not match its declared source size",
116                document.index
117            ),
118        ));
119    }
120    Ok(DecodeOutcome::Decoded(DecodedDocument {
121        bytes: decoded,
122        decrypted: encrypted,
123    }))
124}
125
126/// Decode one document of `dossier`, decrypting it when the options allow.
127///
128/// This is [`Dossier::decode_document`](crate::Dossier::decode_document) with
129/// a decryption policy. With [`DecryptOptions::default`] the two behave
130/// identically: an encrypted document is reported as
131/// [`UnsupportedReason::Encrypted`] and skipped.
132pub fn decode_document_with(
133    dossier: &crate::Dossier,
134    index: usize,
135    limits: &Limits,
136    decrypt: &DecryptOptions<'_>,
137) -> Result<DecodeOutcome, Error> {
138    decode_document_with_options(
139        dossier.documents.get(index).ok_or_else(|| {
140            Error::new(
141                ErrorCode::InvalidAttribute,
142                "document index is out of range",
143            )
144        })?,
145        limits,
146        decrypt,
147    )
148}
149
150fn decode_base64(payload: &str, limits: &Limits) -> Result<Vec<u8>, Error> {
151    let compact: Vec<u8> = payload
152        .bytes()
153        .filter(|byte| !byte.is_ascii_whitespace())
154        .collect();
155    if compact.len() > limits.max_base64_chars {
156        return Err(Error::new(
157            ErrorCode::DecodedTooLarge,
158            "Base64 payload exceeds the encoded-size limit",
159        ));
160    }
161    let estimated = compact.len().div_ceil(4).saturating_mul(3) as u64;
162    if estimated > limits.max_decoded_document_bytes {
163        return Err(Error::new(
164            ErrorCode::DecodedTooLarge,
165            "Base64 payload exceeds the decoded-size limit",
166        ));
167    }
168    let decoded = STANDARD.decode(compact).map_err(|_| {
169        Error::new(
170            ErrorCode::InvalidBase64,
171            "document payload is not valid canonical Base64",
172        )
173    })?;
174    if decoded.len() as u64 > limits.max_decoded_document_bytes {
175        return Err(Error::new(
176            ErrorCode::DecodedTooLarge,
177            "decoded document exceeds the size limit",
178        ));
179    }
180    Ok(decoded)
181}
182
183fn decode_zip(archive_bytes: &[u8], limits: &Limits) -> Result<Vec<u8>, Error> {
184    let reader = Cursor::new(archive_bytes);
185    let mut archive = ZipArchive::new(reader)
186        .map_err(|_| Error::new(ErrorCode::InvalidZip, "payload is not a valid ZIP archive"))?;
187    if archive.len() != 1 || archive.len() > limits.max_zip_members {
188        return Err(Error::new(
189            ErrorCode::ZipMemberLimit,
190            "compressed document ZIP must contain exactly one member",
191        ));
192    }
193
194    let member = archive.by_index(0).map_err(|error| match error {
195        zip::result::ZipError::UnsupportedArchive(_)
196        | zip::result::ZipError::CompressionMethodNotSupported(_) => Error::new(
197            ErrorCode::UnsupportedZipMember,
198            "ZIP member uses encryption or an unsupported compression method",
199        ),
200        _ => Error::new(ErrorCode::InvalidZip, "cannot read ZIP member"),
201    })?;
202    let enclosed = member
203        .enclosed_name()
204        .ok_or_else(|| Error::new(ErrorCode::UnsafeZipMember, "ZIP member has an unsafe path"))?;
205    if member.is_dir()
206        || enclosed.components().count() != 1
207        || member
208            .unix_mode()
209            .is_some_and(|mode| mode & 0o170000 == 0o120000)
210    {
211        return Err(Error::new(
212            ErrorCode::UnsafeZipMember,
213            "ZIP member must be one regular file with a basename",
214        ));
215    }
216
217    let expanded_size = member.size();
218    if expanded_size > limits.max_zip_expanded_bytes
219        || expanded_size > limits.max_decoded_document_bytes
220    {
221        return Err(Error::new(
222            ErrorCode::ZipSizeLimit,
223            "ZIP member exceeds the expanded-size limit",
224        ));
225    }
226    // Header sizes are attacker-controlled. This check is only a cheap
227    // pre-filter; the authoritative ratio check below uses the actual
228    // decoded length against the actual archive length.
229    let compressed_size = member.compressed_size().min(archive_bytes.len() as u64);
230    if exceeds_ratio(expanded_size, compressed_size, limits) {
231        return Err(Error::new(
232            ErrorCode::ZipRatioLimit,
233            "ZIP member exceeds the compression-ratio limit",
234        ));
235    }
236
237    let mut decoded = Vec::with_capacity(expanded_size.min(usize::MAX as u64) as usize);
238    let read_limit = limits
239        .max_zip_expanded_bytes
240        .min(limits.max_decoded_document_bytes)
241        .saturating_add(1);
242    member
243        .take(read_limit)
244        .read_to_end(&mut decoded)
245        .map_err(|_| Error::new(ErrorCode::InvalidZip, "cannot expand ZIP member"))?;
246    if decoded.len() as u64 >= read_limit {
247        return Err(Error::new(
248            ErrorCode::ZipSizeLimit,
249            "ZIP member exceeded the expanded-size limit while reading",
250        ));
251    }
252    if exceeds_ratio(decoded.len() as u64, compressed_size, limits) {
253        return Err(Error::new(
254            ErrorCode::ZipRatioLimit,
255            "ZIP member exceeded the compression-ratio limit while reading",
256        ));
257    }
258    Ok(decoded)
259}
260
261fn exceeds_ratio(expanded: u64, compressed: u64, limits: &Limits) -> bool {
262    expanded > 0
263        && (compressed == 0
264            || expanded > compressed.saturating_mul(limits.max_zip_compression_ratio))
265}
266
267#[cfg(test)]
268mod tests {
269    use super::*;
270
271    fn limits(ratio: u64) -> Limits {
272        Limits {
273            max_zip_compression_ratio: ratio,
274            ..Limits::default()
275        }
276    }
277
278    /// Exactly at the limit (`expanded == compressed * ratio`) is allowed:
279    /// the check is strictly-greater-than, not greater-or-equal.
280    #[test]
281    fn at_the_ratio_boundary_is_not_exceeded() {
282        assert!(!exceeds_ratio(1_000, 10, &limits(100)));
283    }
284
285    /// One byte short of the boundary is also allowed.
286    #[test]
287    fn one_below_the_ratio_boundary_is_not_exceeded() {
288        assert!(!exceeds_ratio(999, 10, &limits(100)));
289    }
290
291    /// One byte past the boundary is rejected.
292    #[test]
293    fn one_above_the_ratio_boundary_is_exceeded() {
294        assert!(exceeds_ratio(1_001, 10, &limits(100)));
295    }
296
297    /// An expanded size of zero never exceeds the ratio, whatever the
298    /// compressed size or configured ratio is.
299    #[test]
300    fn zero_expanded_bytes_never_exceeds() {
301        assert!(!exceeds_ratio(0, 0, &limits(100)));
302        assert!(!exceeds_ratio(0, 10, &limits(1)));
303    }
304
305    /// A compressed size of zero with any positive expanded size is always
306    /// treated as exceeding the ratio, since no finite ratio is satisfiable.
307    #[test]
308    fn zero_compressed_bytes_with_positive_expanded_bytes_exceeds() {
309        assert!(exceeds_ratio(1, 0, &limits(u64::MAX)));
310    }
311}