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