From 5530149af44ac81961e15ff54538311fcd586231 Mon Sep 17 00:00:00 2001
From: Dirk Lemstra <dirk@git.imagemagick.org>
Date: Sun, 7 May 2017 09:53:03 +0200
Subject: [PATCH] CVE-2017-11141 memory exhaustion in ReadMATImage

When identify MAT file, imagemagick will allocate memory to store data in function ReadMATImage in coders\mat.c, line 1094

modifying MAT's MATLAB_HDR can cause ImageMagick to allocate a anysize amount of memory, this may cause a memory exhaustion

This is CVE-2017-11141

bug: https://github.com/ImageMagick/ImageMagick/issues/469
bug-debian: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=868264
origin: https://github.com/ImageMagick/ImageMagick/commit/353b942bd83da7e1356ba99c942848bd1871ee9f
(cherry picked from commit 353b942bd83da7e1356ba99c942848bd1871ee9f)
---
 coders/mat.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/coders/mat.c b/coders/mat.c
index 72fe4ed82..c886a99a3 100644
--- a/coders/mat.c
+++ b/coders/mat.c
@@ -849,9 +849,6 @@ RestoreMSCWarning
     (void) sample_size;
     image->columns = MATLAB_HDR.SizeX;
     image->rows = MATLAB_HDR.SizeY;
-    quantum_info=AcquireQuantumInfo(clone_info,image);
-    if (quantum_info == (QuantumInfo *) NULL)
-      ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
     one=1;
     image->colors = one << image->depth;
     if (image->columns == 0 || image->rows == 0)
@@ -882,6 +879,9 @@ RestoreMSCWarning
         InheritException(exception,&image->exception);
         return(DestroyImageList(image));
       }
+    quantum_info=AcquireQuantumInfo(clone_info,image);
+    if (quantum_info == (QuantumInfo *) NULL)
+      ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
 
   /* ----- Load raster data ----- */
     BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double));    /* Ldblk was set in the check phase */
