diff -rupN --no-dereference Pillow-5.4.1/src/libImaging/SgiRleDecode.c Pillow-5.4.1-new/src/libImaging/SgiRleDecode.c --- Pillow-5.4.1/src/libImaging/SgiRleDecode.c 2020-02-13 14:44:21.492015770 +0100 +++ Pillow-5.4.1-new/src/libImaging/SgiRleDecode.c 2020-02-13 14:44:21.644014641 +0100 @@ -25,7 +25,7 @@ static void read4B(UINT32* dest, UINT8* *dest = (UINT32)((buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3]); } -static int expandrow(UINT8* dest, UINT8* src, int n, int z) +static int expandrow(UINT8* dest, UINT8* src, int n, int z, int xsize) { UINT8 pixel, count; @@ -37,6 +37,9 @@ static int expandrow(UINT8* dest, UINT8* count = pixel & RLE_MAX_RUN; if (!count) return count; + if (count > xsize) { + return -1; + } if (pixel & RLE_COPY_FLAG) { while(count--) { *dest = *src++; @@ -56,7 +59,7 @@ static int expandrow(UINT8* dest, UINT8* return 0; } -static int expandrow2(UINT16* dest, UINT16* src, int n, int z) +static int expandrow2(UINT16* dest, UINT16* src, int n, int z, int xsize) { UINT8 pixel, count; @@ -70,6 +73,9 @@ static int expandrow2(UINT16* dest, UINT count = pixel & RLE_MAX_RUN; if (!count) return count; + if (count > xsize) { + return -1; + } if (pixel & RLE_COPY_FLAG) { while(count--) { *dest = *src++; @@ -95,6 +101,7 @@ ImagingSgiRleDecode(Imaging im, ImagingC UINT8 *ptr; SGISTATE *c; int err = 0; + int status; /* Get all data from File descriptor */ c = (SGISTATE*)state->context; @@ -163,12 +170,16 @@ ImagingSgiRleDecode(Imaging im, ImagingC /* row decompression */ if (c->bpc ==1) { - if(expandrow(&state->buffer[c->channo], &ptr[c->rleoffset], c->rlelength, im->bands)) - goto sgi_finish_decode; + status = expandrow(&state->buffer[c->channo], &ptr[c->rleoffset], c->rlelength, im->bands, im->xsize); } else { - if(expandrow2((UINT16*)&state->buffer[c->channo * 2], (UINT16*)&ptr[c->rleoffset], c->rlelength, im->bands)) - goto sgi_finish_decode; + status = expandrow2((UINT16*)&state->buffer[c->channo * 2], (UINT16*)&ptr[c->rleoffset], c->rlelength, im->bands, im->xsize); + } + if (status == -1) { + state->errcode = IMAGING_CODEC_OVERRUN; + return -1; + } else if (status == 1) { + goto sgi_finish_decode; } state->count += c->rlelength; diff -rupN --no-dereference Pillow-5.4.1/Tests/test_image.py Pillow-5.4.1-new/Tests/test_image.py --- Pillow-5.4.1/Tests/test_image.py 2020-02-13 14:44:21.642014656 +0100 +++ Pillow-5.4.1-new/Tests/test_image.py 2020-02-13 14:44:21.645014634 +0100 @@ -557,6 +557,8 @@ class TestRegistry(PillowTestCase): def test_overrun(self): for file in [ + "sgi_overrun_expandrow.bin", + "sgi_overrun_expandrow2.bin", "pcx_overrun2.bin", ]: im = Image.open(os.path.join("Tests/images", file))