From dd49204609c7b900a45c4e2b45f38fe27c620dac Mon Sep 17 00:00:00 2001 From: Emil Mikulic Date: Mon, 18 Jan 2021 00:25:02 +1100 Subject: [PATCH] Add a fuzzer that runs the server in the background. --- devel/fuzz_socket.cc | 55 ++++++++++++++++++++++++++++++++++++++++++++ devel/fuzz_socket.sh | 7 ++++++ 2 files changed, 62 insertions(+) create mode 100644 devel/fuzz_socket.cc create mode 100755 devel/fuzz_socket.sh diff --git a/devel/fuzz_socket.cc b/devel/fuzz_socket.cc new file mode 100644 index 0000000..bc7e9cd --- /dev/null +++ b/devel/fuzz_socket.cc @@ -0,0 +1,55 @@ +// Fuzzer that runs darkhttpd in a background thread. +#include +#include +#include +#include +#include +#include + +#include + +extern "C" int darkhttpd(int argc, const char** argv); + +namespace { +int argc = 4; +const char* argv[] = {"./a.out", "tmp.fuzz", "--log", "/dev/null"}; +std::thread* thr; +const char* host = "127.0.0.1"; +int port = 8080; +struct sockaddr_in addrin; +} // namespace + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + static bool inited = false; + if (!inited) { + thr = new std::thread([]() { darkhttpd(argc, argv); }); + addrin.sin_family = AF_INET; + addrin.sin_port = htons(port); + if (inet_aton(host, &addrin.sin_addr) == 0) err(1, "inet_aton"); + inited = true; + sleep(1); + } + + char buf[4096]; + ssize_t rcvd, sent; + + int fd = socket(AF_INET, SOCK_STREAM, 0); + if (fd == -1) err(1, "socket"); + + if (connect(fd, (const struct sockaddr*)&addrin, sizeof(struct sockaddr)) == + -1) + err(1, "connect"); + + sent = send(fd, data, size, 0); + if (sent != size) err(1, "send"); + + send(fd, "\n\n\n", 3, 0); // To finish the request so we can recv(). + + rcvd = recv(fd, buf, sizeof(buf), 0); + // if (rcvd == -1) err(1, "recv"); + close(fd); + + return 0; +} + +/* vim:set ts=2 sw=2 sts=2 expandtab tw=78: */ diff --git a/devel/fuzz_socket.sh b/devel/fuzz_socket.sh new file mode 100755 index 0000000..e71a151 --- /dev/null +++ b/devel/fuzz_socket.sh @@ -0,0 +1,7 @@ +#!/bin/bash -e +set -x +mkdir -p tmp.fuzz +echo hi > tmp.fuzz/hello.txt +clang -c -Dmain=darkhttpd -g -O2 -fsanitize=fuzzer,address ../darkhttpd.c -o fuzz_darkhttpd.o +clang++ -g -O2 -fsanitize=fuzzer,address fuzz_socket.cc fuzz_darkhttpd.o -o fuzz_socket +./fuzz_socket fuzz_socket_testcases -detect_leaks=0 -only_ascii=1