From 3719385a3fac5cfb20b487619a5f08abbf967cf8 Mon Sep 17 00:00:00 2001
From: Even Rouault <even.rouault@spatialys.com>
Date: Sun, 11 Mar 2018 11:14:01 +0100
Subject: [PATCH] ChopUpSingleUncompressedStrip: avoid memory exhaustion (CVE-2017-11613)

In ChopUpSingleUncompressedStrip(), if the computed number of strips is big
enough and we are in read only mode, validate that the file size is consistent
with that number of strips to avoid useless attempts at allocating a lot of
memory for the td_stripbytecount and td_stripoffset arrays.

Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2724
---
 libtiff/tif_dirread.c | 11 +++++++++++
 1 file changed, 11 insertions(+)

diff --git a/libtiff/tif_dirread.c b/libtiff/tif_dirread.c
index 3fc0c8e..1a3259c 100644
--- a/libtiff/tif_dirread.c
+++ b/libtiff/tif_dirread.c
@@ -5698,6 +5698,17 @@ ChopUpSingleUncompressedStrip(TIFF* tif)
         if( nstrips == 0 )
             return;
 
+        /* If we are going to allocate a lot of memory, make sure that the */
+        /* file is as big as needed */
+        if( tif->tif_mode == O_RDONLY &&
+            nstrips > 1000000 &&
+            (tif->tif_dir.td_stripoffset[0] >= TIFFGetFileSize(tif) ||
+             tif->tif_dir.td_stripbytecount[0] >
+                    TIFFGetFileSize(tif) - tif->tif_dir.td_stripoffset[0]) )
+        {
+            return;
+        }
+
 	newcounts = (uint64*) _TIFFCheckMalloc(tif, nstrips, sizeof (uint64),
 				"for chopped \"StripByteCounts\" array");
 	newoffsets = (uint64*) _TIFFCheckMalloc(tif, nstrips, sizeof (uint64),
--
libgit2 0.27.0

