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 @@ -579,9 +579,12 @@ int lh_table_insert_w_hash(struct lh_tab
26 - if (t->count >= t->size * LH_LOAD_FACTOR)
27 - if (lh_table_resize(t, t->size * 2) != 0)
28 + if (t->count >= t->size * LH_LOAD_FACTOR) {
29 + /* Avoid signed integer overflow with large tables. */
30 + int new_size = INT_MAX / 2 < t->size ? t->size * 2 : INT_MAX;
31 + if (t->size == INT_MAX || lh_table_resize(t, new_size) != 0)
47 @@ -65,9 +66,16 @@ static int printbuf_extend(struct printb
48 if (p->size >= min_size)
51 - new_size = p->size * 2;
52 - if (new_size < min_size + 8)
53 - new_size = min_size + 8;
54 + /* Prevent signed integer overflows with large buffers. */
55 + if (min_size > INT_MAX - 8)
57 + if (p->size > INT_MAX / 2)
58 + new_size = min_size + 8;
60 + new_size = p->size * 2;
61 + if (new_size < min_size + 8)
62 + new_size = min_size + 8;
65 MC_DEBUG("printbuf_memappend: realloc "
66 "bpos=%d min_size=%d old_size=%d new_size=%d\n",
67 @@ -82,6 +90,9 @@ static int printbuf_extend(struct printb
69 int printbuf_memappend(struct printbuf *p, const char *buf, int size)
71 + /* Prevent signed integer overflows with large buffers. */
72 + if (size > INT_MAX - p->bpos - 1)
74 if (p->size <= p->bpos + size + 1) {
75 if (printbuf_extend(p, p->bpos + size + 1) < 0)
77 @@ -98,6 +109,9 @@ int printbuf_memset(struct printbuf *pb,
81 + /* Prevent signed integer overflows with large buffers. */
82 + if (len > INT_MAX - offset)
84 size_needed = offset + len;
85 if (pb->size < size_needed)