mod ciphers;
mod cms;
mod keys;
mod keytrans;
use ::cms::enveloped_data::RecipientInfo;
use der::asn1::OctetString;
pub use keys::RecipientKey;
use crate::{Error, ErrorCode, Limits};
#[derive(Clone, Copy, Debug, Default)]
pub struct DecryptOptions<'a> {
pub key: Option<&'a RecipientKey>,
pub allow_legacy_ciphers: bool,
}
pub(crate) enum CmsOutcome {
Plaintext(Vec<u8>),
NoMatchingRecipient,
UnsupportedAlgorithm(String),
LegacyCipher(String),
}
impl std::fmt::Debug for CmsOutcome {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Plaintext(bytes) => write!(formatter, "Plaintext({} bytes)", bytes.len()),
Self::NoMatchingRecipient => formatter.write_str("NoMatchingRecipient"),
Self::UnsupportedAlgorithm(oid) => write!(formatter, "UnsupportedAlgorithm({oid})"),
Self::LegacyCipher(oid) => write!(formatter, "LegacyCipher({oid})"),
}
}
}
pub(crate) fn decrypt_cms(
payload: &[u8],
key: &RecipientKey,
allow_legacy_ciphers: bool,
limits: &Limits,
) -> Result<CmsOutcome, Error> {
let enveloped = match cms::parse_content_info(payload)? {
Err(outcome) => return Ok(outcome),
Ok(enveloped) => enveloped,
};
let Some(recipient) = enveloped
.recip_infos
.0
.iter()
.filter_map(|info| match info {
RecipientInfo::Ktri(ktri) => Some(ktri),
_ => None,
})
.find(|ktri| key.matches(&ktri.rid))
else {
return Ok(CmsOutcome::NoMatchingRecipient);
};
let cipher = match ciphers::content_cipher(&enveloped.encrypted_content.content_enc_alg.oid) {
Some(cipher) => cipher,
None => {
return Ok(CmsOutcome::UnsupportedAlgorithm(
enveloped.encrypted_content.content_enc_alg.oid.to_string(),
));
}
};
if cipher.legacy && !allow_legacy_ciphers {
return Ok(CmsOutcome::LegacyCipher(
enveloped.encrypted_content.content_enc_alg.oid.to_string(),
));
}
let content_encryption_key = match cms::unwrap_key(recipient, &key.private, cipher.key_bytes)? {
cms::Unwrapped::Key(cek) => cek,
cms::Unwrapped::UnsupportedAlgorithm(oid) => {
return Ok(CmsOutcome::UnsupportedAlgorithm(oid));
}
};
let initialisation_vector = enveloped
.encrypted_content
.content_enc_alg
.parameters
.as_ref()
.and_then(|parameters| parameters.decode_as::<OctetString>().ok())
.ok_or_else(|| {
Error::new(
ErrorCode::InvalidCms,
"the content encryption algorithm carries no initialisation vector",
)
})?;
if initialisation_vector.as_bytes().len() != cipher.block_bytes {
return Err(Error::new(
ErrorCode::InvalidCms,
"the content encryption initialisation vector has the wrong length",
));
}
let ciphertext = enveloped
.encrypted_content
.encrypted_content
.as_ref()
.ok_or_else(|| {
Error::new(
ErrorCode::InvalidCms,
"the CMS EnvelopedData carries no encrypted content; detached content is not supported",
)
})?;
if ciphertext.as_bytes().len() as u64 > limits.max_decoded_document_bytes {
return Err(Error::new(
ErrorCode::DecodedTooLarge,
"encrypted document exceeds the decoded-size limit",
));
}
let plaintext = ciphers::decrypt_content(
cipher.kind,
&content_encryption_key,
initialisation_vector.as_bytes(),
ciphertext.as_bytes(),
)?;
if plaintext.len() as u64 > limits.max_decoded_document_bytes {
return Err(Error::new(
ErrorCode::DecodedTooLarge,
"decrypted document exceeds the decoded-size limit",
));
}
Ok(CmsOutcome::Plaintext(plaintext))
}
fn invalid_cms() -> Error {
Error::new(
ErrorCode::InvalidCms,
"the encrypted payload is not well-formed CMS",
)
}
fn decrypt_failed() -> Error {
Error::new(ErrorCode::DecryptFailed, "decryption failed")
}
#[cfg(test)]
mod tests {
use ::cms::content_info::ContentInfo;
use const_oid::ObjectIdentifier;
use der::Encode;
use super::cms::{ID_AUTH_ENVELOPED_DATA, ID_ENVELOPED_DATA};
use super::*;
#[test]
fn a_content_info_that_is_not_enveloped_data_is_named_or_refused() {
fn content_info(content_type: ObjectIdentifier) -> Vec<u8> {
ContentInfo {
content_type,
content: der::asn1::Any::null(),
}
.to_der()
.expect("ContentInfo encodes")
}
let key = RecipientKey::unusable_for_tests();
let limits = Limits::default();
let outcome = decrypt_cms(&content_info(ID_AUTH_ENVELOPED_DATA), &key, false, &limits)
.expect("a recognised container is not an error");
match outcome {
CmsOutcome::UnsupportedAlgorithm(oid) => {
assert_eq!(oid, ID_AUTH_ENVELOPED_DATA.to_string());
}
_ => panic!("AuthEnvelopedData must be reported as unsupported"),
}
let error = decrypt_cms(
&content_info(ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.1")),
&key,
false,
&limits,
)
.expect_err("a non-enveloped container is malformed");
assert_eq!(error.code(), ErrorCode::InvalidCms);
assert_eq!(
decrypt_cms(b"not DER", &key, false, &limits)
.expect_err("garbage is malformed")
.code(),
ErrorCode::InvalidCms
);
assert_eq!(
decrypt_cms(&content_info(ID_ENVELOPED_DATA), &key, false, &limits)
.expect_err("a null EnvelopedData is malformed")
.code(),
ErrorCode::InvalidCms
);
}
}