CVE-2017-9144 (published 2017-05-22T14:29Z)

In ImageMagick 7.0.5-5, a crafted RLE image can trigger a crash because of incorrect EOF handling in coders/rle.c.

Severity: MEDIUM
CVSS v2 base score: 4.3 (AV:N/AC:M/Au:N/C:N/I:N/A:P)
CVSS v3 base score: 6.5, MEDIUM (CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H)

Weakness information:
cwe_id: CWE-20
cwe_name: Improper Input Validation
description: The product receives input or data, but it does
        not validate or incorrectly validates that the input has the
        properties that are required to process the data safely and
        correctly.
extended_description: 
	   Input validation is a frequently-used technique
	   for checking potentially dangerous inputs in order to
	   ensure that the inputs are safe for processing within the
	   code, or when communicating with other components.  When
	   software does not validate input properly, an attacker is
	   able to craft the input in a form that is not expected by
	   the rest of the application. This will lead to parts of the
	   system receiving unintended input, which may result in
	   altered control flow, arbitrary control of a resource, or
	   arbitrary code execution.
	   Input validation is not the only technique for
	   processing input, however.  Other techniques attempt to
	   transform potentially-dangerous input into something safe, such
	   as filtering (CWE-790) - which attempts to remove dangerous
	   inputs - or encoding/escaping (CWE-116), which attempts to
	   ensure that the input is not misinterpreted when it is included
	   in output to another component. Other techniques exist as well
	   (see CWE-138 for more examples.)
	   Input validation can be applied to:
	   
	     raw data - strings, numbers, parameters, file contents, etc.
	     metadata - information about the raw data, such as headers or size
	   
	   Data can be simple or structured.  Structured data
	   can be composed of many nested layers, composed of
	   combinations of metadata and raw data, with other simple or
	   structured data.
	   Many properties of raw data or metadata may need
	   to be validated upon entry into the code, such
	   as:
	   
	     specified quantities such as size, length, frequency, price, rate, number of operations, time, etc.
	     implied or derived quantities, such as the actual size of a file instead of a specified size
	     indexes, offsets, or positions into more complex data structures
	     symbolic keys or other elements into hash tables, associative arrays, etc.
	     well-formedness, i.e. syntactic correctness - compliance with expected syntax 
	     lexical token correctness - compliance with rules for what is treated as a token
	     specified or derived type - the actual type of the input (or what the input appears to be)
	     consistency - between individual data elements, between raw data and metadata, between references, etc.
	     conformance to domain-specific rules, e.g. business logic 
	     equivalence - ensuring that equivalent inputs are treated the same
	     authenticity, ownership, or other attestations about the input, e.g. a cryptographic signature to prove the source of the data
	   
	   Implied or derived properties of data must often
	   be calculated or inferred by the code itself.  Errors in
	   deriving properties may be considered a contributing factor
	   to improper input validation.
	   
	   Note that "input validation" has very different
	   meanings to different people, or within different
	   classification schemes.  Caution must be used when
	   referencing this CWE entry or mapping to it.  For example,
	   some weaknesses might involve inadvertently giving control
	   to an attacker over an input when they should not be able
	   to provide an input at all, but sometimes this is referred
	   to as input validation.
	   Finally, it is important to emphasize that the
	   distinctions between input validation and output escaping
	   are often blurred, and developers must be careful to
	   understand the difference, including how input validation
	   is not always sufficient to prevent vulnerabilities,
	   especially when less stringent data types must be
	   supported, such as free-form text. Consider a SQL injection
	   scenario in which a person's last name is inserted into a
	   query. The name "O'Reilly" would likely pass the validation
	   step since it is a common last name in the English
	   language. However, this valid name cannot be directly
	   inserted into the database because it contains the "'"
	   apostrophe character, which would need to be escaped or
	   otherwise transformed. In this case, removing the
	   apostrophe might reduce the risk of SQL injection, but it
	   would produce incorrect behavior because the wrong name
	   would be recorded.
       
         

