Skip to content

About

A grammar-based custom mutator for AFL++

Topics

Resources

Contributing

Stars

279 stars

Watchers

3 watching

Forks

Latest commit

 

History

338 Commits

Folders and files

Repository files navigation

Grammar Mutator - AFL++

Grammar Mutator CI

A grammar-based custom mutator for AFL++ to handle highly-structured inputs.

Contents

Overview

The grammar mutator lets AFL++ fuzz targets that read highly-structured inputs, such as JSON or Ruby. It does not mutate a byte buffer. It parses each test case into a tree, changes the tree, and writes the tree back as bytes. It uses ideas from the F1 fuzzer for test case generation and from Nautilus for the mutations.

This repository includes:

  • Grammars in a JSON format or in the ANTLR 4 format (.g4), for example from grammars-v4
  • Tree-based mutation: rules mutation, random mutation, random recursive mutation, splicing mutation
  • Tree-based trimming: subtree trimming, recursive trimming
  • An ANTLR 4 shim that parses test cases while AFL++ runs
  • Tools that generate seeds (grammar_generator) and parse existing seeds (grammar_parser, for .g4 grammars)
  • Sample grammars and a script that converts Nautilus Python grammars
  • Unit tests

For more details about tree-based mutation, trimming, and grammar-based fuzzing, refer to the Nautilus paper. A fuzzing writeup on Apache that uses the AFL++ Grammar Mutator is at https://securitylab.github.com/research/fuzzing-apache-1.

Quick Start

make antlr-jar                         # download the ANTLR 4.13.2 jar
make GRAMMAR_FILE=grammars/ruby.json   # build the mutator for a grammar
./grammar_generator-ruby 100 1000 ./seeds ./trees
mkdir -p out/default && cp -r trees out/default

export AFL_CUSTOM_MUTATOR_LIBRARY=./libgrammarmutator-ruby.so
export AFL_CUSTOM_MUTATOR_ONLY=1
afl-fuzz -i seeds -o out -- /path/to/target @@

The sections below explain each step.

Prerequisites

Install these packages:

sudo apt install valgrind uuid-dev default-jre python3 python3-venv

The build needs the ANTLR 4.13.2 jar (Java 11 or later). In the Grammar-Mutator folder, make antlr-jar downloads it. You can also download it yourself:

wget https://www.antlr.org/download/antlr-4.13.2-complete.jar
sudo cp -f antlr-4.13.2-complete.jar /usr/local/lib

The build looks for the jar in the Grammar-Mutator folder and in /usr/local/lib. If the jar is in another place, add ANTLR_JAR_LOCATION=... to the make command.

A .g4 grammar also needs the Python tools in .venv. Run make deps once to install them (this needs python3-venv and access to PyPI).

The grammar mutator uses the latest custom mutator APIs of AFL++. Use the latest stable or dev branch of AFL++:

git clone https://github.com/AFLplusplus/AFLplusplus.git
cd AFLplusplus
make distrib
sudo make install

Building the Grammar Mutator

Set the grammar with GRAMMAR_FILE. The grammar can be one of two kinds:

  • A JSON grammar file. There are several in the grammars folder, such as json.json, ruby.json, and http.json.
  • An ANTLR 4 grammar (.g4 files). You can use a grammar from grammars-v4 directly. Give all its .g4 files, for example the lexer grammar and the parser grammar. Samples are in grammars/g4.
# A JSON grammar
make GRAMMAR_FILE=grammars/ruby.json

# An ANTLR 4 grammar: one combined grammar ...
make deps
make GRAMMAR_FILE=grammars/g4/JSON.g4

# ... or a lexer grammar and a parser grammar. This grammar has action code,
# so it also needs its C++ base classes (G4_SUPPORT_DIR).
make GRAMMAR_FILE="grammars/g4/javascript/JavaScriptLexer.g4 grammars/g4/javascript/JavaScriptParser.g4" \
     G4_SUPPORT_DIR=grammars/g4/javascript/Cpp

Refer to customizing-grammars.md for both kinds of grammar. Its ANTLR 4 section gives the limits of .g4 grammars. Pull requests with new grammars are welcome! :-)

Output Files

The build creates these files in the src folder, with symbolic links to them in the repository root:

  • libgrammarmutator-<name>.so: the custom mutator library for AFL++
  • grammar_generator-<name>: makes seeds and their trees (see Generating Seeds)
  • grammar_parser-<name>: parses existing seeds into trees, for a .g4 grammar only (see Using Existing Seeds)

