libjson-c: backport security fixes
[openwrt/staging/mkresin.git] / package / libs / libjson-c / patches / 003-Fix-integer-overflows.patch
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.
5
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.
8
9 If too much data is added, then size variable can overflow, which is
10 an undefined behaviour in C programming language.
11
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.
15 ---
16 linkhash.c | 7 +++++--
17 printbuf.c | 19 ++++++++++++++++---
18 2 files changed, 21 insertions(+), 5 deletions(-)
19
20 --- a/linkhash.c
21 +++ b/linkhash.c
22 @@ -579,9 +579,12 @@ int lh_table_insert_w_hash(struct lh_tab
23 {
24 unsigned long n;
25
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)
32 return -1;
33 + }
34
35 n = h % t->size;
36
37 --- a/printbuf.c
38 +++ b/printbuf.c
39 @@ -15,6 +15,7 @@
40
41 #include "config.h"
42
43 +#include <limits.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 @@ -65,9 +66,16 @@ static int printbuf_extend(struct printb
48 if (p->size >= min_size)
49 return 0;
50
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)
56 + return -1;
57 + if (p->size > INT_MAX / 2)
58 + new_size = min_size + 8;
59 + else {
60 + new_size = p->size * 2;
61 + if (new_size < min_size + 8)
62 + new_size = min_size + 8;
63 + }
64 #ifdef PRINTBUF_DEBUG
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
68
69 int printbuf_memappend(struct printbuf *p, const char *buf, int size)
70 {
71 + /* Prevent signed integer overflows with large buffers. */
72 + if (size > INT_MAX - p->bpos - 1)
73 + return -1;
74 if (p->size <= p->bpos + size + 1) {
75 if (printbuf_extend(p, p->bpos + size + 1) < 0)
76 return -1;
77 @@ -98,6 +109,9 @@ int printbuf_memset(struct printbuf *pb,
78
79 if (offset == -1)
80 offset = pb->bpos;
81 + /* Prevent signed integer overflows with large buffers. */
82 + if (len > INT_MAX - offset)
83 + return -1;
84 size_needed = offset + len;
85 if (pb->size < size_needed)
86 {