Fix information:
repo_url: https://github.com/ImageMagick/ImageMagick
commit_details: repo_url: https://github.com/ImageMagick/ImageMagick
author: Cristy
author_date: 2017-05-12 07:12:29-04:00
msg: Check for EOF conditions for RLE image format
repository: repo_url: https://github.com/ImageMagick/ImageMagick
repo_name: ImageMagick/ImageMagick
description: 🧙‍♂️ ImageMagick 7
repo_language: C
owner: ImageMagick
file_changes: filename: ChangeLog
change_type: ModificationType.MODIFY
diff: @@ -11,6 +11,7 @@
     https://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=31862).
   * Ensure backwards compatibility for the -combine option (reference
     https://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=31855).
+  * Check for EOF conditions for RLE image format.
 
 2017-04-24  7.0.5-5 Cristy  <quetzlzacatenango@image...>
   * Release ImageMagick version 7.0.5-5, GIT revision 19915:12eec43:20170424.

programming_language: Markdown
filename: rle.c
change_type: ModificationType.MODIFY
diff: @@ -132,6 +132,14 @@ static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
 #define ByteDataOp  0x05
 #define RunDataOp  0x06
 #define EOFOp  0x07
+#define ThrowRLEException(exception,message) \
+{ \
+  if (colormap != (unsigned char *) NULL) \
+    colormap=(unsigned char *) RelinquishMagickMemory(colormap); \
+  if (pixel_info != (MemoryInfo *) NULL) \
+    pixel_info=RelinquishVirtualMemory(pixel_info); \
+  ThrowReaderException((exception),(message)); \
+}
 
   char
     magick[12];
@@ -206,6 +214,8 @@ static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
   /*
     Determine if this a RLE file.
   */
+  colormap=(unsigned char *) NULL;
+  pixel_info=(MemoryInfo *) NULL;
   count=ReadBlob(image,2,(unsigned char *) magick);
   if ((count != 2) || (memcmp(magick,"\122\314",2) != 0))
     ThrowReaderException(CorruptImageError,"ImproperImageHeader");
@@ -214,8 +224,8 @@ static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
     /*
       Read image header.
     */
-    image->page.x=ReadBlobLSBShort(image);
-    image->page.y=ReadBlobLSBShort(image);
+    image->page.x=(ssize_t) ReadBlobLSBShort(image);
+    image->page.y=(ssize_t) ReadBlobLSBShort(image);
     image->columns=ReadBlobLSBShort(image);
     image->rows=ReadBlobLSBShort(image);
     flags=(MagickStatusType) ReadBlobByte(image);
@@ -226,6 +236,8 @@ static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
     map_length=(unsigned char) ReadBlobByte(image);
     if (map_length >= 22)
       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
+    if (EOFBlob(image) != MagickFalse)
+      ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile");
     one=1;
     map_length=one << map_length;
     if ((number_planes == 0) || (number_planes == 2) ||
@@ -253,12 +265,7 @@ static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
     if ((number_planes & 0x01) == 0)
       (void) ReadBlobByte(image);
     if (EOFBlob(image) != MagickFalse)
-      {
-        ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
-          image->filename);
-        break;
-      }
-    colormap=(unsigned char *) NULL;
+      ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile");
     if (number_colormaps != 0)
       {
         /*
@@ -271,8 +278,12 @@ static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
         p=colormap;
         for (i=0; i < (ssize_t) number_colormaps; i++)
           for (x=0; x < (ssize_t) map_length; x++)
+	  {
             *p++=(unsigned char) ScaleQuantumToChar(ScaleShortToQuantum(
               ReadBlobLSBShort(image)));
+            if (EOFBlob(image) != MagickFalse)
+              ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile");
+	  }
       }
     if ((flags & 0x08) != 0)
       {
@@ -300,11 +311,7 @@ static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
           }
       }
     if (EOFBlob(image) != MagickFalse)
-      {
-        ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
-          image->filename);
-        break;
-      }
+      ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile");
     if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
       if (image->scene >= (image_info->scene+image_info->number_scenes-1))
         break;
@@ -359,6 +366,8 @@ static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
     x=0;
     y=0;
     opcode=ReadBlobByte(image);
+    if (opcode == EOF)
+      ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile");
     do
     {
       switch (opcode & 0x3f)
@@ -366,8 +375,14 @@ static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
         case SkipLinesOp:
         {
           operand=ReadBlobByte(image);
+          if (opcode == EOF)
+            ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile");
           if (opcode & 0x40)
-            operand=ReadBlobLSBSignedShort(image);
+            {
+              operand=ReadBlobLSBSignedShort(image);
+              if (opcode == EOF)
+                ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile");
+	    }
           x=0;
           y+=operand;
           break;
@@ -375,6 +390,8 @@ static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
         case SetColorOp:
         {
           operand=ReadBlobByte(image);
+          if (opcode == EOF)
+            ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile");
           plane=(unsigned char) operand;
           if (plane == 255)
             plane=(unsigned char) (number_planes-1);
@@ -384,21 +401,33 @@ static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
         case SkipPixelsOp:
         {
           operand=ReadBlobByte(image);
+          if (opcode == EOF)
+            ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile");
           if (opcode & 0x40)
-            operand=ReadBlobLSBSignedShort(image);
+            {
+              operand=ReadBlobLSBSignedShort(image);
+              if (opcode == EOF)
+                ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile");
+            }
           x+=operand;
           break;
         }
         case ByteDataOp:
         {
           operand=ReadBlobByte(image);
+          if (opcode == EOF)
+            ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile");
           if (opcode & 0x40)
-            operand=ReadBlobLSBSignedShort(image);
-          offset=((image->rows-y-1)*image->columns*number_planes)+x*
-            number_planes+plane;
+            {
+              operand=ReadBlobLSBSignedShort(image);
+              if (opcode == EOF)
+                ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile");
+            }
+          offset=(ssize_t) (((image->rows-y-1)*image->columns*number_planes)+x*
+            number_planes+plane);
           operand++;
           if ((offset < 0) ||
-              (offset+((size_t) operand*number_planes) > pixel_info_length))
+              ((offset+operand*number_planes) > (ssize_t) pixel_info_length))
             {
               if (number_colormaps != 0)
                 colormap=(unsigned char *) RelinquishMagickMemory(colormap);
@@ -422,15 +451,21 @@ static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
         case RunDataOp:
         {
           operand=ReadBlobByte(image);
+          if (opcode == EOF)
+            ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile");
           if (opcode & 0x40)
-            operand=ReadBlobLSBSignedShort(image);
+            {
+              operand=ReadBlobLSBSignedShort(image);
+              if (opcode == EOF)
+                ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile");
+            }
           pixel=(unsigned char) ReadBlobByte(image);
           (void) ReadBlobByte(image);
-          offset=((image->rows-y-1)*image->columns*number_planes)+x*
-            number_planes+plane;
+          offset=(ssize_t) (((image->rows-y-1)*image->columns*number_planes)+x*
+            number_planes+plane);
           operand++;
           if ((offset < 0) ||
-              (offset+((size_t) operand*number_planes) > pixel_info_length))
+              ((offset+operand*number_planes) > (ssize_t) pixel_info_length))
             {
               if (number_colormaps != 0)
                 colormap=(unsigned char *) RelinquishMagickMemory(colormap);
@@ -452,6 +487,8 @@ static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
           break;
       }
       opcode=ReadBlobByte(image);
+      if (opcode == EOF)
+        ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile");
     } while (((opcode & 0x3f) != EOFOp) && (opcode != EOF));
     if (number_colormaps != 0)
       {
@@ -467,7 +504,7 @@ static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
         if (number_colormaps == 1)
           for (i=0; i < (ssize_t) number_pixels; i++)
           {
-            ValidateColormapValue(image,*p & mask,&index,exception);
+            ValidateColormapValue(image,(ssize_t) (*p & mask),&index,exception);
             *p=colormap[(ssize_t) index];
             p++;
           }
@@ -476,7 +513,7 @@ static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
             for (i=0; i < (ssize_t) number_pixels; i++)
               for (x=0; x < (ssize_t) number_planes; x++)
               {
-                ValidateColormapValue(image,(size_t) (x*map_length+
+                ValidateColormapValue(image,(ssize_t) (x*map_length+
                   (*p & mask)),&index,exception);
                 *p=colormap[(ssize_t) index];
                 p++;
@@ -570,7 +607,7 @@ static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
                 break;
               for (x=0; x < (ssize_t) image->columns; x++)
               {
-                SetPixelIndex(image,*p++,q);
+                SetPixelIndex(image,(Quantum) *p++,q);
                 q+=GetPixelChannels(image);
               }
               if (SyncAuthenticPixels(image,exception) == MagickFalse)

programming_language: Objective-C