From b41ac105abeb9e8bf0d2b278074c00d4060ea42f Mon Sep 17 00:00:00 2001 From: 5225225 <5225225@mailbox.org> Date: Sat, 29 May 2021 11:38:46 +0100 Subject: [PATCH] Use checked multiplication when calculating buffer size --- src/decoder/mod.rs | 8 +++++++- tests/decode_images.rs | 20 ++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/decoder/mod.rs b/src/decoder/mod.rs index f7b3665..136523b 100644 --- a/src/decoder/mod.rs +++ b/src/decoder/mod.rs @@ -1550,7 +1550,13 @@ impl Decoder { } fn result_buffer(&self, width: usize, height: usize) -> TiffResult { - let buffer_size = width * height * self.bits_per_sample.len(); + let buffer_size = match width + .checked_mul(height) + .and_then(|x| x.checked_mul(self.bits_per_sample.len())) + { + Some(s) => s, + None => return Err(TiffError::LimitsExceeded), + }; let max_sample_bits = self.bits_per_sample.iter().cloned().max().unwrap_or(8); match self.sample_format.first().unwrap_or(&SampleFormat::Uint) { diff --git a/tests/decode_images.rs b/tests/decode_images.rs index 0f2ba80..192423f 100644 --- a/tests/decode_images.rs +++ b/tests/decode_images.rs @@ -345,3 +345,23 @@ fn test_bad_strip_count() { unexpected => panic!("Unexpected error {}", unexpected), } } + +#[test] +fn test_too_big_buffer_size() { + let image = [ + 73, 73, 42, 0, 8, 0, 0, 0, 8, 0, 0, 1, 4, 0, 1, 0, 0, 0, 99, 255, 255, 254, 1, 1, 4, 0, 1, + 0, 0, 0, 158, 0, 0, 251, 3, 1, 3, 255, 254, 255, 255, 0, 1, 0, 0, 0, 6, 1, 3, 0, 1, 0, 0, + 0, 0, 0, 0, 0, 17, 1, 4, 0, 9, 0, 0, 0, 0, 0, 0, 0, 2, 1, 3, 0, 2, 0, 0, 0, 63, 0, 0, 0, + 22, 1, 4, 0, 1, 0, 0, 0, 44, 0, 0, 0, 23, 1, 4, 0, 0, 0, 0, 0, 0, 0, 2, 1, 3, 1, 0, 178, + 178, + ]; + + let mut decoder = tiff::decoder::Decoder::new(std::io::Cursor::new(&image)).unwrap(); + + let err = decoder.read_image().unwrap_err(); + + match err { + tiff::TiffError::LimitsExceeded => {} + unexpected => panic!("Unexpected error {}", unexpected), + } +}