fuzzing.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. ========
  2. Fuzzing
  3. ========
  4. This document describes the virtual-device fuzzing infrastructure in QEMU and
  5. how to use it to implement additional fuzzers.
  6. Basics
  7. ------
  8. Fuzzing operates by passing inputs to an entry point/target function. The
  9. fuzzer tracks the code coverage triggered by the input. Based on these
  10. findings, the fuzzer mutates the input and repeats the fuzzing.
  11. To fuzz QEMU, we rely on libfuzzer. Unlike other fuzzers such as AFL, libfuzzer
  12. is an *in-process* fuzzer. For the developer, this means that it is their
  13. responsibility to ensure that state is reset between fuzzing-runs.
  14. Building the fuzzers
  15. --------------------
  16. To build the fuzzers, install a recent version of clang:
  17. Configure with (substitute the clang binaries with the version you installed).
  18. Here, enable-sanitizers, is optional but it allows us to reliably detect bugs
  19. such as out-of-bounds accesses, use-after-frees, double-frees etc.::
  20. CC=clang-8 CXX=clang++-8 /path/to/configure --enable-fuzzing \
  21. --enable-sanitizers
  22. Fuzz targets are built similarly to system targets::
  23. make qemu-fuzz-i386
  24. This builds ``./qemu-fuzz-i386``
  25. The first option to this command is: ``--fuzz-target=FUZZ_NAME``
  26. To list all of the available fuzzers run ``qemu-fuzz-i386`` with no arguments.
  27. For example::
  28. ./qemu-fuzz-i386 --fuzz-target=virtio-scsi-fuzz
  29. Internally, libfuzzer parses all arguments that do not begin with ``"--"``.
  30. Information about these is available by passing ``-help=1``
  31. Now the only thing left to do is wait for the fuzzer to trigger potential
  32. crashes.
  33. Useful libFuzzer flags
  34. ----------------------
  35. As mentioned above, libFuzzer accepts some arguments. Passing ``-help=1`` will
  36. list the available arguments. In particular, these arguments might be helpful:
  37. * ``CORPUS_DIR/`` : Specify a directory as the last argument to libFuzzer.
  38. libFuzzer stores each "interesting" input in this corpus directory. The next
  39. time you run libFuzzer, it will read all of the inputs from the corpus, and
  40. continue fuzzing from there. You can also specify multiple directories.
  41. libFuzzer loads existing inputs from all specified directories, but will only
  42. write new ones to the first one specified.
  43. * ``-max_len=4096`` : specify the maximum byte-length of the inputs libFuzzer
  44. will generate.
  45. * ``-close_fd_mask={1,2,3}`` : close, stderr, or both. Useful for targets that
  46. trigger many debug/error messages, or create output on the serial console.
  47. * ``-jobs=4 -workers=4`` : These arguments configure libFuzzer to run 4 fuzzers in
  48. parallel (4 fuzzing jobs in 4 worker processes). Alternatively, with only
  49. ``-jobs=N``, libFuzzer automatically spawns a number of workers less than or equal
  50. to half the available CPU cores. Replace 4 with a number appropriate for your
  51. machine. Make sure to specify a ``CORPUS_DIR``, which will allow the parallel
  52. fuzzers to share information about the interesting inputs they find.
  53. * ``-use_value_profile=1`` : For each comparison operation, libFuzzer computes
  54. ``(caller_pc&4095) | (popcnt(Arg1 ^ Arg2) << 12)`` and places this in the
  55. coverage table. Useful for targets with "magic" constants. If Arg1 came from
  56. the fuzzer's input and Arg2 is a magic constant, then each time the Hamming
  57. distance between Arg1 and Arg2 decreases, libFuzzer adds the input to the
  58. corpus.
  59. * ``-shrink=1`` : Tries to make elements of the corpus "smaller". Might lead to
  60. better coverage performance, depending on the target.
  61. Note that libFuzzer's exact behavior will depend on the version of
  62. clang and libFuzzer used to build the device fuzzers.
  63. Generating Coverage Reports
  64. ---------------------------
  65. Code coverage is a crucial metric for evaluating a fuzzer's performance.
  66. libFuzzer's output provides a "cov: " column that provides a total number of
  67. unique blocks/edges covered. To examine coverage on a line-by-line basis we
  68. can use Clang coverage:
  69. 1. Configure libFuzzer to store a corpus of all interesting inputs (see
  70. CORPUS_DIR above)
  71. 2. ``./configure`` the QEMU build with ::
  72. --enable-fuzzing \
  73. --extra-cflags="-fprofile-instr-generate -fcoverage-mapping"
  74. 3. Re-run the fuzzer. Specify $CORPUS_DIR/* as an argument, telling libfuzzer
  75. to execute all of the inputs in $CORPUS_DIR and exit. Once the process
  76. exits, you should find a file, "default.profraw" in the working directory.
  77. 4. Execute these commands to generate a detailed HTML coverage-report::
  78. llvm-profdata merge -output=default.profdata default.profraw
  79. llvm-cov show ./path/to/qemu-fuzz-i386 -instr-profile=default.profdata \
  80. --format html -output-dir=/path/to/output/report
  81. Adding a new fuzzer
  82. -------------------
  83. Coverage over virtual devices can be improved by adding additional fuzzers.
  84. Fuzzers are kept in ``tests/qtest/fuzz/`` and should be added to
  85. ``tests/qtest/fuzz/meson.build``
  86. Fuzzers can rely on both qtest and libqos to communicate with virtual devices.
  87. 1. Create a new source file. For example ``tests/qtest/fuzz/foo-device-fuzz.c``.
  88. 2. Write the fuzzing code using the libqtest/libqos API. See existing fuzzers
  89. for reference.
  90. 3. Add the fuzzer to ``tests/qtest/fuzz/meson.build``.
  91. Fuzzers can be more-or-less thought of as special qtest programs which can
  92. modify the qtest commands and/or qtest command arguments based on inputs
  93. provided by libfuzzer. Libfuzzer passes a byte array and length. Commonly the
  94. fuzzer loops over the byte-array interpreting it as a list of qtest commands,
  95. addresses, or values.
  96. The Generic Fuzzer
  97. ------------------
  98. Writing a fuzz target can be a lot of effort (especially if a device driver has
  99. not be built-out within libqos). Many devices can be fuzzed to some degree,
  100. without any device-specific code, using the generic-fuzz target.
  101. The generic-fuzz target is capable of fuzzing devices over their PIO, MMIO,
  102. and DMA input-spaces. To apply the generic-fuzz to a device, we need to define
  103. two env-variables, at minimum:
  104. * ``QEMU_FUZZ_ARGS=`` is the set of QEMU arguments used to configure a machine, with
  105. the device attached. For example, if we want to fuzz the virtio-net device
  106. attached to a pc-i440fx machine, we can specify::
  107. QEMU_FUZZ_ARGS="-M pc -nodefaults -netdev user,id=user0 \
  108. -device virtio-net,netdev=user0"
  109. * ``QEMU_FUZZ_OBJECTS=`` is a set of space-delimited strings used to identify
  110. the MemoryRegions that will be fuzzed. These strings are compared against
  111. MemoryRegion names and MemoryRegion owner names, to decide whether each
  112. MemoryRegion should be fuzzed. These strings support globbing. For the
  113. virtio-net example, we could use one of ::
  114. QEMU_FUZZ_OBJECTS='virtio-net'
  115. QEMU_FUZZ_OBJECTS='virtio*'
  116. QEMU_FUZZ_OBJECTS='virtio* pcspk' # Fuzz the virtio devices and the speaker
  117. QEMU_FUZZ_OBJECTS='*' # Fuzz the whole machine``
  118. The ``"info mtree"`` and ``"info qom-tree"`` monitor commands can be especially
  119. useful for identifying the ``MemoryRegion`` and ``Object`` names used for
  120. matching.
  121. As a generic rule-of-thumb, the more ``MemoryRegions``/Devices we match, the
  122. greater the input-space, and the smaller the probability of finding crashing
  123. inputs for individual devices. As such, it is usually a good idea to limit the
  124. fuzzer to only a few ``MemoryRegions``.
  125. To ensure that these env variables have been configured correctly, we can use::
  126. ./qemu-fuzz-i386 --fuzz-target=generic-fuzz -runs=0
  127. The output should contain a complete list of matched MemoryRegions.
  128. OSS-Fuzz
  129. --------
  130. QEMU is continuously fuzzed on `OSS-Fuzz
  131. <https://github.com/google/oss-fuzz>`_. By default, the OSS-Fuzz build
  132. will try to fuzz every fuzz-target. Since the generic-fuzz target
  133. requires additional information provided in environment variables, we
  134. pre-define some generic-fuzz configs in
  135. ``tests/qtest/fuzz/generic_fuzz_configs.h``. Each config must specify:
  136. - ``.name``: To identify the fuzzer config
  137. - ``.args`` OR ``.argfunc``: A string or pointer to a function returning a
  138. string. These strings are used to specify the ``QEMU_FUZZ_ARGS``
  139. environment variable. ``argfunc`` is useful when the config relies on e.g.
  140. a dynamically created temp directory, or a free tcp/udp port.
  141. - ``.objects``: A string that specifies the ``QEMU_FUZZ_OBJECTS`` environment
  142. variable.
  143. To fuzz additional devices/device configuration on OSS-Fuzz, send patches for
  144. either a new device-specific fuzzer or a new generic-fuzz config.
  145. Build details:
  146. - The Dockerfile that sets up the environment for building QEMU's
  147. fuzzers on OSS-Fuzz can be fund in the OSS-Fuzz repository
  148. __(https://github.com/google/oss-fuzz/blob/master/projects/qemu/Dockerfile)
  149. - The script responsible for building the fuzzers can be found in the
  150. QEMU source tree at ``scripts/oss-fuzz/build.sh``
  151. Building Crash Reproducers
  152. -----------------------------------------
  153. When we find a crash, we should try to create an independent reproducer, that
  154. can be used on a non-fuzzer build of QEMU. This filters out any potential
  155. false-positives, and improves the debugging experience for developers.
  156. Here are the steps for building a reproducer for a crash found by the
  157. generic-fuzz target.
  158. - Ensure the crash reproduces::
  159. qemu-fuzz-i386 --fuzz-target... ./crash-...
  160. - Gather the QTest output for the crash::
  161. QEMU_FUZZ_TIMEOUT=0 QTEST_LOG=1 FUZZ_SERIALIZE_QTEST=1 \
  162. qemu-fuzz-i386 --fuzz-target... ./crash-... &> /tmp/trace
  163. - Reorder and clean-up the resulting trace::
  164. scripts/oss-fuzz/reorder_fuzzer_qtest_trace.py /tmp/trace > /tmp/reproducer
  165. - Get the arguments needed to start qemu, and provide a path to qemu::
  166. less /tmp/trace # The args should be logged at the top of this file
  167. export QEMU_ARGS="-machine ..."
  168. export QEMU_PATH="path/to/qemu-system"
  169. - Ensure the crash reproduces in qemu-system::
  170. $QEMU_PATH $QEMU_ARGS -qtest stdio < /tmp/reproducer
  171. - From the crash output, obtain some string that identifies the crash. This
  172. can be a line in the stack-trace, for example::
  173. export CRASH_TOKEN="hw/usb/hcd-xhci.c:1865"
  174. - Minimize the reproducer::
  175. scripts/oss-fuzz/minimize_qtest_trace.py -M1 -M2 \
  176. /tmp/reproducer /tmp/reproducer-minimized
  177. - Confirm that the minimized reproducer still crashes::
  178. $QEMU_PATH $QEMU_ARGS -qtest stdio < /tmp/reproducer-minimized
  179. - Create a one-liner reproducer that can be sent over email::
  180. ./scripts/oss-fuzz/output_reproducer.py -bash /tmp/reproducer-minimized
  181. - Output the C source code for a test case that will reproduce the bug::
  182. ./scripts/oss-fuzz/output_reproducer.py -owner "John Smith <john@smith.com>"\
  183. -name "test_function_name" /tmp/reproducer-minimized
  184. - Report the bug and send a patch with the C reproducer upstream
  185. Implementation Details / Fuzzer Lifecycle
  186. -----------------------------------------
  187. The fuzzer has two entrypoints that libfuzzer calls. libfuzzer provides it's
  188. own ``main()``, which performs some setup, and calls the entrypoints:
  189. ``LLVMFuzzerInitialize``: called prior to fuzzing. Used to initialize all of the
  190. necessary state
  191. ``LLVMFuzzerTestOneInput``: called for each fuzzing run. Processes the input and
  192. resets the state at the end of each run.
  193. In more detail:
  194. ``LLVMFuzzerInitialize`` parses the arguments to the fuzzer (must start with two
  195. dashes, so they are ignored by libfuzzer ``main()``). Currently, the arguments
  196. select the fuzz target. Then, the qtest client is initialized. If the target
  197. requires qos, qgraph is set up and the QOM/LIBQOS modules are initialized.
  198. Then the QGraph is walked and the QEMU cmd_line is determined and saved.
  199. After this, the ``vl.c:main`` is called to set up the guest. There are
  200. target-specific hooks that can be called before and after main, for
  201. additional setup(e.g. PCI setup, or VM snapshotting).
  202. ``LLVMFuzzerTestOneInput``: Uses qtest/qos functions to act based on the fuzz
  203. input. It is also responsible for manually calling ``main_loop_wait`` to ensure
  204. that bottom halves are executed and any cleanup required before the next input.
  205. Since the same process is reused for many fuzzing runs, QEMU state needs to
  206. be reset at the end of each run. For example, this can be done by rebooting the
  207. VM, after each run.
  208. - *Pros*: Straightforward and fast for simple fuzz targets.
  209. - *Cons*: Depending on the device, does not reset all device state. If the
  210. device requires some initialization prior to being ready for fuzzing (common
  211. for QOS-based targets), this initialization needs to be done after each
  212. reboot.
  213. - *Example target*: ``i440fx-qtest-reboot-fuzz``