Skip to main content

openszigno_core/decrypt/
mod.rs

1//! Decryption of the e-dossier `encrypt` transform.
2//!
3//! The e-dossier specification says only that `encrypt` is "S/MIME
4//! encryption" and that `es:RecipientCertificateList` may name the
5//! certificates whose private keys can undo it. It fixes no algorithms and no
6//! recipient-identifier form. Microsec's own `eszigno3` reference CLI is more
7//! concrete: its `cm_decrypt` command is documented as "RFC5652 szerinti CMS
8//! titkosítás feloldása" — undoing CMS encryption per RFC 5652 — and its
9//! `export_recipient_infos` command exports the recipients' certificates *and
10//! their encrypted keys*, which is the CMS `RecipientInfos` structure. This
11//! module therefore reads the Base64-decoded payload as a DER
12//! `ContentInfo` carrying `id-envelopedData` (RFC 5652 §6).
13//!
14//! What is supported is deliberately a small subset, listed in
15//! `docs/architecture.md`:
16//!
17//! - `KeyTransRecipientInfo` only, with the recipient named either by
18//!   `issuerAndSerialNumber` or by `subjectKeyIdentifier`;
19//! - key transport with RSAES-PKCS1-v1_5 or RSAES-OAEP (MGF1, SHA-1/256/384/512);
20//! - content encryption with AES-128/192/256-CBC, and DES-EDE3-CBC only when
21//!   the caller opts in, because it is weak and is merely what the reference
22//!   implementation defaulted to.
23//!
24//! Nothing here establishes authenticity. Decrypting a document says a key
25//! could unwrap it, not that anybody signed it.
26//!
27//! The module is split by concern: [`cms`] parses and validates the CMS
28//! `ContentInfo` / `EnvelopedData` / `RecipientInfo` structure; [`keytrans`]
29//! runs the RSA private operation and unwraps the content-encryption key
30//! under implicit rejection, so an unusable key transport is never
31//! distinguishable from a usable one; [`ciphers`] identifies and runs the
32//! content cipher; [`keys`] loads the recipient's private key and matches it
33//! against a `RecipientIdentifier`. This module ties the four together and
34//! holds the public entry points.
35
36mod ciphers;
37mod cms;
38mod keys;
39mod keytrans;
40
41use ::cms::enveloped_data::RecipientInfo;
42use der::asn1::OctetString;
43
44pub use keys::RecipientKey;
45
46use crate::{Error, ErrorCode, Limits};
47
48/// How `decode_document_with` may treat an encrypted document.
49///
50/// The default decrypts nothing: an encrypted document stays skipped unless
51/// the caller supplies a key.
52#[derive(Clone, Copy, Debug, Default)]
53pub struct DecryptOptions<'a> {
54    /// The recipient key, or `None` to keep encrypted documents skipped.
55    pub key: Option<&'a RecipientKey>,
56    /// Accept DES-EDE3-CBC content encryption. Off by default: 3DES has a
57    /// 64-bit block and an effective strength well below its key length.
58    pub allow_legacy_ciphers: bool,
59}
60
61/// What one CMS payload turned into.
62///
63/// Everything except `Plaintext` is a reason to skip the document rather than
64/// to fail the run: another recipient's document, or one encrypted with an
65/// algorithm outside the supported subset, is not a broken dossier.
66pub(crate) enum CmsOutcome {
67    Plaintext(Vec<u8>),
68    NoMatchingRecipient,
69    UnsupportedAlgorithm(String),
70    LegacyCipher(String),
71}
72
73impl std::fmt::Debug for CmsOutcome {
74    /// Deliberately hand-written: a derived `Debug` would print the decrypted
75    /// bytes, and a plaintext must never reach a diagnostic by accident.
76    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        match self {
78            Self::Plaintext(bytes) => write!(formatter, "Plaintext({} bytes)", bytes.len()),
79            Self::NoMatchingRecipient => formatter.write_str("NoMatchingRecipient"),
80            Self::UnsupportedAlgorithm(oid) => write!(formatter, "UnsupportedAlgorithm({oid})"),
81            Self::LegacyCipher(oid) => write!(formatter, "LegacyCipher({oid})"),
82        }
83    }
84}
85
86/// Undo one `encrypt` transform.
87///
88/// `payload` is the Base64-decoded document: a DER `ContentInfo`. The result
89/// is the enveloped content, bounded by `max_decoded_document_bytes` both
90/// before the plaintext buffer is allocated (using the ciphertext length,
91/// which the plaintext can never exceed) and again once it exists.
92pub(crate) fn decrypt_cms(
93    payload: &[u8],
94    key: &RecipientKey,
95    allow_legacy_ciphers: bool,
96    limits: &Limits,
97) -> Result<CmsOutcome, Error> {
98    let enveloped = match cms::parse_content_info(payload)? {
99        Err(outcome) => return Ok(outcome),
100        Ok(enveloped) => enveloped,
101    };
102
103    let Some(recipient) = enveloped
104        .recip_infos
105        .0
106        .iter()
107        .filter_map(|info| match info {
108            RecipientInfo::Ktri(ktri) => Some(ktri),
109            _ => None,
110        })
111        .find(|ktri| key.matches(&ktri.rid))
112    else {
113        return Ok(CmsOutcome::NoMatchingRecipient);
114    };
115
116    let cipher = match ciphers::content_cipher(&enveloped.encrypted_content.content_enc_alg.oid) {
117        Some(cipher) => cipher,
118        None => {
119            return Ok(CmsOutcome::UnsupportedAlgorithm(
120                enveloped.encrypted_content.content_enc_alg.oid.to_string(),
121            ));
122        }
123    };
124    if cipher.legacy && !allow_legacy_ciphers {
125        return Ok(CmsOutcome::LegacyCipher(
126            enveloped.encrypted_content.content_enc_alg.oid.to_string(),
127        ));
128    }
129
130    // The cipher is resolved first because the key length it announces is
131    // what the unwrap unpads against. `unwrap_key` cannot fail and always
132    // returns `cipher.key_bytes` bytes: an unusable RSA block is replaced by
133    // a synthetic key, and the run continues into the content cipher either
134    // way. There is deliberately no check here that would tell the two
135    // apart -- that check is the padding oracle.
136    let content_encryption_key = match cms::unwrap_key(recipient, &key.private, cipher.key_bytes)? {
137        cms::Unwrapped::Key(cek) => cek,
138        cms::Unwrapped::UnsupportedAlgorithm(oid) => {
139            return Ok(CmsOutcome::UnsupportedAlgorithm(oid));
140        }
141    };
142
143    let initialisation_vector = enveloped
144        .encrypted_content
145        .content_enc_alg
146        .parameters
147        .as_ref()
148        .and_then(|parameters| parameters.decode_as::<OctetString>().ok())
149        .ok_or_else(|| {
150            Error::new(
151                ErrorCode::InvalidCms,
152                "the content encryption algorithm carries no initialisation vector",
153            )
154        })?;
155    if initialisation_vector.as_bytes().len() != cipher.block_bytes {
156        return Err(Error::new(
157            ErrorCode::InvalidCms,
158            "the content encryption initialisation vector has the wrong length",
159        ));
160    }
161
162    let ciphertext = enveloped
163        .encrypted_content
164        .encrypted_content
165        .as_ref()
166        .ok_or_else(|| {
167            Error::new(
168                ErrorCode::InvalidCms,
169                "the CMS EnvelopedData carries no encrypted content; detached content is not supported",
170            )
171        })?;
172    // The plaintext is never longer than the ciphertext, so this bounds the
173    // buffer before it is allocated.
174    if ciphertext.as_bytes().len() as u64 > limits.max_decoded_document_bytes {
175        return Err(Error::new(
176            ErrorCode::DecodedTooLarge,
177            "encrypted document exceeds the decoded-size limit",
178        ));
179    }
180
181    let plaintext = ciphers::decrypt_content(
182        cipher.kind,
183        &content_encryption_key,
184        initialisation_vector.as_bytes(),
185        ciphertext.as_bytes(),
186    )?;
187    if plaintext.len() as u64 > limits.max_decoded_document_bytes {
188        return Err(Error::new(
189            ErrorCode::DecodedTooLarge,
190            "decrypted document exceeds the decoded-size limit",
191        ));
192    }
193    Ok(CmsOutcome::Plaintext(plaintext))
194}
195
196fn invalid_cms() -> Error {
197    Error::new(
198        ErrorCode::InvalidCms,
199        "the encrypted payload is not well-formed CMS",
200    )
201}
202
203/// The single message every decryption failure gets.
204///
205/// It deliberately does not say whether the key unwrap, the CEK length, or the
206/// padding was what failed: telling those apart is exactly the distinction a
207/// padding oracle needs. Under implicit rejection the RSA half no longer
208/// raises it at all, so a failed key transport reaches the caller as the
209/// content cipher's own failure, indistinguishable from a tampered body.
210fn decrypt_failed() -> Error {
211    Error::new(ErrorCode::DecryptFailed, "decryption failed")
212}
213
214#[cfg(test)]
215mod tests {
216    //! Unit tests for the `decrypt_cms` orchestration: which `ContentInfo`
217    //! shapes are recognised, named as unsupported, or rejected outright.
218    //!
219    //! The round trips live in `tests/decryption.rs`, which can build whole
220    //! synthetic messages.
221
222    use ::cms::content_info::ContentInfo;
223    use const_oid::ObjectIdentifier;
224    use der::Encode;
225
226    use super::cms::{ID_AUTH_ENVELOPED_DATA, ID_ENVELOPED_DATA};
227    use super::*;
228
229    #[test]
230    fn a_content_info_that_is_not_enveloped_data_is_named_or_refused() {
231        fn content_info(content_type: ObjectIdentifier) -> Vec<u8> {
232            ContentInfo {
233                content_type,
234                content: der::asn1::Any::null(),
235            }
236            .to_der()
237            .expect("ContentInfo encodes")
238        }
239        let key = RecipientKey::unusable_for_tests();
240        let limits = Limits::default();
241
242        // RFC 5083 AuthEnvelopedData is recognised, and skipped by name.
243        let outcome = decrypt_cms(&content_info(ID_AUTH_ENVELOPED_DATA), &key, false, &limits)
244            .expect("a recognised container is not an error");
245        match outcome {
246            CmsOutcome::UnsupportedAlgorithm(oid) => {
247                assert_eq!(oid, ID_AUTH_ENVELOPED_DATA.to_string());
248            }
249            _ => panic!("AuthEnvelopedData must be reported as unsupported"),
250        }
251
252        // id-data, or anything else, is not an encrypted document at all.
253        let error = decrypt_cms(
254            &content_info(ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.1")),
255            &key,
256            false,
257            &limits,
258        )
259        .expect_err("a non-enveloped container is malformed");
260        assert_eq!(error.code(), ErrorCode::InvalidCms);
261
262        // And neither is a payload that is not DER.
263        assert_eq!(
264            decrypt_cms(b"not DER", &key, false, &limits)
265                .expect_err("garbage is malformed")
266                .code(),
267            ErrorCode::InvalidCms
268        );
269        // Nor a ContentInfo whose content is not an EnvelopedData.
270        assert_eq!(
271            decrypt_cms(&content_info(ID_ENVELOPED_DATA), &key, false, &limits)
272                .expect_err("a null EnvelopedData is malformed")
273                .code(),
274            ErrorCode::InvalidCms
275        );
276    }
277}