diff --git a/Makefile.am b/Makefile.am --- a/Makefile.am +++ b/Makefile.am @@ -230,7 +230,11 @@ dist_noinst_SCRIPTS = autogen.sh -EXTRA_DIST = $(DIST_SHARE) test/functional/test_runner.py test/functional $(DIST_CONTRIB) $(DIST_DOCS) $(WINDOWS_PACKAGING) $(OSX_PACKAGING) $(BIN_CHECKS) +EXTRA_DIST = $(DIST_SHARE) $(DIST_CONTRIB) $(DIST_DOCS) $(WINDOWS_PACKAGING) $(OSX_PACKAGING) $(BIN_CHECKS) + +EXTRA_DIST += \ + test/functional \ + test/fuzz EXTRA_DIST += \ test/util/bitcoin-util-test.py \ diff --git a/doc/fuzzing.md b/doc/fuzzing.md --- a/doc/fuzzing.md +++ b/doc/fuzzing.md @@ -5,6 +5,29 @@ provide an easy entry point for fuzzers and the like. In this document we'll describe how to use it with AFL and libFuzzer. +## Preparing fuzzing + +AFL needs an input directory with examples, and an output directory where it +will place examples that it found. These can be anywhere in the file system, +we'll define environment variables to make it easy to reference them. + +libFuzzer will use the input directory as output directory. + +Extract the example seeds (or other starting inputs) into the inputs +directory before starting fuzzing. + +``` +git clone https://github.com/Bitcoin-ABC/qa-assets +export DIR_FUZZ_IN=$PWD/qa-assets/fuzz_seed_corpus +``` + +Only for AFL: + +``` +mkdir outputs +export AFLOUT=$PWD/outputs +``` + ## AFL ### Building AFL @@ -41,30 +64,14 @@ mode" and "deferred forkserver" can be used. See https://github.com/mcarpenter/afl/tree/master/llvm_mode for details. -### Preparing fuzzing - -AFL needs an input directory with examples, and an output directory where it -will place examples that it found. These can be anywhere in the file system, -we'll define environment variables to make it easy to reference them. - -``` -mkdir inputs -AFLIN=$PWD/inputs -mkdir outputs -AFLOUT=$PWD/outputs -``` - -Example inputs are available from: - -- https://download.visucore.com/bitcoin/bitcoin_fuzzy_in.tar.xz - -Extract these (or other starting inputs) into the `inputs` directory before starting fuzzing. - ### Fuzzing To start the actual fuzzing use: + ``` -$AFLPATH/afl-fuzz -i ${AFLIN} -o ${AFLOUT} -m52 -- src/test/fuzz/fuzz_target_foo +export FUZZ_TARGET=fuzz_target_foo # Pick a fuzz_target +mkdir ${AFLOUT}/${FUZZ_TARGET} +$AFLPATH/afl-fuzz -i ${DIR_FUZZ_IN}/${FUZZ_TARGET} -o ${AFLOUT}/${FUZZ_TARGET} -m52 -- src/test/fuzz/${FUZZ_TARGET} ``` You may have to change a few kernel parameters to test optimally - `afl-fuzz` @@ -75,7 +82,7 @@ A recent version of `clang`, the address sanitizer and libFuzzer is needed (all found in the `compiler-rt` runtime libraries package). -To build the `test/test_bitcoin_fuzzy` executable run +To build all fuzz targets with libFuzzer, run ``` mkdir -p buildFuzzer @@ -93,3 +100,6 @@ See https://llvm.org/docs/LibFuzzer.html#running on how to run the libFuzzer instrumented executable. + +Alternatively run the script in `./test/fuzz/test_runner.py` and provide it +with the `${DIR_FUZZ_IN}` created earlier. diff --git a/src/Makefile.test.include b/src/Makefile.test.include --- a/src/Makefile.test.include +++ b/src/Makefile.test.include @@ -2,7 +2,6 @@ # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. -bin_PROGRAMS += test/test_bitcoin FUZZ_TARGETS = \ test/fuzz/address_deserialize \ @@ -28,6 +27,8 @@ if ENABLE_FUZZ noinst_PROGRAMS += $(FUZZ_TARGETS:=) +else +bin_PROGRAMS += test/test_bitcoin endif TEST_SRCDIR = test diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -17,6 +17,9 @@ if(NOT BUILD_BITCOIN_ZMQ) set(ENABLE_ZMQ_TRUE "#") endif() +if(NOT "fuzzer" IN_LIST ENABLE_SANITIZERS) + set(ENABLE_FUZZ_TRUE "#") +endif() # Create build ini file configure_file(config.ini.in config.ini @ONLY) @@ -28,6 +31,11 @@ function(make_link file) set(src "${CMAKE_CURRENT_SOURCE_DIR}/${file}") set(dest "${CMAKE_CURRENT_BINARY_DIR}/${file}") + + # Create the target directory and parents if needed. + get_filename_component(dest_dir "${dest}" DIRECTORY) + file(MAKE_DIRECTORY "${dest_dir}") + add_custom_command( OUTPUT "${dest}" COMMAND ${CMAKE_COMMAND} -E create_symlink "${src}" "${dest}" @@ -39,12 +47,10 @@ add_custom_target(${NAME} ALL DEPENDS "${dest}") endfunction() -file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/functional/) -file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/util/) - make_link(functional/test_runner.py) make_link(util/bitcoin-util-test.py) make_link(util/rpcauth-test.py) +make_link(fuzz/test_runner.py) macro(add_functional_test_check TARGET COMMENT) add_custom_target(${TARGET} diff --git a/test/config.ini.in b/test/config.ini.in --- a/test/config.ini.in +++ b/test/config.ini.in @@ -16,4 +16,5 @@ @ENABLE_WALLET_TRUE@ENABLE_WALLET=true @BUILD_BITCOIN_UTILS_TRUE@ENABLE_UTILS=true @BUILD_BITCOIND_TRUE@ENABLE_BITCOIND=true +@ENABLE_FUZZ_TRUE@ENABLE_FUZZ=true @ENABLE_ZMQ_TRUE@ENABLE_ZMQ=true diff --git a/test/fuzz/test_runner.py b/test/fuzz/test_runner.py new file mode 100755 --- /dev/null +++ b/test/fuzz/test_runner.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python3 +# Copyright (c) 2019 The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or http://www.opensource.org/licenses/mit-license.php. +"""Run fuzz test targets. +""" + +import argparse +import configparser +import logging +import os +import subprocess +import sys + + +def main(): + parser = argparse.ArgumentParser( + formatter_class=argparse.ArgumentDefaultsHelpFormatter) + parser.add_argument( + "-l", + "--loglevel", + dest="loglevel", + default="INFO", + help="log events at this level and higher to the console. Can be set to DEBUG, INFO, WARNING, ERROR or CRITICAL. Passing --loglevel DEBUG will output all logs to console.", + ) + parser.add_argument( + '--export_coverage', + action='store_true', + help='If true, export coverage information to files in the seed corpus', + ) + parser.add_argument( + 'seed_dir', + help='The seed corpus to run on (must contain subfolders for each fuzz target).', + ) + parser.add_argument( + 'target', + nargs='*', + help='The target(s) to run. Default is to run all targets.', + ) + + args = parser.parse_args() + + # Set up logging + logging.basicConfig( + format='%(message)s', + level=int(args.loglevel) if args.loglevel.isdigit( + ) else args.loglevel.upper(), + ) + + # Read config generated by configure. + config = configparser.ConfigParser() + configfile = os.path.abspath(os.path.dirname(__file__)) + "/../config.ini" + config.read_file(open(configfile, encoding="utf8")) + + if not config["components"].getboolean("ENABLE_FUZZ"): + logging.error("Must have fuzz targets built") + sys.exit(1) + + # Build list of tests + test_list_all = parse_test_list(makefile=os.path.join( + config["environment"]["SRCDIR"], 'src', 'Makefile.test.include')) + + if not test_list_all: + logging.error("No fuzz targets found") + sys.exit(1) + + logging.info("Fuzz targets found: {}".format(test_list_all)) + + # By default run all + args.target = args.target or test_list_all + test_list_error = list(set(args.target).difference(set(test_list_all))) + if test_list_error: + logging.error( + "Unknown fuzz targets selected: {}".format(test_list_error)) + test_list_selection = list( + set(test_list_all).intersection(set(args.target))) + if not test_list_selection: + logging.error("No fuzz targets selected") + logging.info("Fuzz targets selected: {}".format(test_list_selection)) + + try: + help_output = subprocess.run( + args=[ + os.path.join(config["environment"]["BUILDDIR"], + 'src', 'test', 'fuzz', test_list_selection[0]), + '-help=1', + ], + timeout=1, + check=True, + stderr=subprocess.PIPE, + universal_newlines=True, + ).stderr + if "libFuzzer" not in help_output: + logging.error("Must be built with libFuzzer") + sys.exit(1) + except subprocess.TimeoutExpired: + logging.error( + "subprocess timed out: Currently only libFuzzer is supported") + sys.exit(1) + + run_once( + corpus=args.seed_dir, + test_list=test_list_selection, + build_dir=config["environment"]["BUILDDIR"], + export_coverage=args.export_coverage, + ) + + +def run_once(*, corpus, test_list, build_dir, export_coverage): + for t in test_list: + args = [ + os.path.join(build_dir, 'src', 'test', 'fuzz', t), + '-runs=1', + os.path.join(corpus, t), + ] + logging.debug('Run {} with args {}'.format(t, args)) + output = subprocess.run( + args, check=True, stderr=subprocess.PIPE, universal_newlines=True).stderr + logging.debug('Output: {}'.format(output)) + if not export_coverage: + continue + for l in output.splitlines(): + if 'INITED' in l: + with open(os.path.join(corpus, t + '_coverage'), 'w', encoding='utf-8') as cov_file: + cov_file.write(l) + break + + +def parse_test_list(makefile): + with open(makefile, encoding='utf-8') as makefile_test: + test_list_all = [] + read_targets = False + for line in makefile_test.readlines(): + line = line.strip().replace('test/fuzz/', '').replace(' \\', '') + if read_targets: + if not line: + break + test_list_all.append(line) + continue + + if line == 'FUZZ_TARGETS =': + read_targets = True + return test_list_all + + +if __name__ == '__main__': + main()