1// Package dmarc implements DMARC (Domain-based Message Authentication,
2// Reporting, and Conformance; RFC 7489) verification.
4// DMARC is a mechanism for verifying ("authenticating") the address in the "From"
5// message header, since users will look at that header to identify the sender of a
6// message. DMARC compares the "From"-(sub)domain against the SPF and/or
7// DKIM-validated domains, based on the DMARC policy that a domain has published in
8// DNS as TXT record under "_dmarc.<domain>". A DMARC policy can also ask for
9// feedback about evaluations by other email servers, for monitoring/debugging
10// problems with email delivery.
21 "github.com/mjl-/mox/dkim"
22 "github.com/mjl-/mox/dns"
23 "github.com/mjl-/mox/mlog"
24 "github.com/mjl-/mox/publicsuffix"
25 "github.com/mjl-/mox/spf"
26 "github.com/mjl-/mox/stub"
30 MetricVerify stub.HistogramVec = stub.HistogramVecIgnore{}
38 ErrNoRecord = errors.New("dmarc: no dmarc dns record")
39 ErrMultipleRecords = errors.New("dmarc: multiple dmarc dns records") // Must also be treated as if domain does not implement DMARC.
40 ErrDNS = errors.New("dmarc: dns lookup")
41 ErrSyntax = errors.New("dmarc: malformed dmarc dns record")
44// Status is the result of DMARC policy evaluation, for use in an Authentication-Results header.
50 StatusNone Status = "none" // No DMARC TXT DNS record found.
51 StatusPass Status = "pass" // SPF and/or DKIM pass with identifier alignment.
52 StatusFail Status = "fail" // Either both SPF and DKIM failed or identifier did not align with a pass.
53 StatusTemperror Status = "temperror" // Typically a DNS lookup. A later attempt may results in a conclusion.
54 StatusPermerror Status = "permerror" // Typically a malformed DMARC DNS record.
57// Result is a DMARC policy evaluation.
59 // Whether to reject the message based on policies. If false, the message should
60 // not necessarily be accepted: other checks such as reputation-based and
61 // content-based analysis may lead to reject the message.
63 // Result of DMARC validation. A message can fail validation, but still
64 // not be rejected, e.g. if the policy is "none".
68 // Domain with the DMARC DNS record. May be the organizational domain instead of
69 // the domain in the From-header.
71 // Parsed DMARC record.
73 // Whether DMARC DNS response was DNSSEC-signed, regardless of whether SPF/DKIM records were DNSSEC-signed.
75 // Details about possible error condition, e.g. when parsing the DMARC record failed.
79// Lookup looks up the DMARC TXT record at "_dmarc.<domain>" for the domain in the
80// "From"-header of a message.
82// If no DMARC record is found for the "From"-domain, another lookup is done at
83// the organizational domain of the domain (if different). The organizational
84// domain is determined using the public suffix list. E.g. for
85// "sub.example.com", the organizational domain is "example.com". The returned
86// domain is the domain with the DMARC record.
88// rauthentic indicates if the DNS results were DNSSEC-verified.
89func Lookup(ctx context.Context, elog *slog.Logger, resolver dns.Resolver, msgFrom dns.Domain) (status Status, domain dns.Domain, record *Record, txt string, rauthentic bool, rerr error) {
90 log := mlog.New("dmarc", elog)
93 log.Debugx("dmarc lookup result", rerr,
94 slog.Any("fromdomain", msgFrom),
95 slog.Any("status", status),
96 slog.Any("domain", domain),
97 slog.Any("record", record),
98 slog.Duration("duration", time.Since(start)))
103 status, record, txt, authentic, err := lookupRecord(ctx, resolver, domain)
104 if status != StatusNone {
105 return status, domain, record, txt, authentic, err
109 domain = publicsuffix.Lookup(ctx, log.Logger, msgFrom)
110 if domain == msgFrom {
111 return StatusNone, domain, nil, txt, authentic, err
115 status, record, txt, xauth, err = lookupRecord(ctx, resolver, domain)
116 authentic = authentic && xauth
118 return status, domain, record, txt, authentic, err
121func lookupRecord(ctx context.Context, resolver dns.Resolver, domain dns.Domain) (Status, *Record, string, bool, error) {
122 name := "_dmarc." + domain.ASCII + "."
123 txts, result, err := dns.WithPackage(resolver, "dmarc").LookupTXT(ctx, name)
124 if err != nil && !dns.IsNotFound(err) {
125 return StatusTemperror, nil, "", result.Authentic, fmt.Errorf("%w: %s", ErrDNS, err)
129 var rerr error = ErrNoRecord
130 for _, txt := range txts {
131 r, isdmarc, err := ParseRecord(txt)
135 } else if err != nil {
136 return StatusPermerror, nil, text, result.Authentic, fmt.Errorf("%w: %s", ErrSyntax, err)
140 return StatusNone, nil, "", result.Authentic, ErrMultipleRecords
146 return StatusNone, record, text, result.Authentic, rerr
149func lookupReportsRecord(ctx context.Context, resolver dns.Resolver, dmarcDomain, extDestDomain dns.Domain) (Status, []*Record, []string, bool, error) {
151 name := dmarcDomain.ASCII + "._report._dmarc." + extDestDomain.ASCII + "."
152 txts, result, err := dns.WithPackage(resolver, "dmarc").LookupTXT(ctx, name)
153 if err != nil && !dns.IsNotFound(err) {
154 return StatusTemperror, nil, nil, result.Authentic, fmt.Errorf("%w: %s", ErrDNS, err)
156 var records []*Record
158 var rerr error = ErrNoRecord
159 for _, txt := range txts {
160 r, isdmarc, err := ParseRecordNoRequired(txt)
161 // Examples in the RFC use "v=DMARC1", even though it isn't a valid DMARC record.
162 // Accept the specific example.
164 if !isdmarc && txt == "v=DMARC1" {
166 r, isdmarc, err = &xr, true, nil
172 texts = append(texts, txt)
173 records = append(records, r)
175 return StatusPermerror, records, texts, result.Authentic, fmt.Errorf("%w: %s", ErrSyntax, err)
177 // Multiple records are allowed for the _report record, unlike for policies.
../rfc/7489:1593
180 return StatusNone, records, texts, result.Authentic, rerr
183// LookupExternalReportsAccepted returns whether the extDestDomain has opted in
184// to receiving dmarc reports for dmarcDomain (where the dmarc record was found),
185// through a "._report._dmarc." DNS TXT DMARC record.
187// accepts is true if the external domain has opted in.
188// If a temporary error occurred, the returned status is StatusTemperror, and a
189// later retry may give an authoritative result.
190// The returned error is ErrNoRecord if no opt-in DNS record exists, which is
191// not a failure condition.
193// The normally invalid "v=DMARC1" record is accepted since it is used as
194// example in RFC 7489.
196// authentic indicates if the DNS results were DNSSEC-verified.
197func LookupExternalReportsAccepted(ctx context.Context, elog *slog.Logger, resolver dns.Resolver, dmarcDomain dns.Domain, extDestDomain dns.Domain) (accepts bool, status Status, records []*Record, txts []string, authentic bool, rerr error) {
198 log := mlog.New("dmarc", elog)
201 log.Debugx("dmarc externalreports result", rerr,
202 slog.Bool("accepts", accepts),
203 slog.Any("dmarcdomain", dmarcDomain),
204 slog.Any("extdestdomain", extDestDomain),
205 slog.Any("records", records),
206 slog.Duration("duration", time.Since(start)))
209 status, records, txts, authentic, rerr = lookupReportsRecord(ctx, resolver, dmarcDomain, extDestDomain)
210 accepts = rerr == nil
211 return accepts, status, records, txts, authentic, rerr
214// Verify evaluates the DMARC policy for the domain in the From-header of a
215// message given the DKIM and SPF evaluation results.
217// applyRandomPercentage determines whether the records "pct" is honored. This
218// field specifies the percentage of messages the DMARC policy is applied to. It
219// is used for slow rollout of DMARC policies and should be honored during normal
222// Verify always returns the result of verifying the DMARC policy
223// against the message (for inclusion in Authentication-Result headers).
225// useResult indicates if the result should be applied in a policy decision,
226// based on the "pct" field in the DMARC record.
227func Verify(ctx context.Context, elog *slog.Logger, resolver dns.Resolver, msgFrom dns.Domain, dkimResults []dkim.Result, spfResult spf.Status, spfIdentity *dns.Domain, applyRandomPercentage bool) (useResult bool, result Result) {
228 log := mlog.New("dmarc", elog)
239 MetricVerify.ObserveLabels(float64(time.Since(start))/float64(time.Second), string(result.Status), reject, use)
240 log.Debugx("dmarc verify result", result.Err,
241 slog.Any("fromdomain", msgFrom),
242 slog.Any("dkimresults", dkimResults),
243 slog.Any("spfresult", spfResult),
244 slog.Any("status", result.Status),
245 slog.Bool("reject", result.Reject),
246 slog.Bool("use", useResult),
247 slog.Duration("duration", time.Since(start)))
250 status, recordDomain, record, _, authentic, err := Lookup(ctx, log.Logger, resolver, msgFrom)
252 return false, Result{false, status, false, false, recordDomain, record, authentic, err}
254 result.Domain = recordDomain
255 result.Record = record
256 result.RecordAuthentic = authentic
258 // Record can request sampling of messages to apply policy.
260 useResult = !applyRandomPercentage || record.Percentage == 100 || mathrand.Intn(100) < record.Percentage
262 // We treat "quarantine" and "reject" the same. Thus, we also don't "downgrade"
263 // from reject to quarantine if this message was sampled out.
265 if recordDomain != msgFrom && record.SubdomainPolicy != PolicyEmpty {
266 result.Reject = record.SubdomainPolicy != PolicyNone
268 result.Reject = record.Policy != PolicyNone
272 result.Status = StatusFail
273 if spfResult == spf.StatusTemperror {
274 result.Status = StatusTemperror
275 result.Reject = false
278 // Below we can do a bunch of publicsuffix lookups. Cache the results, mostly to
279 // reduce log pollution.
280 pubsuffixes := map[dns.Domain]dns.Domain{}
281 pubsuffix := func(name dns.Domain) dns.Domain {
282 if r, ok := pubsuffixes[name]; ok {
285 r := publicsuffix.Lookup(ctx, log.Logger, name)
286 pubsuffixes[name] = r
292 if spfResult == spf.StatusPass && spfIdentity != nil && (*spfIdentity == msgFrom || result.Record.ASPF == "r" && pubsuffix(msgFrom) == pubsuffix(*spfIdentity)) {
293 result.AlignedSPFPass = true
296 for _, dkimResult := range dkimResults {
297 if dkimResult.Status == dkim.StatusTemperror {
298 result.Reject = false
299 result.Status = StatusTemperror
303 if dkimResult.Status == dkim.StatusPass && dkimResult.Sig != nil && (dkimResult.Sig.Domain == msgFrom || result.Record.ADKIM == "r" && pubsuffix(msgFrom) == pubsuffix(dkimResult.Sig.Domain)) {
305 result.AlignedDKIMPass = true
310 if result.AlignedSPFPass || result.AlignedDKIMPass {
311 result.Reject = false
312 result.Status = StatusPass