1From 4e76b08f7171a8603d74fcafb27409a91f578647 Mon Sep 17 00:00:00 2001
2From: Daniel Axtens <dja@axtens.net>
3Date: Thu, 21 Jan 2021 12:20:49 +1100
4Subject: [PATCH] io/gzio: Catch missing values in huft_build() and bail
5
6In huft_build(), "v" is a table of values in order of bit length.
7The code later (when setting up table entries in "r") assumes that all
8elements of this array corresponding to a code are initialized and less
9than N_MAX. However, it doesn't enforce this.
10
11With sufficiently manipulated inputs (e.g. from fuzzing), there can be
12elements of "v" that are not filled. Therefore a lookup into "e" or "d"
13will use an uninitialized value. This can lead to an invalid/OOB read on
14those values, often leading to a crash.
15
16Signed-off-by: Daniel Axtens <dja@axtens.net>
17Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
18Signed-off-by: Stefan Sørensen <stefan.sorensen@spectralink.com>
19---
20 grub-core/io/gzio.c | 10 +++++++++-
21 1 file changed, 9 insertions(+), 1 deletion(-)
22
23diff --git a/grub-core/io/gzio.c b/grub-core/io/gzio.c
24index 4236f0f..19adebe 100644
25--- a/grub-core/io/gzio.c
26+++ b/grub-core/io/gzio.c
27@@ -507,6 +507,7 @@ huft_build (unsigned *b,	/* code lengths in bits (all assumed <= BMAX) */
28     }
29
30   /* Make a table of values in order of bit lengths */
31+  grub_memset (v, N_MAX, ARRAY_SIZE (v));
32   p = b;
33   i = 0;
34   do
35@@ -588,11 +589,18 @@ huft_build (unsigned *b,	/* code lengths in bits (all assumed <= BMAX) */
36 	      r.v.n = (ush) (*p);	/* simple code is just the value */
37 	      p++;		/* one compiler does not like *p++ */
38 	    }
39-	  else
40+	  else if (*p < N_MAX)
41 	    {
42 	      r.e = (uch) e[*p - s];	/* non-simple--look up in lists */
43 	      r.v.n = d[*p++ - s];
44 	    }
45+	  else
46+	    {
47+	      /* Detected an uninitialised value, abort. */
48+	      if (h)
49+		huft_free (u[0]);
50+	      return 2;
51+	    }
52
53 	  /* fill code-like entries with r */
54 	  f = 1 << (k - w);
55--
562.14.2
57
58