DMARC (RFC 7489) for Zig: the record grammar, identifier alignment, and policy discovery by DNS tree walk rather than a public suffix list.
zig-dmarc README.md
13 kB · 307 lines
Markdown
at main

zig-dmarc #

Domain-based Message Authentication, Reporting, and Conformance — RFC 7489 — for Zig.

SPF and DKIM each authenticate an identifier a reader never sees: the envelope sender, and whatever domain happened to sign the message. DMARC is the part that ties either of those to the From: field a person actually reads, and lets the domain in it say what to do when nothing does.

So this library consumes results rather than producing them. It takes an SPF result and the domain it was for, the DKIM signatures that verified and the domains that signed them, and the From: domain, and answers whether any of them line up — and what the domain owner asked for if none do.

Requires Zig 0.17.0. The zig-0.16 branch and the v0.1.0 tag build with Zig 0.16.0.

Where this lives #

git clone https://git.jcollie.dev/jeff/zig-dmarc.git
rad clone rad:zkzyA2aWM1MzffvnqjBHysjxdg5J

Status #

Early. Record is here: the tag-value grammar of §6.4, every tag §6.3 defines, and the two rules that turn a parsed record into a policy.

Policy discovery is here — the DNS tree walk and the organizational domain it yields — and so is the evaluation: identifier alignment, and the verdict that follows.

AuthenticationResults writes the RFC 8601 field that records all of it.

For a worked example as an SMTP handler, see examples/dmarc_policy.zig in zig-smtp: five libraries, none of which knows what another is for — the session, the SPF check, the From: field, the signatures, and this library tying them together.

Reading a record #

const record = try dmarc.Record.parse("v=DMARC1; p=reject; sp=none; rua=mailto:d@example.com");
// record.policyFor("example.com", "news.example.com") == .none

Nothing allocates: every value is a slice of the record text the caller still owns. Reporting is not this library's job, so rua and ruf are handed over as written rather than parsed into URIs.

Three rules in §6.3 and §6.6.3 are easy to miss and each changes the answer:

  • error.NotDmarc is not a parse failure. §6.6.3 discards records that do not start with v=DMARC1 while selecting one, so a _dmarc name carrying an ownership token has no policy rather than a broken one — and _dmarc names carry ownership tokens all the time.
  • A record with no usable p but a rua is read as p=none. §6.6.3 step 6: a domain owner who published something unusable and a reporting address is watching rather than asking, so reports still go out. With neither, DMARC does not apply to the message at all, which is error.NoPolicy. An invalid sp poisons the record the same way, because a receiver cannot tell which half the owner meant.
  • An unknown tag is ignored, not fatal. The tag registry is meant to grow; a receiver that refused a record carrying a tag it had not heard of would stop honouring policies the day one was added. np= and psd= from the coming revision already turn up in the wild. A known tag with an unusable value falls back to its default, for the same reason — except p and sp, where the question of whether there is a policy at all turns on the value.

sp is the tag the whole design turns on, and policyFor is where it is applied: an organization can refuse forgeries of example.com outright while leaving a subdomain it has not finished inventorying at none.

Judging a message #

var buffer: [dmarc.max_name_len]u8 = undefined;
var storage: [1024]u8 = undefined;
const outcome = try dmarc.evaluate(io, resolver, .{
    .from_domain = "example.com",              // the From: field
    .spf = .{ .result = .pass, .domain = "bounces.example.com" },
    .dkim = &.{.{ .result = .pass, .domain = "example.com" }},
}, &buffer, &storage);

switch (outcome.disposition) {
    .pass => {},       // something aligned
    .fail => {},       // nothing did; outcome.policy is what the owner asked for
    .none => {},       // no policy: DMARC does not apply to this message
    .temperror => {},  // the DNS got in the way; deliver or defer, your call
}

DMARC's whole contribution is one sentence: a message passes if some authenticated identifier belongs to the same domain as the From: field a person reads. Everything else — the record, the walk, the policy — is in service of that sentence.

It is needed because both underlying mechanisms authenticate something else. A message can carry a perfectly valid DKIM signature from a domain its sender controls, and pass SPF for a bounce address its sender controls, while saying From: whatever it likes. There is a test for exactly that, because it is the attack the protocol exists to stop.

Four things the library will not decide for you:

  • none is not p=none. The first means a receiver has been told nothing; the second means it has been told to do nothing. Conflating them throws away the distinction p=none exists to create.
  • temperror is reported, not resolved. §4.10.1 leaves the choice between delivering and deferring to the receiver, so the library hands back what it knows.
  • pct is reported, not rolled. Applying a policy to a share of failing mail is how an owner rolls one out, and the selection is the receiver's — a library that rolled a die here would be making a delivery decision on somebody else's behalf, unrepeatably.
  • A message with two From: addresses is not evaluated. §6.6.1 says so; a caller that flattens them into one has decided something DMARC declined to.

Recording the answer #

const results: dmarc.AuthenticationResults = .{
    .authserv_id = "mx.example.org",
    .spf = .{ .result = .pass, .value = "bounces.example.net" },
    .dkim = &.{.{ .result = .pass, .domain = "example.net", .selector = "s1" }},
    .dmarc = .{ .result = .fail, .from_domain = "example.com", .policy = .reject },
};
try writer.print("{f}", .{results});
Authentication-Results: mx.example.org;
 spf=pass smtp.mailfrom=bounces.example.net;
 dkim=pass header.d=example.net header.s=s1;
 dmarc=fail header.from=example.com policy.dmarc=reject

