bzip2: Fix CVE-2019-12900
[openwrt/openwrt.git] / package / utils / bzip2 / patches / 020-CVE-2019-12900.patch
1 From 812a898b7622de90e98f103ff7fed0984e4548e4 Mon Sep 17 00:00:00 2001
2 From: Mark Wielaard <mark@klomp.org>
3 Date: Wed, 3 Jul 2019 01:28:11 +0200
4 Subject: [PATCH] Accept as many selectors as the file format allows.
5
6 But ignore any larger than the theoretical maximum, BZ_MAX_SELECTORS.
7
8 The theoretical maximum number of selectors depends on the maximum
9 blocksize (900000 bytes) and the number of symbols (50) that can be
10 encoded with a different Huffman tree. BZ_MAX_SELECTORS is 18002.
11
12 But the bzip2 file format allows the number of selectors to be encoded
13 with 15 bits (because 18002 isn't a factor of 2 and doesn't fit in
14 14 bits). So the file format maximum is 32767 selectors.
15
16 Some bzip2 encoders might actually have written out more selectors
17 than the theoretical maximum because they rounded up the number of
18 selectors to some convenient factor of 8.
19
20 The extra 14766 selectors can never be validly used by the decompression
21 algorithm. So we can read them, but then discard them.
22
23 This is effectively what was done (by accident) before we added a
24 check for nSelectors to be at most BZ_MAX_SELECTORS to mitigate
25 CVE-2019-12900.
26
27 The extra selectors were written out after the array inside the
28 EState struct. But the struct has extra space allocated after the
29 selector arrays of 18060 bytes (which is larger than 14766).
30 All of which will be initialized later (so the overwrite of that
31 space with extra selector values would have been harmless).
32 ---
33 compress.c | 2 +-
34 decompress.c | 10 +++++++-
35 2 files changed, 8 insertions(+), 2 deletions(-)
36
37 --- a/compress.c
38 +++ b/compress.c
39 @@ -454,7 +454,7 @@ void sendMTFValues ( EState* s )
40
41 AssertH( nGroups < 8, 3002 );
42 AssertH( nSelectors < 32768 &&
43 - nSelectors <= (2 + (900000 / BZ_G_SIZE)),
44 + nSelectors <= BZ_MAX_SELECTORS,
45 3003 );
46
47
48 --- a/decompress.c
49 +++ b/decompress.c
50 @@ -296,8 +296,14 @@ Int32 BZ2_decompress ( DState* s )
51 j++;
52 if (j >= nGroups) RETURN(BZ_DATA_ERROR);
53 }
54 - s->selectorMtf[i] = j;
55 + /* Having more than BZ_MAX_SELECTORS doesn't make much sense
56 + since they will never be used, but some implementations might
57 + "round up" the number of selectors, so just ignore those. */
58 + if (i < BZ_MAX_SELECTORS)
59 + s->selectorMtf[i] = j;
60 }
61 + if (nSelectors > BZ_MAX_SELECTORS)
62 + nSelectors = BZ_MAX_SELECTORS;
63
64 /*--- Undo the MTF values for the selectors. ---*/
65 {