From 49db4a4192482eec9c27669f75db144cf5434804 Mon Sep 17 00:00:00 2001
From: Shawn Walker-Salas <shawn.walker@oracle.com>
Date: Tue, 30 May 2017 19:07:52 -0700
Subject: [PATCH] Add additional input validation in an attempt to resolve
 issue #232

---
 IlmImf/ImfDwaCompressor.cpp           |   7 +-
 IlmImf/ImfHuf.cpp                     |  10 +-
 IlmImf/ImfPizCompressor.cpp           |   6 +
 3 files changed, 18 insertions(+), 5 deletions(-)

diff --git a/IlmImf/ImfDwaCompressor.cpp b/IlmImf/ImfDwaCompressor.cpp
index 1c1bd454e..2ef88786f 100644
--- a/IlmImf/ImfDwaCompressor.cpp
+++ b/IlmImf/ImfDwaCompressor.cpp
@@ -2377,7 +2377,12 @@ DwaCompressor::uncompress
 
     const char *dataPtr            = inPtr + NUM_SIZES_SINGLE * sizeof(Int64);
 
-    if (inSize < headerSize + compressedSize) 
+    /* Both the sum and individual sizes are checked in case of overflow. */
+    if (inSize < (headerSize + compressedSize) ||
+        inSize < unknownCompressedSize ||
+        inSize < acCompressedSize ||
+        inSize < dcCompressedSize ||
+        inSize < rleCompressedSize)
     {
         throw Iex::InputExc("Error uncompressing DWA data"
                             "(truncated file).");
diff --git a/IlmImf/ImfHuf.cpp b/IlmImf/ImfHuf.cpp
index a375d05d8..97909a5b1 100644
--- a/IlmImf/ImfHuf.cpp
+++ b/IlmImf/ImfHuf.cpp
@@ -822,7 +822,7 @@ hufEncode				// return: output size (in bits)
 }
 
 
-#define getCode(po, rlc, c, lc, in, out, oe)	\
+#define getCode(po, rlc, c, lc, in, out, ob, oe)\
 {						\
     if (po == rlc)				\
     {						\
@@ -835,6 +835,8 @@ hufEncode				// return: output size (in bits)
 						\
 	if (out + cs > oe)			\
 	    tooMuchData();			\
+	else if (out - 1 < ob)			\
+	    notEnoughData();			\
 						\
 	unsigned short s = out[-1];		\
 						\
@@ -895,7 +897,7 @@ hufDecode
 		//
 
 		lc -= pl.len;
-		getCode (pl.lit, rlc, c, lc, in, out, oe);
+		getCode (pl.lit, rlc, c, lc, in, out, outb, oe);
 	    }
 	    else
 	    {
@@ -925,7 +927,7 @@ hufDecode
 			    //
 
 			    lc -= l;
-			    getCode (pl.p[j], rlc, c, lc, in, out, oe);
+			    getCode (pl.p[j], rlc, c, lc, in, out, outb, oe);
 			    break;
 			}
 		    }
@@ -952,7 +954,7 @@ hufDecode
 	if (pl.len)
 	{
 	    lc -= pl.len;
-	    getCode (pl.lit, rlc, c, lc, in, out, oe);
+	    getCode (pl.lit, rlc, c, lc, in, out, outb, oe);
 	}
 	else
 	{
diff --git a/IlmImf/ImfPizCompressor.cpp b/IlmImf/ImfPizCompressor.cpp
index 46c6fbace..8b3ee38c3 100644
--- a/IlmImf/ImfPizCompressor.cpp
+++ b/IlmImf/ImfPizCompressor.cpp
@@ -573,6 +573,12 @@ PizCompressor::uncompress (const char *inPtr,
     int length;
     Xdr::read <CharPtrIO> (inPtr, length);
 
+    if (length > inSize)
+    {
+	throw InputExc ("Error in header for PIZ-compressed data "
+			"(invalid array length).");
+    }
+
     hufUncompress (inPtr, length, _tmpBuffer, tmpBufferEnd - _tmpBuffer);
 
     //
