libjson-c: backport security fixes
[openwrt/staging/jow.git] / package / libs / libjson-c / patches / 002-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 @@ -498,7 +498,12 @@ int lh_table_insert(struct lh_table *t,
23 unsigned long h, n;
24
25 t->inserts++;
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);
32 + }
33
34 h = t->hash_fn(k);
35 n = h % t->size;
36 --- a/printbuf.c
37 +++ b/printbuf.c
38 @@ -15,6 +15,7 @@
39
40 #include "config.h"
41
42 +#include <limits.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46 @@ -63,7 +64,16 @@ static int printbuf_extend(struct printb
47 if (p->size >= min_size)
48 return 0;
49
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)
53 + return -1;
54 + if (p->size > INT_MAX / 2)
55 + new_size = min_size + 8;
56 + else {
57 + new_size = p->size * 2;
58 + if (new_size < min_size + 8)
59 + new_size = min_size + 8;
60 + }
61 #ifdef PRINTBUF_DEBUG
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
65
66 int printbuf_memappend(struct printbuf *p, const char *buf, int size)
67 {
68 + /* Prevent signed integer overflows with large buffers. */
69 + if (size > INT_MAX - p->bpos - 1)
70 + return -1;
71 if (p->size <= p->bpos + size + 1) {
72 if (printbuf_extend(p, p->bpos + size + 1) < 0)
73 return -1;
74 @@ -94,6 +107,9 @@ int printbuf_memset(struct printbuf *pb,
75
76 if (offset == -1)
77 offset = pb->bpos;
78 + /* Prevent signed integer overflows with large buffers. */
79 + if (len > INT_MAX - offset)
80 + return -1;
81 size_needed = offset + len;
82 if (pb->size < size_needed)
83 {