1// Package dmarc implements DMARC (Domain-based Message Authentication,
2// Reporting, and Conformance; RFC 7489) verification.
3//
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.
11package dmarc
12
13import (
14 "context"
15 "errors"
16 "fmt"
17 "log/slog"
18 mathrand "math/rand"
19 "time"
20
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"
27)
28
29var (
30 MetricVerify stub.HistogramVec = stub.HistogramVecIgnore{}
31)
32
33// link errata:
34// ../rfc/7489-eid5440 ../rfc/7489:1585
35
36// Lookup errors.
37var (
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")
42)
43
44// Status is the result of DMARC policy evaluation, for use in an Authentication-Results header.
45type Status string
46
47// ../rfc/7489:2339
48
49const (
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.
55)
56
57// Result is a DMARC policy evaluation.
58type Result struct {
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.
62 Reject bool
63 // Result of DMARC validation. A message can fail validation, but still
64 // not be rejected, e.g. if the policy is "none".
65 Status Status
66 AlignedSPFPass bool
67 AlignedDKIMPass bool
68 // Domain with the DMARC DNS record. May be the organizational domain instead of
69 // the domain in the From-header.
70 Domain dns.Domain
71 // Parsed DMARC record.
72 Record *Record
73 // Whether DMARC DNS response was DNSSEC-signed, regardless of whether SPF/DKIM records were DNSSEC-signed.
74 RecordAuthentic bool
75 // Details about possible error condition, e.g. when parsing the DMARC record failed.
76 Err error
77}
78
79// Lookup looks up the DMARC TXT record at "_dmarc.<domain>" for the domain in the
80// "From"-header of a message.
81//
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.
87//
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)
91 start := time.Now()
92 defer func() {
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)))
99 }()
100
101 // ../rfc/7489:859 ../rfc/7489:1370
102 domain = msgFrom
103 status, record, txt, authentic, err := lookupRecord(ctx, resolver, domain)
104 if status != StatusNone {
105 return status, domain, record, txt, authentic, err
106 }
107 if record == nil {
108 // ../rfc/7489:761 ../rfc/7489:1377
109 domain = publicsuffix.Lookup(ctx, log.Logger, msgFrom)
110 if domain == msgFrom {
111 return StatusNone, domain, nil, txt, authentic, err
112 }
113
114 var xauth bool
115 status, record, txt, xauth, err = lookupRecord(ctx, resolver, domain)
116 authentic = authentic && xauth
117 }
118 return status, domain, record, txt, authentic, err
119}
120
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)
126 }
127 var record *Record
128 var text string
129 var rerr error = ErrNoRecord
130 for _, txt := range txts {
131 r, isdmarc, err := ParseRecord(txt)
132 if !isdmarc {
133 // ../rfc/7489:1374
134 continue
135 } else if err != nil {
136 return StatusPermerror, nil, text, result.Authentic, fmt.Errorf("%w: %s", ErrSyntax, err)
137 }
138 if record != nil {
139 // ../rfc/7489:1388
140 return StatusNone, nil, "", result.Authentic, ErrMultipleRecords
141 }
142 text = txt
143 record = r
144 rerr = nil
145 }
146 return StatusNone, record, text, result.Authentic, rerr
147}
148
149func lookupReportsRecord(ctx context.Context, resolver dns.Resolver, dmarcDomain, extDestDomain dns.Domain) (Status, []*Record, []string, bool, error) {
150 // ../rfc/7489:1566
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)
155 }
156 var records []*Record
157 var texts []string
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.
163 // ../rfc/7489-eid5440
164 if !isdmarc && txt == "v=DMARC1" {
165 xr := DefaultRecord
166 r, isdmarc, err = &xr, true, nil
167 }
168 if !isdmarc {
169 // ../rfc/7489:1586
170 continue
171 }
172 texts = append(texts, txt)
173 records = append(records, r)
174 if err != nil {
175 return StatusPermerror, records, texts, result.Authentic, fmt.Errorf("%w: %s", ErrSyntax, err)
176 }
177 // Multiple records are allowed for the _report record, unlike for policies. ../rfc/7489:1593
178 rerr = nil
179 }
180 return StatusNone, records, texts, result.Authentic, rerr
181}
182
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.
186//
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.
192//
193// The normally invalid "v=DMARC1" record is accepted since it is used as
194// example in RFC 7489.
195//
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)
199 start := time.Now()
200 defer func() {
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)))
207 }()
208
209 status, records, txts, authentic, rerr = lookupReportsRecord(ctx, resolver, dmarcDomain, extDestDomain)
210 accepts = rerr == nil
211 return accepts, status, records, txts, authentic, rerr
212}
213
214// Verify evaluates the DMARC policy for the domain in the From-header of a
215// message given the DKIM and SPF evaluation results.
216//
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
220// email processing
221//
222// Verify always returns the result of verifying the DMARC policy
223// against the message (for inclusion in Authentication-Result headers).
224//
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)
229 start := time.Now()
230 defer func() {
231 use := "no"
232 if useResult {
233 use = "yes"
234 }
235 reject := "no"
236 if result.Reject {
237 reject = "yes"
238 }
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)))
248 }()
249
250 status, recordDomain, record, _, authentic, err := Lookup(ctx, log.Logger, resolver, msgFrom)
251 if record == nil {
252 return false, Result{false, status, false, false, recordDomain, record, authentic, err}
253 }
254 result.Domain = recordDomain
255 result.Record = record
256 result.RecordAuthentic = authentic
257
258 // Record can request sampling of messages to apply policy.
259 // See ../rfc/7489:1432
260 useResult = !applyRandomPercentage || record.Percentage == 100 || mathrand.Intn(100) < record.Percentage
261
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.
264 // ../rfc/7489:1446 ../rfc/7489:1024
265 if recordDomain != msgFrom && record.SubdomainPolicy != PolicyEmpty {
266 result.Reject = record.SubdomainPolicy != PolicyNone
267 } else {
268 result.Reject = record.Policy != PolicyNone
269 }
270
271 // ../rfc/7489:1338
272 result.Status = StatusFail
273 if spfResult == spf.StatusTemperror {
274 result.Status = StatusTemperror
275 result.Reject = false
276 }
277
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 {
283 return r
284 }
285 r := publicsuffix.Lookup(ctx, log.Logger, name)
286 pubsuffixes[name] = r
287 return r
288 }
289
290 // ../rfc/7489:1319
291 // ../rfc/7489:544
292 if spfResult == spf.StatusPass && spfIdentity != nil && (*spfIdentity == msgFrom || result.Record.ASPF == "r" && pubsuffix(msgFrom) == pubsuffix(*spfIdentity)) {
293 result.AlignedSPFPass = true
294 }
295
296 for _, dkimResult := range dkimResults {
297 if dkimResult.Status == dkim.StatusTemperror {
298 result.Reject = false
299 result.Status = StatusTemperror
300 continue
301 }
302 // ../rfc/7489:511
303 if dkimResult.Status == dkim.StatusPass && dkimResult.Sig != nil && (dkimResult.Sig.Domain == msgFrom || result.Record.ADKIM == "r" && pubsuffix(msgFrom) == pubsuffix(dkimResult.Sig.Domain)) {
304 // ../rfc/7489:535
305 result.AlignedDKIMPass = true
306 break
307 }
308 }
309
310 if result.AlignedSPFPass || result.AlignedDKIMPass {
311 result.Reject = false
312 result.Status = StatusPass
313 }
314 return
315}
316