Something went wrong. Try again.
Sender Policy Framework (RFC 7208) for Zig: the record grammar, the macro language, and an evaluator that takes its resolver from you.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! `check_host()` — [RFC 7208//! §4](https://datatracker.ietf.org/doc/html/rfc7208#section-4), the//! function the whole specification is written around.//!//! It takes an address, a domain and a sender, fetches the domain's//! policy, and walks it until something matches. Everything else in this//! library is either the grammar it reads or the DNS it reads through.//!//! The limits of §4.6.4 are not an afterthought here. SPF is a language//! whose evaluation a stranger controls: the domain being checked writes//! the record, and every `include:` in it is another record written by//! somebody else again. Ten queries is the whole budget, and an//! implementation without it is a DNS amplifier with a mail server//! attached.
const std = @import("std");const Io = std.Io;const z46 = @import("z46");const Record = @import("Record.zig");const Resolver = @import("Resolver.zig");const macro = @import("macro.zig");
/// The seven results of §2.6, which are the whole vocabulary SPF has.pub const Result = enum { /// No policy: the domain publishes no SPF record, or none that /// parses as one. Not a judgement of the mail. none, /// A policy that declines to say. `?all`, and the default when a /// record runs out of mechanisms without matching. neutral, /// The client is authorized. pass, /// The client is not authorized and the domain says so explicitly. /// `-all`. fail, /// The domain believes the client is not authorized but is not /// asking anyone to act on it. `~all`, which is where a domain sits /// while it finds out what it forgot. softfail, /// The answer could not be determined now and might be later: a /// nameserver that did not answer, a timeout. §8.6 asks a receiver /// to defer rather than refuse. temperror, /// The policy is broken: a syntax error, too many lookups, a /// contradiction. §8.7 leaves the choice of what to do to the /// receiver, because the fault is the sender's. permerror,};
/// §4.6.4's budget. The defaults are the values that section names, and/// both exist because the record is written by somebody else.pub const Limits = struct { /// Terms that may cost a DNS query: `include`, `a`, `mx`, `ptr`, /// `exists` and `redirect`. `all`, `ip4` and `ip6` are free, which /// is why a large sender publishes addresses rather than names. queries: u8 = 10, /// Queries that may come back empty before the record is judged /// broken. §4.6.4 recommends two. A record full of names that do not /// exist is either a mistake or an attempt to make a receiver do /// work on somebody else's behalf. void_lookups: u8 = 2,};
pub const Options = struct { limits: Limits = .{}, /// Where an explanation is written when the result is `fail` and the /// domain published an `exp=`. Null skips the lookup entirely, which /// is a query saved on the one path where nobody may read the text. explanation: ?[]u8 = null, /// `%{r}`: the name of the host doing the checking. receiver: []const u8 = "unknown", /// `%{t}`: the current time, in seconds since the epoch. Only an /// explanation can reach it, and only a caller has a clock. timestamp: i64 = 0,};
pub const Outcome = struct { result: Result, /// The explanation the domain published for a `fail`, expanded. /// Null unless the result is `fail`, the record had an `exp=`, and /// `Options.explanation` gave it somewhere to go. /// /// It is written by the domain being checked, so it is somebody /// else's text: §6.2 warns that it goes in front of a human and /// should be treated as untrusted. explanation: ?[]const u8 = null,};
/// The RFC's own entry point: may `client` send mail as `domain`?////// `sender` is the full address the domain came from, which the macros/// need — `%{l}` and `%{o}` are its halves. For a HELO check there is no/// address, and §2.4 says to use `postmaster` at the greeting domain;/// `checkHelo` does that rather than leaving it to the caller to/// remember.pub fn checkHost( io: Io, resolver: Resolver, client: z46.Address, domain: []const u8, sender: macro.Sender, options: Options,) Outcome { var state: State = .{ .io = io, .resolver = resolver, // §5: "Even if the SMTP connection is via IPv6, an IPv4-mapped // IPv6 address MUST still be considered an IPv4 address." A // receiver on a dual-stack socket sees every IPv4 client this // way, so without this line every `ip4:` mechanism in the world // stops matching. .client = switch (client) { .ipv4 => client, .ipv6 => |ipv6| if (ipv6.toIpv4Mapped()) |ipv4| .{ .ipv4 = ipv4 } else client, }, .sender = sender, .helo = sender.domain, .options = options, }; return state.evaluate(domain, 0, true);}
/// The MAIL FROM check of §2.4, which is the one that matters: it is the/// identity a bounce would go to.////// An empty reverse-path — the `MAIL FROM:<>` of a bounce — has no domain/// to check, so §2.4 says to check `postmaster` at the HELO domain/// instead. That is not a fallback but the point: a bounce claiming to/// come from nowhere is still coming from some host.pub fn checkMailFrom( io: Io, resolver: Resolver, client: z46.Address, helo: []const u8, mail_from: []const u8, options: Options,) Outcome { if (mail_from.len == 0) return checkHelo(io, resolver, client, helo, options); const at = std.mem.lastIndexOfScalar(u8, mail_from, '@') orelse return checkHelo(io, resolver, client, helo, options); const sender: macro.Sender = .{ .local_part = if (at == 0) "postmaster" else mail_from[0..at], .domain = mail_from[at + 1 ..], }; if (sender.domain.len == 0) return .{ .result = .none }; var state: State = .{ .io = io, .resolver = resolver, .client = normalize(client), .sender = sender, .helo = helo, .options = options, }; return state.evaluate(sender.domain, 0, true);}
/// The HELO check of §2.3: is this host allowed to greet as this name?////// Worth doing on its own. It can be answered before the envelope/// arrives, and it is the only identity a client with nothing else to/// claim still has.pub fn checkHelo( io: Io, resolver: Resolver, client: z46.Address, helo: []const u8, options: Options,) Outcome { return checkHost(io, resolver, client, helo, .{ .local_part = "postmaster", .domain = helo, }, options);}
fn normalize(client: z46.Address) z46.Address { return switch (client) { .ipv4 => client, .ipv6 => |ipv6| if (ipv6.toIpv4Mapped()) |ipv4| .{ .ipv4 = ipv4 } else client, };}
/// How deep `include:` and `redirect=` may nest. Each level costs a query/// so the budget already bounds this; the cap is here so that the bound/// does not depend on a caller's `Limits` when what is at stake is the/// stack.const max_depth = 20;
/// One TXT answer, which is where a record's text lives while its/// mechanisms are evaluated.////// Sized for a record *set* rather than a record, and generously,/// because a domain's SPF policy shares that set with every ownership/// token it has ever been asked to publish: `google.com` carries/// seventeen TXT records and larger organizations carry more. Reading/// part of the set is not an option — §4.5 has to see every record to/// notice that a domain published two policies — so a set that does not/// fit is a `temperror`, and the way to make that never happen is for it/// to fit.////// Only the records that claim to be SPF are kept —/// `Resolver.Strings.keep_prefix` does the discarding — which is what/// makes this small enough to sit in a recursion frame. A domain's/// policy shares its TXT record set with every ownership token it has/// ever been asked to publish, and `amazon.com`'s set is sixty-four/// records and 4.6 kilobytes; the part of it SPF reads is one record.////// What is left has to fit whole: §4.5 must see every SPF record to/// notice that a domain published two, so a set that does not fit is a/// `temperror` rather than a guess.const max_txt_bytes = 2048;const max_txt_records = 8;
/// Answers a mechanism looks at. Ten is §4.6.4's own cap on names, so a/// resolver that fills this and says `NoSpace` has found the eleventh,/// which is exactly the condition that section describes.const max_names = 10;const max_name_bytes = max_names * (macro.max_domain_len + 1);/// Addresses of one name. There is no cap in the specification, so this/// is a judgement: more than this and the evaluation is abandoned as/// `temperror` rather than answered from part of the set.const max_addresses = 64;
/// Room for a macro expansion *before* §7.3 truncates it to a name.////// A domain-spec such as `foobar.%{o}.%{o}.%{o}.%{o}.%{o}.%{o}.%{o}.%{o}.example.com`/// expands past 253 octets and is then trimmed from the left, so a/// buffer sized for the answer would fail on the way to it.const max_expansion = 4 * macro.max_domain_len;
const State = struct { io: Io, resolver: Resolver, client: z46.Address, sender: macro.Sender, helo: []const u8, options: Options, queries: u8 = 0, voids: u8 = 0, /// `%{p}`, worked out at most once and only if a record asks for it. validated: ?[]const u8 = null, validated_done: bool = false, validated_storage: [macro.max_domain_len]u8 = undefined,
/// Whether a mechanism may spend a query, and the spending of it. fn spend(state: *State) bool { if (state.queries >= state.options.limits.queries) return false; state.queries += 1; return true; }
/// A lookup that came back empty. §4.6.4 counts these separately /// because they cost a receiver just as much as a lookup that /// answers and tell the sender nothing. fn countVoid(state: *State) bool { if (state.voids >= state.options.limits.void_lookups) return false; state.voids += 1; return true; }
fn evaluate(state: *State, domain: []const u8, depth: u8, explain: bool) Outcome { if (depth > max_depth) return .{ .result = .permerror }; // §4.3: a malformed name is not a policy, and asking about it // would be asking a nameserver a question with no answer. if (!validDomain(domain)) return .{ .result = .none };
var storage: [max_txt_bytes]u8 = undefined; var index: [max_txt_records][]const u8 = undefined; var answers: Resolver.Strings = .init(&storage, &index); // §4.5 selects by this prefix, so everything else in the record // set can be dropped as it arrives rather than carried. answers.keep_prefix = "v=spf1"; state.resolver.txt(state.io, domain, &answers) catch |err| switch (err) { // §4.4: no record, or no such name, is the absence of a // policy rather than a policy of refusal. error.NotFound => return .{ .result = .none }, error.Temporary => return .{ .result = .temperror }, error.NoSpace => return .{ .result = .temperror }, error.Canceled => return .{ .result = .temperror }, };
// §4.5: select by the version prefix, then insist on exactly one. // Two SPF records are a contradiction rather than a choice, which // is why this is an error and not a preference. var chosen: ?[]const u8 = null; var found: usize = 0; for (answers.slice()) |text| { if (!Record.isSpf(text)) continue; found += 1; chosen = text; } if (found == 0) return .{ .result = .none }; if (found > 1) return .{ .result = .permerror };
// §4.6: the record is checked as a whole before any of it runs, // so a typo behind an `all` is still an error. const record = Record.parse(chosen.?) catch return .{ .result = .permerror };
var terms = record.iterate(); while (terms.next() catch return .{ .result = .permerror }) |term| { const directive = switch (term) { .directive => |directive| directive, .modifier => continue, }; switch (state.match(domain, directive, depth)) { .no_match => continue, .result => |result| return .{ .result = result }, .matched => { const result: Result = switch (directive.qualifier) { .pass => .pass, .fail => .fail, .softfail => .softfail, .neutral => .neutral, }; if (result != .fail) return .{ .result = result }; return .{ .result = .fail, .explanation = if (explain) state.explainWith(record, domain) else null, }; }, } }
// §6.1: a redirect is reached only when nothing matched, which is // also why a record with an `all` can never reach one — `all` // always matches. The redirect replaces the record entirely, // explanation and all, where an `include` does not. if (record.redirect) |spec| { if (!state.spend()) return .{ .result = .permerror }; var buffer: [max_expansion]u8 = undefined; const target = state.expand(&buffer, spec, domain) catch return .{ .result = .permerror }; const outcome = state.evaluate(target, depth + 1, explain); // A redirect to a domain with no policy is a broken record, // not an absent one: the first record promised an answer // somewhere else and there was nothing there. if (outcome.result == .none) return .{ .result = .permerror }; return outcome; }
// §4.7: a record that runs out of mechanisms has declined to say. return .{ .result = .neutral }; }
const Match = union(enum) { matched, no_match, /// The evaluation is over, whatever the qualifier said. result: Result, };
fn match(state: *State, domain: []const u8, directive: Record.Directive, depth: u8) Match { if (directive.mechanism.queries() and !state.spend()) { return .{ .result = .permerror }; } return switch (directive.mechanism) { .all => .matched, .ip4 => |network| if (state.client == .ipv4 and network.contains(state.client.ipv4)) .matched else .no_match, .ip6 => |network| if (state.client == .ipv6 and network.contains(state.client.ipv6)) .matched else .no_match, .a => |dual| state.matchAddress(domain, dual.domain, dual), .mx => |dual| state.matchMx(domain, dual), .ptr => |spec| state.matchPtr(domain, spec), .exists => |spec| state.matchExists(domain, spec), .include => |spec| state.matchInclude(domain, spec, depth), }; }
/// §5.3, and the same comparison `mx` makes once it has a name. fn matchAddress(state: *State, domain: []const u8, spec: ?[]const u8, dual: Record.Dual) Match { var buffer: [max_expansion]u8 = undefined; const target = if (spec) |text| state.expand(&buffer, text, domain) catch return .{ .result = .permerror } else domain; return state.matchName(target, dual); }
fn matchName(state: *State, target: []const u8, dual: Record.Dual) Match { var index: [max_addresses]z46.Address = undefined; var found: Resolver.Addresses = .init(&index); state.resolver.addresses(state.io, target, state.client.family(), &found) catch |err| switch (err) { error.NotFound => return if (state.countVoid()) .no_match else .{ .result = .permerror }, error.Temporary, error.Canceled => return .{ .result = .temperror }, // More addresses than this will look at. Answering from // part of the set would be answering a different // question, so it does not answer. error.NoSpace => return .{ .result = .temperror }, }; for (found.slice()) |address| { if (contains(address, dual, state.client)) return .matched; } return .no_match; }
/// §5.4. The exchangers of a domain are the hosts it receives mail /// on, and a domain that sends from them says so this way. fn matchMx(state: *State, domain: []const u8, dual: Record.Dual) Match { var buffer: [max_expansion]u8 = undefined; const target = if (dual.domain) |text| state.expand(&buffer, text, domain) catch return .{ .result = .permerror } else domain;
var storage: [max_name_bytes]u8 = undefined; var index: [max_names][]const u8 = undefined; var names: Resolver.Strings = .init(&storage, &index); state.resolver.mx(state.io, target, &names) catch |err| switch (err) { error.NotFound => return if (state.countVoid()) .no_match else .{ .result = .permerror }, error.Temporary, error.Canceled => return .{ .result = .temperror }, // §4.6.4: "the evaluation of each 'MX' record MUST NOT // result in querying more than 10 address records ... If // this limit is exceeded, the 'mx' mechanism MUST produce a // 'permerror' result." The storage holds exactly ten, so a // resolver with no room left has found the eleventh. error.NoSpace => return .{ .result = .permerror }, };
for (names.slice()) |name| { switch (state.matchName(name, dual)) { .matched => return .matched, .no_match => {}, .result => |result| return .{ .result = result }, } } return .no_match; }
/// §5.5, which the specification implements and then tells you not to /// use: it costs a lookup per name and the answer is controlled by /// whoever runs the reverse zone for the client's address. /// /// Its error handling is its own: "if a DNS error occurs while doing /// the PTR RR lookup, then this mechanism fails to match", where /// every other mechanism would report a temperror. A deprecated /// mechanism does not get to make the whole check fail. fn matchPtr(state: *State, domain: []const u8, spec: ?[]const u8) Match { var buffer: [max_expansion]u8 = undefined; const target = if (spec) |text| state.expand(&buffer, text, domain) catch return .{ .result = .permerror } else domain;
const validated = state.validatedName() orelse return .no_match; if (isSubdomainOf(validated, target)) return .matched; return .no_match; }
/// §5.7. The lookup is for an A record whatever the client's family /// is: the name is being used as a flag, and only its existence is /// the answer. That is what makes `exists:%{ir}.%{l1r+}._spf.%{d}` /// work — a whole policy encoded in a zone rather than a record. fn matchExists(state: *State, domain: []const u8, spec: []const u8) Match { var buffer: [max_expansion]u8 = undefined; const target = state.expand(&buffer, spec, domain) catch return .{ .result = .permerror };
var index: [1]z46.Address = undefined; var found: Resolver.Addresses = .init(&index); state.resolver.addresses(state.io, target, .ipv4, &found) catch |err| switch (err) { error.NotFound => return if (state.countVoid()) .no_match else .{ .result = .permerror }, error.Temporary, error.Canceled => return .{ .result = .temperror }, // One address is all the question needs, so a full buffer is // the answer "yes" rather than a problem. error.NoSpace => return .matched, }; return if (found.len > 0) .matched else .no_match; }
/// §5.2. An `include` asks somebody else's record the same question /// and takes only a `pass` for an answer. /// /// The table in §5.2 is the part everybody gets wrong: an included /// record that says `fail` does **not** make this record fail, it /// just does not match — otherwise `include:` could never be used /// twice, since every sensible record ends in `-all`. And an include /// of a domain with no policy is a `permerror`, because the record /// pointed somewhere and there was nothing there. fn matchInclude(state: *State, domain: []const u8, spec: []const u8, depth: u8) Match { var buffer: [max_expansion]u8 = undefined; const target = state.expand(&buffer, spec, domain) catch return .{ .result = .permerror }; // §6.2: an explanation belongs to the record that was asked // about, so an included record's `exp=` is not used. const outcome = state.evaluate(target, depth + 1, false); return switch (outcome.result) { .pass => .matched, .fail, .softfail, .neutral => .no_match, .temperror => .{ .result = .temperror }, .none, .permerror => .{ .result = .permerror }, }; }
/// The name the client's address points at, confirmed by looking /// that name back up and finding the address again. §5.5 calls this /// the "validated domain name", and the confirmation is what stops /// anyone who controls a reverse zone from claiming any name they /// like. fn validatedName(state: *State) ?[]const u8 { if (state.validated_done) return state.validated; state.validated_done = true;
var reverse_buffer: [z46.Address.max_reverse_name_len]u8 = undefined; const reverse = state.client.reverseName(&reverse_buffer) catch return null;
var storage: [max_name_bytes]u8 = undefined; var index: [max_names][]const u8 = undefined; var names: Resolver.Strings = .init(&storage, &index); // §4.6.4 caps the names looked at and says the rest "MUST be // ignored", so running out of room is the cap being reached // rather than a failure. state.resolver.ptr(state.io, reverse, &names) catch |err| switch (err) { error.NoSpace => {}, else => return null, };
for (names.slice()) |name| { var index_forward: [max_addresses]z46.Address = undefined; var found: Resolver.Addresses = .init(&index_forward); state.resolver.addresses(state.io, name, state.client.family(), &found) catch // §5.5: "if a DNS error occurs while doing an A RR // lookup, then that host is not used" — the name is // skipped, the mechanism carries on. continue; for (found.slice()) |address| { if (!address.eql(state.client)) continue; const copy = state.validated_storage[0..name.len]; @memcpy(copy, name); state.validated = copy; return state.validated; } } return null; }
fn expand( state: *State, buffer: []u8, spec: []const u8, domain: []const u8, ) macro.Error![]const u8 { return macro.expand(buffer, spec, state.context(domain, spec), .{}, true); }
fn context(state: *State, domain: []const u8, spec: []const u8) macro.Context { return .{ .sender = state.sender, .domain = domain, .client_ip = state.client, .helo = state.helo, // The lookup `%{p}` needs is expensive and almost never // asked for, so it happens only when a record actually // mentions it. .validated_domain = if (mentionsValidatedDomain(spec)) state.validatedName() else null, .receiver = state.options.receiver, .timestamp = state.options.timestamp, }; }
/// §6.2's explanation, fetched only for a `fail` and only when the /// caller gave it somewhere to go. /// /// Every way this can go wrong ends in no explanation rather than in /// a different result: the mail has already been judged, and a /// broken `exp=` is not grounds to revisit that. §6.2 says so /// outright. fn explainWith(state: *State, record: Record, domain: []const u8) ?[]const u8 { const out = state.options.explanation orelse return null; const spec = record.exp orelse return null;
var name_buffer: [max_expansion]u8 = undefined; const target = state.expand(&name_buffer, spec, domain) catch return null;
// No prefix here: an explanation is ordinary text, and §6.2 // wants to know whether the name carries exactly one record. var storage: [max_txt_bytes]u8 = undefined; var index: [max_txt_records][]const u8 = undefined; var answers: Resolver.Strings = .init(&storage, &index); state.resolver.txt(state.io, target, &answers) catch return null; // §6.2: exactly one TXT record, or there is no explanation. if (answers.len != 1) return null;
// The text is itself a macro-string, and the only one in SPF // where `%{c}`, `%{r}` and `%{t}` are allowed — it is written for // a person to read rather than for a name to be looked up. return macro.expand( out, answers.slice()[0], state.context(domain, answers.slice()[0]), .{ .explanation = true }, false, ) catch null; }};
/// Whether `address` is inside the network `candidate` describes at the/// prefix length for its family. The two families never meet: an `a`/// mechanism resolving to an IPv6 address says nothing about an IPv4/// client.fn contains(candidate: z46.Address, dual: Record.Dual, address: z46.Address) bool { return switch (candidate) { .ipv4 => |ipv4| switch (address) { .ipv4 => |client| (z46.Ipv4Network.initTruncate(ipv4, dual.ip4_prefix) catch return false).contains(client), .ipv6 => false, }, .ipv6 => |ipv6| switch (address) { .ipv6 => |client| (z46.Ipv6Network.initTruncate(ipv6, dual.ip6_prefix) catch return false).contains(client), .ipv4 => false, }, };}
/// Whether `name` is `domain` or sits under it. §5.5 accepts either, so/// a `ptr` mechanism covers a whole zone rather than one host.fn isSubdomainOf(name: []const u8, domain: []const u8) bool { const trimmed_name = std.mem.trimEnd(u8, name, "."); const trimmed_domain = std.mem.trimEnd(u8, domain, "."); if (std.ascii.eqlIgnoreCase(trimmed_name, trimmed_domain)) return true; if (trimmed_name.len <= trimmed_domain.len + 1) return false; const at = trimmed_name.len - trimmed_domain.len; if (trimmed_name[at - 1] != '.') return false; return std.ascii.eqlIgnoreCase(trimmed_name[at..], trimmed_domain);}
/// §4.3's check, which is about the name being askable rather than about/// it existing: a label longer than 63 octets or a name longer than 253/// is a question no nameserver can be asked.fn validDomain(name: []const u8) bool { if (name.len == 0 or name.len > macro.max_domain_len) return false; // A single trailing dot is the root and is how an absolute name is // written, so it is not an empty label. const trimmed = std.mem.trimEnd(u8, name, "."); if (trimmed.len == 0) return false; var labels = std.mem.splitScalar(u8, trimmed, '.'); while (labels.next()) |label| { if (label.len == 0 or label.len > 63) return false; } return true;}
/// Whether a macro-string asks for `%{p}`, in either case.fn mentionsValidatedDomain(spec: []const u8) bool { var index: usize = 0; while (std.mem.indexOfScalarPos(u8, spec, index, '%')) |at| { if (at + 2 < spec.len and spec[at + 1] == '{' and (spec[at + 2] == 'p' or spec[at + 2] == 'P')) return true; index = at + 1; } return false;}
const testing = std.testing;const Zone = @import("Zone.zig");
/// One zone shared by most of the tests below, so that each says only/// what it is about.const zone: Zone = .{ .entries = &.{ .{ .name = "simple.example.com", .data = .{ .txt = "v=spf1 ip4:192.0.2.0/24 -all" } }, .{ .name = "soft.example.com", .data = .{ .txt = "v=spf1 ip4:192.0.2.0/24 ~all" } }, .{ .name = "quiet.example.com", .data = .{ .txt = "v=spf1 ip4:192.0.2.0/24 ?all" } }, .{ .name = "bare.example.com", .data = .{ .txt = "v=spf1 ip4:192.0.2.0/24" } }, .{ .name = "sixes.example.com", .data = .{ .txt = "v=spf1 ip6:2001:db8::/32 -all" } },
// A domain whose own address records are the policy. .{ .name = "self.example.com", .data = .{ .txt = "v=spf1 a -all" } }, .{ .name = "self.example.com", .data = .{ .a = "192.0.2.10" } }, .{ .name = "wide.example.com", .data = .{ .txt = "v=spf1 a/24 -all" } }, .{ .name = "wide.example.com", .data = .{ .a = "192.0.2.10" } }, .{ .name = "other.example.com", .data = .{ .txt = "v=spf1 a:hosts.example.com -all" } }, .{ .name = "hosts.example.com", .data = .{ .a = "192.0.2.20" } }, .{ .name = "hosts.example.com", .data = .{ .a = "192.0.2.21" } },
// Exchangers. .{ .name = "mail.example.com", .data = .{ .txt = "v=spf1 mx -all" } }, .{ .name = "mail.example.com", .data = .{ .mx = "in1.example.com" } }, .{ .name = "mail.example.com", .data = .{ .mx = "in2.example.com" } }, .{ .name = "in1.example.com", .data = .{ .a = "192.0.2.30" } }, .{ .name = "in2.example.com", .data = .{ .a = "192.0.2.31" } },
// A policy published as a zone rather than as a record. .{ .name = "flag.example.com", .data = .{ .txt = "v=spf1 exists:%{ir}.ok.example.com -all" } }, .{ .name = "3.2.0.192.ok.example.com", .data = .{ .a = "127.0.0.2" } },
// Delegation, both ways round. .{ .name = "includer.example.com", .data = .{ .txt = "v=spf1 include:third.example.com -all" } }, .{ .name = "third.example.com", .data = .{ .txt = "v=spf1 ip4:198.51.100.0/24 -all" } }, // The shape everybody actually publishes: somebody else's // record, then your own addresses. .{ .name = "chained.example.com", .data = .{ .txt = "v=spf1 include:third.example.com ip4:192.0.2.0/24 -all", } }, .{ .name = "nowhere.example.com", .data = .{ .txt = "v=spf1 include:blank.example.com -all" } }, .{ .name = "blank.example.com", .data = .{ .txt = "not an spf record" } }, .{ .name = "moved.example.com", .data = .{ .txt = "v=spf1 redirect=third.example.com" } }, .{ .name = "dangling.example.com", .data = .{ .txt = "v=spf1 redirect=blank.example.com" } },
// The reverse zone, for `ptr` and `%{p}`. Each address below is // one of the three ways the mechanism can answer. .{ .name = "pointed.example.com", .data = .{ .txt = "v=spf1 ptr -all" } }, // Points into the domain, and the name points back. .{ .name = "40.2.0.192.in-addr.arpa", .data = .{ .ptr = "host.pointed.example.com" } }, .{ .name = "host.pointed.example.com", .data = .{ .a = "192.0.2.40" } }, // Points into the domain, and the name does not point back. .{ .name = "41.2.0.192.in-addr.arpa", .data = .{ .ptr = "fake.pointed.example.com" } }, .{ .name = "fake.pointed.example.com", .data = .{ .a = "203.0.113.1" } }, // Points back, but at a name in somebody else's domain. .{ .name = "43.2.0.192.in-addr.arpa", .data = .{ .ptr = "host.elsewhere.example.org" } }, .{ .name = "host.elsewhere.example.org", .data = .{ .a = "192.0.2.43" } },
// Broken in various ways. .{ .name = "twice.example.com", .data = .{ .txt = "v=spf1 -all" } }, .{ .name = "twice.example.com", .data = .{ .txt = "v=spf1 +all" } }, .{ .name = "typo.example.com", .data = .{ .txt = "v=spf1 ip4:192.0.2.0/33 -all" } }, .{ .name = "plain.example.com", .data = .{ .txt = "just a note" } }, .{ .name = "void.example.com", .data = .{ .txt = "v=spf1 a:one.invalid a:two.invalid a:three.invalid -all", } },
// An explanation. .{ .name = "sorry.example.com", .data = .{ .txt = "v=spf1 -all exp=why.example.com" } }, .{ .name = "why.example.com", .data = .{ .txt = "%{i} is not one of ours; ask %{o}" } }, }, .failing = &.{"broken.example.com"},};
fn expect(result: Result, client: []const u8, domain: []const u8) !void { const address = try z46.Address.parse(client); const outcome = checkHost(std.testing.io, zone.resolver(), address, domain, .{ .local_part = "alice", .domain = domain, }, .{}); try testing.expectEqual(result, outcome.result);}
test "an address inside and outside a published network" { try expect(.pass, "192.0.2.1", "simple.example.com"); try expect(.fail, "198.51.100.1", "simple.example.com"); try expect(.pass, "2001:db8::1", "sixes.example.com"); // A record about IPv4 says nothing about an IPv6 client, and the // other way round: the families never meet. try expect(.fail, "2001:db8::1", "simple.example.com"); try expect(.fail, "192.0.2.1", "sixes.example.com");}
test "the qualifier of the matching mechanism is the result" { try expect(.softfail, "198.51.100.1", "soft.example.com"); try expect(.neutral, "198.51.100.1", "quiet.example.com"); // §4.7: a record that runs out of mechanisms has declined to say, // which is not the same as saying no. try expect(.neutral, "198.51.100.1", "bare.example.com");}
test "a domain with no policy is none, not a refusal" { try expect(.none, "192.0.2.1", "missing.example.com"); // A TXT record that is not an SPF record is not a broken SPF // record. Every domain publishing a DKIM key would be permerror // otherwise. try expect(.none, "192.0.2.1", "plain.example.com");}
test "a broken policy is permerror" { // §4.5: two records are a contradiction rather than a choice. try expect(.permerror, "192.0.2.1", "twice.example.com"); try expect(.permerror, "192.0.2.1", "typo.example.com");}
test "a nameserver that will not answer is temperror" { // The result that asks a sender to come back rather than telling // them they are forged. try expect(.temperror, "192.0.2.1", "broken.example.com");}
test "the a mechanism, with and without a prefix" { try expect(.pass, "192.0.2.10", "self.example.com"); try expect(.fail, "192.0.2.11", "self.example.com"); // The prefix widens the record's own address into a network. try expect(.pass, "192.0.2.11", "wide.example.com"); try expect(.fail, "198.51.100.1", "wide.example.com"); // And a named host, which may have several addresses. try expect(.pass, "192.0.2.20", "other.example.com"); try expect(.pass, "192.0.2.21", "other.example.com"); try expect(.fail, "192.0.2.22", "other.example.com");}
test "the mx mechanism asks about the hosts that receive the mail" { try expect(.pass, "192.0.2.30", "mail.example.com"); try expect(.pass, "192.0.2.31", "mail.example.com"); try expect(.fail, "192.0.2.32", "mail.example.com");}
test "the exists mechanism is a policy kept in a zone" { // `%{ir}` is the client address reversed, so the record is asking // whether a name built out of the client exists. A large sender can // change its policy by changing a zone rather than a record. try expect(.pass, "192.0.2.3", "flag.example.com"); try expect(.fail, "192.0.2.4", "flag.example.com");}
test "include takes only a pass for an answer" { try expect(.pass, "198.51.100.1", "includer.example.com"); try expect(.fail, "192.0.2.1", "includer.example.com"); // The included record says `-all` for this client, and that does // *not* make the including record fail — it does not match, and // evaluation carries on to the next term. This is the record shape // that shows the difference: somebody else's policy, then your own // addresses. An implementation that propagated the fail would refuse // this domain's own mail, and `include:` could never be used twice, // since every sensible record ends in `-all`. try expect(.pass, "192.0.2.1", "chained.example.com"); try expect(.pass, "198.51.100.1", "chained.example.com"); try expect(.fail, "203.0.113.1", "chained.example.com"); // §5.2: an include of a domain with no policy is a broken record. // The record pointed somewhere and there was nothing there. try expect(.permerror, "192.0.2.1", "nowhere.example.com");}
test "redirect replaces the record" { try expect(.pass, "198.51.100.1", "moved.example.com"); try expect(.fail, "192.0.2.1", "moved.example.com"); // §6.1: unlike an include, a redirect to a domain with no policy is // a permerror rather than a none. try expect(.permerror, "192.0.2.1", "dangling.example.com");}
test "ptr matches only a name that points back from inside the domain" { try expect(.pass, "192.0.2.40", "pointed.example.com"); // The reverse zone claims a name inside the domain, and that name's // address is somewhere else entirely. Without the forward // confirmation of §5.5, anyone who controls the reverse zone for // their own address could claim any domain they liked — which is // the whole reason the mechanism does two lookups instead of one. try expect(.fail, "192.0.2.41", "pointed.example.com"); // A name that does point back, but is not in this domain. try expect(.fail, "192.0.2.43", "pointed.example.com"); // No reverse record at all. try expect(.fail, "192.0.2.42", "pointed.example.com");}
test "an IPv4-mapped IPv6 client is an IPv4 client" { // §5 says so outright, and a receiver on a dual-stack socket sees // every IPv4 client this way — so without it, every `ip4:` // mechanism in the world stops matching. try expect(.pass, "::ffff:192.0.2.1", "simple.example.com"); try expect(.fail, "::ffff:198.51.100.1", "simple.example.com");}
test "the query budget of section 4.6.4" { // Eleven `include:` mechanisms against a budget of ten. The chain is // written out because that is what an attacker would publish: a // record is somebody else's program, and this budget is the only // thing bounding how long it runs. const chain: Zone = .{ .entries = &.{ .{ .name = "a0.example.com", .data = .{ .txt = "v=spf1 include:a1.example.com -all" } }, .{ .name = "a1.example.com", .data = .{ .txt = "v=spf1 include:a2.example.com -all" } }, .{ .name = "a2.example.com", .data = .{ .txt = "v=spf1 include:a3.example.com -all" } }, .{ .name = "a3.example.com", .data = .{ .txt = "v=spf1 include:a4.example.com -all" } }, .{ .name = "a4.example.com", .data = .{ .txt = "v=spf1 include:a5.example.com -all" } }, .{ .name = "a5.example.com", .data = .{ .txt = "v=spf1 include:a6.example.com -all" } }, .{ .name = "a6.example.com", .data = .{ .txt = "v=spf1 include:a7.example.com -all" } }, .{ .name = "a7.example.com", .data = .{ .txt = "v=spf1 include:a8.example.com -all" } }, .{ .name = "a8.example.com", .data = .{ .txt = "v=spf1 include:a9.example.com -all" } }, .{ .name = "a9.example.com", .data = .{ .txt = "v=spf1 include:a10.example.com -all" } }, .{ .name = "a10.example.com", .data = .{ .txt = "v=spf1 include:a11.example.com -all" } }, .{ .name = "a11.example.com", .data = .{ .txt = "v=spf1 +all" } }, } }; const address = try z46.Address.parse("192.0.2.1"); const sender: macro.Sender = .{ .local_part = "alice", .domain = "a0.example.com" }; try testing.expectEqual(Result.permerror, checkHost( std.testing.io, chain.resolver(), address, "a0.example.com", sender, .{}, ).result); // Raising the budget by one reaches the end of the same chain, which // is how the test shows it is the budget doing the refusing and not // something else about the records. try testing.expectEqual(Result.pass, checkHost( std.testing.io, chain.resolver(), address, "a0.example.com", sender, .{ .limits = .{ .queries = 11 } }, ).result); // And one below the default stops one link earlier, so the budget is // being counted rather than compared against a constant. try testing.expectEqual(Result.permerror, checkHost( std.testing.io, chain.resolver(), address, "a1.example.com", sender, .{ .limits = .{ .queries = 9 } }, ).result);}
test "the void lookup budget" { // Three names that do not exist, where §4.6.4 recommends allowing // two. A record like this is either a mistake nobody noticed or a // way to make a receiver do work on somebody else's behalf. try expect(.permerror, "192.0.2.1", "void.example.com"); const address = try z46.Address.parse("192.0.2.1"); try testing.expectEqual(Result.fail, checkHost( std.testing.io, zone.resolver(), address, "void.example.com", .{ .local_part = "alice", .domain = "void.example.com" }, .{ .limits = .{ .void_lookups = 3 } }, ).result);}
test "an explanation is fetched for a fail and expanded" { var explanation: [256]u8 = undefined; const address = try z46.Address.parse("192.0.2.1"); const outcome = checkHost( std.testing.io, zone.resolver(), address, "sorry.example.com", .{ .local_part = "alice", .domain = "sorry.example.com" }, .{ .explanation = &explanation }, ); try testing.expectEqual(Result.fail, outcome.result); try testing.expectEqualStrings( "192.0.2.1 is not one of ours; ask sorry.example.com", outcome.explanation.?, ); // Without somewhere to put it, the lookup is not made at all. const quiet = checkHost( std.testing.io, zone.resolver(), address, "sorry.example.com", .{ .local_part = "alice", .domain = "sorry.example.com" }, .{}, ); try testing.expectEqual(Result.fail, quiet.result); try testing.expectEqual(@as(?[]const u8, null), quiet.explanation);}
test "a HELO check and an empty reverse-path" { const address = try z46.Address.parse("192.0.2.1"); try testing.expectEqual(Result.pass, checkHelo( std.testing.io, zone.resolver(), address, "simple.example.com", .{}, ).result); // §2.4: `MAIL FROM:<>` has no domain of its own, so the greeting is // checked instead. A bounce claiming to come from nowhere is still // coming from some host. try testing.expectEqual(Result.pass, checkMailFrom( std.testing.io, zone.resolver(), address, "simple.example.com", "", .{}, ).result); try testing.expectEqual(Result.fail, checkMailFrom( std.testing.io, zone.resolver(), try z46.Address.parse("198.51.100.1"), "simple.example.com", "bob@simple.example.com", .{}, ).result);}