diff --git a/lib/src/core/comms/secure_channel.rs b/lib/src/core/comms/secure_channel.rs index 87905ff77..39697c0c2 100644 --- a/lib/src/core/comms/secure_channel.rs +++ b/lib/src/core/comms/secure_channel.rs @@ -1212,10 +1212,13 @@ impl SecureChannel { // There is an expectation that the block is padded so, this is a quick test let ciphertext_size = encrypted_range.end - encrypted_range.start; - // if ciphertext_size % 16 != 0 { - // error!("The cipher text size is not padded properly, size = {}", ciphertext_size); - // return Err(StatusCode::BadUnexpectedError); - // } + if ciphertext_size % 16 != 0 { + error!( + "The cipher text size is not padded properly, size = {}", + ciphertext_size + ); + return Err(StatusCode::BadUnexpectedError); + } // Copy security header dst[..encrypted_range.start].copy_from_slice(&src[..encrypted_range.start]); diff --git a/lib/src/core/tests/chunk.rs b/lib/src/core/tests/chunk.rs index 0aed69bba..4d3bc2726 100644 --- a/lib/src/core/tests/chunk.rs +++ b/lib/src/core/tests/chunk.rs @@ -472,6 +472,33 @@ fn security_policy_symmetric_encrypt_decrypt() { assert_eq!(&src[..80], &src2[..80]); } +#[test] +fn security_policy_symmetric_encrypt_decrypt_ciphertext_invalid_padding_returns_error() { + let (secure_channel1, secure_channel2) = make_secure_channels( + MessageSecurityMode::SignAndEncrypt, + SecurityPolicy::Basic128Rsa15, + ); + + let src = vec![0u8; 100]; + let mut dst = vec![0u8; 200]; + + let encrypted_len = secure_channel1 + .symmetric_sign_and_encrypt(&src, 0..80, 20..100, &mut dst) + .unwrap(); + assert_eq!(encrypted_len, 100); + + let mut src2 = vec![0u8; 200]; + + // length of encrypted range should be dividable by 16 + let invalid_encrypted_range = 21..100; + + let error = secure_channel2 + .symmetric_decrypt_and_verify(&dst, 0..80, invalid_encrypted_range, &mut src2) + .unwrap_err(); + + assert!(error.contains(StatusCode::BadUnexpectedError)) +} + #[test] fn asymmetric_decrypt_and_verify_sample_chunk() { let _ = Test::setup();