// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Run the fuzz targets in `tests/fuzz.zig` against input this makes up. //! //! Zig has a fuzzer of its own and those targets are written for it, so //! `zig build fuzz --fuzz` is the thing to run when coverage is wanted. This //! is the plainer loop beside it: it makes an input, hands it to a target, and //! says so when one comes back with an error. What it has that Zig's does not is a bounded run of every //! target in turn, a leak check after every input, a watchdog for hangs, a //! seed that repeats a run exactly, and findings written where a workflow can //! keep them. //! //! ```console //! $ zig build fuzz-run # a minute of each //! $ zig build fuzz-run -- --seconds 300 --target netascii //! $ zig build fuzz-run -- --seed 12345 # exactly again //! $ zig build fuzz-run -- --input fuzz-findings/x.bin --target packets //! ``` //! //! # What an input is //! //! Not a file: a `std.testing.Smith` reads it as a stream of answers, and //! `smith.slice(buf)` reads **four** bytes as a little-endian `u32` length and //! then that many bytes of content. A length larger than `buf.len` is not //! reduced into range -- it yields an *empty* slice. So a string of random //! bytes gives a target nothing at all, and a generator that does not write a //! plausible length is fuzzing nothing. //! //! Every target here reads exactly one slice and takes any choices it has to //! make from that slice's first bytes, so `makeInput` writes one //! length-prefixed chunk, capped at the target's own buffer size, and each //! chunk is usually a mutation of one of the target's own seeds. That corpus //! is the whole of what stands in for coverage feedback: a packet that already //! parses gets past the opcode, and random bytes almost never do. //! //! # Panics //! //! A panic is the most important thing a fuzzer finds and the one thing it //! cannot return from, so the panic handler writes the running input out //! before handing over to the default one, which prints the trace. //! //! # The watchdog //! //! Nothing here should be able to loop, but "should" is what a fuzzer is for. //! A thread watches the clock, and an iteration that outlasts `--timeout` //! seconds is reported as a hang with the input that caused it. There is no //! way to unwind out of it, so that ends the run. const std = @import("std"); const targets = @import("fuzz_targets"); const Smith = std.testing.Smith; /// The session target fails transfers on purpose, and the server logs every /// one; only something worse than that is worth printing. pub const std_options: std.Options = .{ .log_level = .err }; /// Saves the input that panicked, then panics as usual. pub const panic = std.debug.FullPanic(fuzzPanic); fn fuzzPanic(msg: []const u8, first_trace_addr: ?usize) noreturn { if (watch.io) |io| if (watch.started_ms.load(.acquire) != 0) { std.debug.print("\n{s}: panic: {s}\n", .{ watch.target, msg }); saveInput(io, "panic"); }; std.debug.defaultPanic(msg, first_trace_addr); } /// Milliseconds on a clock that only goes forwards while the machine is up. fn nowMs(io: std.Io) i64 { return @intCast(@divFloor(std.Io.Timestamp.now(io, .awake).nanoseconds, std.time.ns_per_ms)); } /// What the watchdog needs to see, written before each iteration begins. const Watch = struct { /// When the running iteration started, or zero between iterations. started_ms: std.atomic.Value(i64) = .init(0), /// The input it is running, which is what a hang has to report. input: []const u8 = &.{}, target: []const u8 = "", timeout_s: u32 = 10, dir: []const u8 = "", /// For the panic handler, which is handed none. io: ?std.Io = null, }; var watch: Watch = .{}; pub fn main(init: std.process.Init) !void { const io = init.io; // Two allocators, and they have to be two. The targets are written to run // against the testing allocator, which cannot be named outside a test // build; this is the same thing by another route, a debug allocator whose // outstanding allocations are counted after every input, since a leak is // one of the things being fuzzed for. Nothing else may allocate from it -- // the loop's own buffer would be indistinguishable from a target's leak -- // so everything here uses the process allocator instead. var checked: std.heap.DebugAllocator(.{}) = .init; defer _ = checked.deinit(); targets.backing = checked.allocator(); const gpa = init.gpa; // The session target runs a server and a client at once, which needs an // `Io` that can run two tasks concurrently. It has an allocator of its own // for the same reason as the loop does. var threaded: std.Io.Threaded = .init(std.heap.smp_allocator, .{}); defer threaded.deinit(); targets.session_io = threaded.io(); var seconds: u32 = 60; var iterations: ?u64 = null; var seed: u64 = @bitCast(@as(i64, @truncate(std.Io.Timestamp.now(io, .real).nanoseconds))); var only: ?[]const u8 = null; var input_path: ?[]const u8 = null; var dir: []const u8 = "fuzz-findings"; var timeout_s: u32 = 10; var args: std.process.Args.Iterator = .init(init.minimal.args); _ = args.skip(); while (args.next()) |arg| { if (std.mem.eql(u8, arg, "--seconds")) { seconds = std.fmt.parseInt(u32, args.next() orelse "60", 10) catch 60; } else if (std.mem.eql(u8, arg, "--iterations")) { iterations = std.fmt.parseInt(u64, args.next() orelse "0", 10) catch null; } else if (std.mem.eql(u8, arg, "--seed")) { seed = std.fmt.parseInt(u64, args.next() orelse "0", 10) catch seed; } else if (std.mem.eql(u8, arg, "--target")) { only = args.next(); } else if (std.mem.eql(u8, arg, "--input")) { input_path = args.next(); } else if (std.mem.eql(u8, arg, "--findings")) { dir = args.next() orelse dir; } else if (std.mem.eql(u8, arg, "--timeout")) { timeout_s = std.fmt.parseInt(u32, args.next() orelse "10", 10) catch 10; } else { std.debug.print( \\usage: fuzz [--target NAME] [--seconds N | --iterations N] [--seed S] \\ [--timeout S] [--findings DIR] [--input FILE] \\ \\Targets: {s} \\ , .{targetNames()}); std.process.exit(2); } } watch.timeout_s = timeout_s; watch.dir = dir; watch.io = io; const thread = try std.Thread.spawn(.{}, watchdog, .{io}); thread.detach(); // One input, from a file, and nothing else: this is how a finding is // looked at again after it has been fixed. if (input_path) |path| { const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 20)); defer gpa.free(bytes); const name = only orelse targets.all[0].name; const target = find(name) orelse { std.debug.print("no target called {s}; there are: {s}\n", .{ name, targetNames() }); std.process.exit(2); }; watch.input = bytes; watch.target = target.name; watch.started_ms.store(nowMs(io), .release); target.run(bytes) catch |err| { std.debug.print("{s}: {t}\n", .{ target.name, err }); show(bytes); std.process.exit(1); }; std.debug.print("{s}: that input is fine now\n", .{target.name}); return; } var prng: std.Random.DefaultPrng = .init(seed); const random = prng.random(); var buffer: std.ArrayList(u8) = .empty; defer buffer.deinit(gpa); std.debug.print("seed {d}\n", .{seed}); var failures: usize = 0; for (targets.all) |target| { if (only) |name| if (!std.mem.eql(u8, name, target.name)) continue; var runs: u64 = 0; const deadline = nowMs(io) + @as(i64, seconds) * 1000; while (if (iterations) |n| runs < n else nowMs(io) < deadline) : (runs += 1) { try makeInput(gpa, &buffer, random, target); watch.input = buffer.items; watch.target = target.name; watch.started_ms.store(nowMs(io), .release); const result = target.run(buffer.items); watch.started_ms.store(0, .release); if (checked.detectLeaks() != 0) { std.debug.print("\n{s}: leaked\n", .{target.name}); try report(io, dir, target.name, buffer.items); std.process.exit(1); } result catch |err| { failures += 1; std.debug.print("\n{s}: {t}\n", .{ target.name, err }); try report(io, dir, target.name, buffer.items); // Keep going: one shape of failure is usually many inputs, and // stopping at the first says less than a handful does. if (failures >= 10) { std.debug.print("ten failures; stopping\n", .{}); std.process.exit(1); } }; } std.debug.print("{s}: {d} runs\n", .{ target.name, runs }); } if (failures != 0) std.process.exit(1); } fn find(name: []const u8) ?targets.Target { for (targets.all) |t| if (std.mem.eql(u8, t.name, name)) return t; return null; } fn targetNames() []const u8 { comptime var names: []const u8 = ""; inline for (targets.all, 0..) |t, i| { names = names ++ (if (i == 0) "" else ", ") ++ t.name; } return names; } /// Make the next input: one length-prefixed chunk, which is what every target /// reads. /// /// The length is capped at `target.content_max` rather than at some number /// chosen here, because `Smith.slice` answers a length larger than its buffer /// with an *empty* slice rather than a truncated one. Getting that wrong is /// silent: the target runs, reports no failure, and has been handed nothing. fn makeInput( gpa: std.mem.Allocator, out: *std.ArrayList(u8), random: std.Random, target: targets.Target, ) !void { out.clearRetainingCapacity(); var content: std.ArrayList(u8) = .empty; defer content.deinit(gpa); if (target.corpus.len == 0 or random.uintLessThan(u8, 8) == 0) { // Sometimes nothing but noise, so that the shapes nobody thought of // are reachable at all. Mostly short, since the targets that care // about length are the ones with a structure noise does not have. const len = random.uintLessThan(usize, @min(target.content_max, 4096)); try content.ensureUnusedCapacity(gpa, len); for (0..len) |_| content.appendAssumeCapacity(random.int(u8)); } else { const seed = target.corpus[random.uintLessThan(usize, target.corpus.len)]; try content.appendSlice(gpa, seed); const rounds = 1 + random.uintLessThan(usize, 8); for (0..rounds) |_| try mutate(gpa, &content, random, target); } if (content.items.len > target.content_max) { content.shrinkRetainingCapacity(target.content_max); } var length: [4]u8 = undefined; std.mem.writeInt(u32, &length, @intCast(content.items.len), .little); try out.appendSlice(gpa, &length); try out.appendSlice(gpa, content.items); } fn mutate(gpa: std.mem.Allocator, content: *std.ArrayList(u8), random: std.Random, target: targets.Target) !void { if (content.items.len == 0) { try content.append(gpa, random.int(u8)); return; } const at = random.uintLessThan(usize, content.items.len); switch (random.uintLessThan(u8, 10)) { // A byte, replaced. The commonest useful mutation, and the one that // turns an opcode into a nearly-an-opcode. 0, 1 => content.items[at] = random.int(u8), // A byte, replaced by one of the ones this protocol is made of. 2, 3 => content.items[at] = interesting[random.uintLessThan(usize, interesting.len)], 4 => try content.insert(gpa, at, random.int(u8)), 5 => try content.insert(gpa, at, interesting[random.uintLessThan(usize, interesting.len)]), // A word from the protocol, which a byte at a time would never spell. 6 => try content.insertSlice(gpa, at, words[random.uintLessThan(usize, words.len)]), // A splice of another seed, which is how a request grows a second // option or a script grows a packet it did not have. 7 => if (target.corpus.len > 0) { const other = target.corpus[random.uintLessThan(usize, target.corpus.len)]; if (other.len > 0) { const from = random.uintLessThan(usize, other.len); const len = 1 + random.uintLessThan(usize, other.len - from); try content.insertSlice(gpa, at, other[from..][0..len]); } }, // A run of the same byte, which is how a buffer is filled to its edge. 8 => { const byte = interesting[random.uintLessThan(usize, interesting.len)]; try content.appendNTimes(gpa, byte, 1 + random.uintLessThan(usize, 64)); }, else => _ = content.orderedRemove(at), } } /// The bytes TFTP is mostly made of: the ends of strings and lines, the /// halves of opcodes and block numbers, and digits for option values. const interesting = blk: { var set: []const u8 = &.{ 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xff }; set = set ++ "\r\n\r\n\r\n"; set = set ++ "0123456789"; break :blk set; }; /// Whole words the protocol is made of. const words = [_][]const u8{ "octet\x00", "netascii\x00", "mail\x00", "blksize\x00", "timeout\x00", "tsize\x00", "0\x00", "8\x00", "512\x00", "65464\x00", "65465\x00", "\r\x00", "\r\n", "\x00\x03", "\x00\x04", "\x00\x05", "\xff\xff", "\x00\x00", }; /// Print a failing input and write it where it can be fed back. fn report(io: std.Io, dir: []const u8, target: []const u8, input: []const u8) !void { show(input); var name: [128]u8 = undefined; const path = std.fmt.bufPrint(&name, "{s}/{s}-{x:0>16}.bin", .{ dir, target, std.hash.Wyhash.hash(0, input), }) catch return; std.Io.Dir.cwd().createDirPath(io, dir) catch {}; var file = std.Io.Dir.cwd().createFile(io, path, .{}) catch |err| { std.debug.print("(could not write {s}: {t})\n", .{ path, err }); return; }; defer file.close(io); file.writeStreamingAll(io, input) catch {}; std.debug.print( "written to {s}, and `--input {s} --target {s}` runs it again\n", .{ path, path, target }, ); } /// What a target actually reads out of an input, in hex: the slice after the /// length. At most the first 256 bytes, which is where a finding's interesting /// part almost always is. fn show(input: []const u8) void { var smith: Smith = .{ .in = input }; const buffer = std.heap.page_allocator.alloc(u8, 1 << 17) catch return; defer std.heap.page_allocator.free(buffer); const content = buffer[0..smith.slice(buffer)]; std.debug.print("input, {d} bytes of content:\n ", .{content.len}); for (content[0..@min(content.len, 256)], 0..) |b, i| { if (i != 0 and i % 32 == 0) std.debug.print("\n ", .{}); std.debug.print(" {x:0>2}", .{b}); } if (content.len > 256) std.debug.print(" ...", .{}); std.debug.print("\n", .{}); } /// Watch for an iteration that never ends. fn watchdog(io: std.Io) void { while (true) { std.Io.sleep(io, .fromMilliseconds(500), .awake) catch return; const started = watch.started_ms.load(.acquire); if (started == 0) continue; const elapsed = nowMs(io) - started; if (elapsed < @as(i64, watch.timeout_s) * 1000) continue; std.debug.print( "\n{s}: no answer after {d} seconds, which is a hang\n", .{ watch.target, @divTrunc(elapsed, 1000) }, ); saveInput(io, "hang"); std.process.exit(3); } } /// Shows the running input and writes it into the findings directory, named /// for `kind` of failure, for when the failure cannot be returned from. fn saveInput(io: std.Io, kind: []const u8) void { show(watch.input); var name: [128]u8 = undefined; const path = std.fmt.bufPrint(&name, "{s}/{s}-{s}-{x:0>16}.bin", .{ watch.dir, watch.target, kind, std.hash.Wyhash.hash(0, watch.input), }) catch return; std.Io.Dir.cwd().createDirPath(io, watch.dir) catch {}; if (std.Io.Dir.cwd().createFile(io, path, .{})) |file| { defer file.close(io); file.writeStreamingAll(io, watch.input) catch {}; std.debug.print( "written to {s}, and `--input {s} --target {s}` runs it again\n", .{ path, path, watch.target }, ); } else |_| {} }