Something went wrong. Try again.
DNS message encoding and decoding for Zig, with no I/O and no allocation.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! What the decoder must do with input nobody wrote.//!//! A DNS library reads bytes that arrived over UDP from whoever felt like//! sending them, before anything has had a chance to check who that was. The//! properties here are the ones that have to hold for *any* input at all://!//! * it terminates -- which for this format is a real question, because a//! compression pointer can point backwards and two of them can point at each//! other;//! * it stays inside the buffer it was given;//! * and anything it claims to have understood survives being written out and//! read again.//!//! That last one is what catches a decoder and an encoder that have drifted//! apart, which no test written against a fixed example can see.//!//! 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: it catches a decoder and an encoder//! that have drifted apart, and cannot catch both of them being wrong the same//! way. The check for that is `zig build differential`, which puts the same//! mutated messages to this library and to dnspython and compares the//! verdicts. It lives in `tests/differential.py` rather than here because the//! comparison happens outside Zig, and the strictness choices this library//! makes are written down in it -- a kind of disagreement that is not already//! accounted for fails the run.//!//! `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 testing = std.testing;const Smith = std.testing.Smith;
const corpus = @import("corpus");const dns = @import("dns");
// -- whole messages ---------------------------------------------------------
/// The captured messages next door, and then the shapes a capture will never/// have: an empty message, a header whose counts lie about what follows, and/// input that is not a message at all.const message_seeds = corpus.messages ++ [_][]const u8{ // A query for example.com A, with an OPT record. "\x12\x34\x01\x00\x00\x01\x00\x00\x00\x00\x00\x01" ++ "\x07example\x03com\x00\x00\x01\x00\x01" ++ "\x00\x00\x29\x10\x00\x00\x00\x00\x00\x00\x00", // The answer, with the owner name compressed against the question. "\x12\x34\x81\x80\x00\x01\x00\x01\x00\x00\x00\x00" ++ "\x07example\x03com\x00\x00\x01\x00\x01" ++ "\xc0\x0c\x00\x01\x00\x01\x00\x00\x00\x15\x00\x04\xac\x42\x93\xf3", // A referral: NS records and the addresses that go with them. "\x00\x01\x80\x00\x00\x01\x00\x00\x00\x02\x00\x01" ++ "\x03www\x07example\x03com\x00\x00\x01\x00\x01" ++ "\xc0\x10\x00\x02\x00\x01\x00\x01\x51\x80\x00\x06\x03ns1\xc0\x10" ++ "\xc0\x10\x00\x02\x00\x01\x00\x01\x51\x80\x00\x06\x03ns2\xc0\x10" ++ "\xc0\x36\x00\x01\x00\x01\x00\x01\x51\x80\x00\x04\xc0\x00\x02\x01", // An empty message, and a header with counts that lie about what follows. "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff", // Not a message at all. "", "\x00", "GET / HTTP/1.1\r\n\r\n",};
/// Whatever arrives, parsing either fails or produces a message that can be/// walked, printed, built again, and printed to the same text.fn messageProperty(input: []const u8) !void { const message = dns.Message.parse(input) catch return;
// Everything in it can be reached without an error, because `parse` // already walked it. var questions = message.questions(); while (try questions.next()) |_| {} inline for ([_]dns.Section{ .answer, .authority, .additional }) |which| { var it = message.section(which); while (try it.next()) |record| _ = record.data() catch {}; }
// Building it again. This can run out of room -- the servers that send // these compress names inside record data that this library will not, so // a rebuilt message can be larger than the one it came from -- and that is // not a finding. var out: [dns.max_message_len]u8 = undefined; var b = dns.Builder.init(&out, message.header, .{}) catch return; var again = message.questions(); while (try again.next()) |q| b.question(q) catch return; inline for ([_]dns.Section{ .answer, .authority, .additional }) |which| { var it = message.section(which); while (try it.next()) |record| { const data = record.data() catch return; b.record(which, .{ .name = record.name, .class = record.class, .ttl = record.ttl, .data = data, }) catch return; } } const rebuilt = try dns.Message.parse(b.finish());
// And it says the same thing. Not the same bytes: compression is a choice. var original_text: [1 << 18]u8 = undefined; var rebuilt_text: [1 << 18]u8 = undefined; const before = std.fmt.bufPrint(&original_text, "{f}", .{message}) catch return; const after = std.fmt.bufPrint(&rebuilt_text, "{f}", .{rebuilt}) catch return; try testing.expectEqualStrings(before, after);}
test "fuzz messages" { for (message_seeds) |seed| try messageProperty(seed); try testing.fuzz({}, fuzzMessage, .{});}
fn fuzzMessage(_: void, smith: *Smith) !void { var buffer: [4096]u8 = undefined; const len = smith.slice(&buffer); try messageProperty(buffer[0..len]);}
// -- names in a message -----------------------------------------------------
const name_seeds = [_][]const u8{ "\x07example\x03com\x00", "\x07example\x03com\x00\x03www\xc0\x00", "\x00", // A pointer to itself, and a pair that point at each other. "\xc0\x00", "\x01a\xc0\x00", "\x01a\xc0\x04\x01b\xc0\x00", // The reserved label types. "\x40\x00", "\x80\x00", // A label of every byte value. "\x04\x00\xff\x2e\x5c\x00",};
/// Every offset in the buffer is tried as the start of a name, which is what/// gets the pointer handling exercised: a pointer is only reachable from/// somewhere, and the somewheres are what this enumerates. A name that parses/// must then survive being copied out and printed.fn nameProperty(input: []const u8) !void { for (0..input.len) |offset| { const at: u16 = @intCast(offset); const name = dns.Name.parse(input, at) catch continue;
try testing.expect(name.encodedLen() <= dns.Name.max_encoded_len); try testing.expect(name.labelCount() <= dns.Name.max_labels);
// A copy is the same name, and stands on its own. var buf: dns.Name.Buffer = undefined; const copied = name.clone(&buf); try testing.expect(name.eql(copied)); try testing.expectEqual(std.math.Order.eq, name.order(copied)); try testing.expectEqual(name.encodedLen(), copied.encodedLen()); try testing.expect((try dns.Name.fromBytes(copied.message)).eql(name));
// And the presentation form reads back as the same name, which is the // whole job of the escaping. var text: dns.Name.TextBuffer = undefined; const written = try name.toText(&text); var reparsed_buf: dns.Name.Buffer = undefined; const reparsed = try dns.Name.fromText(&reparsed_buf, written); try testing.expect(name.eql(reparsed));
// A name is always a subdomain of itself and of the root, and never of // anything with more labels than it has. try testing.expect(name.isSubdomainOf(name)); try testing.expect(name.isSubdomainOf(.root)); if (!name.isRoot()) try testing.expect(name.parent().?.labelCount() + 1 == name.labelCount()); }}
test "fuzz names" { for (name_seeds) |seed| try nameProperty(seed); try testing.fuzz({}, fuzzName, .{});}
fn fuzzName(_: void, smith: *Smith) !void { var buffer: [512]u8 = undefined; const len = smith.slice(&buffer); try nameProperty(buffer[0..len]);}
// -- names written as text --------------------------------------------------
const name_text_seeds = [_][]const u8{ "example.com", "example.com.", ".", "", "a\\.b.example.com", "\\255\\000.example", @as([63]u8, @splat('a')) ++ ".b", &@as([64]u8, @splat('a')), "..", "\\", "\\9",};
/// Text that parses must print back to text that parses to the same name./// The two escapes that matter are the ones that are not reversible if either/// half is wrong: a dot inside a label, and a byte that is not printable.fn nameTextProperty(input: []const u8) !void { var buf: dns.Name.Buffer = undefined; const name = dns.Name.fromText(&buf, input) catch return;
var text: dns.Name.TextBuffer = undefined; const written = try name.toText(&text);
var again_buf: dns.Name.Buffer = undefined; const again = try dns.Name.fromText(&again_buf, written); try testing.expect(name.eql(again)); try testing.expectEqualSlices(u8, name.message, again.message);
// And printing it a second time gives the same text: the presentation // form is a fixed point, which is what lets it be compared. var text_again: dns.Name.TextBuffer = undefined; try testing.expectEqualStrings(written, try again.toText(&text_again));}
test "fuzz names written as text" { for (name_text_seeds) |seed| try nameTextProperty(seed); try testing.fuzz({}, fuzzNameText, .{});}
fn fuzzNameText(_: void, smith: *Smith) !void { var buffer: [300]u8 = undefined; const len = smith.slice(&buffer); try nameTextProperty(buffer[0..len]);}
// -- record data ------------------------------------------------------------
/// The first two bytes of a seed are the record type; the rest is the data.const rdata_seeds = [_][]const u8{ "\x00\x01\xc0\x00\x02\x01", // A "\x00\x1c\x20\x01\x0d\xb8" ++ @as([11]u8, @splat(0)) ++ "\x01", // AAAA "\x00\x05\x03www\x07example\x03com\x00", // CNAME "\x00\x0f\x00\x0a\x04mail\x00", // MX "\x00\x10\x05hello\x05world", // TXT "\x00\x06\x01a\x00\x01b\x00" ++ @as([5 * 4]u8, @bitCast(@as([5][4]u8, @splat("\x00\x00\x00\x01".*)))), // SOA "\x00\x21\x00\x01\x00\x00\x14\x51\x04sip1\x00", // SRV "\x00\x2f\x01a\x00\x00\x06\x40\x01\x00\x00\x00\x03", // NSEC "\x00\x41\x00\x01\x00\x00\x01\x00\x06\x02h3\x02h2", // HTTPS "\x01\x01\x00\x05issue\x0aletsencrypt.org", // CAA "\x00\x29\x00\x0a\x00\x08\x01\x02\x03\x04\x05\x06\x07\x08", // OPT, a cookie "\xff\x00\xde\xad\xbe\xef", // a type nobody knows};
/// Data that decodes must re-encode to something that decodes to the same/// data and encodes to the same bytes again.////// Not "the same bytes it came from": a name inside record data may have/// arrived compressed, and this library writes the types that carry names/// uncompressed except where RFC 1035 allows otherwise, so the bytes are/// legitimately allowed to shrink or grow. What may not change is what they/// mean, and a fixed point after one encoding is how that is checked -- an/// encoder and a decoder that disagree about a field will not agree about it/// the second time either.fn rdataProperty(input: []const u8) !void { if (input.len < 2) return; const record_type: dns.Type = @fromBackingInt(std.mem.readInt(u16, input[0..2], .big)); const bytes = input[2..];
var d = dns.wire.Decoder.init(bytes) catch return; const data = dns.rdata.Data.parse(record_type, &d) catch return; try testing.expectEqual(record_type, data.recordType());
var first_buf: [dns.max_message_len]u8 = undefined; var first_builder = try dns.Builder.init(&first_buf, .{ .id = 0 }, .{ .compression = false }); const start = first_builder.pos; data.writeTo(&first_builder) catch return; const first = first_builder.buffer[start..first_builder.pos];
var again = try dns.wire.Decoder.init(first); const reparsed = try dns.rdata.Data.parse(record_type, &again);
var second_buf: [dns.max_message_len]u8 = undefined; var second_builder = try dns.Builder.init(&second_buf, .{ .id = 0 }, .{ .compression = false }); try reparsed.writeTo(&second_builder); try testing.expectEqualSlices(u8, first, second_builder.buffer[start..second_builder.pos]);
// And it prints, the same way both times, which is the other thing a // decoded record is for. var before: [1 << 16]u8 = undefined; var after: [1 << 16]u8 = undefined; const printed = std.fmt.bufPrint(&before, "{f}", .{data}) catch return; try testing.expectEqualStrings(printed, try std.fmt.bufPrint(&after, "{f}", .{reparsed}));}
test "fuzz record data" { for (rdata_seeds) |seed| try rdataProperty(seed); try testing.fuzz({}, fuzzRdata, .{});}
fn fuzzRdata(_: void, smith: *Smith) !void { var buffer: [1024]u8 = undefined; const len = smith.slice(&buffer); try rdataProperty(buffer[0..len]);}
// -- the builder, and what it does when it runs out of room -----------------
/// The rooms the seeds are built into. Twelve is a header and nothing else,/// and the rest step through the sizes where a record starts to not fit.const builder_rooms = [_]u16{ 0, 12, 13, 32, 64, 128, 512, 1232, 4096, 65535 };
/// However little room a builder has, what comes out of `finish` is a complete/// message holding exactly the entries that were accepted, and nothing of the/// one that was not.////// This is the property the whole rollback path exists for, and the one that/// is hardest to be sure of by reading: a record that does not fit has already/// written an owner name, and may have left compression targets pointing at/// bytes that are about to be written over by the next thing anybody adds.fn builderProperty(input: []const u8, room: u16) !void { const message = dns.Message.parse(input) catch return;
var out: [dns.max_message_len]u8 = undefined; var b = dns.Builder.init(out[0..room], message.header, .{}) catch return;
// Stopping at the first thing that does not fit, the way a server filling // a response does, so that what was accepted is a prefix of each section // and can be compared against the original entry for entry. var accepted: dns.Header.Counts = .{}; fill: { var questions = message.questions(); while (try questions.next()) |q| { b.question(q) catch break :fill; accepted.question += 1; } inline for ([_]dns.Section{ .answer, .authority, .additional }) |which| { var it = message.section(which); while (try it.next()) |record| { const data = record.data() catch break :fill; b.record(which, .{ .name = record.name, .class = record.class, .ttl = record.ttl, .data = data, }) catch break :fill; accepted.getPtr(which).* += 1; } } }
const built = b.finish(); try testing.expect(built.len <= room);
const rebuilt = try dns.Message.parse(built); try testing.expectEqual(@as(usize, 0), rebuilt.trailing().len); try testing.expectEqual(accepted, rebuilt.header.counts);
// And what is in it is what went in, entry for entry. var wanted_questions = message.questions(); var got_questions = rebuilt.questions(); for (0..accepted.question) |_| { try testing.expect((try wanted_questions.next()).?.eql((try got_questions.next()).?)); }
var wanted_text: [1 << 16]u8 = undefined; var got_text: [1 << 16]u8 = undefined; inline for ([_]dns.Section{ .answer, .authority, .additional }) |which| { var wanted = message.section(which); var got = rebuilt.section(which); for (0..accepted.get(which)) |_| { try testing.expectEqualStrings( try std.fmt.bufPrint(&wanted_text, "{f}", .{(try wanted.next()).?}), try std.fmt.bufPrint(&got_text, "{f}", .{(try got.next()).?}), ); } }}
test "fuzz the builder running out of room" { for (message_seeds) |seed| { for (builder_rooms) |room| try builderProperty(seed, room); } try testing.fuzz({}, fuzzBuilder, .{});}
fn fuzzBuilder(_: void, smith: *Smith) !void { var buffer: [4096]u8 = undefined; const len = smith.slice(&buffer); // The room comes from the length of the driver's *second* chunk rather // than from `smith.value`, which answers anything outside its range with // the range's minimum and so would say zero almost every time. var room_buffer: [4096]u8 = undefined; const room: u16 = @intCast(smith.slice(&room_buffer)); try builderProperty(buffer[0..len], room);}
// -- the table the standalone driver reads ----------------------------------
/// One fuzz target, reachable from bytes rather than from a `Smith`.////// `zig build test` reaches these through the `test` blocks above and Zig's/// own fuzzer reaches them through `std.testing.fuzz`. This is the third way/// in, for `tools/fuzz.zig`, which runs a fixed number of inputs from a seed/// that can be given again, and replays one input from a file.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 = "messages", .run = Driven(fuzzMessage).run, .corpus = &message_seeds, .content_max = 4096 }, .{ .name = "names", .run = Driven(fuzzName).run, .corpus = &name_seeds, .content_max = 512 }, .{ .name = "nametext", .run = Driven(fuzzNameText).run, .corpus = &name_text_seeds, .content_max = 300 }, .{ .name = "rdata", .run = Driven(fuzzRdata).run, .corpus = &rdata_seeds, .content_max = 1024 }, .{ .name = "builder", .run = Driven(fuzzBuilder).run, .corpus = &message_seeds, .content_max = 4096 },};