bunzip2: reject blocks whose run-length count overflows

Based ob the patch by Matt Turner <mattst88@gmail.com>:
> get_next_block() accumulates a run length in the unsigned 32-bit runCnt:
>
>         runCnt += (runPos << nextSym);
>
> A crafted stream with a long enough RUNA/RUNB sequence can drive runCnt
> up to ~2^32. Once it is that large, the existing guard
>
>         if (dbufCount + runCnt > bd->dbufSize)
>
> is bypassed: dbufCount + runCnt overflows the unsigned addition and
> wraps to a small value, so the check passes. The following
> byteCount[tmp_byte] += runCnt then overflows byteCount[] (an int) to a
> negative value. The inverse Burrows-Wheeler sort loop computes negative
> cumulative offsets from it and writes before the start of dbuf[], an
> out-of-bounds heap write (confirmed with AddressSanitizer as a write 48
> bytes before the dbuf allocation).

function                                             old     new   delta
get_next_block                                      1452    1458      +6

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
This commit is contained in:
Denys Vlasenko committed 2026-10-02 20:35:04 +02:00
1 parent 904511662e
commit 14f6b6b580
3 files changed
+18 -7

No files matched your search

+6 -7
View File
@@ -463,13 +463,12 @@ static int get_next_block(bunzip_data *bd)
symbols, but a run of length 0 doesn't mean anything in this
context). Thus space is saved. */
runCnt += (runPos << nextSym); /* +runPos if RUNA; +2*runPos if RUNB */
//The 32-bit overflow of runCnt wasn't yet seen, but probably can happen.
//This would be the fix (catches too large count way before it can overflow):
// if (runCnt > bd->dbufSize) {
// dbg("runCnt:%u > dbufSize:%u RETVAL_DATA_ERROR",
// runCnt, bd->dbufSize);
// return RETVAL_DATA_ERROR;
// }
/* Catch 32-bit overflow (we have an example .bz2 file) */
if ((int)runCnt < 0) {
dbg("runCnt:%u > dbufSize:%u RETVAL_DATA_ERROR",
runCnt, bd->dbufSize);
return RETVAL_DATA_ERROR;
}
if (runPos < bd->dbufSize) runPos <<= 1;
goto end_of_huffman_loop;
}
+12
View File
@@ -568,6 +568,18 @@ if test "${0##*/}" = "bunzip2.tests"; then
echo "FAIL: $unpack: bz2_issue_12.bz2 corrupted example"
FAILCOUNT=$((FAILCOUNT + 1))
fi
# specially crafted file to attack the
# runCnt += (runPos << nextSym); /* +runPos if RUNA; +2*runPos if RUNB */
# code, making (dbufCount + runCnt) overflow 32 bits and become small.
# (there is a fix now which catches when runCnt reaches 0x80000000)
errout="`${bb}bunzip2 <bz2_runcnt_overflow.bz2 2>&1 >/dev/null`"
if test x"$errout:$?" = x"bunzip2: bunzip error -5:1"; then
echo "PASS: $unpack: bz2_runcnt_overflow.bz2 corrupted example"
else
echo "FAIL: $unpack: bz2_runcnt_overflow.bz2 corrupted example"
FAILCOUNT=$((FAILCOUNT + 1))
fi
fi
exit $((FAILCOUNT <= 255 ? FAILCOUNT : 255))
Binary file not shown.