From 59c38e3e45b9112c2bcb4392bccf56e297854f8a Mon Sep 17 00:00:00 2001
From: Anton Gladky <gladk@debian.org>
Date: Sat, 23 May 2020 17:44:33 +0200
Subject: [PATCH] Prevent integer overflow in computeDimensions. #12

Fix for CVE-2019-5086 and CVE-2019-5087

The code checks the sizes of width and height and stop execution, if it exceeds
maximal values.
---
 xcf-general.c | 16 ++++++++++++++++
 xcftools.h    |  2 +-
 2 files changed, 17 insertions(+), 1 deletion(-)

diff --git a/xcf-general.c b/xcf-general.c
index b23c260..169b4f7 100644
--- a/xcf-general.c
+++ b/xcf-general.c
@@ -19,6 +19,7 @@
 #include "xcftools.h"
 #include <string.h>
 #include <errno.h>
+#include <limits.h>
 #ifdef HAVE_ICONV
 # include <iconv.h>
 #elif !defined(ICONV_CONST)
@@ -182,6 +183,21 @@ xcfString(uint32_t ptr,uint32_t *after)
 void
 computeDimensions(struct tileDimensions *d)
 {
+  // [ CVE-2019-5086 and CVE-2019-5087 ]
+  // This part of code is the check to prevent integer overflow, see CVE-2019-5086 and CVE-2019-5087
+
+  if ((d->c.l + d->width)*4 > INT_MAX) {
+    fprintf(stderr,("Width is too large (%d)! Stopping execution...\n"), (d->c.l + d->width));
+    exit(0);
+  }
+
+  if ((d->c.t + d->height)*4 > INT_MAX) {
+    fprintf(stderr,("Height is too large (%d)! Stopping execution...\n"), (d->c.t + d->height));
+    exit(0);
+  }
+
+  // [ CVE-2019-5086 and CVE-2019-5087 ]
+
   d->c.r = d->c.l + d->width ;
   d->c.b = d->c.t + d->height ;
   d->tilesx = (d->width+TILE_WIDTH-1)/TILE_WIDTH ;
diff --git a/xcftools.h b/xcftools.h
index 5a1efcc..4bb02ea 100644
--- a/xcftools.h
+++ b/xcftools.h
@@ -121,7 +121,7 @@ FILE* openout(const char*);
 void closeout(FILE *,const char*);
 
 struct rect {
-  int t, b, l, r ;
+  int64_t t, b, l, r ;
 };
 
 #define isSubrect(A,B) \
