bughunt

Fuzz

bughunt fuzz finds the fuzz targets a repo already has, in whatever languages it has them, runs each one, and reports any that crash, hang or break a promise.

bughunt fuzz ~/code/parser                 # 60 seconds per target
bughunt fuzz ~/code/parser --seconds 600
bughunt fuzz ~/code/parser --only python,go

What it finds and runs

There is no layout to adopt. bughunt looks for what a harness for each fuzzer contains.

LanguageFuzzerA target is
Rustcargo-fuzzfuzz/Cargo.toml, the cargo-fuzz layout
Gobuilt infunc Fuzz… in a _test.go file
PythonAtherisa file that calls atheris.Setup(
JavaScript and TypeScriptJazzer.jsa .js, .mjs, .cjs or .ts file with "fuzz" in its path that exports fuzz
RubyRuzzya file that calls Ruzzy.trace( (it names the harness)
JavaJazzera class with fuzzerTestOneInput
C and C++libFuzzera file with LLVMFuzzerTestOneInput
PHPPHP-Fuzzera file that calls $config->setTarget(
anything elseyoursa command in bughunt.toml: see your own fuzzer

A repo with targets in several languages has all of them run. Every runner is proven on each change against the real fuzzer, on an example with one sound target that must come out clean and one planted bug that must be found.

A target in each language

Rust: a target, and what to install

cargo install cargo-fuzz and rustup toolchain install nightly

#![no_main]
use libfuzzer_sys::fuzz_target;

fuzz_target!(|data: &[u8]| {
    // A promise, not just "did not crash":
    assert_eq!(shop::decode(&shop::encode(data)).as_deref(), Some(data));
});
Go: a target, and what to install

Install Go.

func FuzzRoundTrip(f *testing.F) {
    f.Add([]byte("order 41"))                 // a real example to start from
    f.Fuzz(func(t *testing.T, data []byte) {
        back, err := Decode(Encode(data))
        if err != nil || !bytes.Equal(back, data) {
            t.Fatalf("%q does not round-trip", data)
        }
    })
}
Python: a target, and what to install

pip install atheris. Point BUGHUNT_PYTHON at the Python that has it, if that is not python3.

import sys
import atheris

with atheris.instrument_imports():
    import shop

def TestOneInput(data: bytes) -> None:
    assert shop.decode(shop.encode(data)) == data

if __name__ == "__main__":
    atheris.Setup(sys.argv, TestOneInput)
    atheris.Fuzz()
JavaScript and TypeScript: a target, and what to install

npm install --save-dev @jazzer.js/core in the repo. For .ts targets also typescript: bughunt compiles them first.

const shop = require("../shop");

module.exports.fuzz = function (data) {
  if (!shop.decode(shop.encode(data)).equals(data)) {
    throw new Error("the round trip changed the bytes");
  }
};
Ruby: a target, and what to install

gem install ruzzy, built with clang as its README describes. bughunt sets the preload it needs.

# fuzz_codec.rb: the file bughunt runs
require 'ruzzy'
Ruzzy.trace('fuzz_codec_harness.rb')

# fuzz_codec_harness.rb
require 'ruzzy'
require_relative '../lib/shop'

Ruzzy.fuzz(lambda do |data|
  raise 'the round trip changed the bytes' unless Shop.decode(Shop.encode(data)) == data
  0
end)
Java: a target, and what to install

A JDK, and the jazzer launcher from its releases on your PATH. Name the project's classes in fuzz.java_classpath.

public class CodecFuzzer {
  public static void fuzzerTestOneInput(byte[] input) {
    byte[] back = Codec.decode(Codec.encode(input));
    if (!java.util.Arrays.equals(back, input)) {
      throw new IllegalStateException("the round trip changed the bytes");
    }
  }
}
C and C++: a target, and what to install

LLVM's clang. Apple's clang has no libFuzzer; Homebrew's does, and bughunt looks for it. Name the project's sources in fuzz.c_flags.

#include "shop.h"
#include <stdlib.h>
#include <string.h>

int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
  char *text = malloc(2 * size + 1);
  uint8_t *back = malloc(size + 1);
  shop_encode(data, size, text);
  shop_decode(text, size, back);
  if (memcmp(back, data, size) != 0) abort();
  free(text);
  free(back);
  return 0;
}
PHP: a target, and what to install

php-fuzzer on your PATH, or BUGHUNT_PHP_FUZZER pointing at php-fuzzer.phar.

<?php
/** @var PhpFuzzer\Config $config */
$config->setTarget(function (string $input) {
    if (hex2bin(bin2hex($input)) !== $input) {
        throw new Error('the round trip changed the bytes');
    }
});

Seeds and word lists

If fuzz/seeds/<target>/ or <target>_seed_corpus/ exists, its files are the starting inputs. If <target>.dict sits beside the target, or there is a fuzz/*.dict, it is the word list. What the fuzzer learns is kept between runs, so each run starts where the last one stopped.

What a report looks like

clean   decode   88,179 inputs
clean   request  220,766 inputs
FAILED  mask

HIGH fuzz-failure         mask  | thread '<unnamed>' panicked at fuzz_targets/mask.rs:21:9:
     the target failed after 412 inputs
     a found value survived
     SUMMARY: libFuzzer: deadly signal
     artifact_prefix='fuzz/artifacts/mask/'; Test unit written to fuzz/artifacts/mask/crash-ab12
     fix: Replay it with: cargo +nightly fuzz run mask fuzz/artifacts/mask/crash-ab12. Fix the cause, then keep the failing input with the target's seeds so every run tests it again.

The finding names the input that broke the target and the command that replays it. Keep the input: it becomes your regression test.

Not run is not clean

  • A target that did not build, or failed before it tried any input, is reported as failed.
  • If a language's fuzzer is not installed, its targets are listed as "did not run" with what to install, and the exit status is 2.
  • Every run has a time limit, so one target that hangs cannot hold up the rest.

Targets that find more than crashes

Blind random input is shallow: most of it is thrown out by the first check. A target earns its keep when it does three things.

1. Check a promise

"It did not crash" finds little. State something that must always be true and let the fuzzer hunt for the input that breaks it:

  • round trip: decoding what you encoded gives the original back;
  • nothing survives: a value that was found and masked is gone from the output;
  • same answer either way: a stream gives the same result whole or cut into chunks;
  • two readers agree: your parser and a second, independent one read the input the same way.

2. Start from real examples

Give it a few real inputs and a word list of the tokens your format uses (keywords, delimiters, magic values). The fuzzer mutates those instead of guessing them from nothing.

3. Build structured input

For strict formats such as JSON or event streams, random bytes almost never parse. Generate a valid structure and let the fuzzer vary its fields.

Your own fuzzer

Any fuzzer bughunt does not find by itself can be given as a command in bughunt.toml. This is AFL++:

[[fuzz.target]]
name = "decode"
build = ["afl-clang-fast", "-fsanitize=fuzzer", "fuzz/decode.c", "-o", "{artifacts}/target"]
run = ["afl-fuzz", "-i", "fuzz/seeds", "-o", "{artifacts}", "-V", "{seconds}", "--", "{artifacts}/target"]
engine = "afl"
env = { AFL_NO_UI = "1" }

{seconds}, {corpus} and {artifacts} are filled in. engine says how the result is read:

engineThe run failed when
exit (default)the command exits with an error
libfuzzerits log has a failure summary or no final count, or it exits with an error
aflAFL++'s fuzzer_stats in {artifacts}/default counts a saved crash or hang, or is missing

The same works for a Java project fuzzed through Maven or Gradle, or a C project with a build of its own.

How long to run

A minute per target on every pull request catches regressions. Ten minutes or more on a schedule goes deeper. Set a default for a repo in Settings.

bughunt fuzz builds and runs code from the repo, and the commands its bughunt.toml names. Run it only on code you would run the tests of. To look at code you do not trust, use scan.