Skip to content

Commit

Permalink
Merge pull request #1807 from fisherdarling/fisher/prevent-overflow-b…
Browse files Browse the repository at this point in the history
…mp-writer

use checked_adds in the bmp writer when calculating `file_size`
  • Loading branch information
HeroicKatora committed Oct 17, 2022
2 parents 72485f1 + 52b1927 commit 14eae6d
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions src/codecs/bmp/encoder.rs
@@ -1,9 +1,11 @@
use byteorder::{LittleEndian, WriteBytesExt};
use std::io::{self, Write};

use crate::color;
use crate::error::{ImageError, ImageResult, ParameterError, ParameterErrorKind};
use crate::error::{
EncodingError, ImageError, ImageFormatHint, ImageResult, ParameterError, ParameterErrorKind,
};
use crate::image::ImageEncoder;
use crate::{color, ImageFormat};

const BITMAPFILEHEADER_SIZE: u32 = 14;
const BITMAPINFOHEADER_SIZE: u32 = 40;
Expand Down Expand Up @@ -68,7 +70,16 @@ impl<'a, W: Write + 'a> BmpEncoder<'a, W> {
))
})?;
let palette_size = palette_color_count * 4; // all palette colors are BGRA
let file_size = bmp_header_size + dib_header_size + palette_size + image_size;
let file_size = bmp_header_size
.checked_add(dib_header_size)
.and_then(|v| v.checked_add(palette_size))
.and_then(|v| v.checked_add(image_size))
.ok_or_else(|| {
ImageError::Encoding(EncodingError::new(
ImageFormatHint::Exact(ImageFormat::Bmp),
"calculated BMP header size larger than 2^32",
))
})?;

// write BMP header
self.writer.write_u8(b'B')?;
Expand Down

0 comments on commit 14eae6d

Please sign in to comment.