Repository navigation
Description
Current behavior
The unbound project is onboarded to OSS-Fuzz: https://introspector.oss-fuzz.com/project-profile?project=unbound.
However, as of May 2025, it has low fuzzing code coverage of ~9%. This is in contrast to well-fuzzed projects (e.g., exiv2 and sqlite3) which typically have ~70% code coverage.
There was initial onboarding to OSS-Fuzz (done by an external developer) with one unit-test-style fuzz target in 2019 and then 4 more similarly small in scope fuzz targets were added in 2020 (done as a result of a limited external audit).
However, unbound has a testbound program used in its test suite. This program is perfect for fuzzing: it emulates network via local files, it consumes not only client requests but also the configuration in the same test run. Additionally, testbound already has a set of ~450 inputs (testdata/*.rpl files) which can be directly used as the seed corpus for fuzzing.
My experiments show that a single fuzz target of testbound is sufficient to cover almost all functionality of unbound. The fuzzing code coverage improves to ~60% (after couple hours of fuzzing) and renders existing OSS-Fuzz fuzz targets redundant.
Describe the desired feature
I propose to rework fuzz targets (aka fuzz harnesses) available on OSS-Fuzz. In particular:
- Five existing fuzz targets (
parse_packet_fuzzer.candfuzz_*.c) can be removed, - A new
testboundtarget is added.
I reproduced OSS-Fuzz environment for unbound, see Dockerfile and build script in the unbound project page of OSS-Fuzz. Here is a full list of modifications I required to fuzz testbound:
- Dockerfile requires a minimal modification to add more dependencies.
build.shrequires a modification: remove build steps for previous fuzz targets and create a similar build step fortestbound. Needs discussion, see below.- Remove non-determinism from unbound itself. To this end, we patch
util/random.c, see below. - Modify
main()oftestboundtoLLVMFuzzerTestOneInput(); this is a libFuzzer-style requirement of OSS-Fuzz. To this end, we patchtestcode/testbound.c, see below. - Harden the
testboundprogram itself. Currently,testboundwrappers (like pre- and post-condition checks and network emulation functions) segfault on malformed inputs, leading to false positives (when the fuzzing engine crashes because of the bugs in wrappers, not real bugs in unbound). To this end, we patchtestboundsource code with additional checks, see below.
I am willing to submit PRs and drive this effort, if you agree on the usefulness and can clear some of the questions I have below (in collapsed sections).
Details on item 2: build for `testbound`
I didn't find a way to build only the testbound test. The closest to this was make tests. Did I miss a simple way to only build the testbound program? It is not that important for the process (we can build whatever redundant binaries we want in OSS-Fuzz), but for cleanness would be good to have a separate make target.
As for the seed corpus, a simple copy was enough: cp testdata/*.rpl $OUT.
Details on item 3: remove non-determinism from unbound
The only source of non-determinism that I found was the randomness functions. The patch is straight-forward and was applied on top of commit 71bb60e. Note that FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION is a standard macro for fuzzing engines.
diff --git a/util/random.c b/util/random.c
index 6eb102c..a924d95 100644
--- a/util/random.c
+++ b/util/random.c
@@ -78,6 +78,35 @@
*/
#define MAX_VALUE 0x7fffffff
+#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
+struct ub_randstate {
+ unsigned int dummy;
+};
+
+struct ub_randstate* ub_initstate(struct ub_randstate* ATTR_UNUSED(from))
+{
+ struct ub_randstate* s = (struct ub_randstate*)calloc(1, sizeof(*s));
+ if(!s) {
+ log_err("malloc failure in random init");
+ return NULL;
+ }
+ return s;
+}
+
+long int ub_random(struct ub_randstate* state)
+{
+ state->dummy++;
+ return (long int)(state->dummy & MAX_VALUE);
+}
+
+long int
+ub_random_max(struct ub_randstate* state, long int x)
+{
+ state->dummy++;
+ return ((long int)state->dummy % x);
+}
+#else
+
#if defined(HAVE_SSL) || defined(HAVE_LIBBSD)
struct ub_randstate*
ub_initstate(struct ub_randstate* ATTR_UNUSED(from))
@@ -200,6 +229,8 @@ ub_random_max(struct ub_randstate* state, long int x)
}
#endif /* HAVE_NSS or HAVE_NETTLE and !HAVE_LIBBSD */
+#endif // FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
+
void
ub_randfree(struct ub_randstate* s)
{Details on item 4: modify `main()` to `LLVMFuzzerTestOneInput()`
The below patch modifies testbound to be runnable in libFuzzer style. This implementation of the fuzz target is required by OSS-Fuzz. The patch was applied on top of commit 71bb60e.
The patch is quite ugly, I could be more frugal by surgically placing ifdefs in correct places in main(), but it shows the idea. In fact, for maintenance reasons, this should be indeed rewritten to not duplicate code in main, but ifdef parts of main.
I also added delete_file() and buf_to_file() helpers, because the fuzzing engine provides the input in a buffer, whereas testbound expects input to be in a file. These helpers could be simplified or maybe replaced by similar unbound functions, if they already exist. These helpers are standard practice in fuzzing.
diff --git a/testcode/testbound.c b/testcode/testbound.c
index f9ea86e..a833fbe 100644
--- a/testcode/testbound.c
+++ b/testcode/testbound.c
@@ -340,7 +340,7 @@ static void remove_configfile(void)
* @return program failure if test fails.
*/
int
-main(int argc, char* argv[])
+dummy_main(int argc, char* argv[])
{
int c, res;
int pass_argc = 0;
@@ -493,6 +493,101 @@ main(int argc, char* argv[])
return res;
}
+static int delete_file(const char *pathname) {
+ int ret = unlink(pathname);
+ free((void *)pathname);
+ return ret;
+}
+
+static char *buf_to_file(const uint8_t *buf, size_t size) {
+ char *pathname = strdup("/tmp/fuzz-XXXXXX");
+ if (pathname == NULL)
+ return NULL;
+
+ int fd = mkstemp(pathname);
+ if (fd == -1) {
+ free(pathname);
+ return NULL;
+ }
+ size_t pos = 0;
+ while (pos < size) {
+ int nbytes = write(fd, &buf[pos], size - pos);
+ if (nbytes <= 0) {
+ if (nbytes == -1 && errno == EINTR)
+ continue;
+ goto err;
+ }
+ pos += nbytes;
+ }
+
+ if (close(fd) == -1)
+ goto err;
+
+ return pathname;
+err:
+ delete_file(pathname);
+ return NULL;
+}
+
+
+/* based on main() above, but with: hard-coded passed args, file created from fuzz input */
+int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
+ int c, res;
+ int pass_argc = 0;
+ char* pass_argv[MAXARG];
+ char* playback_file = NULL;
+ struct replay_scenario* scen = NULL;
+
+ /* we do not want the test to depend on the timezone */
+ (void)putenv("TZ=UTC");
+ memset(pass_argv, 0, sizeof(pass_argv));
+#ifdef HAVE_SYSTEMD
+ /* we do not want the test to use systemd daemon startup notification*/
+ (void)unsetenv("NOTIFY_SOCKET");
+#endif /* HAVE_SYSTEMD */
+
+ checklock_start();
+ log_init(NULL, 0, NULL);
+ /* determine commandline options for the daemon */
+ pass_argc = 1;
+ pass_argv[0] = "unbound";
+ add_opts("-d", &pass_argc, pass_argv);
+
+ playback_file = buf_to_file(Data, Size);
+ if (playback_file) {
+ log_info("Start of %s testbound program.", PACKAGE_STRING);
+ scen = setup_playback(playback_file, &pass_argc, pass_argv);
+ fake_event_init(scen);
+
+ pass_argv[pass_argc] = NULL;
+ echo_cmdline(pass_argc, pass_argv);
+
+ res = daemon_main(pass_argc, pass_argv);
+ fake_event_cleanup();
+
+ if(res == 0) {
+ log_info("Testbound Exit Success\n");
+ /* remove configfile from here, the atexit() is for when
+ * there is a crash to remove the tmpdir file.
+ * This one removes the file while alloc and log locks are
+ * still valid, and can be logged (for memory calculation),
+ * it leaves the ptr NULL so the atexit does nothing. */
+ remove_configfile();
+#ifdef HAVE_PTHREAD
+ /* dlopen frees its thread state (dlopen of gost engine) */
+ pthread_exit(NULL);
+#endif
+ }
+
+ delete_file(playback_file);
+ }
+
+ if(log_get_lock()) {
+ lock_basic_destroy((lock_basic_type*)log_get_lock());
+ }
+ return res;
+}
+
/* fake remote control */
struct listen_port* daemon_remote_open_ports(struct config_file*
ATTR_UNUSED(cfg))Details on item 5: harden `testbound` itself
The below patch is required to get rid of false positives, when the fuzzing engine detects bugs in the testbound wrappers rather than in unbound itself. The patch was applied on top of commit 71bb60e.
The changes are minimal and "just make it work" style, maybe there are more robust ways of fixing these corner cases.
diff --git a/testcode/fake_event.c b/testcode/fake_event.c
index 48843f1..e6549f9 100644
--- a/testcode/fake_event.c
+++ b/testcode/fake_event.c
@@ -900,8 +900,9 @@ run_scenario(struct replay_runtime* runtime)
runtime->now->evt_type == repevt_front_reply) {
answer_check_it(runtime);
advance_moment(runtime);
- } else if(pending_matches_range(runtime, &entry, &pending)) {
- answer_callback_from_entry(runtime, entry, pending);
+ } else if(runtime->now && pending_matches_range(runtime, &entry, &pending)) {
+ if (entry)
+ answer_callback_from_entry(runtime, entry, pending);
} else {
do_moment_and_advance(runtime);
}
diff --git a/testcode/testpkts.c b/testcode/testpkts.c
index 8c68c48..0f288e1 100644
--- a/testcode/testpkts.c
+++ b/testcode/testpkts.c
@@ -927,6 +927,8 @@ pkt_snip_edns_option(uint8_t* pkt, size_t len, sldns_edns_option code,
while(rdlen > 0) {
if(rdlen < 4) return -1; /* malformed */
optlen = sldns_read_uint16(rdata+2);
+ if (optlen >= 65532U || rdlen < 4 + optlen)
+ return -1; /* malformed */
if(sldns_read_uint16(rdata) == code) {
/* save data to buf for caller inspection */
memmove(buf, rdata+4, optlen);
@@ -1134,8 +1136,9 @@ static void lowercase_dname(uint8_t** p, size_t* remain)
while(**p != 0) {
/* compressed? */
if((**p & 0xc0) == 0xc0) {
- *p += 2;
- *remain -= 2;
+ llen = *remain < 2 ? (unsigned int)*remain : 2;
+ *p += llen;
+ *remain -= llen;
return;
}
llen = (unsigned int)**p;
@@ -1178,6 +1181,12 @@ static void lowercase_rdata(uint8_t** p, size_t* remain,
uint8_t len;
if(rdataremain == 0) return;
len = **p;
+ if (len >= 255U || rdataremain < len+1) {
+ /* malformed LDNS_RDF_TYPE_STR, skip remainder */
+ *p += rdataremain;
+ *remain -= rdatalen;
+ return;
+ }
*p += len+1;
rdataremain -= len+1;
} else {
@@ -1207,6 +1216,12 @@ static void lowercase_rdata(uint8_t** p, size_t* remain,
break;
default: error("bad rdf type in lowercase %d", (int)f);
}
+ if (rdataremain < len) {
+ /* malformed RDF, skip remainder */
+ *p += rdataremain;
+ *remain -= rdatalen;
+ return;
+ }
*p += len;
rdataremain -= len;
}
diff --git a/testcode/replay.c b/testcode/replay.c
index 95dde40..2db3bc9 100644
--- a/testcode/replay.c
+++ b/testcode/replay.c
@@ -832,7 +832,10 @@ macro_expand(rbtree_type* store, struct replay_runtime* runtime, char** text)
}
/* actual macro text expansion */
+ int tries = 0;
while(*at) {
+ if (tries++ > 10000)
+ return NULL; /* looks like got into an infinite loop, bail out */
size_t remain = sizeof(buf)-strlen(buf);
if(strncmp(at, "${", 2) == 0) {
at = do_macro_recursion(store, runtime, at, remain);Note: There is one more bug in testbound code that I didn't know how to fix nicely. It needs discussion. Bug is: attach_edns_record() assumes that the package buffer-to-be-filled is large enough to hold the EDNS entries. Moreover, this func is void, so there are no checks and explicit asserts on the buffer size. Based on callers of this func, the buffer's size is calculated first and then correctly allocated to fit all EDNS entries. However, the testbound's fake_event.c wrapper outnet_serviced_query() simply allocates 512 bytes and assumes it will be enough for everything (which is not the case during fuzzing, where EDNS entries can be malformed and too large). My internal solution was to increase from 512B to 32KB, but this is just shifting the problem, not solving it.
Potential use-case
Fuzzing of an end-to-end test program like testbound uncovers real bugs, without false positives. Quick fuzzing runs detected several bugs which I reported to unbound maintainers: 1 2 3.
Activity
wcawijngaards commentedon May 21, 2025
The
testboundprogram can be compiled on its own withmake testbound.The commit adds changes when compiled with the define for fuzzing. The randomness change, and also the testbound main program is replaced by the new function. It was changed to share code with the normal main routine. I also picked up the hardening changes, and implemented edns size calculation for the
outnet_serviced_query()routine, that should fix that issue thoroughly. The default size is increased to 4096 bytes, for a fairly normal edns packet size.The items 2, 3, 4 and 5 should be covered. Hopefully this helps with the fuzzing efforts!
gthess commentedon May 21, 2025
Thanks @wcawijngaards !
(I am reopening the issue to allow discussion to continue)