| 1 |
/* SPDX-License-Identifier: LGPL-2.1-or-later */ |
| 2 |
|
| 3 |
/* Fuzz target for the sd-hwdb binary trie parser. |
| 4 |
* |
| 5 |
* sd-hwdb consumes an mmap'd hwdb.bin produced by `systemd-hwdb update`. The |
| 6 |
* file is walked via offset-chasing into struct trie_node_f / trie_child_entry_f |
| 7 |
* / trie_value_entry_f records. A malformed file can drive the walker outside |
| 8 |
* the mapped region; the validators in trie_node_from_off / trie_string don't |
| 9 |
* guard every dereference site. |
| 10 |
* |
| 11 |
* Expected input: bytes that look like an `hwdb.bin` file (header magic |
| 12 |
* "KSLPHHRH" + trie). The harness writes the fuzzer bytes to a temp file, |
| 13 |
* mmaps it via sd_hwdb_new_from_path, then exercises sd_hwdb_get (which |
| 14 |
* drives trie_search_f / trie_fnmatch_f) and sd_hwdb_seek + sd_hwdb_enumerate |
| 15 |
* (capped to bound infinite loops via crafted offset cycles). |
| 16 |
*/ |
| 17 |
|
| 18 |
#include <unistd.h> |
| 19 |
|
| 20 |
#include "sd-hwdb.h" |
| 21 |
|
| 22 |
#include "fd-util.h" |
| 23 |
#include "fileio.h" |
| 24 |
#include "fuzz.h" |
| 25 |
#include "tests.h" |
| 26 |
#include "tmpfile-util.h" |
| 27 |
|
| 28 |
#define MAX_ENUMERATE 1024 |
| 29 |
|
| 30 |
static const char * const modaliases[] = { |
| 31 |
"pci:v00008086d00000A04", |
| 32 |
"usb:v1234p5678", |
| 33 |
"acpi:PNP0C0D:", |
| 34 |
"dmi:bvnLENOVO:bvrR0KET20W:bd02/01/2020:svnLENOVO:pnThinkPadX1:", |
| 35 |
"*", |
| 36 |
}; |
| 37 |
|
| 38 |
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { |
| 39 |
_cleanup_(unlink_tempfilep) char filename[] = "/tmp/fuzz-hwdb.XXXXXX"; |
| 40 |
_cleanup_fclose_ FILE *f = NULL; |
| 41 |
_cleanup_(sd_hwdb_unrefp) sd_hwdb *hwdb = NULL; |
| 42 |
|
| 43 |
if (outside_size_range(size, 0, 4 * 1024 * 1024)) |
| 44 |
return 0; |
| 45 |
|
| 46 |
fuzz_setup_logging(); |
| 47 |
|
| 48 |
ASSERT_OK(fmkostemp_safe(filename, "r+", &f)); |
| 49 |
if (size != 0) |
| 50 |
ASSERT_OK_EQ_ERRNO((ssize_t) fwrite(data, size, 1, f), (ssize_t) 1); |
| 51 |
ASSERT_OK(fflush_and_check(f)); |
| 52 |
|
| 53 |
if (sd_hwdb_new_from_path(filename, &hwdb) < 0) |
| 54 |
return 0; |
| 55 |
|
| 56 |
FOREACH_ELEMENT(modalias, modaliases) { |
| 57 |
const char *key, *value; |
| 58 |
size_t n = 0; |
| 59 |
|
| 60 |
(void) sd_hwdb_get(hwdb, *modalias, "ID_VENDOR", &value); |
| 61 |
|
| 62 |
if (sd_hwdb_seek(hwdb, *modalias) < 0) |
| 63 |
continue; |
| 64 |
while (sd_hwdb_enumerate(hwdb, &key, &value) > 0) { |
| 65 |
DO_NOT_OPTIMIZE(key); |
| 66 |
DO_NOT_OPTIMIZE(value); |
| 67 |
if (++n >= MAX_ENUMERATE) |
| 68 |
break; |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
return 0; |
| 73 |
} |