From 930cdf0ee3fb9ea4c3ca28a551d8f2388a1040de Mon Sep 17 00:00:00 2001 From: Max Kellermann Date: Tue, 5 Oct 2021 09:39:09 +0200 Subject: [PATCH] mapshape: fix buffer overflow in msSHPReadShape() The data in panParts is never checked. There are checks for "numpoints<=0" and "numpoints>nPoints" (the latter added by commit fcf13d849cb), but that is not enough. It is still possible to overflow the "pabyRec" buffer by repeatedly reading "nPoints". The code allows each single iteration to read "nPoints". Vulnerability found with libFuzzer. --- mapshape.c | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/mapshape.c b/mapshape.c index ab4c8522d8..733f8c3cc0 100644 --- a/mapshape.c +++ b/mapshape.c @@ -1347,11 +1347,12 @@ void msSHPReadShape( SHPHandle psSHP, int hEntity, shapeObj *shape ) k = 0; /* overall point counter */ for( i = 0; i < nParts; i++) { - if( i == nParts-1) - shape->line[i].numpoints = nPoints - psSHP->panParts[i]; - else - shape->line[i].numpoints = psSHP->panParts[i+1] - psSHP->panParts[i]; - if (shape->line[i].numpoints <= 0 || shape->line[i].numpoints > nPoints) { + const ms_int32 end = i == nParts - 1 + ? nPoints + : psSHP->panParts[i+1]; + shape->line[i].numpoints = end - psSHP->panParts[i]; + if (psSHP->panParts[i] < 0 || end < 0 || end > nPoints || + psSHP->panParts[i] >= end) { msSetError(MS_SHPERR, "Corrupted .shp file : shape %d, shape->line[%d].numpoints=%d", "msSHPReadShape()", hEntity, i, shape->line[i].numpoints); while(--i >= 0)