@@ -618,13 +618,31 @@ tmsize_t _TIFFReadEncodedStripAndAllocBuffer(TIFF *tif, uint32_t strip,
618618 if (!TIFFFillStrip (tif , strip ))
619619 return ((tmsize_t )(-1 ));
620620
621- * buf = _TIFFmallocExt (tif , bufsizetoalloc );
621+ /* Sanity checks to avoid excessive memory allocation */
622+ /* Max compression ratio experimentally determined. Might be fragile...
623+ * Only apply this heuristics to situations where the memory allocation
624+ * would be big, to avoid breaking nominal use cases.
625+ */
626+ const uint64_t maxCompressionRatio = TIFFGetMaxCompressionRatio (tif );
627+ if (maxCompressionRatio > 0 && bufsizetoalloc > 100 * 1000 * 1000 &&
628+ (uint64_t )tif -> tif_rawdatasize <
629+ (uint64_t )this_stripsize / maxCompressionRatio )
630+ {
631+ TIFFErrorExtR (tif , TIFFFileName (tif ),
632+ "Likely invalid strip byte count for strip %u. "
633+ "Uncompressed strip size is %" PRIu64 ", "
634+ "compressed one is %" PRIu64 ,
635+ strip , (uint64_t )this_stripsize ,
636+ (uint64_t )tif -> tif_rawdatasize );
637+ return ((tmsize_t )(-1 ));
638+ }
639+
640+ * buf = _TIFFcallocExt (tif , 1 , bufsizetoalloc );
622641 if (* buf == NULL )
623642 {
624643 TIFFErrorExtR (tif , TIFFFileName (tif ), "No space for strip buffer" );
625644 return ((tmsize_t )(-1 ));
626645 }
627- _TIFFmemset (* buf , 0 , bufsizetoalloc );
628646
629647 if ((* tif -> tif_decodestrip )(tif , (uint8_t * )* buf , this_stripsize , plane ) <=
630648 0 )
@@ -1088,17 +1106,10 @@ tmsize_t _TIFFReadEncodedTileAndAllocBuffer(TIFF *tif, uint32_t tile,
10881106 * Only apply this heuristics to situations where the memory allocation
10891107 * would be big, to avoid breaking nominal use cases.
10901108 */
1091- const int maxCompressionRatio =
1092- td -> td_compression == COMPRESSION_ZSTD ? 33000
1093- : td -> td_compression == COMPRESSION_JXL
1094- ?
1095- /* Evaluated on a 8000x8000 tile */
1096- 25000 * (td -> td_planarconfig == PLANARCONFIG_CONTIG
1097- ? td -> td_samplesperpixel
1098- : 1 )
1099- : td -> td_compression == COMPRESSION_LZMA ? 7000 : 1000 ;
1100- if (bufsizetoalloc > 100 * 1000 * 1000 &&
1101- tif -> tif_rawdatasize < tilesize / maxCompressionRatio )
1109+ const uint64_t maxCompressionRatio = TIFFGetMaxCompressionRatio (tif );
1110+ if (maxCompressionRatio > 0 && bufsizetoalloc > 100 * 1000 * 1000 &&
1111+ (uint64_t )tif -> tif_rawdatasize <
1112+ (uint64_t )tilesize / maxCompressionRatio )
11021113 {
11031114 TIFFErrorExtR (tif , TIFFFileName (tif ),
11041115 "Likely invalid tile byte count for tile %u. "
0 commit comments