1 From 18d9cd1d9d95503074db705686d0236c99db5d00 Mon Sep 17 00:00:00 2001
2 From: Paul Pluzhnikov <ppluzhnikov@google.com>
3 Date: Fri, 6 Feb 2015 00:30:42 -0500
4 Subject: [PATCH 2/2] CVE-2015-1472: wscanf allocates too little memory
8 Under certain conditions wscanf can allocate too little memory for the
9 to-be-scanned arguments and overflow the allocated buffer. The
10 implementation now correctly computes the required buffer size when
13 A regression test was added to tst-sscanf.
19 ChangeLog | 133 ++++++++++++++++++++++++++++++++++++++++++++++
20 NEWS | 44 +++++++++++++++
21 stdio-common/tst-sscanf.c | 33 ++++++++++++
22 stdio-common/vfscanf.c | 12 ++---
23 4 files changed, 216 insertions(+), 6 deletions(-)
25 diff --git a/stdio-common/tst-sscanf.c b/stdio-common/tst-sscanf.c
26 index 1214c7d..c62bee6 100644
27 --- a/stdio-common/tst-sscanf.c
28 +++ b/stdio-common/tst-sscanf.c
29 @@ -232,5 +232,38 @@ main (void)
34 + The test will segfault during SSCANF if the buffer overflow
35 + is not fixed. The size of `s` is such that it forces the use
36 + of malloc internally and this triggers the incorrect computation.
37 + Thus the value for SIZE is arbitrariy high enough that malloc
41 + CHAR *s = malloc ((SIZE + 1) * sizeof (*s));
44 + for (size_t i = 0; i < SIZE; i++)
48 + /* Scan multi-digit zero into `i`. */
49 + if (SSCANF (s, L("%d"), &i) != 1)
51 + printf ("FAIL: bug16618: SSCANF did not read one input item.\n");
56 + printf ("FAIL: bug16618: Value of `i` was not zero as expected.\n");
61 + printf ("PASS: bug16618: Did not crash.\n");
68 diff --git a/stdio-common/vfscanf.c b/stdio-common/vfscanf.c
69 index 2e1e91a..d7a18e3 100644
70 --- a/stdio-common/vfscanf.c
71 +++ b/stdio-common/vfscanf.c
72 @@ -272,9 +272,10 @@ _IO_vfscanf_internal (_IO_FILE *s, const char *format, _IO_va_list argptr,
73 if (__builtin_expect (wpsize == wpmax, 0)) \
76 - size_t newsize = (UCHAR_MAX + 1 > 2 * wpmax \
77 - ? UCHAR_MAX + 1 : 2 * wpmax); \
78 - if (use_malloc || !__libc_use_alloca (newsize)) \
79 + bool fits = __glibc_likely (wpmax <= SIZE_MAX / sizeof (CHAR_T) / 2); \
80 + size_t wpneed = MAX (UCHAR_MAX + 1, 2 * wpmax); \
81 + size_t newsize = fits ? wpneed * sizeof (CHAR_T) : SIZE_MAX; \
82 + if (!__libc_use_alloca (newsize)) \
84 wp = realloc (use_malloc ? wp : NULL, newsize); \
86 @@ -286,14 +287,13 @@ _IO_vfscanf_internal (_IO_FILE *s, const char *format, _IO_va_list argptr,
89 MEMCPY (wp, old, wpsize); \
96 size_t s = wpmax * sizeof (CHAR_T); \
97 - wp = (CHAR_T *) extend_alloca (wp, s, \
98 - newsize * sizeof (CHAR_T)); \
99 + wp = (CHAR_T *) extend_alloca (wp, s, newsize); \
100 wpmax = s / sizeof (CHAR_T); \
102 MEMCPY (wp, old, wpsize); \