From 1f90f191cef5f4d18cb229e3717d0b2010e9b434 Mon Sep 17 00:00:00 2001
From: Andrew Murray <radarhere@users.noreply.github.com>
Date: Mon, 30 Sep 2019 18:45:43 +1000
Subject: [PATCH] Catch buffer overruns

Signed-off-by: hanxinke <hanxinke@huawei.com>
---
 src/libImaging/FliDecode.c    | 14 +++++++++++---
 src/libImaging/PcxDecode.c    |  5 +++++
 src/libImaging/SgiRleDecode.c |  5 +++++
 3 files changed, 21 insertions(+), 3 deletions(-)

diff --git a/src/libImaging/FliDecode.c b/src/libImaging/FliDecode.c
index 6d22c6c..600528e 100644
--- a/src/libImaging/FliDecode.c
+++ b/src/libImaging/FliDecode.c
@@ -30,7 +30,7 @@ ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
 {
     UINT8* ptr;
     int framesize;
-    int c, chunks;
+    int c, chunks, advance;
     int l, lines;
     int i, j, x = 0, y, ymax;
 
@@ -59,10 +59,16 @@ ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
 
     chunks = I16(ptr+6);
     ptr += 16;
+    bytes -= 16;
 
     /* Process subchunks */
     for (c = 0; c < chunks; c++) {
-	UINT8 *data = ptr + 6;
+	UINT8* data;
+	if (bytes < 10) {
+	    state->errcode = IMAGING_CODEC_OVERRUN;
+	    return -1;
+	}
+	data = ptr + 6;
 	switch (I16(ptr+4)) {
 	case 4: case 11:
 	    /* FLI COLOR chunk */
@@ -198,7 +204,9 @@ ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
 	    state->errcode = IMAGING_CODEC_UNKNOWN;
 	    return -1;
 	}
-	ptr += I32(ptr);
+	advance = I32(ptr);
+	ptr += advance;
+	bytes -= advance;
     }
 
     return -1; /* end of frame */
diff --git a/src/libImaging/PcxDecode.c b/src/libImaging/PcxDecode.c
index e5417f1..51de069 100644
--- a/src/libImaging/PcxDecode.c
+++ b/src/libImaging/PcxDecode.c
@@ -22,6 +22,11 @@ ImagingPcxDecode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
     UINT8 n;
     UINT8* ptr;
 
+    if (strcmp(im->mode, "1") == 0 && state->xsize > state->bytes * 8) {
+        state->errcode = IMAGING_CODEC_OVERRUN;
+        return -1;
+    }
+
     ptr = buf;
 
     for (;;) {
diff --git a/src/libImaging/SgiRleDecode.c b/src/libImaging/SgiRleDecode.c
index 9d8e563..39e7b3a 100644
--- a/src/libImaging/SgiRleDecode.c
+++ b/src/libImaging/SgiRleDecode.c
@@ -156,6 +156,11 @@ ImagingSgiRleDecode(Imaging im, ImagingCodecState state,
             c->rlelength = c->lengthtab[c->rowno + c->channo * im->ysize];
             c->rleoffset -= SGI_HEADER_SIZE;
 
+            if (c->rleoffset + c->rlelength > c->bufsize) {
+                state->errcode = IMAGING_CODEC_OVERRUN;
+                return -1;
+            }
+
             /* row decompression */
             if (c->bpc ==1) {
                 if(expandrow(&state->buffer[c->channo], &ptr[c->rleoffset], c->rlelength, im->bands))
-- 
2.19.1

