1 From d07b91014986900a3a75f306d302e13e005e9d67 Mon Sep 17 00:00:00 2001
2 From: Tobias Stoeckmann <tobias@stoeckmann.org>
3 Date: Mon, 4 May 2020 19:47:25 +0200
4 Subject: [PATCH] Fix integer overflows.
6 The data structures linkhash and printbuf are limited to 2 GB in size
7 due to a signed integer being used to track their current size.
9 If too much data is added, then size variable can overflow, which is
10 an undefined behaviour in C programming language.
12 Assuming that a signed int overflow just leads to a negative value,
13 like it happens on many sytems (Linux i686/amd64 with gcc), then
14 printbuf is vulnerable to an out of boundary write on 64 bit systems.
16 linkhash.c | 7 +++++--
17 printbuf.c | 19 ++++++++++++++++---
18 2 files changed, 21 insertions(+), 5 deletions(-)
22 @@ -498,7 +498,12 @@ int lh_table_insert(struct lh_table *t,
26 - if(t->count >= t->size * LH_LOAD_FACTOR) lh_table_resize(t, t->size * 2);
27 + if(t->count >= t->size * LH_LOAD_FACTOR) {
28 + /* Avoid signed integer overflow with large tables. */
29 + int new_size = (t->size > INT_MAX / 2) ? INT_MAX : (t->size * 2);
30 + if (t->size != INT_MAX)
31 + lh_table_resize(t, new_size);
46 @@ -63,7 +64,16 @@ static int printbuf_extend(struct printb
47 if (p->size >= min_size)
50 - new_size = json_max(p->size * 2, min_size + 8);
51 + /* Prevent signed integer overflows with large buffers. */
52 + if (min_size > INT_MAX - 8)
54 + if (p->size > INT_MAX / 2)
55 + new_size = min_size + 8;
57 + new_size = p->size * 2;
58 + if (new_size < min_size + 8)
59 + new_size = min_size + 8;
62 MC_DEBUG("printbuf_memappend: realloc "
63 "bpos=%d min_size=%d old_size=%d new_size=%d\n",
64 @@ -78,6 +88,9 @@ static int printbuf_extend(struct printb
66 int printbuf_memappend(struct printbuf *p, const char *buf, int size)
68 + /* Prevent signed integer overflows with large buffers. */
69 + if (size > INT_MAX - p->bpos - 1)
71 if (p->size <= p->bpos + size + 1) {
72 if (printbuf_extend(p, p->bpos + size + 1) < 0)
74 @@ -94,6 +107,9 @@ int printbuf_memset(struct printbuf *pb,
78 + /* Prevent signed integer overflows with large buffers. */
79 + if (len > INT_MAX - offset)
81 size_needed = offset + len;
82 if (pb->size < size_needed)