Skip to contentSkip to conversation

initial support for the afl++ (american fuzzy lop++) fuzzer

PATCH Superseded Florian Westphal 2 participants 2 messages Dec 14, 2023

Subsystems (2)

v2 of 3 Superseded Latest is v3 →

lore
Share & tools
lore

Florian Westphal

author maintainer
#0 lore raw

PATCH v2 1/1 initial support for the afl++ (american fuzzy lop++) fuzzer

afl comes with a compiler frontend that can add instrumentation suitable for running nftables via the "afl-fuzz" fuzzer.

This change adds a "--with-fuzzer" option to configure script and enables specific handling in nftables and libnftables to speed up the fuzzing process. It also adds the "--fuzzer" command line option.

afl-fuzz initialisation gets delayed until after the netlink context is set up and symbol tables such as (e.g. route marks) have been parsed.

When afl-fuzz restarts the process with a new input round, it will resume *after* this point (see __AFL_INIT macro in main.c).

With --fuzzer <stage>, nft will perform multiple fuzzing rounds per
invocation: this increases processing rate by an order of magnitude.

Each new input passes through the following processing stages:

1: pre-validation. Checks the input buffer (the fuzzer generated
ruleset/commands) to make sure minimal requirements are met:
- minimum "ineresting" length
- 0-terminated input (command, ruleset)
- initial keywords could result in state change (ruleset load, deletion or addition of rules/chains/tables,..

This stage is always executed.

2: 'parser':
Only run flex/bison parser and quit instantly if that fails, without evaluation of the generated AST (No need to generate error messages for the user).

3: 'eval': pass the input through the evaluation phase as well.
This attempts to build a complete ruleset in memory, does symbol resolution, adds needed shift/masks to payload instructions etc.

4: 'netlink-ro' or 'netlink-write'.
'netlink-ro' builds the netlink buffer to send to the kernel, without actually doing so.
With 'write', the generated command/ruleset will be passed to the kernel.

The argument to '--fuzzer' specifies the last stage to run.

Use 'netlink-ro' if you want to prevent the fuzzing from ever submitting any changes to the kernel.

You can combine '--fuzzer netlink-write' with the '--check' option to send data to the kernel but without actually committing any changes.

This could still end up triggering a kernel crash if there are bugs in the valiation / transaction / abort phases.

Before sending a command to the kernel, the input is stored in temporary files (named [0-255]/[0-255] in the "tests/afl++/nft-afl-work" directory.

In case a splat is detected, the fuzzing process halts. This will also block all further fuzzer attempts until reboot.

nft-afl-work/log logs when a "talk to kernel" phase begins or when a kernel crash/warning splat was detected.

Check "tests/afl++/hooks" for script hooks, those allow to customize the fuzzing process by making regular snapshots of the ruleset, deleting old temporary files, flushing rules, checking KASAN, etc.

The default hook scripts will enable fault injection for the nft process being fuzzed, i.e. kernel memory allocations will randonly fail.

---
 .gitignore                     |   6 +
 Makefile.am                    |   5 +
 configure.ac                   |  14 +
 include/afl++.h                |  49 +++
 include/nftables.h             |   3 +
 src/afl++.c                    | 729 +++++++++++++++++++++++++++++++++
 src/libnftables.c              |  23 +-
 src/main.c                     | 101 +++++
 src/mnl.c                      |   2 +-
 tests/afl++/README             | 126 ++++++
 tests/afl++/TODO               |   6 +
 tests/afl++/afl-sysctl.cfg     |   5 +
 tests/afl++/hooks/init         |  54 +++
 tests/afl++/hooks/post-commit  |   8 +
 tests/afl++/hooks/post-restart |   8 +
 tests/afl++/hooks/pre-commit   |   6 +
 tests/afl++/hooks/pre-restart  |  12 +
 tests/afl++/run-afl.sh         |  43 ++
 18 files changed, 1198 insertions(+), 2 deletions(-)
 create mode 100644 include/afl++.h
 create mode 100644 src/afl++.c
 create mode 100644 tests/afl++/README
 create mode 100644 tests/afl++/TODO
 create mode 100644 tests/afl++/afl-sysctl.cfg
 create mode 100755 tests/afl++/hooks/init
 create mode 100755 tests/afl++/hooks/post-commit
 create mode 100755 tests/afl++/hooks/post-restart
 create mode 100755 tests/afl++/hooks/pre-commit
 create mode 100755 tests/afl++/hooks/pre-restart
 create mode 100755 tests/afl++/run-afl.sh
.gitignore +6 -0
index a62e31f31c6b..1d9eb9c22a70 100644
@@ -22,6 +22,12 @@ libtool
 *.payload.got
 tests/build/tests.log
 
+# generated by run-afl.sh
+tests/afl++/in/
+tests/afl++/nft.dict
+tests/afl++/out/
+tests/afl++/nft-afl-work/
+
 # Debian package build temporary files
 build-stamp
 
Makefile.am +5 -0
index 0ed831a19e95..21c01e712010 100644
@@ -63,6 +63,7 @@ noinst_HEADERS = \
 	include/linux/netfilter_ipv6.h \
 	include/linux/netfilter_ipv6/ip6_tables.h \
 	\
+	include/afl++.h	\
 	include/cache.h \
 	include/cli.h \
 	include/cmd.h \
@@ -284,6 +285,10 @@ sbin_PROGRAMS += src/nft
 
 src_nft_SOURCES = src/main.c
 
+if BUILD_AFL
+src_nft_SOURCES += src/afl++.c
+endif
+
 if BUILD_CLI
 src_nft_SOURCES += src/cli.c
 endif
configure.ac +14 -0
index 724a4ae726c1..c162f388ce7c 100644
@@ -91,6 +91,15 @@ AC_MSG_ERROR([unexpected CLI value: $with_cli])
 ])
 AM_CONDITIONAL([BUILD_CLI], [test "x$with_cli" != xno])
 
