Skip to content

Commit

Permalink
Validate offsets do not point beyond end of message
Browse files Browse the repository at this point in the history
  • Loading branch information
int08h committed Mar 20, 2018
1 parent 1b21bbc commit a029e50
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,12 @@ pub enum Error {
/// Request was less than 1024 bytes
RequestTooShort,

/// Offset within message was not 32-bit aligned
/// Offset was not 32-bit aligned
InvalidOffsetAlignment(u32),

/// Offset is outside of valid message range
InvalidOffsetValue(u32),

/// Invalid number of tags specified
InvalidNumTags(u32),

Expand Down
33 changes: 33 additions & 0 deletions src/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,17 @@ impl RtMessage {

let mut offsets = Vec::with_capacity((num_tags - 1) as usize);
let mut tags = Vec::with_capacity(num_tags as usize);
let end_of_data = bytes.len() as u32;

for _ in 0..num_tags - 1 {
let offset = msg.read_u32::<LittleEndian>()?;

if offset % 4 != 0 {
return Err(Error::InvalidOffsetAlignment(offset));
} else if offset > end_of_data {
return Err(Error::InvalidOffsetValue(offset));
}

offsets.push(offset as usize);
}

Expand Down Expand Up @@ -343,4 +348,32 @@ mod test {
// Everything was read
assert_eq!(encoded.position() as usize, msg.encoded_size());
}

#[test]
#[should_panic(expected="InvalidOffsetValue(128)")]
fn from_bytes_offset_past_end_of_message() {
let mut msg = RtMessage::new(2);
msg.add_field(Tag::NONC, "1111".as_bytes()).unwrap();
msg.add_field(Tag::PAD, "aaaaaaaaa".as_bytes()).unwrap();

let mut bytes = msg.encode().unwrap();
// set the PAD value offset to beyond end of the message
bytes[4] = 128;

RtMessage::from_bytes(&bytes).unwrap();
}

#[test]
#[should_panic(expected="InvalidNumTags(0)")]
fn from_bytes_zero_tags() {
let mut msg = RtMessage::new(1);
msg.add_field(Tag::NONC, "1111".as_bytes()).unwrap();

let mut bytes = msg.encode().unwrap();
// set num_tags to zero
bytes[0] = 0;

RtMessage::from_bytes(&bytes).unwrap();
}

}

0 comments on commit a029e50

Please sign in to comment.