87e604
From a11f47475e6443b7f32d21f2271f28f417e2ac04 Mon Sep 17 00:00:00 2001
87e604
From: "Christoph M. Becker" <cmbecker69@gmx.de>
87e604
Date: Wed, 29 Nov 2017 19:37:38 +0100
87e604
Subject: [PATCH] Fix #420: Potential infinite loop in gdImageCreateFromGifCtx
87e604
87e604
Due to a signedness confusion in `GetCode_` a corrupt GIF file can
87e604
trigger an infinite loop.  Furthermore we make sure that a GIF without
87e604
any palette entries is treated as invalid *after* open palette entries
87e604
have been removed.
87e604
87e604
CVE-2018-5711
87e604
87e604
See also https://bugs.php.net/bug.php?id=75571.
87e604
---
87e604
 src/gd_gif_in.c             |  12 ++++++------
87e604
 tests/gif/.gitignore        |   1 +
87e604
 tests/gif/CMakeLists.txt    |   1 +
87e604
 tests/gif/Makemodule.am     |   2 ++
87e604
 tests/gif/php_bug_75571.c   |  28 ++++++++++++++++++++++++++++
87e604
 tests/gif/php_bug_75571.gif | Bin 0 -> 1731 bytes
87e604
 6 files changed, 38 insertions(+), 6 deletions(-)
87e604
 create mode 100644 tests/gif/php_bug_75571.c
87e604
 create mode 100644 tests/gif/php_bug_75571.gif
87e604
87e604
diff --git a/src/gd_gif_in.c b/src/gd_gif_in.c
87e604
index daf26e79..0a8bd717 100644
87e604
--- a/src/gd_gif_in.c
87e604
+++ b/src/gd_gif_in.c
87e604
@@ -335,11 +335,6 @@ BGD_DECLARE(gdImagePtr) gdImageCreateFromGifCtx(gdIOCtxPtr fd)
87e604
 		return 0;
87e604
 	}
87e604
 
87e604
-	if(!im->colorsTotal) {
87e604
-		gdImageDestroy(im);
87e604
-		return 0;
87e604
-	}
87e604
-
87e604
 	/* Check for open colors at the end, so
87e604
 	 * we can reduce colorsTotal and ultimately
87e604
 	 * BitsPerPixel */
87e604
@@ -351,6 +346,11 @@ BGD_DECLARE(gdImagePtr) gdImageCreateFromGifCtx(gdIOCtxPtr fd)
87e604
 		}
87e604
 	}
87e604
 
87e604
+	if(!im->colorsTotal) {
87e604
+		gdImageDestroy(im);
87e604
+		return 0;
87e604
+	}
87e604
+
87e604
 	return im;
87e604
 }
87e604
 
87e604
@@ -447,7 +447,7 @@ static int
87e604
 GetCode_(gdIOCtx *fd, CODE_STATIC_DATA *scd, int code_size, int flag, int *ZeroDataBlockP)
87e604
 {
87e604
 	int i, j, ret;
87e604
-	unsigned char count;
87e604
+	int count;
87e604
 
87e604
 	if(flag) {
87e604
 		scd->curbit = 0;
87e604