From d66b377a8e0001651581ad90917944bb555d571b Mon Sep 17 00:00:00 2001 From: Mostafa Abdelraouf Date: Fri, 17 Mar 2023 12:31:43 -0500 Subject: [PATCH] Check Slice bounds in read_message to avoid panics (#371) When recv is called in the mirroring client, we noticed an occasional panic when reading the message. thread 'tokio-runtime-worker' panicked at 'slice index starts at 5 but ends at 0', src/messages.rs:522:18 We are still debugging the reason why this happens but adding a check for slice bounds seems like a good idea. Instead of panicking, this will return an Err to the caller which will close the connection. --- src/messages.rs | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/src/messages.rs b/src/messages.rs index 3fc84b5..c9ace4e 100644 --- a/src/messages.rs +++ b/src/messages.rs @@ -517,14 +517,18 @@ where bytes.resize(bytes.len() + len as usize - mem::size_of::(), b'0'); - match stream - .read_exact( - &mut bytes[mem::size_of::() + mem::size_of::() - ..mem::size_of::() + mem::size_of::() + len as usize - - mem::size_of::()], - ) - .await - { + let slice_start = mem::size_of::() + mem::size_of::(); + let slice_end = slice_start + len as usize - mem::size_of::(); + + // Avoids a panic + if slice_end < slice_start { + return Err(Error::SocketError(format!( + "Error reading message from socket - Code: {:?} - Length {:?}, Error: {:?}", + code, len, "Unexpected length value for message" + ))); + } + + match stream.read_exact(&mut bytes[slice_start..slice_end]).await { Ok(_) => (), Err(err) => { return Err(Error::SocketError(format!(