diff --git a/base_layer/common_types/src/encryption.rs b/base_layer/common_types/src/encryption.rs index 68533e8ff0..20ba9feb66 100644 --- a/base_layer/common_types/src/encryption.rs +++ b/base_layer/common_types/src/encryption.rs @@ -24,7 +24,6 @@ use std::mem::size_of; use chacha20poly1305::{ aead::{Aead, Payload}, - Tag, XChaCha20Poly1305, XNonce, }; @@ -56,13 +55,10 @@ pub fn decrypt_bytes_integral_nonce( domain: Vec, ciphertext: &[u8], ) -> Result, String> { - // We need at least a nonce and tag, or there's no point in attempting decryption - if ciphertext.len() < size_of::() + size_of::() { - return Err("Ciphertext is too short".to_string()); - } - // Extract the nonce - let (nonce, ciphertext) = ciphertext.split_at(size_of::()); + let (nonce, ciphertext) = ciphertext + .split_at_checked(size_of::()) + .ok_or("Ciphertext is too short".to_string())?; let nonce_ga = XNonce::from_slice(nonce); let payload = Payload { @@ -109,7 +105,7 @@ pub fn encrypt_bytes_integral_nonce( #[cfg(test)] mod test { - use chacha20poly1305::{Key, KeyInit}; + use chacha20poly1305::{Key, KeyInit, Tag}; use super::*; diff --git a/comms/core/src/peer_validator/helpers.rs b/comms/core/src/peer_validator/helpers.rs index 4b6b47f910..1d8e272f5c 100644 --- a/comms/core/src/peer_validator/helpers.rs +++ b/comms/core/src/peer_validator/helpers.rs @@ -171,8 +171,13 @@ fn validate_onion3_address(addr: &multiaddr::Onion3Addr<'_>) -> Result<(), PeerV const ONION3_PUBKEY_SIZE: usize = 32; const ONION3_CHECKSUM_SIZE: usize = 2; - let (pub_key, checksum_version) = addr.hash().split_at(ONION3_PUBKEY_SIZE); - let (checksum, version) = checksum_version.split_at(ONION3_CHECKSUM_SIZE); + let (pub_key, checksum_version) = addr + .hash() + .split_at_checked(ONION3_PUBKEY_SIZE) + .ok_or(PeerValidatorError::InvalidMultiaddr("Unable to split data".to_string()))?; + let (checksum, version) = checksum_version + .split_at_checked(ONION3_CHECKSUM_SIZE) + .ok_or(PeerValidatorError::InvalidMultiaddr("Unable to split data".to_string()))?; if version != b"\x03" { return Err(PeerValidatorError::InvalidMultiaddr( diff --git a/docs/src/reviewing_guide.md b/docs/src/reviewing_guide.md index 1d05f9b540..f8fdad202b 100644 --- a/docs/src/reviewing_guide.md +++ b/docs/src/reviewing_guide.md @@ -122,4 +122,4 @@ Here is a good example of nice semantic rust code, but the code has the potentia #### Behind-the-scenes panics -Not all methods in the standard and other libraries that return values are guaranteed not to panic, for example, `pub const fn split_at(&self, mid: usize) -> (&[T], &[T])` will panic if `mid` > `self.len()`. Create custom wrappers that will return an error before the underlying function will panic, for example, `pub fn split_at_checked(vec: &[T], n: usize) -> Result<(&[T], &[T]), Error>`. +Not all methods in the standard and other libraries that return values are guaranteed not to panic. Create custom wrappers that will return an error before the underlying function will panic.