Cleanup buffer length calculation.

This commit is contained in:
KAMADA Ken'ichi 2021-01-24 19:38:31 +09:00
parent 37001e4cba
commit 6c08800089
3 changed files with 18 additions and 6 deletions

View File

@ -85,12 +85,10 @@ fn get_exif_attr_sub<R>(reader: &mut R)
_ => {}, _ => {},
} }
// Read marker segments. // Read marker segments.
let seglen = read16(reader)?; let len = read16(reader)?.checked_sub(2)
if seglen < 2 { .ok_or(Error::InvalidFormat("Invalid segment length"))?;
return Err(Error::InvalidFormat("Invalid segment length"));
}
let mut seg = Vec::new(); let mut seg = Vec::new();
reader.by_ref().take(seglen as u64 - 2).read_to_end(&mut seg)?; reader.by_ref().take(len.into()).read_to_end(&mut seg)?;
if code == marker::APP1 && seg.starts_with(&EXIF_ID) { if code == marker::APP1 && seg.starts_with(&EXIF_ID) {
seg.drain(..EXIF_ID.len()); seg.drain(..EXIF_ID.len());
return Ok(seg); return Ok(seg);

View File

@ -77,7 +77,8 @@ fn get_exif_attr_sub<R>(reader: &mut R)
return Ok(data); return Ok(data);
} }
// Chunk data and CRC. // Chunk data and CRC.
reader.discard_exact(len + 4)?; reader.discard_exact(len.checked_add(4).ok_or(
Error::InvalidFormat("Invalid chunk length"))?)?;
} }
} }

View File

@ -131,6 +131,19 @@ mod tests {
assert_err_pat!(get_exif_attr(&mut &data[..]), Error::NotFound(_)); assert_err_pat!(get_exif_attr(&mut &data[..]), Error::NotFound(_));
} }
#[test]
fn overflowing_parent() {
let mut data = b"RIFF\x10\0\0\0WEBPEXIF\x04\0\0\0Exif".to_vec();
assert_eq!(get_exif_attr(&mut &data[..]).unwrap(), b"Exif");
for x in 0x05..=0x0f {
data[4] = x;
assert_err_pat!(get_exif_attr(&mut &data[..]),
Error::InvalidFormat(_));
}
data[4] = 0x04;
assert_err_pat!(get_exif_attr(&mut &data[..]), Error::NotFound(_));
}
#[test] #[test]
fn odd_at_last_without_padding() { fn odd_at_last_without_padding() {
let data = b"RIFF\x17\0\0\0WEBPwhat\0\0\0\0EXIF\x03\0\0\0abc"; let data = b"RIFF\x17\0\0\0WEBPwhat\0\0\0\0EXIF\x03\0\0\0abc";