···11+From 83a95bd8c8561875b948cadd417c653dbe7ef2e2 Mon Sep 17 00:00:00 2001
22+From: Yuliy Pisetsky <ypisetsky@fb.com>
33+Date: Thu, 01 Jan 2015 23:36:55 +0000
44+Subject: grep -F: fix a heap buffer (read) overrun
55+66+grep's read buffer is often filled to its full size, except when
77+reading the final buffer of a file. In that case, the number of
88+bytes read may be far less than the size of the buffer. However, for
99+certain unusual pattern/text combinations, grep -F would mistakenly
1010+examine bytes in that uninitialized region of memory when searching
1111+for a match. With carefully chosen inputs, one can cause grep -F to
1212+read beyond the end of that buffer altogether. This problem arose via
1313+commit v2.18-90-g73893ff with the introduction of a more efficient
1414+heuristic using what is now the memchr_kwset function. The use of
1515+that function in bmexec_trans could leave TP much larger than EP,
1616+and the subsequent call to bm_delta2_search would mistakenly access
1717+beyond end of the main input read buffer.
1818+1919+* src/kwset.c (bmexec_trans): When TP reaches or exceeds EP,
2020+do not call bm_delta2_search.
2121+* tests/kwset-abuse: New file.
2222+* tests/Makefile.am (TESTS): Add it.
2323+* THANKS.in: Update.
2424+* NEWS (Bug fixes): Mention it.
2525+2626+Prior to this patch, this command would trigger a UMR:
2727+2828+ printf %0360db 0 | valgrind src/grep -F $(printf %019dXb 0)
2929+3030+ Use of uninitialised value of size 8
3131+ at 0x4142BE: bmexec_trans (kwset.c:657)
3232+ by 0x4143CA: bmexec (kwset.c:678)
3333+ by 0x414973: kwsexec (kwset.c:848)
3434+ by 0x414DC4: Fexecute (kwsearch.c:128)
3535+ by 0x404E2E: grepbuf (grep.c:1238)
3636+ by 0x4054BF: grep (grep.c:1417)
3737+ by 0x405CEB: grepdesc (grep.c:1645)
3838+ by 0x405EC1: grep_command_line_arg (grep.c:1692)
3939+ by 0x4077D4: main (grep.c:2570)
4040+4141+See the accompanying test for how to trigger the heap buffer overrun.
4242+4343+Thanks to Nima Aghdaii for testing and finding numerous
4444+ways to break early iterations of this patch.
4545+4646+Nix: @vcunat restricted this to the runtime code only to avoid needing autoreconfiguration.
4747+---
4848+diff --git a/src/kwset.c b/src/kwset.c
4949+index 4003c8d..376f7c3 100644
5050+--- a/src/kwset.c
5151++++ b/src/kwset.c
5252+@@ -643,6 +643,8 @@ bmexec_trans (kwset_t kwset, char const *text, size_t size)
5353+ if (! tp)
5454+ return -1;
5555+ tp++;
5656++ if (ep <= tp)
5757++ break;
5858+ }
5959+ }
6060+ }