// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A `Resolver` over the real DNS. //! //! The asking is //! [zig-dns-client](https://git.jcollie.dev/jeff/zig-dns-client)'s: the //! socket, `/etc/resolv.conf`, the identifier that has to be unguessable, //! the EDNS0 buffer size, the move to TCP when an answer did not fit, and //! the retry when a server does not answer. What is here is the seam //! between that and SPF — the five record types §5 asks about, and the //! error distinctions §4.4 turns on. //! //! # Where the answers come from //! //! `init` reads `/etc/resolv.conf` once and keeps the nameservers it //! named; `asking` takes a list instead, which is how a receiver points //! this at the resolver it trusts rather than at whatever the host is //! configured for. //! //! The search list is read and thrown away. Every name SPF looks up comes //! out of a record or an envelope and is already absolute, so appending a //! search domain to one would ask about a name nobody published — and a //! check that answered out of a neighbouring zone would be worse than one //! that failed. //! //! # It does not make the answer trustworthy //! //! Plain DNS is a suggestion from whoever is nearest the wire, and SPF is //! a protocol whose entire purpose is deciding whether to believe //! somebody. An off-path forgery has to guess the identifier, the source //! port and the question to be believed, which refuses one that did not //! bother, and that is all: nothing here validates DNSSEC. A `pass` //! obtained this way is worth what the network is worth. //! //! What can be done about it from here is `transport`: a resolver handed //! `dns_client.tls.Client.transport()` reaches a DNS over TLS or DNS over //! HTTPS server, which authenticates the server it is talking to against //! a certificate rather than against a route. //! //! # It does not cache //! //! Which matters more here than it looks. §4.6.4 allows ten queries per //! check and a busy receiver runs a check per message, so a real //! deployment wants a cache underneath — and the whole reason `Resolver` //! is an interface is that it can have one without this file knowing. const std = @import("std"); const Io = std.Io; const dns_client = @import("dns_client"); const dns = dns_client.dns; const z46 = @import("z46"); const Resolver = @import("Resolver.zig"); const StubResolver = @This(); /// The nameservers to ask, in the order to ask them. /// /// Copied out of the configuration rather than borrowed from it, so that /// a `StubResolver` is a value with nothing pointing into anything else: /// it can be returned, copied and handed to another task. nameservers: [max_nameservers]dns_client.Server = undefined, nameserver_count: u8 = 0, /// How long a server has to answer, how many times to go round the list, /// how large an answer to advertise, and where identifiers come from. /// `init` fills in what the configuration had an opinion about and leaves /// the rest at the client's defaults. options: dns_client.Resolver.Options = .{}, /// How a query reaches a server. The default picks by the server's /// protocol and speaks UDP and TCP; see the note above on what handing in /// an encrypted one buys. transport: dns_client.Transport = .automatic, /// As many nameservers as `/etc/resolv.conf` can name, since that is /// where they usually come from. pub const max_nameservers = dns_client.resolv_conf.max_nameservers; /// The largest answer this will read, which is the largest a DNS message /// can be: the TCP framing gives its length in sixteen bits. /// /// Over UDP only what the query advertised is used. The rest is for the /// TCP path, where a large TXT record set actually lands — `amazon.com` /// publishes sixty-four TXT records and about 4.6 kilobytes of them, and /// a buffer sized for "surely this is enough" is how a truncation bug /// gets in. pub const max_answer_len = dns.max_message_len; /// Whoever the machine is configured to ask. /// /// Read once here rather than per query: the file does not change during /// a check, and a resolver that opened it ten times to answer §4.6.4's /// ten lookups would be paying for the configuration more often than for /// the DNS. pub fn init(io: Io) Resolver.Error!StubResolver { var text: [dns_client.resolv_conf.max_file_len]u8 = undefined; const conf = dns_client.resolv_conf.read(io, &text) catch |err| switch (err) { error.Canceled => return error.Canceled, // No file, or a file that cannot be read. A host may be // configured again a moment from now, so this is not a permanent // answer about anybody's mail. else => return error.Temporary, }; return .fromResolvConf(&conf); } /// The same, from a configuration already read — one belonging to the /// program rather than to the host, most often. /// /// Only the nameservers and the options are kept; see the note above on /// the search list. pub fn fromResolvConf(conf: *const dns_client.ResolvConf) StubResolver { var stub: StubResolver = .{}; stub.ask(conf.servers()); // Taken through `resolver()` rather than field by field, so that // which option a `resolv.conf` keyword turns into stays that // library's business. stub.options = conf.resolver().options; return stub; } /// A resolver that asks the servers named, rather than whoever the host /// is configured to ask. /// /// ```zig /// const stub: spf.StubResolver = .asking(&.{ /// .init(try .parse("1.1.1.1"), .udp), /// .init(try .parse("2606:4700:4700::1111"), .udp), /// }); /// ``` pub fn asking(list: []const dns_client.Server) StubResolver { var stub: StubResolver = .{}; stub.ask(list); return stub; } /// The servers, as the client wants them. pub fn servers(stub: *const StubResolver) []const dns_client.Server { return stub.nameservers[0..stub.nameserver_count]; } /// More servers than there is room for are dropped rather than refused: /// a host listing nine nameservers is misconfigured, and asking the first /// eight is what every other stub resolver does with it. fn ask(stub: *StubResolver, list: []const dns_client.Server) void { const count = @min(list.len, max_nameservers); @memcpy(stub.nameservers[0..count], list[0..count]); stub.nameserver_count = @intCast(count); } pub fn resolver(stub: *const StubResolver) Resolver { return .{ .context = @constCast(stub), .vtable = &.{ .txt = txtRecords, .addresses = addressRecords, .mx = mxRecords, .ptr = ptrRecords, } }; } /// The client this asks through. Built per query rather than kept, /// because it borrows `nameservers` and a `StubResolver` that had a /// pointer into itself could not be copied. fn client(stub: *const StubResolver) dns_client.Resolver { return .{ .servers = stub.servers(), // No search list. See the note at the top of the file. .options = stub.options, .transport = stub.transport, }; } /// Asks the configured nameservers one question. /// /// The error set is `Resolver`'s, because the distinctions this makes are /// exactly the ones SPF turns on: a name that does not exist and a /// nameserver that did not answer lead to different results, and an /// implementation that conflated them would turn an outage into a /// permanent refusal of somebody's mail. /// /// The message borrows `buffer`. fn query( stub: *const StubResolver, io: Io, name: []const u8, record_type: dns.Type, buffer: []u8, ) Resolver.Error!dns.Message { // The root is not a name SPF ever asks about, and an empty string // encodes as the root rather than being refused. if (std.mem.trimEnd(u8, name, ".").len == 0) return error.NotFound; const asker = stub.client(); const reply = asker.queryText(io, name, record_type, buffer) catch |err| switch (err) { error.Canceled => return error.Canceled, // A name that cannot be encoded is a name nobody has published, // which is what a mechanism naming one should see: no match, and // a void lookup against §4.6.4's budget. error.EmptyLabel, error.LabelTooLong, error.NameTooLong, error.BadEscape, => return error.NotFound, // Everything else — no servers, a timeout, `servfail`, `refused`, // an answer to a question that was not asked — may be answered // differently tomorrow, and §4.4 asks for `temperror` rather than // for a refusal of the mail. else => return error.Temporary, }; switch (reply.responseCode() catch return error.Temporary) { .noerror => {}, // The name does not exist, which is permanent and is a void // lookup against §4.6.4's budget. .nxdomain => return error.NotFound, // `servfail`, `refused` and the rest are somebody else's problem // and may not be tomorrow. else => return error.Temporary, } return reply.message; } /// Every TXT record of a name, each joined from the character-strings it /// was published in. /// /// All of them, not the first: §4.5 has to see every record to notice /// that a domain published two `v=spf1` records, which is a `permerror` /// and one of the commonest ways a policy is broken. fn txtRecords( context: ?*anyopaque, io: Io, name: []const u8, out: *Resolver.Strings, ) Resolver.Error!void { const stub: *const StubResolver = @ptrCast(@alignCast(context.?)); var answer: [max_answer_len]u8 = undefined; return collectText(try stub.query(io, name, .txt, &answer), out); } fn collectText(message: dns.Message, out: *Resolver.Strings) Resolver.Error!void { var found = false; // A record's value is its character-strings joined with nothing // between. Not a formality: a policy longer than 255 octets arrives // split, and reading only the first string would silently truncate // it. var joined: [max_answer_len]u8 = undefined; var records = message.answers(); while (records.next() catch return error.Temporary) |record| { if (record.class != .in or record.type != .txt) continue; const text = switch (record.data() catch return error.Temporary) { .txt => |value| value, else => continue, }; found = true; var used: usize = 0; var strings = text.iterator(); while (strings.next()) |string| { if (used + string.len > joined.len) return error.NoSpace; @memcpy(joined[used..][0..string.len], string); used += string.len; } try out.append(joined[0..used]); } if (!found) return error.NotFound; } fn addressRecords( context: ?*anyopaque, io: Io, name: []const u8, family: z46.Family, out: *Resolver.Addresses, ) Resolver.Error!void { const stub: *const StubResolver = @ptrCast(@alignCast(context.?)); const wanted: dns.Type = switch (family) { .ipv4 => .a, .ipv6 => .aaaa, }; var answer: [max_answer_len]u8 = undefined; return collectAddresses(try stub.query(io, name, wanted, &answer), wanted, out); } fn collectAddresses( message: dns.Message, wanted: dns.Type, out: *Resolver.Addresses, ) Resolver.Error!void { var found = false; var records = message.answers(); while (records.next() catch return error.Temporary) |record| { if (record.class != .in or record.type != wanted) continue; found = true; // A recursive server puts the whole `cname` chain in the answer // alongside the addresses, so the section holds records this is // not asking about and the type is what selects. switch (record.data() catch return error.Temporary) { .a => |address| try out.append(.{ .ipv4 = address }), .aaaa => |address| try out.append(.{ .ipv6 = address }), else => continue, } } if (!found) return error.NotFound; } fn mxRecords( context: ?*anyopaque, io: Io, name: []const u8, out: *Resolver.Strings, ) Resolver.Error!void { const stub: *const StubResolver = @ptrCast(@alignCast(context.?)); var answer: [max_answer_len]u8 = undefined; return collectNames(try stub.query(io, name, .mx, &answer), .mx, out); } /// The names an address points at. /// /// §4.6.4 caps this at ten and says the rest "MUST be ignored" — ignored, /// not refused, which is why a full buffer leaves what it already wrote /// in place, as `Resolver` promises. fn ptrRecords( context: ?*anyopaque, io: Io, name: []const u8, out: *Resolver.Strings, ) Resolver.Error!void { const stub: *const StubResolver = @ptrCast(@alignCast(context.?)); var answer: [max_answer_len]u8 = undefined; return collectNames(try stub.query(io, name, .ptr, &answer), .ptr, out); } fn collectNames( message: dns.Message, wanted: dns.Type, out: *Resolver.Strings, ) Resolver.Error!void { var found = false; var records = message.answers(); while (records.next() catch return error.Temporary) |record| { if (record.class != .in or record.type != wanted) continue; const name = switch (record.data() catch return error.Temporary) { // The preference is the first two octets of an `mx` and SPF // never asks for it: `mx` is a membership test, not a routing // decision. .mx => |exchanger| exchanger.exchange, .ptr => |target| target, else => continue, }; found = true; var buffer: [dns.Name.max_encoded_len]u8 = undefined; try out.append(try nameText(name, &buffer)); } if (!found) return error.NotFound; } /// A name written out with dots between its labels and no trailing one. /// /// Deliberately not presentation form: RFC 1035 §5.1's escaping is for a /// zone file, and what these names are for here is comparison against a /// domain out of a record and lookups of their own, both of which want /// the bytes as they were published. fn nameText(name: dns.Name, buffer: []u8) Resolver.Error![]const u8 { var used: usize = 0; var labels = name.labels(); while (labels.next()) |label| { if (used != 0) { if (used == buffer.len) return error.NoSpace; buffer[used] = '.'; used += 1; } if (used + label.len > buffer.len) return error.NoSpace; @memcpy(buffer[used..][0..label.len], label); used += label.len; } return buffer[0..used]; } const testing = std.testing; /// A transport that answers out of a table, which is what lets the whole /// of this file be driven without a socket: the record walking, the /// response codes, and the joining of a TXT record's character-strings. const Canned = struct { response: []const u8 = &.{}, /// What to answer with instead, for the half of the error mapping /// that is about a server that did not answer at all. fail: ?dns_client.Transport.Error = null, /// How many times a query was actually sent, so that a test can say /// that a name was refused before anything was asked. asked: usize = 0, /// Identifiers from a fixed source, so that a test is repeatable. /// A real one comes from `io.random`; see `dns_client.Resolver /// .Options.random`. prng: std.Random.DefaultPrng = .init(0), fn exchange( userdata: ?*anyopaque, _: Io, request: dns_client.Transport.Request, ) dns_client.Transport.Error![]u8 { const canned: *Canned = @ptrCast(@alignCast(userdata.?)); canned.asked += 1; if (canned.fail) |err| return err; if (request.buffer.len < canned.response.len) return error.ResponseTooLarge; @memcpy(request.buffer[0..canned.response.len], canned.response); // The identifier is the query's: a resolver refuses an answer // carrying anybody else's, which is most of what makes an // off-path forgery hard. @memcpy(request.buffer[0..2], request.query[0..2]); return request.buffer[0..canned.response.len]; } fn stubResolver(canned: *Canned) StubResolver { var stub: StubResolver = .asking(&.{.init(.{ .ipv4 = .{ .octets = .{ 192, 0, 2, 1 } } }, .udp)}); stub.options.random = canned.prng.random(); stub.transport = .{ .userdata = canned, .vtable = &.{ .exchange = Canned.exchange } }; return stub; } }; /// A response to `name`/`record_type` carrying `records`, so that a test /// can say what a server said rather than spell out bytes. fn cannedResponse( buffer: []u8, name: []const u8, record_type: dns.Type, code: dns.ResponseCode, records: []const dns.Builder.RecordSpec, ) []u8 { var names: dns.Name.Buffer = undefined; const owner = dns.Name.fromText(&names, name) catch unreachable; var builder = dns.Builder.init(buffer, .{ .id = 0, .response = true, .recursion_desired = true, .recursion_available = true, .rcode = code, }, .{}) catch unreachable; builder.question(.{ .name = owner, .type = record_type }) catch unreachable; for (records) |record| builder.record(.answer, record) catch unreachable; return builder.finish(); } test "a TXT record is its character-strings joined, and every record comes back" { var names: dns.Name.Buffer = undefined; const owner = try dns.Name.fromText(&names, "example.com"); var message: [512]u8 = undefined; var canned: Canned = .{ .response = cannedResponse(&message, "example.com", .txt, .noerror, &.{ // A policy longer than 255 octets arrives split like this, and // reading only the first string would silently truncate it. .{ .name = owner, .ttl = 300, .data = .{ .txt = .{ .strings = &.{ "v=spf1 ip4:192.0.2.0/24 ", "-all" } } } }, // §4.5 has to see this one too, to notice a domain that // published two `v=spf1` records. .{ .name = owner, .ttl = 300, .data = .{ .txt = .{ .strings = &.{"v=spf1 +all"} } } }, }), }; const stub = canned.stubResolver(); var storage: [256]u8 = undefined; var index: [8][]const u8 = undefined; var strings: Resolver.Strings = .init(&storage, &index); try stub.resolver().txt(testing.io, "example.com", &strings); try testing.expectEqual(@as(usize, 2), strings.len); try testing.expectEqualStrings("v=spf1 ip4:192.0.2.0/24 -all", strings.slice()[0]); try testing.expectEqualStrings("v=spf1 +all", strings.slice()[1]); } test "a name that does not exist and a server that could not answer are different" { var message: [512]u8 = undefined; var storage: [256]u8 = undefined; var index: [8][]const u8 = undefined; // NXDOMAIN is permanent, and a void lookup against §4.6.4's budget. { var canned: Canned = .{ .response = cannedResponse(&message, "example.com", .txt, .nxdomain, &.{}), }; const stub = canned.stubResolver(); var strings: Resolver.Strings = .init(&storage, &index); try testing.expectError( error.NotFound, stub.resolver().txt(testing.io, "example.com", &strings), ); } // SERVFAIL may be answered differently tomorrow, and §4.4 asks for // `temperror` rather than for a refusal of the mail. { var canned: Canned = .{ .response = cannedResponse(&message, "example.com", .txt, .servfail, &.{}), }; const stub = canned.stubResolver(); var strings: Resolver.Strings = .init(&storage, &index); try testing.expectError( error.Temporary, stub.resolver().txt(testing.io, "example.com", &strings), ); } // And so may a server that said nothing at all. { var canned: Canned = .{ .fail = error.Timeout }; const stub = canned.stubResolver(); var strings: Resolver.Strings = .init(&storage, &index); try testing.expectError( error.Temporary, stub.resolver().txt(testing.io, "example.com", &strings), ); } } test "a name exists with nothing of the type asked for" { var names: dns.Name.Buffer = undefined; const owner = try dns.Name.fromText(&names, "example.com"); var target: dns.Name.Buffer = undefined; const elsewhere = try dns.Name.fromText(&target, "elsewhere.example.net"); // NOERROR with a `cname` and nothing else: a recursive server puts // the chain in the answer section, so the section is not empty and // the type is what decides. var message: [512]u8 = undefined; var canned: Canned = .{ .response = cannedResponse(&message, "example.com", .txt, .noerror, &.{ .{ .name = owner, .ttl = 300, .data = .{ .cname = elsewhere } }, }) }; const stub = canned.stubResolver(); var storage: [256]u8 = undefined; var index: [8][]const u8 = undefined; var strings: Resolver.Strings = .init(&storage, &index); try testing.expectError( error.NotFound, stub.resolver().txt(testing.io, "example.com", &strings), ); } test "an exchanger is its name, and the preference is not asked for" { var names: dns.Name.Buffer = undefined; const owner = try dns.Name.fromText(&names, "example.com"); var first: dns.Name.Buffer = undefined; var second: dns.Name.Buffer = undefined; var message: [512]u8 = undefined; var canned: Canned = .{ .response = cannedResponse(&message, "example.com", .mx, .noerror, &.{ .{ .name = owner, .ttl = 300, .data = .{ .mx = .{ .preference = 20, .exchange = try dns.Name.fromText(&first, "backup.example.com"), } } }, .{ .name = owner, .ttl = 300, .data = .{ .mx = .{ .preference = 10, .exchange = try dns.Name.fromText(&second, "mail.example.com"), } } }, }) }; const stub = canned.stubResolver(); var storage: [256]u8 = undefined; var index: [8][]const u8 = undefined; var strings: Resolver.Strings = .init(&storage, &index); try stub.resolver().mx(testing.io, "example.com", &strings); // In the order they were published, since SPF asks whether the // client is one of them rather than which to use. try testing.expectEqual(@as(usize, 2), strings.len); try testing.expectEqualStrings("backup.example.com", strings.slice()[0]); try testing.expectEqualStrings("mail.example.com", strings.slice()[1]); } test "the names an address points at, and what happens when they run out of room" { var names: dns.Name.Buffer = undefined; const owner = try dns.Name.fromText(&names, "1.2.0.192.in-addr.arpa"); var first: dns.Name.Buffer = undefined; var second: dns.Name.Buffer = undefined; var message: [512]u8 = undefined; const canned_response = cannedResponse(&message, "1.2.0.192.in-addr.arpa", .ptr, .noerror, &.{ .{ .name = owner, .ttl = 300, .data = .{ .ptr = try dns.Name.fromText(&first, "mail.example.com") } }, .{ .name = owner, .ttl = 300, .data = .{ .ptr = try dns.Name.fromText(&second, "www.example.com") } }, }); { var canned: Canned = .{ .response = canned_response }; const stub = canned.stubResolver(); var storage: [256]u8 = undefined; var index: [8][]const u8 = undefined; var strings: Resolver.Strings = .init(&storage, &index); try stub.resolver().ptr(testing.io, "1.2.0.192.in-addr.arpa", &strings); try testing.expectEqual(@as(usize, 2), strings.len); try testing.expectEqualStrings("mail.example.com", strings.slice()[0]); } // §4.6.4 caps the names used at ten and says the rest "MUST be // ignored" — ignored, not refused, so what was written stays // written. `check_host` reads it and moves on. { var canned: Canned = .{ .response = canned_response }; const stub = canned.stubResolver(); var storage: [256]u8 = undefined; var index: [1][]const u8 = undefined; var strings: Resolver.Strings = .init(&storage, &index); try testing.expectError( error.NoSpace, stub.resolver().ptr(testing.io, "1.2.0.192.in-addr.arpa", &strings), ); try testing.expectEqual(@as(usize, 1), strings.len); try testing.expectEqualStrings("mail.example.com", strings.slice()[0]); } } test "addresses come back in the family that was asked for" { var names: dns.Name.Buffer = undefined; const owner = try dns.Name.fromText(&names, "mail.example.com"); var message: [512]u8 = undefined; var canned: Canned = .{ .response = cannedResponse(&message, "mail.example.com", .a, .noerror, &.{ .{ .name = owner, .ttl = 300, .data = .{ .a = .{ .octets = .{ 192, 0, 2, 1 } } } }, .{ .name = owner, .ttl = 300, .data = .{ .a = .{ .octets = .{ 192, 0, 2, 2 } } } }, }) }; const stub = canned.stubResolver(); var index: [8]z46.Address = undefined; var addresses: Resolver.Addresses = .init(&index); try stub.resolver().addresses(testing.io, "mail.example.com", .ipv4, &addresses); try testing.expectEqual(@as(usize, 2), addresses.len); try testing.expectEqual( z46.Address{ .ipv4 = .{ .octets = .{ 192, 0, 2, 2 } } }, addresses.slice()[1], ); } test "a name that cannot be asked about is refused before anything is sent" { var storage: [256]u8 = undefined; var index: [8][]const u8 = undefined; // The root, a name with an empty label, and a label of 64 octets. for ([_][]const u8{ "", ".", "a..b", "a" ** 64 ++ ".com" }) |name| { var canned: Canned = .{}; const stub = canned.stubResolver(); var strings: Resolver.Strings = .init(&storage, &index); try testing.expectError( error.NotFound, stub.resolver().txt(testing.io, name, &strings), ); try testing.expectEqual(@as(usize, 0), canned.asked); } } test "a configuration becomes the servers to ask, and its options" { const conf = dns_client.resolv_conf.parse( \\nameserver 192.0.2.1 \\nameserver 2001:db8::1 \\search example.com example.net \\options attempts:3 \\ ); const stub: StubResolver = .fromResolvConf(&conf); try testing.expectEqual(@as(usize, 2), stub.servers().len); try testing.expectEqual( z46.Address{ .ipv4 = .{ .octets = .{ 192, 0, 2, 1 } } }, stub.servers()[0].endpoint.address(), ); try testing.expectEqual(@as(u8, 3), stub.options.attempts); // And the search list is not kept: every name SPF looks up is // absolute, so appending a search domain to one would ask about a // name nobody published. try testing.expectEqual(@as(usize, 0), stub.client().search.len); } test "more nameservers than there is room for" { var many: [max_nameservers + 1]dns_client.Server = undefined; for (&many, 0..) |*server, i| server.* = .init( .{ .ipv4 = .{ .octets = .{ 192, 0, 2, @intCast(i + 1) } } }, .udp, ); const stub: StubResolver = .asking(&many); try testing.expectEqual(@as(usize, max_nameservers), stub.servers().len); }