+AC_ARG_ENABLE([fuzzer],
+	      AS_HELP_STRING([--enable-fuzzer], [Enable fuzzer support.  NEVER use this unless you work on nftables project]),
+	      [enable_fuzzer=yes], [enable_fuzzer=no])
+
+AM_CONDITIONAL([BUILD_AFL], [test "x$enable_fuzzer" = xyes])
+AS_IF([test "x$enable_fuzzer" != xno], [
+	AC_DEFINE([HAVE_FUZZER_BUILD], [1], [Define if you want to build with fuzzer support])
+	], [])
+
 AC_ARG_WITH([xtables], [AS_HELP_STRING([--with-xtables],
             [Use libxtables for iptables interaction])],
 	    [], [with_xtables=no])
@@ -128,3 +137,8 @@ nft configuration:
   enable man page:              ${enable_man_doc}
   libxtables support:		${with_xtables}
   json output support:          ${with_json}"
+
+# Do not print "fuzzer support:		no", this is development-only.
+AS_IF([test "x$enable_fuzzer" = xyes ], [
+	echo "  fuzzer support:		yes"
+	], [ ])
include/afl++.h new file +49 -0

49 lines not on this page · raw message

include/nftables.h +3 -0
index 4b7c335928da..02d110e609eb 100644
@@ -144,6 +144,9 @@ struct nft_ctx {
 	void			*json_root;
 	json_t			*json_echo;
 	const char		*stdin_buf;
+#if defined(HAVE_FUZZER_BUILD)
+	int			afl_ctx_stage;
+#endif
 };
 
 enum nftables_exit_codes {
src/afl++.c new file +729 -0

729 lines not on this page · raw message

src/libnftables.c +22 -1
index 0dee1bacb0db..d4ba696a7e7a 100644
@@ -9,6 +9,7 @@
 #include <nft.h>
 
 #include <nftables/libnftables.h>
+#include <afl++.h>
 #include <erec.h>
 #include <mnl.h>
 #include <parser.h>
@@ -18,6 +19,17 @@
 #include <errno.h>
 #include <sys/stat.h>
 
+static int do_mnl_batch_talk(struct netlink_ctx *ctx, struct list_head *err_list,
+			     uint32_t num_cmds)
+{
+#if defined(HAVE_FUZZER_BUILD)
+	if (ctx->nft->afl_ctx_stage &&
+	    ctx->nft->afl_ctx_stage < NFT_AFL_FUZZER_NETLINK_RW)
+		return 0;
+#endif
+	return mnl_batch_talk(ctx, err_list, num_cmds);
+}
+
 static int nft_netlink(struct nft_ctx *nft,
 		       struct list_head *cmds, struct list_head *msgs)
 {
@@ -36,6 +48,11 @@ static int nft_netlink(struct nft_ctx *nft,
 	if (list_empty(cmds))
 		goto out;
 
+#if defined(HAVE_FUZZER_BUILD)
+	if (nft->afl_ctx_stage &&
+	    nft->afl_ctx_stage <= NFT_AFL_FUZZER_EVALUATION)
+		goto out;
+#endif
 	batch_seqnum = mnl_batch_begin(ctx.batch, mnl_seqnum_alloc(&seqnum));
 	list_for_each_entry(cmd, cmds, list) {
 		ctx.seqnum = cmd->seqnum = mnl_seqnum_alloc(&seqnum);
@@ -54,7 +71,7 @@ static int nft_netlink(struct nft_ctx *nft,
 	if (!mnl_batch_ready(ctx.batch))
 		goto out;
 
-	ret = mnl_batch_talk(&ctx, &err_list, num_cmds);
+	ret = do_mnl_batch_talk(&ctx, &err_list, num_cmds);
 	if (ret < 0) {
 		if (ctx.maybe_emsgsize && errno == EMSGSIZE) {
 			netlink_io_error(&ctx, NULL,
@@ -579,6 +596,10 @@ int nft_run_cmd_from_buffer(struct nft_ctx *nft, const char *buf)
 		rc = nft_parse_bison_buffer(nft, nlbuf, &msgs, &cmds,
 					    &indesc_cmdline);
 
+#if defined(HAVE_FUZZER_BUILD)
+	if (nft->afl_ctx_stage == NFT_AFL_FUZZER_PARSER)
+		goto err;
+#endif
 	parser_rc = rc;
 
 	rc = nft_evaluate(nft, &msgs, &cmds);
src/main.c +101 -0

161 lines not on this page · raw message

src/mnl.c +1 -1
index 9e4bfcd9a030..fa699e3205ba 100644
@@ -27,6 +27,7 @@
 #include <linux/netfilter/nfnetlink_hook.h>
 #include <linux/netfilter/nf_tables.h>
 
+#include <afl++.h>
 #include <mnl.h>
 #include <cmd.h>
 #include <net/if.h>
@@ -427,7 +428,6 @@ int mnl_batch_talk(struct netlink_ctx *ctx, struct list_head *err_list,
 	}
 
 	mnl_set_rcvbuffer(ctx->nft->nf_sock, rcvbufsiz);
-
 	ret = mnl_nft_socket_sendmsg(ctx, &msg);
 	if (ret == -1)
 		return -1;
tests/afl++/README new file +126 -0

126 lines not on this page · raw message

tests/afl++/TODO new file +6 -0
new file mode 100644
index 000000000000..d31ba71d2364
@@ -0,0 +1,6 @@
+Fuzzing is sometimes VERY slow, this happens when current inputs contain
+"host names".  Either --fuzzer could set NFT_CTX_INPUT_NO_DNS to avoid this,
+or nft needs a new command line option so both (dns and no dns) can be combined.
+
+Investigate custom mutator for afl to further improve the fuzzing rate.
+This would likely allow to get rid of the pre-validation in src/afl++.c.
tests/afl++/afl-sysctl.cfg new file +5 -0
new file mode 100644
index 000000000000..490e62b00094
@@ -0,0 +1,5 @@
+kernel.core_pattern=core
+fs.suid_dumpable=1
+kernel.core_uses_pid=0
+kernel.randomize_va_space=0
+kernel.sched_autogroup_enabled=1
tests/afl++/hooks/init new file +54 -0

54 lines not on this page · raw message

tests/afl++/hooks/post-commit new file +8 -0
new file mode 100755
index 000000000000..be81ce6747b4
@@ -0,0 +1,8 @@
+#!/bin/bash
+
+# This script is run right after "nft --fuzzer" has committed a
+# fuzzer-generated ruleset to the kernel.
+
+test -f $NFT_AFL_WORKDIR/TAINT || exit 0
+
+exec nft list ruleset > $NFT_AFL_WORKDIR/post_taint_ruleset
tests/afl++/hooks/post-restart new file +8 -0
new file mode 100755
index 000000000000..1848709a4ea1
@@ -0,0 +1,8 @@
+#!/bin/bash
+
+# This script is run when afl-fuzz has re-started nft with a new fuzzer
+# input round and after "nft --fuzzer" has read the existing input files
+# from its workdir ($NFT_AFL_WORKDIR).
+
+# start each round with a clean kernel state
+nft flush ruleset
tests/afl++/hooks/pre-commit new file +6 -0
new file mode 100755
index 000000000000..c89167475907
@@ -0,0 +1,6 @@
+#!/bin/bash
+
+# This script is run right before "nft --fuzzer" is going to submit a new
+# fuzzer-generated ruleset to the kernel.
+
+nft list ruleset > $NFT_AFL_WORKDIR/last_precommit_ruleset
tests/afl++/hooks/pre-restart new file +12 -0
new file mode 100755
index 000000000000..4595dfb05889
@@ -0,0 +1,12 @@
+#!/bin/bash
+
+# This script is run when afl-fuzz has re-started nft with a new fuzzer
+# input round and before "nft --fuzzer" has read the existing input files
+# from its workdir ($NFT_AFL_WORKDIR).
+
+test -f /sys/kernel/debug/kmemleak && echo "scan" > /sys/kernel/debug/kmemleak &
+
+# house-cleaning: delete old inputs
+find $NFT_AFL_WORKDIR/*/ -type f -mmin +15 -exec rm -f {} + &
+
+nft list ruleset > $NFT_AFL_WORKDIR/current_ruleset
tests/afl++/run-afl.sh new file +43 -0

43 lines not on this page · raw message

Signature · 1 line
2.41.0
#1 lore raw

Hi,

configure.ac AC_MSG_ERROR([unexpected CLI value: $with_cli]) · line 101

Quoted 5 lines
configure.ac +3 -0
+AM_CONDITIONAL([BUILD_AFL], [test "x$enable_fuzzer" = xyes])
+AS_IF([test "x$enable_fuzzer" != xno], [
+	AC_DEFINE([HAVE_FUZZER_BUILD], [1], [Define if you want to

build with fuzzer support])

configure.ac +1 -0
+	], [])

could you always define HAVE_FUZZER_BUILD, and check with #if HAVE_FUZZER_BUILD, instead of #ifdef.

The benefit is, that compiler will emit a warning, when #if is used and the variable doesn't exist (e.g. due to a typo).

something like:

HAVE_FUZZER_BUILD=0
if [ "$enable_fuzzer" != no ] ; then
HAVE_FUZZER_BUILD=1
fi
AC_DEFINE_UNQUOTED([HAVE_FUZZER_BUILD], [$HAVE_FUZZER_BUILD], [Whether to build with fuzzer support])

include/afl++.h line 5

Quoted 11 lines
include/afl++.h new file +5 -0
new file mode 100644
index 000000000000..28244dcaaf62
@@ -0,0 +1,49 @@
+#ifndef _NFT_AFLPLUSPLUS_H_
+#define _NFT_AFLPLUSPLUS_H_
+
+#include <nftables/libnftables.h>
+#include <config.h>

<config.h> should always be included as very first in all sources. For example, it brings _GNU_SOURCE, which enables certain features in libc headers. If you define _GNU_SOURCE somewhere in the middle of a list of #include, it becomes cumbersome to be sure which libc header version we have.

Similarly, src/afl++.c also must include <config.h> as first.

But note, we should not actually include <config.h> at all. Instead, #include <nft.h> as first (which takes care of getting this right). Also, only include <nft.h> in C-sources (as first). Thereby, all C sources can rely to have what <nft.h> provides. Furthermore, since header files are only indirectly compiled by being included from C sources, they also can rely on having <nft.h>.

I would avoid the "++" in filenames. E.g. it's a special character for regexes (depending on regex syntax).