All three methods in one field, which is the point: dmarc=fail on its own tells a reader nothing about why. Beside the other two it says the message was authenticated by somebody who is not the domain in the From: field — the whole story, in one line.

A host that checked nothing still writes the field, with §2.2's no-result, so a reader can tell "nobody checked" from "the field was stripped on the way".

The field is worth exactly what the receiver's boundary is worth. RFC 8601 §7.1 is blunt: anyone can write one of these, so a receiver MUST strip any field bearing its own authserv-id from messages arriving from outside before adding its own. This library writes the field; deleting the forgeries above it is the caller's job, and nothing here can do it for them.

Every value in the field came from the message being judged, so the escaping is the job rather than a detail. A value is written bare only when it is a token or an address — @ is one of RFC 2045's tspecials, which is why the ABNF allows an address as a separate alternative — and anything else is a quoted-string with " and \ escaped and CR and LF dropped. There is a test built from an envelope sender that tries to close the quoted string and write dmarc=pass of its own.

Finding a policy #

var owner: [dmarc.max_name_len]u8 = undefined;
var storage: [1024]u8 = undefined;
const found = try dmarc.policy(io, resolver, "news.example.com", &owner, &storage);
if (found) |policy_record| {
    const p = policy_record.record.policyFor(policy_record.owner, "news.example.com", exists);
}

Null means DMARC does not apply to the message, which is not the same as a policy of none: a receiver has been told nothing rather than told to do nothing.

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 — which is why policyFor takes it.

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, changing continuously. The RFC said receivers should use one, did not say which, acknowledged that receivers choosing different lists would disagree about the same message, and said that if a more reliable method were found it should replace the list.

This is that method, taken from the revision in progress. The boundary is published in the DNS by the people who own it, with the psd tag, and a receiver finds it by climbing from a name towards the root reading _dmarc records. Nothing to ship and nothing to keep up to date.

_dmarc.a.mail.example.com   ->  nothing
_dmarc.mail.example.com     ->  v=DMARC1; p=none; psd=n
                                ^ "I am an organization in my own right"

The cost is DNS queries, so the walk is bounded at eight. That number is not arbitrary: a sender with bad intentions can put a From: address with hundreds of labels on a message, and a receiver that walked all of them would be doing that sender's denial-of-service work for it. A name longer than seven labels jumps straight to seven.

Three rules decide where the walk stops, and organizationalDomain applies them in this order: a record saying psd=n is an organizational domain; a record saying psd=y is a public suffix, so the organization begins one label below it; otherwise the record found at the fewest labels wins. With nothing found anywhere, a name is its own organizational domain — the honest answer rather than a guess, and the one that makes strict and relaxed alignment agree.

Two more rules from §4.10 are worth naming because both surprise people:

  • A name publishing two DMARC records has published none. That 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.
  • Only records claiming to be DMARC count towards that rule. A _dmarc name shares its record set with whatever else was put there, and something usually is.

The tool #

$ dmarc parse 'v=DMARC1; p=reject; sp=quarantine; adkim=s; pct=50; rua=mailto:d@example.com'
  policy       reject
  subdomains   quarantine
  alignment    dkim strict, spf relaxed
  applied to   50%
  aggregate    mailto:d@example.com
  interval     86400s

It prints what a record means rather than what it says, which is the point: subdomains is filled in when sp was absent, and an assumed p=none says so.

Licence #

MIT. The project follows REUSE; reuse lint passes.

References cited #

  • [RFC7489] Kucherawy, M., Ed., and E. Zwicky, Ed., "Domain-based Message Authentication, Reporting, and Conformance (DMARC)", RFC 7489, March 2015, https://www.rfc-editor.org/info/rfc7489.
  • [RFC6376] Crocker, D., Ed., Hansen, T., Ed., and M. Kucherawy, Ed., "DomainKeys Identified Mail (DKIM) Signatures", STD 76, RFC 6376, September 2011, https://www.rfc-editor.org/info/rfc6376. The tag-value syntax §6.3 borrows, and one of the two identifiers DMARC aligns.
  • [RFC7208] Kitterman, S., "Sender Policy Framework (SPF) for Authorizing Use of Domains in Email, Version 1", RFC 7208, April 2014, https://www.rfc-editor.org/info/rfc7208. The other.
  • [RFC8601] Kucherawy, M., "Message Header Field for Indicating Message Authentication Status", RFC 8601, May 2019, https://www.rfc-editor.org/info/rfc8601. The Authentication-Results field.
  • [RFC2045] Freed, N. and N. Borenstein, "Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies", RFC 2045, November 1996, https://www.rfc-editor.org/info/rfc2045. §5.1's token, which is what decides whether a value in that field needs quoting.
  • [RFC9091] Kitterman, S. and T. Wicinski, Ed., "Experimental Domain-Based Message Authentication, Reporting, and Conformance (DMARC) Extension for Public Suffix Domains", RFC 9091, July 2021, https://www.rfc-editor.org/info/rfc9091. Defines the np tag.
  • [DMARCBIS] Levine, J., Ed., "Domain-based Message Authentication, Reporting, and Conformance (DMARC)", Work in Progress, Internet-Draft, draft-ietf-dmarc-dmarcbis-41, https://datatracker.ietf.org/doc/draft-ietf-dmarc-dmarcbis/. The revision in progress, which is where the DNS tree walk and the psd tag come from. Not yet an RFC; RFC 7489 remains the published specification and is what the record syntax here follows.
  • [RFC5322] Resnick, P., Ed., "Internet Message Format", RFC 5322, October 2008, https://www.rfc-editor.org/info/rfc5322. Defines the From: field, which is the identifier DMARC exists to protect.

Tests #

zig build test