// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! EDNS(0): the extension mechanism that let DNS outgrow the twelve-byte //! header without changing it. //! //! RFC 6891 found room the only place there was any -- in a record. An `opt` //! record in the additional section is not a record at all: it is never //! stored, never cached, never in a zone, and its owner name means nothing. //! What it carries is in the fields a real record would use for something //! else. The class holds the largest response the sender can reassemble, the //! TTL holds eight more bits of response code, the version and the DNSSEC OK //! flag, and the record data holds a list of options. //! //! Almost everything after 1999 needs one: a response larger than 512 bytes, a //! response code above 15, DNSSEC records in an answer, cookies, the client's //! subnet, a reason for a failure. A query without an `opt` is a query saying //! it understands none of it. const std = @import("std"); const Writer = std.Io.Writer; const z46 = @import("z46"); const Builder = @import("Builder.zig"); const Name = @import("Name.zig"); const Record = @import("Record.zig"); const presentation = @import("presentation.zig"); const types = @import("types.zig"); const wire = @import("wire.zig"); /// What RFC 6891 §6.2.5 suggests a requestor advertise, and what RFC 9715 /// recommends after fragmented UDP turned out to be worse than a retry over /// TCP. Larger is not better: a response that has to be fragmented is a /// response that may never arrive. pub const default_payload_size = 1232; /// The smallest a requestor may advertise, and what a message with no `opt` /// record is taken to mean (RFC 1035 §4.2.1). pub const min_payload_size = 512; /// What reading the option list itself can go wrong with. pub const ParseError = wire.Error || error{ /// The record data is not a well-formed list of options. MalformedRdata, }; pub const Error = ParseError || error{ /// The record was not an `opt` record. NotAnOptRecord, /// An `opt` record whose owner name is not the root. RFC 6891 §6.1.2 says /// it must be, and a message with anything else there is either broken or /// trying something. BadOwnerName, }; /// The `opt` pseudo-record, with each of its fields read out of whichever /// part of a record it was hidden in. pub const Opt = struct { /// The largest UDP response the sender can reassemble. Kept in the class /// field, where a real record keeps `in`. udp_payload_size: u16 = default_payload_size, /// The high eight bits of the response code, which the header has no room /// for. Kept in the first byte of the TTL. extended_rcode: u8 = 0, /// Always 0. A server that does not speak the version it is sent answers /// `badvers` with its own highest version here. version: u8 = 0, /// The requestor understands DNSSEC and wants the records; the responder /// has included them. Without it, a server omits every signature, which is /// what keeps DNSSEC from breaking resolvers that never asked. dnssec_ok: bool = false, /// The other fifteen flag bits, all reserved. Kept so that a message /// carrying one survives being decoded and encoded again. reserved_flags: u15 = 0, /// The options themselves. options: Options = .none, /// The four TTL bytes, which is where the version, the flags and the high /// bits of the response code live. pub fn ttlBits(self: Opt) u32 { return @as(u32, self.extended_rcode) << 24 | @as(u32, self.version) << 16 | @as(u32, @intFromBool(self.dnssec_ok)) << 15 | self.reserved_flags; } /// Reads an `opt` record's fields out of the places they are kept. pub fn fromRecord(record: Record) Error!Opt { if (record.type != .opt) return error.NotAnOptRecord; if (!record.name.isRoot()) return error.BadOwnerName; var d = record.rdataDecoder(); return .{ .udp_payload_size = @intFromEnum(record.class), .extended_rcode = @truncate(record.ttl >> 24), .version = @truncate(record.ttl >> 16), .dnssec_ok = record.ttl & 0x8000 != 0, .reserved_flags = @truncate(record.ttl), .options = try Options.parse(&d), }; } /// The record to write for this `opt`, with each field back where the wire /// format keeps it. `Builder.opt` is the usual way to reach this. pub fn toRecordSpec(self: Opt) Builder.RecordSpec { return .{ .name = Name.root, .class = @enumFromInt(self.udp_payload_size), .ttl = self.ttlBits(), .data = .{ .opt = self.options }, }; } /// As `dig` prints the pseudo-section. pub fn format(self: Opt, w: *Writer) Writer.Error!void { try w.print("EDNS: version: {d}, flags:", .{self.version}); if (self.dnssec_ok) try w.writeAll(" do"); try w.print("; udp: {d}", .{self.udp_payload_size}); var it = self.options.iterator(); while (it.next()) |option| try w.print("\n{f}", .{option}); } }; /// An option code from the EDNS(0) option registry. pub const OptionCode = enum(u16) { /// Long-lived queries. Never standardized. llq = 1, /// A name server identifier: ask an anycast address which instance /// answered (RFC 5001). The first thing to reach for when one node out of /// a hundred is wrong. nsid = 3, /// Which DNSSEC algorithms the requestor understands (RFC 6975). dau = 5, /// Which DS hash algorithms it understands. dhu = 6, /// Which NSEC3 hash algorithms it understands. n3u = 7, /// The client's subnet, so that an authoritative server can answer /// according to where the client is rather than where its resolver is /// (RFC 7871). A privacy trade, and one the RFC itself is uneasy about. client_subnet = 8, /// How much longer the response will remain valid (RFC 7314). expire = 9, /// A cookie, which is what makes off-path spoofing and reflection /// amplification hard over UDP without needing TCP (RFC 7873). cookie = 10, /// How long a TCP connection should be held open (RFC 7828). tcp_keepalive = 11, /// Bytes of nothing, to make every query the same size so that its length /// leaks nothing (RFC 7830). padding = 12, /// The closest ancestor the requestor already has, so a chain of trust can /// be completed in one round trip (RFC 7901). chain = 13, /// Which keys the requestor has as trust anchors (RFC 8145). key_tag = 14, /// Why a server answered the way it did (RFC 8914). The difference between /// a `servfail` and a `servfail` that says "the signature had expired". extended_error = 15, /// Where to report a resolution failure (RFC 9567). report_channel = 18, /// Which version of the zone the answer came from (RFC 9660). zoneversion = 19, _, pub fn name(self: OptionCode) ?[]const u8 { return switch (self) { _ => null, inline else => |c| @tagName(c), }; } pub fn format(self: OptionCode, w: *Writer) Writer.Error!void { if (self.name()) |n| return w.writeAll(n); try w.print("OPT{d}", .{@intFromEnum(self)}); } }; /// One option: a code and the bytes that go with it. pub const Option = struct { code: OptionCode, data: []const u8, /// The reason a server gives for its answer, if this is an extended DNS /// error and it is the right shape. pub fn asExtendedError(self: Option) ?ExtendedError { if (self.code != .extended_error or self.data.len < 2) return null; return .{ .info_code = @enumFromInt(std.mem.readInt(u16, self.data[0..2], .big)), .text = self.data[2..], }; } /// The cookie, if this is one. A query carries the client's eight bytes /// alone; a response adds the server's eight to thirty-two. pub fn asCookie(self: Option) ?Cookie { if (self.code != .cookie) return null; if (self.data.len != 8 and (self.data.len < 16 or self.data.len > 40)) return null; return .{ .client = self.data[0..8].*, .server = self.data[8..] }; } /// The client's subnet, if this is one and it is the right shape. pub fn asClientSubnet(self: Option) ?ClientSubnet { if (self.code != .client_subnet or self.data.len < 4) return null; const family = std.mem.readInt(u16, self.data[0..2], .big); const source = self.data[2]; const scope = self.data[3]; const address = self.data[4..]; // RFC 7871 section 6: the address carries only the significant bits, // rounded up to a byte, and no more than that. if (address.len != (@as(usize, source) + 7) / 8) return null; return .{ .family = @enumFromInt(family), .source_prefix_len = source, .scope_prefix_len = scope, .address = address, }; } pub fn format(self: Option, w: *Writer) Writer.Error!void { if (self.asExtendedError()) |extended| return w.print("{f}", .{extended}); if (self.asClientSubnet()) |subnet| return w.print("{f}", .{subnet}); try w.print("{f}: ", .{self.code}); switch (self.code) { .nsid => try presentation.writeHexLower(w, self.data), .cookie => try presentation.writeHexLower(w, self.data), .padding => try w.print("({d} bytes)", .{self.data.len}), else => try presentation.writeHexLower(w, self.data), } } }; /// Why a server answered the way it did. pub const ExtendedError = struct { info_code: InfoCode, /// Free text for a human, which a program must not parse and a server need /// not send. text: []const u8, pub const InfoCode = enum(u16) { other = 0, unsupported_dnskey_algorithm = 1, unsupported_ds_digest_type = 2, stale_answer = 3, forged_answer = 4, dnssec_indeterminate = 5, dnssec_bogus = 6, signature_expired = 7, signature_not_yet_valid = 8, dnskey_missing = 9, rrsigs_missing = 10, no_zone_key_bit_set = 11, nsec_missing = 12, cached_error = 13, not_ready = 14, blocked = 15, censored = 16, filtered = 17, prohibited = 18, stale_nxdomain_answer = 19, not_authoritative = 20, not_supported = 21, no_reachable_authority = 22, network_error = 23, invalid_data = 24, signature_expired_before_valid = 25, too_early = 26, unsupported_nsec3_iterations = 27, unable_to_conform_to_policy = 28, synthesized = 29, _, pub fn name(self: InfoCode) ?[]const u8 { return switch (self) { _ => null, inline else => |c| @tagName(c), }; } }; pub fn format(self: ExtendedError, w: *Writer) Writer.Error!void { try w.writeAll("EDE: "); if (self.info_code.name()) |n| { try w.print("{d} ({s})", .{ @intFromEnum(self.info_code), n }); } else { try w.print("{d}", .{@intFromEnum(self.info_code)}); } if (self.text.len > 0) { try w.writeAll(": "); try presentation.writeCharacterString(w, self.text); } } }; /// The eight bytes a client picks and the server echoes, plus whatever the /// server adds. Nothing here generates or verifies one: that is a keyed hash /// over the addresses and a server secret, and it belongs wherever the secret /// is. pub const Cookie = struct { client: [8]u8, /// Empty in a query. Eight to thirty-two bytes in a response. server: []const u8, }; /// The client's subnet, as RFC 7871 sends it. pub const ClientSubnet = struct { family: Family, /// How many bits of the address the requestor is disclosing. source_prefix_len: u8, /// In a response: how many bits of it the answer actually depended on, /// which is what a cache must key on. scope_prefix_len: u8, /// The significant bits, rounded up to whole bytes. address: []const u8, /// The IANA address family numbers, of which two are ever seen. pub const Family = enum(u16) { ipv4 = 1, ipv6 = 2, _, }; /// The subnet as a network, with the bits that were not sent filled in as /// zero. `null` for an address family this does not know, or for a prefix /// longer than the family allows. pub fn network(self: ClientSubnet) ?z46.Network { switch (self.family) { .ipv4 => { if (self.source_prefix_len > 32 or self.address.len > 4) return null; var octets: [4]u8 = @splat(0); @memcpy(octets[0..self.address.len], self.address); return .{ .ipv4 = .{ .address = .{ .octets = octets }, .prefix_len = @intCast(self.source_prefix_len), } }; }, .ipv6 => { if (self.source_prefix_len > 128 or self.address.len > 16) return null; var octets: [16]u8 = @splat(0); @memcpy(octets[0..self.address.len], self.address); return .{ .ipv6 = .{ .address = .{ .octets = octets }, .prefix_len = @intCast(self.source_prefix_len), } }; }, _ => return null, } } pub fn format(self: ClientSubnet, w: *Writer) Writer.Error!void { try w.writeAll("CLIENT-SUBNET: "); if (self.network()) |n| { try w.print("{f}/{d}", .{ n, self.scope_prefix_len }); } else { try w.print("family {d}/{d}/{d}", .{ @intFromEnum(self.family), self.source_prefix_len, self.scope_prefix_len, }); } } }; /// The list of options in an `opt` record, still in wire form. pub const Options = struct { bytes: []const u8, pub const none: Options = .{ .bytes = "" }; /// Reads the rest of the record data as a list of options, checking that /// each one's length fits in what is left. Unlike the parameters of a /// `svcb` record, options have no required order and may repeat. pub fn parse(d: *wire.Decoder) ParseError!Options { const bytes = d.takeRest(); var i: usize = 0; while (i < bytes.len) { if (i + 4 > bytes.len) return error.MalformedRdata; const length = std.mem.readInt(u16, bytes[i + 2 ..][0..2], .big); i += 4 + @as(usize, length); if (i > bytes.len) return error.MalformedRdata; } return .{ .bytes = bytes }; } pub const Iterator = struct { bytes: []const u8, pos: usize = 0, pub fn next(self: *Iterator) ?Option { if (self.pos + 4 > self.bytes.len) return null; const code = std.mem.readInt(u16, self.bytes[self.pos..][0..2], .big); const length = std.mem.readInt(u16, self.bytes[self.pos + 2 ..][0..2], .big); const start = self.pos + 4; const end = start + length; if (end > self.bytes.len) return null; self.pos = end; return .{ .code = @enumFromInt(code), .data = self.bytes[start..end] }; } }; pub fn iterator(self: Options) Iterator { return .{ .bytes = self.bytes }; } /// The first option with this code, or `null`. pub fn get(self: Options, code: OptionCode) ?Option { var it = self.iterator(); while (it.next()) |option| { if (option.code == code) return option; } return null; } pub fn writeTo(self: Options, b: *Builder) Builder.Error!void { try b.writeAll(self.bytes); } pub fn format(self: Options, w: *Writer) Writer.Error!void { var it = self.iterator(); var first = true; while (it.next()) |option| { if (!first) try w.writeByte(' '); first = false; try w.print("{f}", .{option}); } } pub const EncodeError = error{ /// The buffer was too small. NoSpace, /// An option longer than 65535 bytes, which its length cannot express. OptionTooLong, }; /// Writes a list of options into `buf` and returns them, which is how an /// `Opt` to be sent gets its data without an allocator. pub fn encode(buf: []u8, options: []const Option) EncodeError!Options { var out: usize = 0; for (options) |option| { if (option.data.len > std.math.maxInt(u16)) return error.OptionTooLong; if (out + 4 + option.data.len > buf.len) return error.NoSpace; std.mem.writeInt(u16, buf[out..][0..2], @intFromEnum(option.code), .big); std.mem.writeInt(u16, buf[out + 2 ..][0..2], @intCast(option.data.len), .big); @memcpy(buf[out + 4 ..][0..option.data.len], option.data); out += 4 + option.data.len; } return .{ .bytes = buf[0..out] }; } }; const testing = std.testing; test "options round trip through encode" { var buf: [128]u8 = undefined; const options = try Options.encode(&buf, &.{ .{ .code = .nsid, .data = "" }, .{ .code = .cookie, .data = "\x01\x02\x03\x04\x05\x06\x07\x08" }, }); try testing.expectEqual(@as(?Option, null), options.get(.padding)); const cookie = options.get(.cookie).?.asCookie().?; try testing.expectEqualSlices(u8, "\x01\x02\x03\x04\x05\x06\x07\x08", &cookie.client); try testing.expectEqual(@as(usize, 0), cookie.server.len); var d = try wire.Decoder.init(options.bytes); const reparsed = try Options.parse(&d); try testing.expectEqualSlices(u8, options.bytes, reparsed.bytes); } test "a truncated option list is refused" { for ([_][]const u8{ "\x00\x03\x00", "\x00\x03\x00\x04\x01\x02" }) |bytes| { var d = try wire.Decoder.init(bytes); try testing.expectError(error.MalformedRdata, Options.parse(&d)); } } test "an extended error carries a reason" { var buf: [128]u8 = undefined; const options = try Options.encode(&buf, &.{ .{ .code = .extended_error, .data = "\x00\x07expired" }, }); const extended = options.get(.extended_error).?.asExtendedError().?; try testing.expectEqual(ExtendedError.InfoCode.signature_expired, extended.info_code); try testing.expectFmt("EDE: 7 (signature_expired): \"expired\"", "{f}", .{extended}); } test "a client subnet becomes a network" { var buf: [128]u8 = undefined; // 192.0.2.0/24, with the server saying it used all 24 bits. const options = try Options.encode(&buf, &.{ .{ .code = .client_subnet, .data = "\x00\x01\x18\x18\xc0\x00\x02" }, }); const subnet = options.get(.client_subnet).?.asClientSubnet().?; try testing.expectEqual(@as(u8, 24), subnet.source_prefix_len); try testing.expectFmt("CLIENT-SUBNET: 192.0.2.0/24/24", "{f}", .{subnet}); // An address longer than the prefix needs is not a client subnet. const wrong = try Options.encode(&buf, &.{ .{ .code = .client_subnet, .data = "\x00\x01\x18\x18\xc0\x00\x02\x01" }, }); try testing.expectEqual(@as(?ClientSubnet, null), wrong.get(.client_subnet).?.asClientSubnet()); }