lol
1From 83a95bd8c8561875b948cadd417c653dbe7ef2e2 Mon Sep 17 00:00:00 2001
2From: Yuliy Pisetsky <ypisetsky@fb.com>
3Date: Thu, 01 Jan 2015 23:36:55 +0000
4Subject: grep -F: fix a heap buffer (read) overrun
5
6grep's read buffer is often filled to its full size, except when
7reading the final buffer of a file. In that case, the number of
8bytes read may be far less than the size of the buffer. However, for
9certain unusual pattern/text combinations, grep -F would mistakenly
10examine bytes in that uninitialized region of memory when searching
11for a match. With carefully chosen inputs, one can cause grep -F to
12read beyond the end of that buffer altogether. This problem arose via
13commit v2.18-90-g73893ff with the introduction of a more efficient
14heuristic using what is now the memchr_kwset function. The use of
15that function in bmexec_trans could leave TP much larger than EP,
16and the subsequent call to bm_delta2_search would mistakenly access
17beyond end of the main input read buffer.
18
19* src/kwset.c (bmexec_trans): When TP reaches or exceeds EP,
20do not call bm_delta2_search.
21* tests/kwset-abuse: New file.
22* tests/Makefile.am (TESTS): Add it.
23* THANKS.in: Update.
24* NEWS (Bug fixes): Mention it.
25
26Prior to this patch, this command would trigger a UMR:
27
28 printf %0360db 0 | valgrind src/grep -F $(printf %019dXb 0)
29
30 Use of uninitialised value of size 8
31 at 0x4142BE: bmexec_trans (kwset.c:657)
32 by 0x4143CA: bmexec (kwset.c:678)
33 by 0x414973: kwsexec (kwset.c:848)
34 by 0x414DC4: Fexecute (kwsearch.c:128)
35 by 0x404E2E: grepbuf (grep.c:1238)
36 by 0x4054BF: grep (grep.c:1417)
37 by 0x405CEB: grepdesc (grep.c:1645)
38 by 0x405EC1: grep_command_line_arg (grep.c:1692)
39 by 0x4077D4: main (grep.c:2570)
40
41See the accompanying test for how to trigger the heap buffer overrun.
42
43Thanks to Nima Aghdaii for testing and finding numerous
44ways to break early iterations of this patch.
45
46Nix: @vcunat restricted this to the runtime code only to avoid needing autoreconfiguration.
47---
48diff --git a/src/kwset.c b/src/kwset.c
49index 4003c8d..376f7c3 100644
50--- a/src/kwset.c
51+++ b/src/kwset.c
52@@ -643,6 +643,8 @@ bmexec_trans (kwset_t kwset, char const *text, size_t size)
53 if (! tp)
54 return -1;
55 tp++;
56+ if (ep <= tp)
57+ break;
58 }
59 }
60 }