The name comes from the grammar file, so you can build the mutator for more than one grammar:

  • For a JSON grammar, the build cuts the file name at the first underscore, dash, or dot. So ruby.json gives ruby.
  • For a .g4 grammar, the name is the last file name without Lexer or Parser. So the JavaScript example above gives javascript.
  • To set your own name, add GRAMMAR_FILENAME=yourname to the make command.

To fork the project, fix bugs, or contribute, refer to building-grammar-mutator.md for the full build instructions.

Seeds

Before you fuzz the target, prepare the seeds. You can generate seeds from the grammar, or use existing seeds. In both cases, you can give the mutator the trees of the seeds, so that it does not parse them again.

Generating Seeds

grammar_generator-<name> makes seeds and their tree files from the grammar of the build. You can set the number of seeds and the maximum tree size. A larger tree usually gives a more complex seed. The generator does not write empty seeds or the same seed twice. If 100 tries in a row give no new seed, it stops early and writes fewer than <max_num> seeds.

# Usage:
# ./grammar_generator-<name> <max_num> <max_size> <seed_output_dir> <tree_output_dir> [<random seed>]
./grammar_generator-ruby 100 1000 ./seeds ./trees

Then copy the trees.

Using Existing Seeds

You can give your own seeds to the fuzzer. They do not have to match the grammar. The mutator parses each seed when AFL++ loads it. What happens with a seed that the grammar does not cover depends on the kind of grammar:

  • A JSON grammar: the mutator keeps the bad part as a terminal node in the tree, so the seed does not lose much information. For example, grammars/ruby.json is a simplified Ruby grammar, so most real Ruby files have parse errors.
  • A .g4 grammar: a seed with a syntax error gets no tree, and the grammar mutator does not change it. The other AFL++ stages change it, unless AFL_CUSTOM_MUTATOR_ONLY is set. With AFL_CUSTOM_MUTATOR_ONLY=1, AFL++ does not fuzz this seed at all.

For example, to use the test cases of the mruby project as seeds, clone it with git clone https://github.com/mruby/mruby.git and give -i mruby/test/t to afl-fuzz.

For JavaScript, javascript-seeds.md gives a recipe that makes seeds from the test suites of JavaScript engines (test262, V8, and WebKit).

With a .g4 grammar, you can parse the seeds before you fuzz. This makes the start of afl-fuzz faster:

./grammar_parser-javascript ./seeds ./trees

Then copy the trees. The ANTLR 4 section of customizing-grammars.md gives the skip reasons, the parse time limit, and G4_SUPPORT_DIR.

Copying the Trees

Copy the trees folder, with this exact name, into the output folder of afl-fuzz (for example -o out with the default fuzzer name default):

mkdir -p out/default
cp -r trees out/default

If you use more than one fuzzer instance (-M/-S sync mode), do this for each instance. For example, for the instances fuzzer1 to fuzzer8:

for i in 1 2 3 4 5 6 7 8; do
  mkdir -p out/fuzzer$i
  cp -r trees out/fuzzer$i/
done

Fuzzing

Instrumenting the Target

Refer to sample-fuzzing-targets.md to build the sample fuzzing targets.

Running the Fuzzer

This example uses the Ruby grammar (grammars/ruby.json) and the mruby target:

export AFL_CUSTOM_MUTATOR_LIBRARY=./libgrammarmutator-ruby.so
export AFL_CUSTOM_MUTATOR_ONLY=1
afl-fuzz -i seeds -o out -- /path/to/target @@

The fuzzer can be slow at the start, for two reasons:

  • Large seeds take more time to load. A large <max_size> for grammar_generator-<name> gives large seeds.
  • The mutator must parse each seed that has no tree. To skip this step, copy the trees of the seeds (see Copying the Trees).

AFL++ adds the mutation stage to the name of each case that a mutation stage finds, in queue/, crashes/, and hangs/: op:gm-rules, op:gm-random, op:gm-recursive, or op:gm-splice.

Configuration

The mutator reads these environment variables:

