Something went wrong. Try again.
BIND zone files for Zig 0.16: read one, edit it, write it back
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// 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. Without `--fuzz`//! it runs the seeds beside it, so `zig build test` exercises the same//! properties on input that has already been interesting once.//!//! ### 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.//!//! Note that Zig 0.16.0 cannot build a test executable in fuzz mode without a//! patched standard library, and leaves the fuzzer's coverage table empty even//! then; the flake in this repository says more, and `zig build fuzz-run` is//! the loop that works.
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;
// -- 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", // 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 { var reader = Reader.fixed(input); var first = zone.Zone.parse(backing, &reader, .{ .origin = "example.com.", .default_ttl = 3600, }) 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; return; }; defer first.deinit();
// 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" { for (zone_seeds) |seed| try zoneProperty(seed); try testing.fuzz({}, fuzzZone, .{});}
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",};
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" { for (entry_seeds) |seed| try entryProperty(seed); try testing.fuzz({}, fuzzEntry, .{});}
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 ---------------------------------------------------
const name_seeds = [_][]const u8{ "example.com.", "www.example.com", "@", ".", "*", "a\\.b", "a\\\\b", "\\000", "\\255.\\032", "a" ** 63, "a" ** 64, ("a" ** 63 ++ ".") ** 4, "..", "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" { for (name_seeds) |seed| try nameProperty(seed); try testing.fuzz({}, fuzzName, .{});}
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" { for (zone_seeds) |seed| try lexerProperty(seed); for (entry_seeds) |seed| try lexerProperty(seed); try testing.fuzz({}, fuzzLexer, .{});}
fn fuzzLexer(_: void, smith: *Smith) !void { var buffer: [8192]u8 = undefined; const len = smith.slice(&buffer); try lexerProperty(buffer[0..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); } };}
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 = "lexer", .run = Driven(fuzzLexer).run, .corpus = zone_seeds, .content_max = 8192 },};