From 4e2def2539ec13e53a82e06c4b3daf00454100c4 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Wed, 1 Jan 2020 16:38:37 +1100 Subject: [PATCH] Overflow checks for realloc for tiff decoding https://github.com/python-pillow/Pillow/commit/4e2def2539ec13e53a82e06c4b3daf00454100c4 --- src/libImaging/TiffDecode.c | 18 +++++++++++------- 1 files changed, 11 insertions(+), 7 deletions(-) diff --git a/src/libImaging/TiffDecode.c b/src/libImaging/TiffDecode.c index 9830238..1f505ff 100644 --- a/src/libImaging/TiffDecode.c +++ b/src/libImaging/TiffDecode.c @@ -237,20 +237,26 @@ int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, int TIFFSetField(tiff, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); if (TIFFIsTiled(tiff)) { - uint32 x, y, tile_y; + uint32 x, y, tile_y, row_byte_size; uint32 tileWidth, tileLength; UINT8 *new_data; - state->bytes = TIFFTileSize(tiff); + TIFFGetField(tiff, TIFFTAG_TILEWIDTH, &tileWidth); + TIFFGetField(tiff, TIFFTAG_TILELENGTH, &tileLength); + + // We could use TIFFTileSize, but for YCbCr data it returns subsampled data size + row_byte_size = (tileWidth * state->bits + 7) / 8; - /* overflow check for malloc */ - if (state->bytes > INT_MAX - 1) { + /* overflow check for realloc */ + if (INT_MAX / row_byte_size < tileLength) { state->errcode = IMAGING_CODEC_MEMORY; TIFFClose(tiff); return -1; } - /* realloc to fit whole tile */ + state->bytes = row_byte_size * tileLength; + + /* malloc check above */ new_data = realloc (state->buffer, state->bytes); if (!new_data) { state->errcode = IMAGING_CODEC_MEMORY; @@ -262,8 +268,6 @@ int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, int TRACE(("TIFFTileSize: %d\n", state->bytes)); - TIFFGetField(tiff, TIFFTAG_TILEWIDTH, &tileWidth); - TIFFGetField(tiff, TIFFTAG_TILELENGTH, &tileLength); for (y = state->yoff; y < state->ysize; y += tileLength) { for (x = state->xoff; x < state->xsize; x += tileWidth) { -- 2.27.0