Variable Effect
RANDOM_MUTATION_STEPS The weight of the random mutation (default 1000). 0 turns it off. See Fuzz Steps.
RANDOM_RECURSIVE_MUTATION_STEPS The weight of the random recursive mutation (default 1000). 0 turns it off.
SPLICING_MUTATION_STEPS The weight of the splicing mutation (default 1000). 0 turns it off.
RULES_MUTATION_STEPS The largest number of rules mutations in one pick of an entry (default 1000). 0 turns the rules mutation off.
RULES_MUTATION_ONCE 1 (default): the rules mutation of an entry goes on in its next pick. 0: it starts again at each pick.
FUZZ_STEPS_MAX The largest number of fuzz steps in one pick of an entry (default 700). 0 removes the limit. See Fuzz Steps.
TRIMMING_STEPS The maximum number of trimming steps for each queue entry (default 30). 0 turns trimming off.
PARSE_TIME_BUDGET_MS The smallest time limit in ms for the parse of a test case (default 50). 0 removes the limit. See Parse Time Limit and Ambiguous Grammars.
PARSE_CACHE_STATES The largest number of states in the parse cache (default 25000). 0 removes the limit. See Parse Cache.
OUTPUT_HASHES The number of output hashes that the duplicate check keeps (default 1048576, 8 MiB). 0 turns the check off. See Dropped Outputs.
GRAMMAR_MUTATOR_STATS_SECONDS Write a line of statistics every this many seconds (1 to 86400) to grammar_mutator_stats in the AFL++ output folder of the instance (default: no file). See Statistics File.

For example:

export RANDOM_MUTATION_STEPS=2000
export SPLICING_MUTATION_STEPS=500
export RULES_MUTATION_STEPS=10000
export TRIMMING_STEPS=10000
export AFL_CUSTOM_MUTATOR_LIBRARY=./libgrammarmutator-ruby.so
export AFL_CUSTOM_MUTATOR_ONLY=1
afl-fuzz -i seeds -o out -- /path/to/target @@

Fuzz Steps

AFL++ sets the number of fuzz steps of each pick from the energy of the entry, as for its havoc stage (in custom-only mode, twice as many steps). An entry that is fast, new, or finds new coverage gets more steps. Each step picks its mutation. While the entry has rules pairs left for the pick, every second step is a rules mutation. The other steps pick the random, random recursive, or splicing mutation. The three step variables are their weights, so equal values give equal shares.

AFL++ can double the steps of a pick at each new find in the pick, up to a limit. So a pick can have thousands of steps. FUZZ_STEPS_MAX (default 700) limits the steps of a pick. After this many steps, the mutator gives no output, and AFL++ does no run for the rest of the pick. A dropped output also counts as a step. AFL++ still calls the mutator for the rest of the pick, and counts these calls in the custom mutator stage of its statistics. AFL++ then picks more entries in the same time. AFL++ trims each entry at its first pick, so more picked entries also give more trim time. The default of 30 trim steps keeps the trim time low. If you set a higher FUZZ_STEPS_MAX or 0, AFL++ picks fewer entries, and you can set a higher TRIMMING_STEPS. The limit helps most when one pick takes a long time, for example with a slow target. With a fast target, the limit can give fewer edges in a long campaign. To compare, also run with FUZZ_STEPS_MAX=0 and TRIMMING_STEPS=100 on your target.

To give each pick the old fixed number of steps, build with FIXED_FUZZ_COUNT=1 (CMake: -DFIXED_FUZZ_COUNT=ON). The library then exports afl_custom_fuzz_count. A pick then has the rules steps of the pick plus the step variables of the other mutations (the random recursive one only for a tree with a recursion), and the steps still mix the mutations. FUZZ_STEPS_MAX also limits this number. Run make clean before you change this option on a make build.

Rules Mutation

The rules mutation tries every other rule at every nonterminal node of the tree, in tree order. It tries each of these node and rule pairs once in a run, at most RULES_MUTATION_STEPS pairs in one pick of the entry. The next pick of the entry goes on from where the last pick stopped, so a large tree takes several picks. With FUZZ_STEPS_MAX, a pick has at most FUZZ_STEPS_MAX / 2 rules mutations (rounded up), unless the weights of the other mutations are all 0. A successful trim starts the rules mutation of the entry again, because the trimmed tree has other pairs. With RULES_MUTATION_ONCE=0, each pick starts again at the first pair, so only the first pairs run: about half of the steps of a pick, and at most RULES_MUTATION_STEPS. To try all pairs at each pick, as older versions did, build with FIXED_FUZZ_COUNT=1 and set RULES_MUTATION_STEPS to a very large value.

Trimming

The trimming of a new queue entry tries the nonterminal nodes and then the recursions of its tree, from the root down. It stops after TRIMMING_STEPS tries (default 30) and keeps what it has trimmed by then. Each try runs the target once, so a large tree can take a long time to trim. For no limit in practice, set a very large value, for example 1000000000.

