blob: 684d9def787867e39445cb2290daa9ae40f71a4e [file] [log] [blame]
Kostya Serebryany79677382015-03-31 21:39:38 +00001========================================================
Kostya Serebryany35ce8632015-03-30 23:05:30 +00002LibFuzzer -- a library for coverage-guided fuzz testing.
3========================================================
Kostya Serebryany79677382015-03-31 21:39:38 +00004.. contents::
5 :local:
6 :depth: 4
7
8Introduction
9============
Kostya Serebryany35ce8632015-03-30 23:05:30 +000010
11This library is intended primarily for in-process coverage-guided fuzz testing
12(fuzzing) of other libraries. The typical workflow looks like this:
13
14* Build the Fuzzer library as a static archive (or just a set of .o files).
15 Note that the Fuzzer contains the main() function.
16 Preferably do *not* use sanitizers while building the Fuzzer.
17* Build the library you are going to test with -fsanitize-coverage=[234]
18 and one of the sanitizers. We recommend to build the library in several
19 different modes (e.g. asan, msan, lsan, ubsan, etc) and even using different
20 optimizations options (e.g. -O0, -O1, -O2) to diversify testing.
21* Build a test driver using the same options as the library.
22 The test driver is a C/C++ file containing interesting calls to the library
23 inside a single function ``extern "C" void TestOneInput(const uint8_t *Data, size_t Size);``
24* Link the Fuzzer, the library and the driver together into an executable
25 using the same sanitizer options as for the library.
26* Collect the initial corpus of inputs for the
27 fuzzer (a directory with test inputs, one file per input).
28 The better your inputs are the faster you will find something interesting.
29 Also try to keep your inputs small, otherwise the Fuzzer will run too slow.
30* Run the fuzzer with the test corpus. As new interesting test cases are
31 discovered they will be added to the corpus. If a bug is discovered by
32 the sanitizer (asan, etc) it will be reported as usual and the reproducer
33 will be written to disk.
34 Each Fuzzer process is single-threaded (unless the library starts its own
35 threads). You can run the Fuzzer on the same corpus in multiple processes.
36 in parallel. For run-time options run the Fuzzer binary with '-help=1'.
37
38
Kostya Serebryany79677382015-03-31 21:39:38 +000039The Fuzzer is similar in concept to AFL_,
Kostya Serebryany35ce8632015-03-30 23:05:30 +000040but uses in-process Fuzzing, which is more fragile, more restrictive, but
41potentially much faster as it has no overhead for process start-up.
Kostya Serebryany79677382015-03-31 21:39:38 +000042It uses LLVM's SanitizerCoverage_ instrumentation to get in-process
43coverage-feedback
Kostya Serebryany35ce8632015-03-30 23:05:30 +000044
Kostya Serebryany79677382015-03-31 21:39:38 +000045The code resides in the LLVM repository, requires the fresh Clang compiler to build
46and is used to fuzz various parts of LLVM,
47but the Fuzzer itself does not (and should not) depend on any
48part of LLVM and can be used for other projects w/o requiring the rest of LLVM.
Kostya Serebryany35ce8632015-03-30 23:05:30 +000049
Kostya Serebryany79677382015-03-31 21:39:38 +000050Usage examples
51==============
52
53Toy example
54-----------
55
56A simple function that does something interesting if it receives the input "HI!"::
57
58 cat << EOF >> test_fuzzer.cc
59 extern "C" void TestOneInput(const unsigned char *data, unsigned long size) {
60 if (size > 0 && data[0] == 'H')
61 if (size > 1 && data[1] == 'I')
62 if (size > 2 && data[2] == '!')
63 __builtin_trap();
64 }
65 EOF
66 # Get lib/Fuzzer. Assuming that you already have fresh clang in PATH.
67 svn co http://llvm.org/svn/llvm-project/llvm/trunk/lib/Fuzzer
68 # Build lib/Fuzzer files.
69 clang -c -g -O2 -std=c++11 Fuzzer/*.cpp -IFuzzer
70 # Build test_fuzzer.cc with asan and link against lib/Fuzzer.
71 clang++ -fsanitize=address -fsanitize-coverage=3 test_fuzzer.cc Fuzzer*.o
72 # Run the fuzzer with no corpus.
73 ./a.out
74
75You should get ``Illegal instruction (core dumped)`` pretty quickly.
76
77PCRE2
78-----
79
80Here we show how to use lib/Fuzzer on something real, yet simple: pcre2_::
81
82 COV_FLAGS=" -fsanitize-coverage=4 -mllvm -sanitizer-coverage-8bit-counters=1"
83 # Get PCRE2
84 svn co svn://vcs.exim.org/pcre2/code/trunk pcre
85 # Get lib/Fuzzer. Assuming that you already have fresh clang in PATH.
86 svn co http://llvm.org/svn/llvm-project/llvm/trunk/lib/Fuzzer
87 # Build PCRE2 with AddressSanitizer and coverage.
88 (cd pcre; ./autogen.sh; CC="clang -fsanitize=address $COV_FLAGS" ./configure --prefix=`pwd`/../inst && make -j && make install)
89 # Build lib/Fuzzer files.
90 clang -c -g -O2 -std=c++11 Fuzzer/*.cpp -IFuzzer
91 # Build the the actual function that does something interesting with PCRE2.
92 cat << EOF > pcre_fuzzer.cc
93 #include <string.h>
94 #include "pcre2posix.h"
95 extern "C" void TestOneInput(const unsigned char *data, size_t size) {
96 if (size < 1) return;
97 char *str = new char[size+1];
98 memcpy(str, data, size);
99 str[size] = 0;
100 regex_t preg;
101 if (0 == regcomp(&preg, str, 0)) {
102 regexec(&preg, str, 0, 0, 0);
103 regfree(&preg);
104 }
105 delete [] str;
106 }
107 EOF
108 clang++ -g -fsanitize=address $COV_FLAGS -c -std=c++11 -I inst/include/ pcre_fuzzer.cc
109 # Link.
110 clang++ -g -fsanitize=address -Wl,--whole-archive inst/lib/*.a -Wl,-no-whole-archive Fuzzer*.o pcre_fuzzer.o -o pcre_fuzzer
111
112This will give you a binary of the fuzzer, called ``pcre_fuzzer``.
113Now, create a directory that will hold the test corpus::
114
115 mkdir -p CORPUS
116
117For simple input languages like regular expressions this is all you need.
118For more complicated inputs populate the directory with some input samples.
119Now run the fuzzer with the corpus dir as the only parameter::
120
121 ./pcre_fuzzer ./CORPUS
122
123You will see output like this::
124
125 Seed: 1876794929
126 #0 READ cov 0 bits 0 units 1 exec/s 0
127 #1 pulse cov 3 bits 0 units 1 exec/s 0
128 #1 INITED cov 3 bits 0 units 1 exec/s 0
129 #2 pulse cov 208 bits 0 units 1 exec/s 0
130 #2 NEW cov 208 bits 0 units 2 exec/s 0 L: 64
131 #3 NEW cov 217 bits 0 units 3 exec/s 0 L: 63
132 #4 pulse cov 217 bits 0 units 3 exec/s 0
133
134* The ``Seed:`` line shows you the current random seed (you can change it with ``-seed=N`` flag).
135* The ``READ`` line shows you how many input files were read (since you passed an empty dir there were inputs, but one dummy input was synthesised).
136* The ``INITED`` line shows you that how many inputs will be fuzzed.
137* The ``NEW`` lines appear with the fuzzer finds a new interesting input, which is saved to the CORPUS dir. If multiple corpus dirs are given, the first one is used.
138* The ``pulse`` lines appear periodically to show the current status.
139
140Now, interrupt the fuzzer and run it again the same way. You will see::
141
142 Seed: 1879995378
143 #0 READ cov 0 bits 0 units 564 exec/s 0
144 #1 pulse cov 502 bits 0 units 564 exec/s 0
145 ...
146 #512 pulse cov 2933 bits 0 units 564 exec/s 512
147 #564 INITED cov 2991 bits 0 units 344 exec/s 564
148 #1024 pulse cov 2991 bits 0 units 344 exec/s 1024
149 #1455 NEW cov 2995 bits 0 units 345 exec/s 1455 L: 49
150
151This time you were running the fuzzer with a non-empty input corpus (564 items).
152As the first step, the fuzzer minimized the set to produce 344 interesting items (the ``INITED`` line)
153
154You may run ``N`` independent fuzzer jobs in parallel on ``M`` CPUs::
155
156 N=100; M=4; ./pcre_fuzzer ./CORPUS -jobs=$N -workers=$M
157
158This is useful when you already have an exhaustive test corpus.
159If you've just started fuzzing with no good corpus running independent
160jobs will create a corpus with too many duplicates.
161One way to avoid this and still use all of your CPUs is to use the flag ``-exit_on_first=1``
162which will cause the fuzzer to exit on the first new synthesised input::
163
164 N=100; M=4; ./pcre_fuzzer ./CORPUS -jobs=$N -workers=$M -exit_on_first=1
165
Kostya Serebryany043ab1c2015-04-01 21:33:20 +0000166Advanced features
167=================
168
169Tokens
170------
171
172By default, the fuzzer is not aware of complexities of the input language
173and when fuzzing e.g. a C++ parser it will mostly stress the lexer.
174It is very hard for the fuzzer to come up with something like ``reinterpret_cast<int>``
175from a test corpus that doesn't have it.
176See a detailed discussion of this topic at
177http://lcamtuf.blogspot.com/2015/01/afl-fuzz-making-up-grammar-with.html.
178
179lib/Fuzzer implements a simple technique that allows to fuzz input languages with
180long tokens. All you need is to prepare a text file containing up to 253 tokens, one token per line,
181and pass it to the fuzzer as ``-tokens=TOKENS_FILE.txt``.
182Three implicit tokens are added: ``" "``, ``"\t"``, and ``"\n"``.
183The fuzzer itself will still be mutating a string of bytes
184but before passing this input to the target library it will replace every byte ``b`` with the ``b``-th token.
185If there are less than ``b`` tokens, a space will be added instead.
186
Kostya Serebryany79677382015-03-31 21:39:38 +0000187
188Fuzzing components of LLVM
189==========================
Kostya Serebryany35ce8632015-03-30 23:05:30 +0000190
191clang-format-fuzzer
192-------------------
193The inputs are random pieces of C++-like text.
194
195Build (make sure to use fresh clang as the host compiler)::
196
197 cmake -GNinja -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ -DLLVM_USE_SANITIZER=Address -DLLVM_USE_SANITIZE_COVERAGE=YES -DCMAKE_BUILD_TYPE=Release /path/to/llvm
198 ninja clang-format-fuzzer
199 mkdir CORPUS_DIR
200 ./bin/clang-format-fuzzer CORPUS_DIR
201
202Optionally build other kinds of binaries (asan+Debug, msan, ubsan, etc).
203
204TODO: commit the pre-fuzzed corpus to svn (?).
205
Kostya Serebryany79677382015-03-31 21:39:38 +0000206Tracking bug: https://llvm.org/bugs/show_bug.cgi?id=23052
Kostya Serebryany35ce8632015-03-30 23:05:30 +0000207
Kostya Serebryany79677382015-03-31 21:39:38 +0000208clang-fuzzer
209------------
Kostya Serebryany35ce8632015-03-30 23:05:30 +0000210
Kostya Serebryany79677382015-03-31 21:39:38 +0000211The default behavior is very similar to ``clang-format-fuzzer``.
Kostya Serebryany043ab1c2015-04-01 21:33:20 +0000212Clang can also be fuzzed with Tokens_ using ``-tokens=$LLVM/lib/Fuzzer/cxx_fuzzer_tokens.txt`` option.
Kostya Serebryany79677382015-03-31 21:39:38 +0000213
214Tracking bug: https://llvm.org/bugs/show_bug.cgi?id=23057
Kostya Serebryany35ce8632015-03-30 23:05:30 +0000215
216FAQ
217=========================
218
219Q. Why Fuzzer does not use any of the LLVM support?
220---------------------------------------------------
221
222There are two reasons.
223
224First, we want this library to be used outside of the LLVM w/o users having to
225build the rest of LLVM. This may sound unconvincing for many LLVM folks,
226but in practice the need for building the whole LLVM frightens many potential
227users -- and we want more users to use this code.
228
229Second, there is a subtle technical reason not to rely on the rest of LLVM, or
230any other large body of code (maybe not even STL). When coverage instrumentation
231is enabled, it will also instrument the LLVM support code which will blow up the
232coverage set of the process (since the fuzzer is in-process). In other words, by
233using more external dependencies we will slow down the fuzzer while the main
234reason for it to exist is extreme speed.
235
236Q. What about Windows then? The Fuzzer contains code that does not build on Windows.
237------------------------------------------------------------------------------------
238
239The sanitizer coverage support does not work on Windows either as of 01/2015.
240Once it's there, we'll need to re-implement OS-specific parts (I/O, signals).
241
242Q. When this Fuzzer is not a good solution for a problem?
243---------------------------------------------------------
244
245* If the test inputs are validated by the target library and the validator
246 asserts/crashes on invalid inputs, the in-process fuzzer is not applicable
247 (we could use fork() w/o exec, but it comes with extra overhead).
248* Bugs in the target library may accumulate w/o being detected. E.g. a memory
249 corruption that goes undetected at first and then leads to a crash while
250 testing another input. This is why it is highly recommended to run this
251 in-process fuzzer with all sanitizers to detect most bugs on the spot.
252* It is harder to protect the in-process fuzzer from excessive memory
253 consumption and infinite loops in the target library (still possible).
254* The target library should not have significant global state that is not
255 reset between the runs.
256* Many interesting target libs are not designed in a way that supports
257 the in-process fuzzer interface (e.g. require a file path instead of a
258 byte array).
259* If a single test run takes a considerable fraction of a second (or
260 more) the speed benefit from the in-process fuzzer is negligible.
261* If the target library runs persistent threads (that outlive
262 execution of one test) the fuzzing results will be unreliable.
263
264Q. So, what exactly this Fuzzer is good for?
265--------------------------------------------
266
267This Fuzzer might be a good choice for testing libraries that have relatively
268small inputs, each input takes < 1ms to run, and the library code is not expected
269to crash on invalid inputs.
270Examples: regular expression matchers, text or binary format parsers.
271
Kostya Serebryany79677382015-03-31 21:39:38 +0000272.. _pcre2: http://www.pcre.org/
273
274.. _AFL: http://lcamtuf.coredump.cx/afl/
275
276.. _SanitizerCoverage: https://code.google.com/p/address-sanitizer/wiki/AsanCoverage