1 Fix CVE-2015-1472 - heap buffer overflow in wscanf
2 Backport from upstream:
3 https://sourceware.org/git/?p=glibc.git;a=commitdiff;h=5bd80bfe9ca0d955bfbbc002781bc7b01b6bcb06
4 See: https://bugzilla.redhat.com/show_bug.cgi?id=1188235
6 Signed-off-by: Gustavo Zacarias <gustavo@zacarias.com.ar>
8 diff --git a/stdio-common/tst-sscanf.c b/stdio-common/tst-sscanf.c
9 index aece3f2..8a2eb9e 100644
10 --- a/libc/stdio-common/tst-sscanf.c
11 +++ b/libc/stdio-common/tst-sscanf.c
12 @@ -233,5 +233,38 @@ main (void)
17 + The test will segfault during SSCANF if the buffer overflow
18 + is not fixed. The size of `s` is such that it forces the use
19 + of malloc internally and this triggers the incorrect computation.
20 + Thus the value for SIZE is arbitrariy high enough that malloc
24 + CHAR *s = malloc ((SIZE + 1) * sizeof (*s));
27 + for (size_t i = 0; i < SIZE; i++)
31 + /* Scan multi-digit zero into `i`. */
32 + if (SSCANF (s, L("%d"), &i) != 1)
34 + printf ("FAIL: bug16618: SSCANF did not read one input item.\n");
39 + printf ("FAIL: bug16618: Value of `i` was not zero as expected.\n");
44 + printf ("PASS: bug16618: Did not crash.\n");
51 diff --git a/stdio-common/vfscanf.c b/stdio-common/vfscanf.c
52 index cd129a8..0e204e7 100644
53 --- a/libc/stdio-common/vfscanf.c
54 +++ b/libc/stdio-common/vfscanf.c
55 @@ -272,9 +272,10 @@ _IO_vfscanf_internal (_IO_FILE *s, const char *format, _IO_va_list argptr,
56 if (__glibc_unlikely (wpsize == wpmax)) \
59 - size_t newsize = (UCHAR_MAX + 1 > 2 * wpmax \
60 - ? UCHAR_MAX + 1 : 2 * wpmax); \
61 - if (use_malloc || !__libc_use_alloca (newsize)) \
62 + bool fits = __glibc_likely (wpmax <= SIZE_MAX / sizeof (CHAR_T) / 2); \
63 + size_t wpneed = MAX (UCHAR_MAX + 1, 2 * wpmax); \
64 + size_t newsize = fits ? wpneed * sizeof (CHAR_T) : SIZE_MAX; \
65 + if (!__libc_use_alloca (newsize)) \
67 wp = realloc (use_malloc ? wp : NULL, newsize); \
69 @@ -286,14 +287,13 @@ _IO_vfscanf_internal (_IO_FILE *s, const char *format, _IO_va_list argptr,
72 MEMCPY (wp, old, wpsize); \
79 size_t s = wpmax * sizeof (CHAR_T); \
80 - wp = (CHAR_T *) extend_alloca (wp, s, \
81 - newsize * sizeof (CHAR_T)); \
82 + wp = (CHAR_T *) extend_alloca (wp, s, newsize); \
83 wpmax = s / sizeof (CHAR_T); \
85 MEMCPY (wp, old, wpsize); \