From c9a852261bcb3fd4cb633bc31ed59ce1aa1524a0 Mon Sep 17 00:00:00 2001 From: Robin Krahl Date: Tue, 2 Jun 2026 13:42:03 +0200 Subject: [PATCH] Fix panics on wrong nonce or tag length in AEAD decrypt implementation --- src/mechanisms/aead.rs | 7 +++++++ tests/aead.rs | 44 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/src/mechanisms/aead.rs b/src/mechanisms/aead.rs index edd43b69786..bca171f33ff 100644 --- a/src/mechanisms/aead.rs +++ b/src/mechanisms/aead.rs @@ -24,6 +24,7 @@ impl< const KEY_LEN: usize = T::KeySize::USIZE; const NONCE_LEN: usize = T::NonceSize::USIZE; const TOTAL_LEN: usize = KeyNonceSize::USIZE; + const TAG_LEN: usize = T::TagSize::USIZE; const KIND: key::Kind = key::Kind::Symmetric(Self::KEY_LEN); const KIND_NONCE: key::Kind = key::Kind::Symmetric32Nonce(Self::NONCE_LEN); @@ -76,7 +77,13 @@ impl< let mut aead = T::new(&GenericArray::clone_from_slice(symmetric_key)); let mut plaintext = request.message.clone(); + if request.nonce.len() != Self::NONCE_LEN { + return Err(Error::MechanismParamInvalid); + } let nonce = GenericArray::from_slice(&request.nonce); + if request.tag.len() != Self::TAG_LEN { + return Err(Error::MechanismParamInvalid); + } let tag = GenericArray::from_slice(&request.tag); let outcome = diff --git a/tests/aead.rs b/tests/aead.rs index f775d0cd6fa..620f5240ea9 100644 --- a/tests/aead.rs +++ b/tests/aead.rs @@ -23,3 +23,47 @@ fn test_invalid_key_size() { } }); } + +#[test] +fn test_encrypt_bad_nonce_length() { + client::get(|client| { + for mechanism in MECHANISMS { + let key = syscall!(client.generate_secret_key(32, Location::Volatile)).key; + let result = + try_syscall!(client.encrypt(*mechanism, key, &[], &[], Some(b"nonce".into()))); + assert_eq!(result, Err(Error::MechanismParamInvalid)); + } + }) +} + +#[test] +fn test_decrypt_bad_lengths() { + client::get(|client| { + for mechanism in MECHANISMS { + let key = syscall!(client.generate_secret_key(32, Location::Volatile)).key; + let encrypted = syscall!(client.encrypt(*mechanism, key, &[], &[], None)); + + // bad nonce length + let result = try_syscall!(client.decrypt( + *mechanism, + key, + &encrypted.ciphertext, + &[], + b"nonce", + &encrypted.tag + )); + assert_eq!(result, Err(Error::MechanismParamInvalid)); + + // bad tag length + let result = try_syscall!(client.decrypt( + *mechanism, + key, + &encrypted.ciphertext, + &[], + &encrypted.nonce, + b"tag" + )); + assert_eq!(result, Err(Error::MechanismParamInvalid)); + } + }) +}