From 09b7fb0bcc0ee80d9b55709c177f2e53d0fa1291 Mon Sep 17 00:00:00 2001 From: David Venhoek Date: Fri, 6 Dec 2024 11:36:24 +0100 Subject: [PATCH] Fix incorrect indexing in decode of ReferenceIdRequest --- ntp-proto/src/packet/v5/extension_fields.rs | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/ntp-proto/src/packet/v5/extension_fields.rs b/ntp-proto/src/packet/v5/extension_fields.rs index e92f8719c..55fa43d5f 100644 --- a/ntp-proto/src/packet/v5/extension_fields.rs +++ b/ntp-proto/src/packet/v5/extension_fields.rs @@ -124,7 +124,11 @@ impl ReferenceIdRequest { pub fn decode(msg: &[u8]) -> Result> { let payload_len = u16::try_from(msg.len()).expect("NTP fields can not be longer than u16::MAX"); - let offset_bytes: [u8; 2] = msg[0..2].try_into().unwrap(); + let offset_bytes: [u8; 2] = msg + .get(0..2) + .ok_or(ParsingError::IncorrectLength)? + .try_into() + .unwrap(); Ok(Self { payload_len, @@ -222,4 +226,19 @@ mod tests { assert_eq!(bits, bits2); } } + + #[test] + fn test_reference_id_request_too_short() { + assert!(matches!( + ReferenceIdRequest::decode(&[]), + Err(ParsingError::IncorrectLength) + )); + } + + #[test] + fn test_reference_id_request_decode() { + let res = ReferenceIdRequest::decode(&[0, 2, 0, 0, 0]).unwrap(); + assert_eq!(res.payload_len, 5); + assert_eq!(res.offset, 2); + } }