Dropped Outputs

The fuzz stage does not give AFL++ an output that brings nothing new:

  • An output that is equal to the entry, or to an earlier output of this run. The mutator keeps the hashes of the earlier outputs in a table of OUTPUT_HASHES slots. A new hash replaces the old hash in its slot, so the check can forget an earlier output.
  • An output above the size limit of AFL++. The mutator does not cut it.

AFL++ does no run for a dropped output, so each pick ends sooner. The random and splicing mutations also pick again, up to 8 times, if the new subtree has the same text as the old one. dup_outputs and big_outputs in the Statistics File count the dropped outputs.

Parse Cache

The ANTLR parser keeps a cache of its earlier decisions. The cache makes parses faster, but it never becomes smaller. After a parse, the mutator clears the cache if it holds more than PARSE_CACHE_STATES states. The default limit keeps the JavaScript cache at about 1 GB. The parses after a clear are slower until the cache fills again. A clear does not change the trees, but a slower parse can pass the time limit and give no tree. cache_clears in the Statistics File counts the clears. If it increases often, set a higher limit. grammar_parser-<name> never clears the cache.

Statistics File

The statistics file shows the parse counts, the parse cache, the heap, the new entries that got a tree from the mutator, and the dropped outputs during a run. Set GRAMMAR_MUTATOR_STATS_SECONDS to turn it on. Each AFL++ instance writes its own file, grammar_mutator_stats, in its output folder (for example out/default/), next to the AFL++ plot_data file.

The file starts with this header line:

# unix_time, parses, failed_parses, limit_parses, parser_states, lexer_states, heap_kb, pick_parses, new_parses, fuzz_trees, trim_trees, cache_clears, fuzz_outputs, dup_outputs, big_outputs

Each line after it holds these values:

Value Meaning
unix_time The time of the line, in seconds since 1970
parses The number of test cases that the mutator parsed. The mutator parses only a test case that has no usable tree file.
failed_parses The number of parses that gave no tree
limit_parses The number of parses that passed the time limit (see PARSE_TIME_BUDGET_MS)
parser_states The number of states in the prediction cache of the ANTLR parser
lexer_states The number of states in the prediction cache of the ANTLR lexer
heap_kb The heap in use of the whole afl-fuzz process, in KB
pick_parses The parses of a queue entry that AFL++ picked, and that had no usable tree file. This value stays near 0, because AFL++ gives each entry to the mutator as a new entry first. For example, it counts an entry whose tree file was removed during the run
new_parses The parses of a new queue entry that got no tree from the mutator: a seed with no tree file, a find of an AFL++ stage, or a synced entry
fuzz_trees The new queue entries that got the tree of a fuzz output, with no parse
trim_trees The new queue entries that got the tree of a trim output, with no parse
cache_clears The number of clears of the parse cache. The states drop at each clear. See Parse Cache.
fuzz_outputs The outputs of the fuzz stage, also the dropped ones
dup_outputs The outputs that the mutator dropped, because they were equal to the entry or to an earlier output. See Dropped Outputs.
big_outputs The outputs that the mutator dropped, because they were above the size limit of AFL++

parses is the sum of pick_parses and new_parses.

The mutator writes the first line when it gets the first queue entry. Then it writes a line at the first mutator call after the interval, and a last line when AFL++ stops. A long stage outside the mutator can make a line late, so use unix_time, not the number of lines, as the time. -1 means that the value is not known. For example, heap_kb is -1 on a platform without malloc statistics.

A resumed run adds its lines to the same file. A new run in an old output folder also adds its lines to the file. AFL++ does not remove this file. A file from an older version of the mutator has a header with fewer columns. A resumed run then writes lines that do not match it. Use a new output folder, or remove the old file. Each run is a new process, so the counts and the states start again from 0 in its first line.

Contact and Contributions

We welcome questions and contributions! Feel free to open an issue or submit a pull request. Read CONTRIBUTING.md before you open a pull request.

Branches and Releases

stable is the only long-lived branch. Send all pull requests to stable.

The dev branch is abandoned. It stays in the repository for history, but it does not get new changes.

Release Please makes the releases from stable. See CHANGELOG.md and the GitHub releases for the changes in each version.

About

A grammar-based custom mutator for AFL++

Topics

Resources

Contributing

Stars

279 stars

Watchers

3 watching

Forks

Releases

Used by

Contributors

Languages