LibFuzzer.rst 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. ========================================================
  2. LibFuzzer -- a library for coverage-guided fuzz testing.
  3. ========================================================
  4. .. contents::
  5. :local:
  6. :depth: 4
  7. Introduction
  8. ============
  9. This library is intended primarily for in-process coverage-guided fuzz testing
  10. (fuzzing) of other libraries. The typical workflow looks like this:
  11. * Build the Fuzzer library as a static archive (or just a set of .o files).
  12. Note that the Fuzzer contains the main() function.
  13. Preferably do *not* use sanitizers while building the Fuzzer.
  14. * Build the library you are going to test with
  15. `-fsanitize-coverage={bb,edge}[,indirect-calls,8bit-counters]`
  16. and one of the sanitizers. We recommend to build the library in several
  17. different modes (e.g. asan, msan, lsan, ubsan, etc) and even using different
  18. optimizations options (e.g. -O0, -O1, -O2) to diversify testing.
  19. * Build a test driver using the same options as the library.
  20. The test driver is a C/C++ file containing interesting calls to the library
  21. inside a single function ``extern "C" void LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size);``
  22. * Link the Fuzzer, the library and the driver together into an executable
  23. using the same sanitizer options as for the library.
  24. * Collect the initial corpus of inputs for the
  25. fuzzer (a directory with test inputs, one file per input).
  26. The better your inputs are the faster you will find something interesting.
  27. Also try to keep your inputs small, otherwise the Fuzzer will run too slow.
  28. By default, the Fuzzer limits the size of every input to 64 bytes
  29. (use ``-max_len=N`` to override).
  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.
  37. The Fuzzer is similar in concept to AFL_,
  38. but uses in-process Fuzzing, which is more fragile, more restrictive, but
  39. potentially much faster as it has no overhead for process start-up.
  40. It uses LLVM's SanitizerCoverage_ instrumentation to get in-process
  41. coverage-feedback
  42. The code resides in the LLVM repository, requires the fresh Clang compiler to build
  43. and is used to fuzz various parts of LLVM,
  44. but the Fuzzer itself does not (and should not) depend on any
  45. part of LLVM and can be used for other projects w/o requiring the rest of LLVM.
  46. Flags
  47. =====
  48. The most important flags are::
  49. seed 0 Random seed. If 0, seed is generated.
  50. runs -1 Number of individual test runs (-1 for infinite runs).
  51. max_len 64 Maximum length of the test input.
  52. cross_over 1 If 1, cross over inputs.
  53. mutate_depth 5 Apply this number of consecutive mutations to each input.
  54. timeout 1200 Timeout in seconds (if positive). If one unit runs more than this number of seconds the process will abort.
  55. help 0 Print help.
  56. save_minimized_corpus 0 If 1, the minimized corpus is saved into the first input directory
  57. jobs 0 Number of jobs to run. If jobs >= 1 we spawn this number of jobs in separate worker processes with stdout/stderr redirected to fuzz-JOB.log.
  58. workers 0 Number of simultaneous worker processes to run the jobs. If zero, "min(jobs,NumberOfCpuCores()/2)" is used.
  59. tokens 0 Use the file with tokens (one token per line) to fuzz a token based input language.
  60. apply_tokens 0 Read the given input file, substitute bytes with tokens and write the result to stdout.
  61. sync_command 0 Execute an external command "<sync_command> <test_corpus>" to synchronize the test corpus.
  62. sync_timeout 600 Minimum timeout between syncs.
  63. For the full list of flags run the fuzzer binary with ``-help=1``.
  64. Usage examples
  65. ==============
  66. Toy example
  67. -----------
  68. A simple function that does something interesting if it receives the input "HI!"::
  69. cat << EOF >> test_fuzzer.cc
  70. extern "C" void LLVMFuzzerTestOneInput(const unsigned char *data, unsigned long size) {
  71. if (size > 0 && data[0] == 'H')
  72. if (size > 1 && data[1] == 'I')
  73. if (size > 2 && data[2] == '!')
  74. __builtin_trap();
  75. }
  76. EOF
  77. # Get lib/Fuzzer. Assuming that you already have fresh clang in PATH.
  78. svn co http://llvm.org/svn/llvm-project/llvm/trunk/lib/Fuzzer
  79. # Build lib/Fuzzer files.
  80. clang -c -g -O2 -std=c++11 Fuzzer/*.cpp -IFuzzer
  81. # Build test_fuzzer.cc with asan and link against lib/Fuzzer.
  82. clang++ -fsanitize=address -fsanitize-coverage=edge test_fuzzer.cc Fuzzer*.o
  83. # Run the fuzzer with no corpus.
  84. ./a.out
  85. You should get ``Illegal instruction (core dumped)`` pretty quickly.
  86. PCRE2
  87. -----
  88. Here we show how to use lib/Fuzzer on something real, yet simple: pcre2_::
  89. COV_FLAGS=" -fsanitize-coverage=edge,indirect-calls,8bit-counters"
  90. # Get PCRE2
  91. svn co svn://vcs.exim.org/pcre2/code/trunk pcre
  92. # Get lib/Fuzzer. Assuming that you already have fresh clang in PATH.
  93. svn co http://llvm.org/svn/llvm-project/llvm/trunk/lib/Fuzzer
  94. # Build PCRE2 with AddressSanitizer and coverage.
  95. (cd pcre; ./autogen.sh; CC="clang -fsanitize=address $COV_FLAGS" ./configure --prefix=`pwd`/../inst && make -j && make install)
  96. # Build lib/Fuzzer files.
  97. clang -c -g -O2 -std=c++11 Fuzzer/*.cpp -IFuzzer
  98. # Build the actual function that does something interesting with PCRE2.
  99. cat << EOF > pcre_fuzzer.cc
  100. #include <string.h>
  101. #include "pcre2posix.h"
  102. extern "C" void LLVMFuzzerTestOneInput(const unsigned char *data, size_t size) {
  103. if (size < 1) return;
  104. char *str = new char[size+1];
  105. memcpy(str, data, size);
  106. str[size] = 0;
  107. regex_t preg;
  108. if (0 == regcomp(&preg, str, 0)) {
  109. regexec(&preg, str, 0, 0, 0);
  110. regfree(&preg);
  111. }
  112. delete [] str;
  113. }
  114. EOF
  115. clang++ -g -fsanitize=address $COV_FLAGS -c -std=c++11 -I inst/include/ pcre_fuzzer.cc
  116. # Link.
  117. clang++ -g -fsanitize=address -Wl,--whole-archive inst/lib/*.a -Wl,-no-whole-archive Fuzzer*.o pcre_fuzzer.o -o pcre_fuzzer
  118. This will give you a binary of the fuzzer, called ``pcre_fuzzer``.
  119. Now, create a directory that will hold the test corpus::
  120. mkdir -p CORPUS
  121. For simple input languages like regular expressions this is all you need.
  122. For more complicated inputs populate the directory with some input samples.
  123. Now run the fuzzer with the corpus dir as the only parameter::
  124. ./pcre_fuzzer ./CORPUS
  125. You will see output like this::
  126. Seed: 1876794929
  127. #0 READ cov 0 bits 0 units 1 exec/s 0
  128. #1 pulse cov 3 bits 0 units 1 exec/s 0
  129. #1 INITED cov 3 bits 0 units 1 exec/s 0
  130. #2 pulse cov 208 bits 0 units 1 exec/s 0
  131. #2 NEW cov 208 bits 0 units 2 exec/s 0 L: 64
  132. #3 NEW cov 217 bits 0 units 3 exec/s 0 L: 63
  133. #4 pulse cov 217 bits 0 units 3 exec/s 0
  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. Now, interrupt the fuzzer and run it again the same way. You will see::
  140. Seed: 1879995378
  141. #0 READ cov 0 bits 0 units 564 exec/s 0
  142. #1 pulse cov 502 bits 0 units 564 exec/s 0
  143. ...
  144. #512 pulse cov 2933 bits 0 units 564 exec/s 512
  145. #564 INITED cov 2991 bits 0 units 344 exec/s 564
  146. #1024 pulse cov 2991 bits 0 units 344 exec/s 1024
  147. #1455 NEW cov 2995 bits 0 units 345 exec/s 1455 L: 49
  148. This time you were running the fuzzer with a non-empty input corpus (564 items).
  149. As the first step, the fuzzer minimized the set to produce 344 interesting items (the ``INITED`` line)
  150. It is quite convenient to store test corpuses in git.
  151. As an example, here is a git repository with test inputs for the above PCRE2 fuzzer::
  152. git clone https://github.com/kcc/fuzzing-with-sanitizers.git
  153. ./pcre_fuzzer ./fuzzing-with-sanitizers/pcre2/C1/
  154. You may run ``N`` independent fuzzer jobs in parallel on ``M`` CPUs::
  155. N=100; M=4; ./pcre_fuzzer ./CORPUS -jobs=$N -workers=$M
  156. By default (``-reload=1``) the fuzzer processes will periodically scan the CORPUS directory
  157. and reload any new tests. This way the test inputs found by one process will be picked up
  158. by all others.
  159. If ``-workers=$M`` is not supplied, ``min($N,NumberOfCpuCore/2)`` will be used.
  160. Heartbleed
  161. ----------
  162. Remember Heartbleed_?
  163. As it was recently `shown <https://blog.hboeck.de/archives/868-How-Heartbleed-couldve-been-found.html>`_,
  164. fuzzing with AddressSanitizer can find Heartbleed. Indeed, here are the step-by-step instructions
  165. to find Heartbleed with LibFuzzer::
  166. wget https://www.openssl.org/source/openssl-1.0.1f.tar.gz
  167. tar xf openssl-1.0.1f.tar.gz
  168. COV_FLAGS="-fsanitize-coverage=edge,indirect-calls" # -fsanitize-coverage=8bit-counters
  169. (cd openssl-1.0.1f/ && ./config &&
  170. make -j 32 CC="clang -g -fsanitize=address $COV_FLAGS")
  171. # Get and build LibFuzzer
  172. svn co http://llvm.org/svn/llvm-project/llvm/trunk/lib/Fuzzer
  173. clang -c -g -O2 -std=c++11 Fuzzer/*.cpp -IFuzzer
  174. # Get examples of key/pem files.
  175. git clone https://github.com/hannob/selftls
  176. cp selftls/server* . -v
  177. cat << EOF > handshake-fuzz.cc
  178. #include <openssl/ssl.h>
  179. #include <openssl/err.h>
  180. #include <assert.h>
  181. SSL_CTX *sctx;
  182. int Init() {
  183. SSL_library_init();
  184. SSL_load_error_strings();
  185. ERR_load_BIO_strings();
  186. OpenSSL_add_all_algorithms();
  187. assert (sctx = SSL_CTX_new(TLSv1_method()));
  188. assert (SSL_CTX_use_certificate_file(sctx, "server.pem", SSL_FILETYPE_PEM));
  189. assert (SSL_CTX_use_PrivateKey_file(sctx, "server.key", SSL_FILETYPE_PEM));
  190. return 0;
  191. }
  192. extern "C" void LLVMFuzzerTestOneInput(unsigned char *Data, size_t Size) {
  193. static int unused = Init();
  194. SSL *server = SSL_new(sctx);
  195. BIO *sinbio = BIO_new(BIO_s_mem());
  196. BIO *soutbio = BIO_new(BIO_s_mem());
  197. SSL_set_bio(server, sinbio, soutbio);
  198. SSL_set_accept_state(server);
  199. BIO_write(sinbio, Data, Size);
  200. SSL_do_handshake(server);
  201. SSL_free(server);
  202. }
  203. EOF
  204. # Build the fuzzer.
  205. clang++ -g handshake-fuzz.cc -fsanitize=address \
  206. openssl-1.0.1f/libssl.a openssl-1.0.1f/libcrypto.a Fuzzer*.o
  207. # Run 20 independent fuzzer jobs.
  208. ./a.out -jobs=20 -workers=20
  209. Voila::
  210. #1048576 pulse cov 3424 bits 0 units 9 exec/s 24385
  211. =================================================================
  212. ==17488==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x629000004748 at pc 0x00000048c979 bp 0x7fffe3e864f0 sp 0x7fffe3e85ca8
  213. READ of size 60731 at 0x629000004748 thread T0
  214. #0 0x48c978 in __asan_memcpy
  215. #1 0x4db504 in tls1_process_heartbeat openssl-1.0.1f/ssl/t1_lib.c:2586:3
  216. #2 0x580be3 in ssl3_read_bytes openssl-1.0.1f/ssl/s3_pkt.c:1092:4
  217. Advanced features
  218. =================
  219. Tokens
  220. ------
  221. By default, the fuzzer is not aware of complexities of the input language
  222. and when fuzzing e.g. a C++ parser it will mostly stress the lexer.
  223. It is very hard for the fuzzer to come up with something like ``reinterpret_cast<int>``
  224. from a test corpus that doesn't have it.
  225. See a detailed discussion of this topic at
  226. http://lcamtuf.blogspot.com/2015/01/afl-fuzz-making-up-grammar-with.html.
  227. lib/Fuzzer implements a simple technique that allows to fuzz input languages with
  228. long tokens. All you need is to prepare a text file containing up to 253 tokens, one token per line,
  229. and pass it to the fuzzer as ``-tokens=TOKENS_FILE.txt``.
  230. Three implicit tokens are added: ``" "``, ``"\t"``, and ``"\n"``.
  231. The fuzzer itself will still be mutating a string of bytes
  232. but before passing this input to the target library it will replace every byte ``b`` with the ``b``-th token.
  233. If there are less than ``b`` tokens, a space will be added instead.
  234. AFL compatibility
  235. -----------------
  236. LibFuzzer can be used in parallel with AFL_ on the same test corpus.
  237. Both fuzzers expect the test corpus to reside in a directory, one file per input.
  238. You can run both fuzzers on the same corpus in parallel::
  239. ./afl-fuzz -i testcase_dir -o findings_dir /path/to/program -r @@
  240. ./llvm-fuzz testcase_dir findings_dir # Will write new tests to testcase_dir
  241. Periodically restart both fuzzers so that they can use each other's findings.
  242. How good is my fuzzer?
  243. ----------------------
  244. Once you implement your target function ``LLVMFuzzerTestOneInput`` and fuzz it to death,
  245. you will want to know whether the function or the corpus can be improved further.
  246. One easy to use metric is, of course, code coverage.
  247. You can get the coverage for your corpus like this::
  248. ASAN_OPTIONS=coverage_pcs=1 ./fuzzer CORPUS_DIR -runs=0
  249. This will run all the tests in the CORPUS_DIR but will not generate any new tests
  250. and dump covered PCs to disk before exiting.
  251. Then you can subtract the set of covered PCs from the set of all instrumented PCs in the binary,
  252. see SanitizerCoverage_ for details.
  253. User-supplied mutators
  254. ----------------------
  255. LibFuzzer allows to use custom (user-supplied) mutators,
  256. see FuzzerInterface.h_
  257. Fuzzing components of LLVM
  258. ==========================
  259. clang-format-fuzzer
  260. -------------------
  261. The inputs are random pieces of C++-like text.
  262. Build (make sure to use fresh clang as the host compiler)::
  263. 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
  264. ninja clang-format-fuzzer
  265. mkdir CORPUS_DIR
  266. ./bin/clang-format-fuzzer CORPUS_DIR
  267. Optionally build other kinds of binaries (asan+Debug, msan, ubsan, etc).
  268. TODO: commit the pre-fuzzed corpus to svn (?).
  269. Tracking bug: https://llvm.org/bugs/show_bug.cgi?id=23052
  270. clang-fuzzer
  271. ------------
  272. The default behavior is very similar to ``clang-format-fuzzer``.
  273. Clang can also be fuzzed with Tokens_ using ``-tokens=$LLVM/lib/Fuzzer/cxx_fuzzer_tokens.txt`` option.
  274. Tracking bug: https://llvm.org/bugs/show_bug.cgi?id=23057
  275. Buildbot
  276. --------
  277. We have a buildbot that runs the above fuzzers for LLVM components
  278. 24/7/365 at http://lab.llvm.org:8011/builders/sanitizer-x86_64-linux-fuzzer .
  279. Pre-fuzzed test inputs in git
  280. -----------------------------
  281. The buildbot occumulates large test corpuses over time.
  282. The corpuses are stored in git on github and can be used like this::
  283. git clone https://github.com/kcc/fuzzing-with-sanitizers.git
  284. bin/clang-format-fuzzer fuzzing-with-sanitizers/llvm/clang-format/C1
  285. bin/clang-fuzzer fuzzing-with-sanitizers/llvm/clang/C1/
  286. bin/clang-fuzzer fuzzing-with-sanitizers/llvm/clang/TOK1 -tokens=$LLVM/llvm/lib/Fuzzer/cxx_fuzzer_tokens.txt
  287. FAQ
  288. =========================
  289. Q. Why Fuzzer does not use any of the LLVM support?
  290. ---------------------------------------------------
  291. There are two reasons.
  292. First, we want this library to be used outside of the LLVM w/o users having to
  293. build the rest of LLVM. This may sound unconvincing for many LLVM folks,
  294. but in practice the need for building the whole LLVM frightens many potential
  295. users -- and we want more users to use this code.
  296. Second, there is a subtle technical reason not to rely on the rest of LLVM, or
  297. any other large body of code (maybe not even STL). When coverage instrumentation
  298. is enabled, it will also instrument the LLVM support code which will blow up the
  299. coverage set of the process (since the fuzzer is in-process). In other words, by
  300. using more external dependencies we will slow down the fuzzer while the main
  301. reason for it to exist is extreme speed.
  302. Q. What about Windows then? The Fuzzer contains code that does not build on Windows.
  303. ------------------------------------------------------------------------------------
  304. The sanitizer coverage support does not work on Windows either as of 01/2015.
  305. Once it's there, we'll need to re-implement OS-specific parts (I/O, signals).
  306. Q. When this Fuzzer is not a good solution for a problem?
  307. ---------------------------------------------------------
  308. * If the test inputs are validated by the target library and the validator
  309. asserts/crashes on invalid inputs, the in-process fuzzer is not applicable
  310. (we could use fork() w/o exec, but it comes with extra overhead).
  311. * Bugs in the target library may accumulate w/o being detected. E.g. a memory
  312. corruption that goes undetected at first and then leads to a crash while
  313. testing another input. This is why it is highly recommended to run this
  314. in-process fuzzer with all sanitizers to detect most bugs on the spot.
  315. * It is harder to protect the in-process fuzzer from excessive memory
  316. consumption and infinite loops in the target library (still possible).
  317. * The target library should not have significant global state that is not
  318. reset between the runs.
  319. * Many interesting target libs are not designed in a way that supports
  320. the in-process fuzzer interface (e.g. require a file path instead of a
  321. byte array).
  322. * If a single test run takes a considerable fraction of a second (or
  323. more) the speed benefit from the in-process fuzzer is negligible.
  324. * If the target library runs persistent threads (that outlive
  325. execution of one test) the fuzzing results will be unreliable.
  326. Q. So, what exactly this Fuzzer is good for?
  327. --------------------------------------------
  328. This Fuzzer might be a good choice for testing libraries that have relatively
  329. small inputs, each input takes < 1ms to run, and the library code is not expected
  330. to crash on invalid inputs.
  331. Examples: regular expression matchers, text or binary format parsers.
  332. .. _pcre2: http://www.pcre.org/
  333. .. _AFL: http://lcamtuf.coredump.cx/afl/
  334. .. _SanitizerCoverage: http://clang.llvm.org/docs/SanitizerCoverage.html
  335. .. _Heartbleed: http://en.wikipedia.org/wiki/Heartbleed
  336. .. _FuzzerInterface.h: https://github.com/llvm-mirror/llvm/blob/master/lib/Fuzzer/FuzzerInterface.h