1 From c3edc06d1e1360f3570db9155d6b318ae0d0f0f7 Mon Sep 17 00:00:00 2001
2 From: Rich Felker <dalias@aerifal.cx>
3 Date: Thu, 6 Oct 2016 18:34:58 -0400
4 Subject: fix missing integer overflow checks in regexec buffer size
7 most of the possible overflows were already ruled out in practice by
8 regcomp having already succeeded performing larger allocations.
9 however at least the num_states*num_tags multiplication can clearly
10 overflow in practice. for safety, check them all, and use the proper
11 type, size_t, rather than int.
13 also improve comments, use calloc in place of malloc+memset, and
16 src/regex/regexec.c | 23 ++++++++++++++++++-----
17 1 file changed, 18 insertions(+), 5 deletions(-)
19 diff --git a/src/regex/regexec.c b/src/regex/regexec.c
20 index 16c5d0a..dd52319 100644
21 --- a/src/regex/regexec.c
22 +++ b/src/regex/regexec.c
31 @@ -206,11 +207,24 @@ tre_tnfa_run_parallel(const tre_tnfa_t *tnfa, const void *string,
33 /* Allocate memory for temporary data required for matching. This needs to
34 be done for every matching operation to be thread safe. This allocates
35 - everything in a single large block from the stack frame using alloca()
36 - or with malloc() if alloca is unavailable. */
37 + everything in a single large block with calloc(). */
39 - int tbytes, rbytes, pbytes, xbytes, total_bytes;
40 + size_t tbytes, rbytes, pbytes, xbytes, total_bytes;
43 + /* Ensure that tbytes and xbytes*num_states cannot overflow, and that
44 + * they don't contribute more than 1/8 of SIZE_MAX to total_bytes. */
45 + if (num_tags > SIZE_MAX/(8 * sizeof(int) * tnfa->num_states))
48 + /* Likewise check rbytes. */
49 + if (tnfa->num_states+1 > SIZE_MAX/(8 * sizeof(*reach_next)))
52 + /* Likewise check pbytes. */
53 + if (tnfa->num_states > SIZE_MAX/(8 * sizeof(*reach_pos)))
56 /* Compute the length of the block we need. */
57 tbytes = sizeof(*tmp_tags) * num_tags;
58 rbytes = sizeof(*reach_next) * (tnfa->num_states + 1);
59 @@ -221,10 +235,9 @@ tre_tnfa_run_parallel(const tre_tnfa_t *tnfa, const void *string,
60 + (rbytes + xbytes * tnfa->num_states) * 2 + tbytes + pbytes;
62 /* Allocate the memory. */
63 - buf = xmalloc((unsigned)total_bytes);
64 + buf = calloc(total_bytes, 1);
67 - memset(buf, 0, (size_t)total_bytes);
69 /* Get the various pointers within tmp_buf (properly aligned). */
70 tmp_tags = (void *)buf;