// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! What the parser must do with a file nobody wrote. //! //! A zone file is usually something a person typed, which is exactly why this //! matters: the file that breaks a parser is the one somebody typed badly, at //! three in the morning, into a zone that is already live. The properties here //! are the ones that have to hold for *any* input at all: //! //! * it terminates -- which is a real question for a format with `$GENERATE` //! in it, and for a lexer that puts characters back; //! * it never leaves the buffer it was given, and never leaks; //! * whatever it accepted, it can write out, and reading that back gives the //! same records. //! //! That last one is the one that catches a reader and a writer which have //! drifted apart -- a type whose fields are written in one order and read in //! another -- and no test written against a fixed example can see it. //! //! Each target is an ordinary test as well as a fuzz target. Its seeds are //! handed to `testing.fuzz` as its corpus, which without `--fuzz` runs each of //! them once, so `zig build test` exercises the same properties on input that //! has already been interesting once -- and with `--fuzz` is where Zig's //! fuzzer starts from. //! //! ### Compared against something that is not this //! //! Everything here is self-consistency. The check against somebody else's //! opinion is `zig build differential`, which puts the same zone files to //! BIND's parser and compares the records the two of them found. //! //! `zig build fuzz --fuzz` hands these to Zig's own fuzzer, which steers by //! coverage; `zig build fuzz-run` hands them to a loop of our own, which //! steers by the seeds and can be told exactly how many inputs to try. const std = @import("std"); const builtin = @import("builtin"); const Allocator = std.mem.Allocator; const Reader = std.Io.Reader; const Writer = std.Io.Writer; const testing = std.testing; const Smith = std.testing.Smith; const corpus = @import("corpus"); const dns = @import("dns"); const zone = @import("zone"); /// Where the targets get memory. /// /// `std.testing.allocator` exists only in a test build, and these targets are /// reached from `tools/fuzz.zig` as well, which is a program. So the allocator /// is a variable: the test runner leaves it as the testing one, and the /// standalone driver points it at a `DebugAllocator` it checks for leaks after /// every input. pub var backing: Allocator = if (builtin.is_test) testing.allocator else undefined; /// Seeds as `testing.fuzz` wants them, which is in the encoding a `Smith` /// reads rather than as the text a target is handed: each slice a target asks /// for is its length as four little-endian bytes and then the bytes. Handing /// Zig's fuzzer these is what has it start from files that already parse /// instead of from nothing; a zone file is a grammar, and random bytes are /// refused by the first token. fn smithCorpus(comptime seeds: []const []const u8) [seeds.len][]const u8 { var out: [seeds.len][]const u8 = undefined; for (seeds, &out) |seed, *one| one.* = smithSlice(seed); return out; } fn smithSlice(comptime bytes: []const u8) []const u8 { const len: [4]u8 = @bitCast(std.mem.nativeToLittle(u32, bytes.len)); return &len ++ bytes; } // -- whole zone files ---------------------------------------------------------- /// The corpus, and then the shapes a real zone file will never have. const zone_seeds = blk: { var seeds: []const []const u8 = &.{}; for (corpus.zones) |sample| seeds = seeds ++ [_][]const u8{sample.text}; break :blk seeds ++ [_][]const u8{ // The smallest zone there is. "@ 60 IN SOA ns1.example.com. h.example.com. 1 2 3 4 5\n", // Directives, which are the only way to change what a later line // means. "$ORIGIN example.com.\n$TTL 1h\n@ IN NS ns1\n", "$INCLUDE other.zone\n", "$GENERATE 1-10 host-$ A 192.0.2.$\n", "$GENERATE 1-10/2 ${0,4,x} PTR a.\n", // Every radix, and the offsets that take a value out of range. "$GENERATE 0-17 ${0,3,o}.${0,2,X}.${-3,0,d} PTR a.\n", "$GENERATE 250-260 ${0,0,n}.${0,4,N} PTR a.\n", "$GENERATE 0-2 ${-5} A 192.0.2.1\n", "$GENERATE 0-2 ${4294967295} A 192.0.2.1\n", "$GENERATE 0-2 ${1,2,q} A 192.0.2.1\n", "$GENERATE 0-2 ${1,2,x,y} A 192.0.2.1\n", "$GENERATE 0-1 a$ 60 IN TXT \"$ \\$ $$\"\n", "$GENERATE 0-1 $..$ A 192.0.2.1\n", // A time to live that is not one, and a file that never gives one. "a 1x IN A 192.0.2.1\n", "$TTL 1w2d3h4m5s\na IN A 192.0.2.1\n", // Quoting and escaping, which is where a lexer goes wrong. "a IN TXT \"unterminated\n", "a IN TXT \"a\\\"b\" \"c\"\n", "a\\.b IN A 192.0.2.1\n", "a IN A 192.0.2.1 ; comment\n", "a IN ( A\n 192.0.2.1 )\n", // The generic syntax, whose length is the thing to lie about. "a IN TYPE65280 \\# 4 01020304\n", "a IN A \\# 4 01020304\n", // Empty, blank, and not a zone file at all. "", "\n\n\n", " \n\t\n", "GET / HTTP/1.1\r\n\r\n", }; }; /// Whatever arrives, reading it either fails or produces records that can be /// written out and read back as the same records. fn zoneProperty(input: []const u8) !void { const options: zone.Zone.ParseOptions = .{ .origin = "example.com.", .default_ttl = 3600, }; var diagnostics: zone.Diagnostics = .{}; var with_diagnostics = options; with_diagnostics.file = "fuzz.zone"; with_diagnostics.diagnostics = &diagnostics; var reader = Reader.fixed(input); var first = zone.Zone.parse(backing, &reader, with_diagnostics) catch |err| { // Out of memory is the machine's problem and not the input's; anything // else is the parser refusing, which is its job. if (err == error.OutOfMemory) return err; try diagnosticProperty(&diagnostics); // A diagnostics is documented as not load-bearing: the same input is // refused with the same error without one. Only checked on the way // out, because a refusal is where the two paths differ -- every // `note` is on one. var plain = Reader.fixed(input); if (zone.Zone.parse(backing, &plain, options)) |accepted| { var z = accepted; z.deinit(); return error.DiagnosticsChangedTheOutcome; } else |plain_err| try testing.expectEqual(err, plain_err); return; }; defer first.deinit(); try roundTrip(&first); } /// A refusal always says why, and the diagnostic saying it always prints and /// always fits in what it was given. fn diagnosticProperty(diagnostics: *const zone.Diagnostics) !void { if (diagnostics.message().len == 0) return error.RefusedWithoutSayingWhy; try testing.expect(diagnostics.message().len <= diagnostics.buffer.len); var buffer: [512]u8 = undefined; var w = Writer.fixed(&buffer); try w.print("{f}", .{diagnostics.*}); } /// What a zone that was read must survive: every record decodes, and writing /// it out and reading it back gives the same records, the same way twice. fn roundTrip(first: *const zone.Zone) !void { // Every record it accepted decodes -- it was decoded once already, on the // way in, and a record that only decodes sometimes is a finding. for (first.records()) |rr| _ = try rr.data(); var written: Writer.Allocating = .init(backing); defer written.deinit(); try first.write(&written.writer, .{}); var back = Reader.fixed(written.written()); var second = zone.Zone.parse(backing, &back, .{}) catch |err| { if (err == error.OutOfMemory) return err; std.debug.print("could not read back:\n{s}\n", .{written.written()}); return error.WrittenZoneDidNotParse; }; defer second.deinit(); try testing.expectEqual(first.count(), second.count()); for (first.records(), second.records()) |before, after| { try testing.expect(before.eql(after)); try testing.expectEqual(before.ttl, after.ttl); } // And writing is a fixpoint: the second file written is the same as the // third, which is what makes the output a canonical form rather than an // echo of the input. It is the second and third rather than the first and // second because the first parse was told an origin and the ones after it // work it out from the `soa`, and those two can differ for a file whose // apex is not the origin it was read with. var again: Writer.Allocating = .init(backing); defer again.deinit(); try second.write(&again.writer, .{}); var third_reader = Reader.fixed(again.written()); var third = zone.Zone.parse(backing, &third_reader, .{}) catch |err| { if (err == error.OutOfMemory) return err; return error.WrittenZoneDidNotParse; }; defer third.deinit(); var once_more: Writer.Allocating = .init(backing); defer once_more.deinit(); try third.write(&once_more.writer, .{}); try testing.expectEqualStrings(again.written(), once_more.written()); } test "fuzz zone files" { try testing.fuzz({}, fuzzZone, .{ .corpus = &comptime smithCorpus(zone_seeds) }); } fn fuzzZone(_: void, smith: *Smith) !void { var buffer: [8192]u8 = undefined; const len = smith.slice(&buffer); try zoneProperty(buffer[0..len]); } // -- one entry ------------------------------------------------------------------- /// A single record's worth of text. The same property as a whole file, but the /// generator spends every byte on one entry rather than on the shape of a /// file, which is what reaches the record types. const entry_seeds = [_][]const u8{ "a 3600 IN A 192.0.2.1", "a 3600 IN AAAA 2001:db8::1", "a 3600 IN MX 10 mail.example.com.", "a 3600 IN TXT \"one\" \"two\"", "a 3600 IN SRV 10 20 5060 sip.example.com.", "a 3600 IN SVCB 1 . alpn=h2,h3 port=443 ipv4hint=192.0.2.1 mandatory=alpn", "a 3600 IN HTTPS 0 svc.example.net.", "a 3600 IN NSEC next.example.com. A MX RRSIG NSEC TYPE1234", "a 3600 IN NSEC3 1 1 12 aabbccdd 2vptu5timamqttgl4luu9kg21e0aor3s A RRSIG", "a 3600 IN RRSIG A 8 3 3600 20250119180000 20250113180000 1 example.com. AQID", "a 3600 IN DNSKEY 256 3 8 AwEAAQ==", "a 3600 IN DS 12345 8 2 49FD46E6C4B45C55D4AC69CBD3CD34AC1AFE51DE", "a 3600 IN LOC 42 21 54 N 71 06 18 W -24m 30m 10m 2m", "a 3600 IN APL 1:192.0.2.0/24 !2:2001:db8::/32", "a 3600 IN WKS 192.0.2.1 tcp smtp domain 65535", "a 3600 IN HIP 2 200100107B1A74DF365639CC39F1D578 AQID rvs.example.com.", "a 3600 IN IPSECKEY 10 3 2 gateway.example.com. AQID", "a 3600 IN CAA 0 issue \"letsencrypt.org\"", "a 3600 IN NAPTR 100 10 \"u\" \"E2U+sip\" \"!^.*$!sip:x@example.com!\" .", "a 3600 IN TYPE65280 \\# 3 010203", "a 3600 IN CLASS7 TYPE7 \\# 0", // The corners of the types above that one example of each does not // reach: every service parameter and the ones given twice, each kind of // gateway and relay, the locator and EUI forms, a date on the day only a // leap year has, and the limits a field can be written past. "a 3600 IN SVCB 1 svc.example. mandatory=alpn,ipv6hint alpn=h2 no-default-alpn port=53 ipv4hint=192.0.2.1,192.0.2.2 ech=AEX+ ipv6hint=2001:db8::1,::ffff:192.0.2.1 key65000=\"a\\044b\\\\c\"", "a 3600 IN SVCB 1 . port=1 port=2", "a 3600 IN SVCB 1 . key7=\"\" key65535", "a 3600 IN HTTPS 1 . mandatory alpn=\"h2,h3\"", "a 3600 IN IPSECKEY 10 0 2 . AQID", "a 3600 IN IPSECKEY 10 1 2 192.0.2.1 AQID", "a 3600 IN IPSECKEY 10 2 2 2001:db8::1 AQID", "a 3600 IN AMTRELAY 10 0 0 .", "a 3600 IN AMTRELAY 10 1 1 192.0.2.1", "a 3600 IN AMTRELAY 10 0 2 2001:db8::1", "a 3600 IN AMTRELAY 10 1 3 relay.example.com.", "a 3600 IN L64 10 2001:0db8:1140:1000", "a 3600 IN NID 10 0014:4fff:ff20:ee64", "a 3600 IN L32 10 192.0.2.1", "a 3600 IN LP 10 l64.example.com.", "a 3600 IN EUI48 00-00-5e-00-53-2a", "a 3600 IN EUI64 00-00-5e-ef-10-00-00-2a", "a 3600 IN LOC 0 S 0 E 0m", "a 3600 IN LOC 90 0 0.000 S 180 0 0.000 E -100000.00m 90000000m 90000000m 90000000m", "a 3600 IN LOC 42 21 N 71 W 42849672.95m 1m", "a 3600 IN RRSIG A 8 3 3600 20240229000000 20000229235960 1 example.com. AQID", "a 3600 IN RRSIG A RSASHA256 3 3600 1700000000 1600000000 1 example.com. AQID", "a 3600 IN NXT next.example.com. A NS SOA TYPE127", "a 3600 IN APL 1:0.0.0.0/0 2:::/128 !1:192.0.2.1/32", "a 3600 IN TXT \"" ++ @as([255]u8, @splat('x')) ++ "\"", "a 3600 IN CAA 128 tbs \"\"", "a 3600 IN WKS 192.0.2.1 6 25 53", "a 3600 IN CERT PKIX 0 0 AQID", "a 3600 IN TYPE65280 \\# 0", "a 3600 IN AXFR \\# 0", "a IN A 192.0.2.1", "a 1h2m3s IN A 192.0.2.1", "$INCLUDE other.zone", }; fn entryProperty(input: []const u8) !void { var z = zone.Zone.init(backing, "example.com.") catch return; defer z.deinit(); z.addText(input, .{ .default_ttl = 3600 }) catch |err| { if (err == error.OutOfMemory) return err; return; }; for (z.records()) |rr| { var line: Writer.Allocating = .init(backing); defer line.deinit(); try zone.write.record(&line.writer, rr, .canonical); var reader = Reader.fixed(line.written()); var again = zone.Zone.parse(backing, &reader, .{ .origin = "example.com." }) catch |err| { if (err == error.OutOfMemory) return err; std.debug.print("could not read back: {s}", .{line.written()}); return error.WrittenRecordDidNotParse; }; defer again.deinit(); try testing.expectEqual(@as(usize, 1), again.count()); try testing.expect(rr.eql(again.records()[0])); } } test "fuzz entries" { try testing.fuzz({}, fuzzEntry, .{ .corpus = &comptime smithCorpus(&entry_seeds) }); } fn fuzzEntry(_: void, smith: *Smith) !void { var buffer: [2048]u8 = undefined; const len = smith.slice(&buffer); try entryProperty(buffer[0..len]); } // -- names in presentation form --------------------------------------------------- /// The longest label a name may hold. const a63: [63]u8 = @splat('a'); const name_seeds = [_][]const u8{ "example.com.", "www.example.com", "@", ".", "*", "a\\.b", "a\\\\b", "\\000", "\\255.\\032", &a63, &@as([64]u8, @splat('a')), a63 ++ "." ++ a63 ++ "." ++ a63 ++ "." ++ a63 ++ ".", "..", "a..b", "", }; /// A name that encodes is a name the message library can read, and a name it /// can read is one that comes back as the same name through its own text. fn nameProperty(input: []const u8) !void { const origin = dns.Name.literal("example.com"); for ([_]?dns.Name{ null, origin }) |under| { var buffer: dns.Name.Buffer = undefined; const encoded = zone.name.encode(&buffer, input, under) catch continue; // What came out is a name, by the other library's reckoning, and is // within every limit the wire format has. const parsed = try dns.Name.fromBytes(encoded.message); try testing.expect(parsed.encodedLen() <= dns.Name.max_encoded_len); try testing.expect(parsed.labelCount() <= dns.Name.max_labels); // Its presentation form reads back as the same name, absolute this // time, which is what the escaping is for. var text: dns.Name.TextBuffer = undefined; const written = try parsed.toText(&text); var again: dns.Name.Buffer = undefined; const reparsed = try zone.name.encode(&again, written, null); try testing.expect(parsed.eql(reparsed)); // And so does the relative form, read back under the origin it was // written against. if (under) |apex| { var relative: Writer.Allocating = .init(backing); defer relative.deinit(); try zone.name.writeRelative(&relative.writer, parsed, apex); var third: dns.Name.Buffer = undefined; const shortened = try zone.name.encode(&third, relative.written(), apex); try testing.expect(parsed.eql(shortened)); } } } test "fuzz names" { try testing.fuzz({}, fuzzName, .{ .corpus = &comptime smithCorpus(&name_seeds) }); } fn fuzzName(_: void, smith: *Smith) !void { var buffer: [1024]u8 = undefined; const len = smith.slice(&buffer); try nameProperty(buffer[0..len]); } // -- the lexer on its own ----------------------------------------------------------- /// Tokenizing terminates and stays inside the input, whatever the input is. /// The parser above covers this as well, but only for text that gets far /// enough to be a record; this reaches the shapes that do not. fn lexerProperty(input: []const u8) !void { var reader = Reader.fixed(input); var lexer: zone.Lexer = .{ .reader = &reader }; defer lexer.deinit(backing); var tokens: usize = 0; while (true) { const token = lexer.next(backing) catch |err| { if (err == error.OutOfMemory) return err; return; }; if (token.kind == .end_of_file) break; if (token.kind == .string) { // Every token is bytes that were in the input, and no token can be // longer than the input it came from. const text = lexer.text(token); try testing.expect(text.len <= input.len); } tokens += 1; // A token for every byte is the most there can be; more than that // means something is producing tokens out of nothing. try testing.expect(tokens <= input.len + 1); } } test "fuzz the lexer" { try testing.fuzz({}, fuzzLexer, .{ .corpus = &comptime smithCorpus(zone_seeds ++ &entry_seeds) }); } fn fuzzLexer(_: void, smith: *Smith) !void { var buffer: [8192]u8 = undefined; const len = smith.slice(&buffer); try lexerProperty(buffer[0..len]); } // -- $INCLUDE ---------------------------------------------------------------------- /// A file that includes, and the file every `$INCLUDE` in it names. The second /// may include as well, and then it includes itself, which is how the depth /// limit is reached. const include_seeds = [_][]const u8{ "$TTL 60\n$INCLUDE other.zone\n@ IN A 192.0.2.1\n", "$INCLUDE other.zone sub.example.com.\nwww IN A 192.0.2.1\n", "$INCLUDE other.zone sub\n$INCLUDE other.zone\n", "$TTL 60\n$INCLUDE \"other zone\" @\nafter IN TXT \"here\"\n", "a IN A 192.0.2.1\n$INCLUDE other.zone\n IN AAAA 2001:db8::1\n", "$INCLUDE other.zone bad..origin\n", "$INCLUDE\n", "$INCLUDE a b c\n", // What an included file is, with no `$INCLUDE` of its own and then with // one. "$ORIGIN elsewhere.example.\n$TTL 5\nwww IN CNAME @\n", "inside IN TXT \"included\"\n$INCLUDE again.zone\n", }; /// Following includes either fails or reads records that survive the same /// round trip as a whole file, and it leaks nothing whichever it does -- /// several readers deep, with each one's origin, owner and time to live to /// be put back. fn includeProperty(top: []const u8, included: []const u8) !void { const max_depth = 4; var diagnostics: zone.Diagnostics = .{}; var reader = Reader.fixed(top); // No default time to live, unlike the other targets: what a `$TTL` sets // inside an included file has to be put back when the file ends, and a // record that then has none is refused rather than given the wrong one. var parser = zone.Parser.init(backing, &reader, .{ .origin = "example.com.", .includes = .report, .max_include_depth = max_depth, .file = "top.zone", .diagnostics = &diagnostics, }) catch |err| { if (err == error.OutOfMemory) return err; return; }; defer parser.deinit(); var z = try zone.Zone.init(backing, "example.com."); defer z.deinit(); // The parser reads out of these until it is done, so they outlive it. // One more than it will accept, so that refusing is its decision. var readers: [max_depth + 2]Reader = undefined; var depth: usize = 0; while (true) { const item = parser.next() catch |err| { if (err == error.OutOfMemory) return err; return diagnosticProperty(&diagnostics); } orelse break; switch (item) { .record => |rr| z.add(rr) catch |err| { if (err == error.OutOfMemory) return err; return; }, .include => |include| { try testing.expect(depth < readers.len); readers[depth] = Reader.fixed(included); // The path names the file in a diagnostic for as long as the // parser is in it, which is longer than the path is promised // to last; a diagnostic printed from inside is how that would // show. parser.pushInclude(&readers[depth], include.path) catch |err| { if (err == error.OutOfMemory) return err; return diagnosticProperty(&diagnostics); }; depth += 1; }, } } try roundTrip(&z); } test "fuzz includes" { try testing.fuzz({}, fuzzInclude, .{ .corpus = &include_corpus }); } /// Every pair of seeds, one as the file and one as what it includes. const include_corpus = blk: { var pairs: [include_seeds.len * include_seeds.len][]const u8 = undefined; for (include_seeds, 0..) |top, i| { for (include_seeds, 0..) |included, j| { pairs[i * include_seeds.len + j] = smithSlice(top) ++ smithSlice(included); } } break :blk pairs; }; fn fuzzInclude(_: void, smith: *Smith) !void { var top: [4096]u8 = undefined; const top_len = smith.slice(&top); var included: [4096]u8 = undefined; const included_len = smith.slice(&included); try includeProperty(top[0..top_len], included[0..included_len]); } // -- the table the standalone driver reads ------------------------------------------ pub const Target = struct { name: []const u8, run: *const fn (input: []const u8) anyerror!void, /// Inputs worth mutating: the same seeds the tests above run, which are /// what stands in for the coverage feedback a real fuzzer would have. corpus: []const []const u8, /// The buffer this target reads its input into. /// /// `Smith.slice` yields an *empty* slice for a length larger than the /// buffer rather than a truncated one, so a generator that does not know /// this number hands the target nothing at all most of the time. content_max: usize, }; /// Wraps one of the `fuzz*` functions above so that it takes raw bytes. fn Driven(comptime one: fn (void, *Smith) anyerror!void) type { return struct { fn run(input: []const u8) anyerror!void { var smith: Smith = .{ .in = input }; return one({}, &smith); } }; } comptime { // A seed longer than its target's buffer reaches it as the empty string, // silently, so a seed that has outgrown it fails the build instead. for (all) |target| { for (target.corpus) |seed| std.debug.assert(seed.len <= target.content_max); } } pub const all = [_]Target{ .{ .name = "zonefile", .run = Driven(fuzzZone).run, .corpus = zone_seeds, .content_max = 8192 }, .{ .name = "entry", .run = Driven(fuzzEntry).run, .corpus = &entry_seeds, .content_max = 2048 }, .{ .name = "names", .run = Driven(fuzzName).run, .corpus = &name_seeds, .content_max = 1024 }, .{ .name = "includes", .run = Driven(fuzzInclude).run, .corpus = &include_seeds, .content_max = 4096 }, .{ .name = "lexer", .run = Driven(fuzzLexer).run, .corpus = zone_seeds ++ &entry_seeds, .content_max = 8192 }, };