// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Finding a domain's policy, and finding where an organization ends. //! //! Those are the same walk asked two different questions, which is why //! they are in one file. Policy discovery wants the record that applies //! to a `From:` domain; identifier alignment wants to know whether two //! names belong to the same organization. Both are answered by climbing //! the namespace from a name towards the root, reading `_dmarc` records //! on the way. //! //! # Why a walk rather than a list //! //! RFC 7489 answered "where does an organization end" with a public //! suffix list — a file of every name under which anyone may register, //! maintained by volunteers, several hundred kilobytes, and changing //! continuously. It said receivers should use one, did not say which, //! and acknowledged that receivers choosing different lists would //! disagree about the same message. It also said that if a more reliable //! method were found it should replace the list. //! //! This is that method, from the revision in progress: the boundary is //! published in the DNS by the people who own it, using the `psd` tag, //! and a receiver finds it by looking rather than by consulting a copy //! of a file that may be a year old. The cost is DNS queries, which is //! why the walk is bounded — see `max_queries`. const std = @import("std"); const Io = std.Io; const Record = @import("Record.zig"); const Resolver = @import("Resolver.zig"); /// The prefix every DMARC record is published under. pub const prefix = "_dmarc."; /// A DNS name is at most 253 octets, and `_dmarc.` goes in front. pub const max_name_len = 253; const max_query_len = prefix.len + max_name_len; /// One TXT record set. A `_dmarc` name shares its records with whatever /// else was put there, but `Strings.keep_prefix` discards the rest as it /// arrives, so only records claiming to be DMARC are stored. const max_records = 4; const max_record_bytes = 1024; /// How many queries a walk may make. /// /// The revision's own number, and its reasoning is worth keeping: a /// domain owner with bad intentions can put a `From:` address with /// hundreds of labels on a message, and a receiver that walked every one /// of them would be doing that sender's denial-of-service work for it. /// Names with up to seven labels were observed in use when the number /// was chosen, so a walk starts by jumping straight to seven labels when /// the name has more. pub const max_queries = 8; const max_labels = 7; pub const Error = error{ /// The name could not be asked about: too long, or an empty label. InvalidName, } || Resolver.Error; /// A record, and the name it was published at. /// /// The owner matters as much as the record: `sp` and `np` apply only to /// names *below* the one that published them, so a policy cannot be /// applied without knowing where it was found. pub const Found = struct { record: Record, /// A slice of the caller's buffer. owner: []const u8, }; /// The policy record that applies to `domain`, or null when there is /// none and DMARC therefore does not apply to the message. /// /// `buffer` holds the owner name that comes back in `Found`, and must be /// at least `max_name_len` bytes; `record_storage` holds the record text /// the parsed record points into, and must outlive the result. /// /// §4.10.1's order of preference: the author domain's own record first, /// then the organizational domain's, then a public suffix's. The first /// query is separate from the walk because finding a record there means /// something different — it is the domain's own policy, and `p` applies /// rather than `sp`. pub fn policy( io: Io, resolver: Resolver, domain: []const u8, buffer: []u8, record_storage: []u8, ) Error!?Found { if (try lookup(io, resolver, domain, buffer, record_storage)) |record| { return .{ .record = record, .owner = try copy(buffer, domain) }; } // Nothing of its own, so climb. The starting point is the parent, // not the name itself — that has just been asked. var walk: Walk = try .init(domain); _ = walk.next() orelse return null; return walkFrom(io, resolver, &walk, buffer, record_storage); } /// The organizational domain of `domain`: the name at which the /// organization that owns it begins. /// /// This is what relaxed alignment compares. Two names are aligned when /// they resolve to the same answer here, which is why a message signed /// by `example.com` may carry `From: news.example.com` — and why a /// signature by `com` never aligns with anything. /// /// §4.10.2's selection, applied to whatever the walk found: /// /// 1. a record saying `psd=n` is an organizational domain, and the /// longest such name wins; /// 2. a record saying `psd=y` is a public suffix, so the organization /// begins one label below it; /// 3. otherwise the record with the fewest labels. /// /// With nothing found at all, the name is its own organizational domain /// — which is the honest answer rather than a guess, and the one that /// makes strict and relaxed alignment agree. pub fn organizationalDomain( io: Io, resolver: Resolver, domain: []const u8, buffer: []u8, ) Error![]const u8 { var storage: [max_record_bytes]u8 = undefined; var walk: Walk = try .init(domain); // The longest name with a record, and the shortest, are the two the // selection needs; `psd` on any of them ends it early. var shortest: ?[]const u8 = null; var shortest_labels: usize = 0; var previous: ?[]const u8 = null; var scratch: [max_name_len]u8 = undefined; var shortest_storage: [max_name_len]u8 = undefined; var previous_storage: [max_name_len]u8 = undefined; while (walk.next()) |name| { // A temporary failure here ends the walk and keeps what was // already found, where the same failure during policy discovery // is reported. The difference is what the answer is used for. // // A walk always ends at a top-level name, and plenty of those // answer oddly: a resolver serving a private zone with no // forwarders returns SERVFAIL for `test`, and a public one may // for anything it has an opinion about. Failing an entire // evaluation because the root of the namespace was // uncooperative would make alignment unusable. // // It is safe in the direction that matters: with nothing found, // a name becomes its own organizational domain, so relaxed // alignment degrades to strict — and two names that would then // match would have matched exactly anyway. A lost lookup can // turn a pass into a fail, never a fail into a pass. const record = (lookup(io, resolver, name, &scratch, &storage) catch |err| switch (err) { error.Temporary => break, else => |other| return other, }) orelse { // A name with no record cannot end the walk, but it is the // name one label below the next one, which is what `psd=y` // needs. previous = try copy(&previous_storage, name); continue; }; switch (record.psd) { // "I am an organizational domain, for myself and everything // under me." The walk stops and this is the answer. .no => return copy(buffer, name), // "I am a public suffix." The organization begins one label // below, which is the name asked about just before this one. .yes => { if (!std.ascii.eqlIgnoreCase(name, domain)) { if (previous) |below| return copy(buffer, below); } }, .unstated => {}, } const labels = countLabels(name); if (shortest == null or labels < shortest_labels) { shortest = try copy(&shortest_storage, name); shortest_labels = labels; } previous = try copy(&previous_storage, name); } if (shortest) |name| return copy(buffer, name); return copy(buffer, domain); } /// Walks from where `walk` currently is, returning the first record /// found — which for policy discovery is the one to apply, since the /// walk goes from the most specific name outwards. /// /// A temporary failure *here* ends the walk rather than being reported, /// and the difference from the first query is deliberate. §4.10.1 is /// careful that a transient error is not the same as "no record", and /// that is exactly right for the domain's own name: a failure there /// leaves a receiver unable to say what policy applied. Five labels up /// it says something much weaker — that a public suffix's policy could /// not be ruled out — and a walk always ends at a top-level name, so /// treating that as a temporary failure would turn every message from a /// whole top-level domain into a deferral the first time somebody's /// resolver had an opinion about it. fn walkFrom( io: Io, resolver: Resolver, walk: *Walk, buffer: []u8, record_storage: []u8, ) Error!?Found { var scratch: [max_name_len]u8 = undefined; while (walk.next()) |name| { const record = lookup(io, resolver, name, &scratch, record_storage) catch |err| switch (err) { error.Temporary => break, else => |other| return other, }; if (record) |found| { return .{ .record = found, .owner = try copy(buffer, name) }; } } return null; } /// One `_dmarc` lookup, with §4.10 steps 2 and 6 applied: records that /// are not DMARC are discarded, and a name publishing more than one /// record has published none. /// /// The second rule is the one that surprises people. Two records is not /// a choice between two policies, it is a domain owner who has lost /// track of their own DNS, and honouring either would be guessing which. fn lookup( io: Io, resolver: Resolver, name: []const u8, scratch: []u8, record_storage: []u8, ) Error!?Record { var query_buffer: [max_query_len]u8 = undefined; const query = try queryName(&query_buffer, name); _ = scratch; var index: [max_records][]const u8 = undefined; var answers: Resolver.Strings = .init(record_storage, &index); // §4.10 step 2 discards by this prefix, so everything else at the // name can be dropped as it arrives. answers.keep_prefix = "v"; resolver.txt(io, query, &answers) catch |err| switch (err) { error.NotFound => return null, else => |other| return other, }; var chosen: ?[]const u8 = null; var found: usize = 0; for (answers.slice()) |text| { if (!Record.isDmarc(text)) continue; found += 1; chosen = text; } if (found != 1) return null; return Record.parse(chosen.?) catch null; } fn queryName(buffer: []u8, name: []const u8) Error![]const u8 { const trimmed = std.mem.trimEnd(u8, name, "."); if (trimmed.len == 0 or trimmed.len > max_name_len) return error.InvalidName; if (prefix.len + trimmed.len > buffer.len) return error.InvalidName; @memcpy(buffer[0..prefix.len], prefix); @memcpy(buffer[prefix.len..][0..trimmed.len], trimmed); return buffer[0 .. prefix.len + trimmed.len]; } fn copy(buffer: []u8, name: []const u8) Error![]const u8 { if (name.len > buffer.len) return error.InvalidName; @memcpy(buffer[0..name.len], name); return buffer[0..name.len]; } fn countLabels(name: []const u8) usize { const trimmed = std.mem.trimEnd(u8, name, "."); if (trimmed.len == 0) return 0; var count: usize = 1; for (trimmed) |byte| { if (byte == '.') count += 1; } return count; } /// The sequence of names a walk visits: the name itself, then each /// parent, out to the last label. /// /// The shortcut is §4.10 step 4. A name with more than seven labels /// jumps straight to seven, so the eight queries cover the name itself /// and seven ancestors however long the name is — which is what stops a /// `From:` address with two hundred labels from costing two hundred /// lookups. const Walk = struct { rest: []const u8, queries: usize = 0, first: bool = true, start: []const u8, fn init(domain: []const u8) Error!Walk { const trimmed = std.mem.trimEnd(u8, domain, "."); if (trimmed.len == 0 or trimmed.len > max_name_len) return error.InvalidName; return .{ .rest = trimmed, .start = trimmed }; } fn next(walk: *Walk) ?[]const u8 { if (walk.queries >= max_queries) return null; if (walk.first) { walk.first = false; walk.queries += 1; return walk.rest; } // Step 4: from the starting name, drop labels until seven // remain; after that, one at a time. while (true) { const dot = std.mem.indexOfScalar(u8, walk.rest, '.') orelse return null; walk.rest = walk.rest[dot + 1 ..]; if (walk.rest.len == 0) return null; if (countLabels(walk.rest) <= max_labels) break; } walk.queries += 1; return walk.rest; } }; const testing = std.testing; const Zone = @import("Zone.zig"); fn expectPolicy(zone: Zone, domain: []const u8, expected: ?Record.Policy) !void { var owner_buffer: [max_name_len]u8 = undefined; var storage: [max_record_bytes]u8 = undefined; const found = try policy(testing.io, zone.resolver(), domain, &owner_buffer, &storage); if (expected) |want| { const exists = try zone.resolver().exists(testing.io, domain); try testing.expectEqual(want, found.?.record.policyFor(found.?.owner, domain, exists)); } else { try testing.expectEqual(@as(?Found, null), found); } } fn expectOrganizational(zone: Zone, domain: []const u8, expected: []const u8) !void { var buffer: [max_name_len]u8 = undefined; try testing.expectEqualStrings( expected, try organizationalDomain(testing.io, zone.resolver(), domain, &buffer), ); } test "a domain's own record is used before anything above it" { const zone: Zone = .{ .entries = &.{ .{ .name = "_dmarc.example.com", .txt = "v=DMARC1; p=reject; sp=quarantine" }, .{ .name = "_dmarc.news.example.com", .txt = "v=DMARC1; p=none" }, }, .existing = &.{ "example.com", "news.example.com", "sales.example.com" }, }; // Its own record, so `p` applies. try expectPolicy(zone, "example.com", .reject); try expectPolicy(zone, "news.example.com", .none); // Nothing of its own, so the walk reaches example.com and `sp` // applies -- which is the distinction the walk exists to draw. try expectPolicy(zone, "sales.example.com", .quarantine); } test "np applies to a subdomain that was never registered" { const zone: Zone = .{ .entries = &.{ .{ .name = "_dmarc.example.com", .txt = "v=DMARC1; p=none; sp=none; np=reject" }, }, .existing = &.{"example.com"}, }; try expectPolicy(zone, "example.com", .none); // A name nobody registered cannot be sending legitimate mail. try expectPolicy(zone, "typo.example.com", .reject); } test "a domain with no policy anywhere" { const zone: Zone = .{ .entries = &.{.{ .name = "_dmarc.other.test", .txt = "v=DMARC1; p=reject" }}, }; // DMARC does not apply, which is not the same as a policy of none: // a receiver has been told nothing rather than told to do nothing. try expectPolicy(zone, "example.com", null); } test "two records at a name are no records at all" { const zone: Zone = .{ .entries = &.{ .{ .name = "_dmarc.example.com", .txt = "v=DMARC1; p=reject" }, .{ .name = "_dmarc.example.com", .txt = "v=DMARC1; p=none" }, }, }; // §4.10 step 2. Two records is not a choice between two policies, // it is an owner who has lost track of their own DNS, and honouring // either would be guessing which they meant. try expectPolicy(zone, "example.com", null); } test "a _dmarc name shares its records with whatever else was put there" { const zone: Zone = .{ .entries = &.{ .{ .name = "_dmarc.example.com", .txt = "google-site-verification=abc" }, .{ .name = "_dmarc.example.com", .txt = "v=DMARC1; p=reject" }, .{ .name = "_dmarc.example.com", .txt = "some-other-token=xyz" }, }, .existing = &.{"example.com"}, }; // Only records claiming to be DMARC count towards the "exactly one" // rule, or every domain with an ownership token at `_dmarc` would // have no policy. try expectPolicy(zone, "example.com", .reject); } test "the organizational domain is where the records say it is" { const zone: Zone = .{ .entries = &.{ .{ .name = "_dmarc.example.com", .txt = "v=DMARC1; p=reject" }, .{ .name = "_dmarc.mail.example.com", .txt = "v=DMARC1; p=none" }, }, }; // §4.10.2's third rule: with no `psd` anywhere, the fewest labels // wins. The draft's own worked example. try expectOrganizational(zone, "a.mail.example.com", "example.com"); try expectOrganizational(zone, "example.com", "example.com"); } test "psd=n stops the walk where an organization says it begins" { const zone: Zone = .{ .entries = &.{ .{ .name = "_dmarc.example.com", .txt = "v=DMARC1; p=reject" }, .{ .name = "_dmarc.mail.example.com", .txt = "v=DMARC1; p=none; psd=n" }, }, }; // The draft's second worked example: a domain owner asserting that a // subdomain is an organization in its own right, which no public // suffix list could have told you. try expectOrganizational(zone, "a.mail.example.com", "mail.example.com"); } test "psd=y means the organization begins one label below" { const zone: Zone = .{ .entries = &.{ .{ .name = "_dmarc.com", .txt = "v=DMARC1; p=none; psd=y; rua=mailto:a@b.com" }, }, }; // The draft's third worked example, and the case a public suffix // list exists for: `com` is a name anybody may register under, so an // organization begins at `example.com`. try expectOrganizational(zone, "a.mail.example.com", "example.com"); } test "a name nobody has published anything about is its own organization" { const zone: Zone = .{}; // The honest answer rather than a guess, and the one that makes // strict and relaxed alignment agree when there is nothing to go on. try expectOrganizational(zone, "news.example.com", "news.example.com"); } test "the walk is bounded however long the name is" { // §4.10's shortcut. Without it, a `From:` address with two hundred // labels would cost a receiver two hundred lookups -- which is the // sender's denial-of-service work, done for them. var walk: Walk = try .init("a.b.c.d.e.f.g.h.i.j.mail.example.com"); var names: [max_queries][]const u8 = undefined; var count: usize = 0; while (walk.next()) |name| : (count += 1) names[count] = name; try testing.expectEqual(@as(usize, max_queries), count); // Straight from the draft: the name itself, then a jump to seven // labels, then one label at a time. try testing.expectEqualStrings("a.b.c.d.e.f.g.h.i.j.mail.example.com", names[0]); try testing.expectEqualStrings("g.h.i.j.mail.example.com", names[1]); try testing.expectEqualStrings("h.i.j.mail.example.com", names[2]); try testing.expectEqualStrings("i.j.mail.example.com", names[3]); try testing.expectEqualStrings("j.mail.example.com", names[4]); try testing.expectEqualStrings("mail.example.com", names[5]); try testing.expectEqualStrings("example.com", names[6]); try testing.expectEqualStrings("com", names[7]); } test "a short name walks one label at a time" { var walk: Walk = try .init("a.mail.example.com"); var names: [max_queries][]const u8 = undefined; var count: usize = 0; while (walk.next()) |name| : (count += 1) names[count] = name; try testing.expectEqual(@as(usize, 4), count); try testing.expectEqualStrings("a.mail.example.com", names[0]); try testing.expectEqualStrings("mail.example.com", names[1]); try testing.expectEqualStrings("example.com", names[2]); try testing.expectEqualStrings("com", names[3]); } test "a nameserver that will not answer is not a domain with no policy" { const zone: Zone = .{ .entries = &.{.{ .name = "_dmarc.example.com", .txt = "v=DMARC1; p=reject" }}, .failing = &.{"_dmarc.example.com"}, }; var owner_buffer: [max_name_len]u8 = undefined; var storage: [max_record_bytes]u8 = undefined; // Reported rather than swallowed: §4.10.1 leaves the choice between // delivering and deferring to the receiver, and a library that // turned an outage into "no policy" would have made it for them. try testing.expectError(error.Temporary, policy( testing.io, zone.resolver(), "example.com", &owner_buffer, &storage, )); } test "a walk that cannot reach the top still answers" { const zone: Zone = .{ .entries = &.{ .{ .name = "_dmarc.example.test", .txt = "v=DMARC1; p=reject" }, }, // What a nameserver serving a private zone with no forwarders // does with the name above it. .failing = &.{"_dmarc.test"}, }; // The record that was found still decides, because a walk always // ends at a top-level name and plenty of those answer oddly. try expectOrganizational(zone, "mail.example.test", "example.test"); // With nothing found at all, the name is its own organizational // domain — relaxed alignment degrading to strict, which can turn a // pass into a fail but never the reverse. const nothing: Zone = .{ .failing = &.{"_dmarc.test"} }; try expectOrganizational(nothing, "mail.example.test", "mail.example.test"); } test "policy discovery still reports a temporary failure" { // The same failure, asked a different question. §4.10.1 wants the // receiver to choose between delivering and deferring, so the // library must not choose for them. const zone: Zone = .{ .failing = &.{"_dmarc.example.test"} }; var owner_buffer: [max_name_len]u8 = undefined; var storage: [max_record_bytes]u8 = undefined; try testing.expectError(error.Temporary, policy( testing.io, zone.resolver(), "example.test", &owner_buffer, &storage, )); } test "where in the walk a DNS failure happens changes what it means" { // At the domain's own name, a receiver genuinely cannot say what // policy applied, so §4.10.1's distinction between a transient error // and "no record" holds and the failure is reported. const at_the_domain: Zone = .{ .failing = &.{"_dmarc.example.test"} }; var owner_buffer: [max_name_len]u8 = undefined; var storage: [max_record_bytes]u8 = undefined; try testing.expectError(error.Temporary, policy( testing.io, at_the_domain.resolver(), "example.test", &owner_buffer, &storage, )); // Above it, the failure says only that a public suffix's policy // could not be ruled out — and since a walk always ends at a // top-level name, reporting that would defer every message from a // whole top-level domain the first time somebody's resolver had an // opinion about it. const at_the_root: Zone = .{ .failing = &.{"_dmarc.test"} }; try expectPolicy(at_the_root, "example.test", null); // And a record found on the way still decides, whatever the root // did afterwards. const found_first: Zone = .{ .entries = &.{.{ .name = "_dmarc.example.test", .txt = "v=DMARC1; p=reject; sp=quarantine" }}, .failing = &.{"_dmarc.test"}, .existing = &.{ "example.test", "mail.example.test" }, }; try expectPolicy(found_first, "mail.example.test", .quarantine); }