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 mathrand "math/rand"
18 "time"
19
20 "github.com/prometheus/client_golang/prometheus"
21 "github.com/prometheus/client_golang/prometheus/promauto"
22
23 "github.com/mjl-/mox/dkim"
24 "github.com/mjl-/mox/dns"
25 "github.com/mjl-/mox/mlog"
26 "github.com/mjl-/mox/publicsuffix"
27 "github.com/mjl-/mox/spf"
28)
29
30var xlog = mlog.New("dmarc")
31
32var (
33 metricDMARCVerify = promauto.NewHistogramVec(
34 prometheus.HistogramOpts{
35 Name: "mox_dmarc_verify_duration_seconds",
36 Help: "DMARC verify, including lookup, duration and result.",
37 Buckets: []float64{0.001, 0.005, 0.01, 0.05, 0.100, 0.5, 1, 5, 10, 20},
38 },
39 []string{
40 "status",
41 "reject", // yes/no
42 "use", // yes/no, if policy is used after random selection
43 },
44 )
45)
46
47// link errata:
48// ../rfc/7489-eid5440 ../rfc/7489:1585
49
50// Lookup errors.
51var (
52 ErrNoRecord = errors.New("dmarc: no dmarc dns record")
53 ErrMultipleRecords = errors.New("dmarc: multiple dmarc dns records") // Must also be treated as if domain does not implement DMARC.
54 ErrDNS = errors.New("dmarc: dns lookup")
55 ErrSyntax = errors.New("dmarc: malformed dmarc dns record")
56)
57
58// Status is the result of DMARC policy evaluation, for use in an Authentication-Results header.
59type Status string
60
61// ../rfc/7489:2339
62
63const (
64 StatusNone Status = "none" // No DMARC TXT DNS record found.
65 StatusPass Status = "pass" // SPF and/or DKIM pass with identifier alignment.
66 StatusFail Status = "fail" // Either both SPF and DKIM failed or identifier did not align with a pass.
67 StatusTemperror Status = "temperror" // Typically a DNS lookup. A later attempt may results in a conclusion.
68 StatusPermerror Status = "permerror" // Typically a malformed DMARC DNS record.
69)
70
71// Result is a DMARC policy evaluation.
72type Result struct {
73 // Whether to reject the message based on policies. If false, the message should
74 // not necessarily be accepted, e.g. due to reputation or content-based analysis.
75 Reject bool
76 // Result of DMARC validation. A message can fail validation, but still
77 // not be rejected, e.g. if the policy is "none".
78 Status Status
79 // Domain with the DMARC DNS record. May be the organizational domain instead of
80 // the domain in the From-header.
81 Domain dns.Domain
82 // Parsed DMARC record.
83 Record *Record
84 // Details about possible error condition, e.g. when parsing the DMARC record failed.
85 Err error
86}
87
88// Lookup looks up the DMARC TXT record at "_dmarc.<domain>" for the domain in the
89// "From"-header of a message.
90//
91// If no DMARC record is found for the "From"-domain, another lookup is done at
92// the organizational domain of the domain (if different). The organizational
93// domain is determined using the public suffix list. E.g. for
94// "sub.example.com", the organizational domain is "example.com". The returned
95// domain is the domain with the DMARC record.
96func Lookup(ctx context.Context, resolver dns.Resolver, from dns.Domain) (status Status, domain dns.Domain, record *Record, txt string, rerr error) {
97 log := xlog.WithContext(ctx)
98 start := time.Now()
99 defer func() {
100 log.Debugx("dmarc lookup result", rerr, mlog.Field("fromdomain", from), mlog.Field("status", status), mlog.Field("domain", domain), mlog.Field("record", record), mlog.Field("duration", time.Since(start)))
101 }()
102
103 // ../rfc/7489:859 ../rfc/7489:1370
104 domain = from
105 status, record, txt, err := lookupRecord(ctx, resolver, domain)
106 if status != StatusNone {
107 return status, domain, record, txt, err
108 }
109 if record == nil {
110 // ../rfc/7489:761 ../rfc/7489:1377
111 domain = publicsuffix.Lookup(ctx, from)
112 if domain == from {
113 return StatusNone, domain, nil, txt, err
114 }
115
116 status, record, txt, err = lookupRecord(ctx, resolver, domain)
117 }
118 return status, domain, record, txt, err
119}
120
121func lookupRecord(ctx context.Context, resolver dns.Resolver, domain dns.Domain) (Status, *Record, string, error) {
122 name := "_dmarc." + domain.ASCII + "."
123 txts, err := dns.WithPackage(resolver, "dmarc").LookupTXT(ctx, name)
124 if err != nil && !dns.IsNotFound(err) {
125 return StatusTemperror, nil, "", 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, fmt.Errorf("%w: %s", ErrSyntax, err)
137 }
138 if record != nil {
139 // ../ ../rfc/7489:1388
140 return StatusNone, nil, "", ErrMultipleRecords
141 }
142 text = txt
143 record = r
144 rerr = nil
145 }
146 return StatusNone, record, text, rerr
147}
148
149func lookupReportsRecord(ctx context.Context, resolver dns.Resolver, dmarcDomain, extDestDomain dns.Domain) (Status, *Record, string, error) {
150 name := dmarcDomain.ASCII + "._report._dmarc." + extDestDomain.ASCII + "."
151 txts, err := dns.WithPackage(resolver, "dmarc").LookupTXT(ctx, name)
152 if err != nil && !dns.IsNotFound(err) {
153 return StatusTemperror, nil, "", fmt.Errorf("%w: %s", ErrDNS, err)
154 }
155 var record *Record
156 var text string
157 var rerr error = ErrNoRecord
158 for _, txt := range txts {
159 r, isdmarc, err := ParseRecordNoRequired(txt)
160 // Examples in the RFC use "v=DMARC1", even though it isn't a valid DMARC record.
161 // Accept the specific example.
162 // ../rfc/7489-eid5440
163 if !isdmarc && txt == "v=DMARC1" {
164 xr := DefaultRecord
165 r, isdmarc, err = &xr, true, nil
166 }
167 if !isdmarc {
168 // ../rfc/7489:1374
169 continue
170 } else if err != nil {
171 return StatusPermerror, nil, text, fmt.Errorf("%w: %s", ErrSyntax, err)
172 }
173 if record != nil {
174 // ../ ../rfc/7489:1388
175 return StatusNone, nil, "", ErrMultipleRecords
176 }
177 text = txt
178 record = r
179 rerr = nil
180 }
181 return StatusNone, record, text, rerr
182}
183
184// LookupExternalReportsAccepted returns whether the extDestDomain has opted in
185// to receiving dmarc reports for dmarcDomain (where the dmarc record was found),
186// through a "._report._dmarc." DNS TXT DMARC record.
187//
188// Callers should look at status for interpretation, not err, because err will
189// be set to ErrNoRecord when the DNS TXT record isn't present, which means the
190// extDestDomain does not opt in (not a failure condition).
191//
192// The normally invalid "v=DMARC1" record is accepted since it is used as
193// example in RFC 7489.
194func LookupExternalReportsAccepted(ctx context.Context, resolver dns.Resolver, dmarcDomain dns.Domain, extDestDomain dns.Domain) (accepts bool, status Status, record *Record, txt string, rerr error) {
195 log := xlog.WithContext(ctx)
196 start := time.Now()
197 defer func() {
198 log.Debugx("dmarc externalreports result", rerr, mlog.Field("accepts", accepts), mlog.Field("dmarcdomain", dmarcDomain), mlog.Field("extdestdomain", extDestDomain), mlog.Field("record", record), mlog.Field("duration", time.Since(start)))
199 }()
200
201 status, record, txt, rerr = lookupReportsRecord(ctx, resolver, dmarcDomain, extDestDomain)
202 accepts = rerr == nil
203 return accepts, status, record, txt, rerr
204}
205
206// Verify evaluates the DMARC policy for the domain in the From-header of a
207// message given the DKIM and SPF evaluation results.
208//
209// applyRandomPercentage determines whether the records "pct" is honored. This
210// field specifies the percentage of messages the DMARC policy is applied to. It
211// is used for slow rollout of DMARC policies and should be honored during normal
212// email processing
213//
214// Verify always returns the result of verifying the DMARC policy
215// against the message (for inclusion in Authentication-Result headers).
216//
217// useResult indicates if the result should be applied in a policy decision.
218func Verify(ctx context.Context, resolver dns.Resolver, from dns.Domain, dkimResults []dkim.Result, spfResult spf.Status, spfIdentity *dns.Domain, applyRandomPercentage bool) (useResult bool, result Result) {
219 log := xlog.WithContext(ctx)
220 start := time.Now()
221 defer func() {
222 use := "no"
223 if useResult {
224 use = "yes"
225 }
226 reject := "no"
227 if result.Reject {
228 reject = "yes"
229 }
230 metricDMARCVerify.WithLabelValues(string(result.Status), reject, use).Observe(float64(time.Since(start)) / float64(time.Second))
231 log.Debugx("dmarc verify result", result.Err, mlog.Field("fromdomain", from), mlog.Field("dkimresults", dkimResults), mlog.Field("spfresult", spfResult), mlog.Field("status", result.Status), mlog.Field("reject", result.Reject), mlog.Field("use", useResult), mlog.Field("duration", time.Since(start)))
232 }()
233
234 status, recordDomain, record, _, err := Lookup(ctx, resolver, from)
235 if record == nil {
236 return false, Result{false, status, recordDomain, record, err}
237 }
238 result.Domain = recordDomain
239 result.Record = record
240
241 // Record can request sampling of messages to apply policy.
242 // See ../rfc/7489:1432
243 useResult = !applyRandomPercentage || record.Percentage == 100 || mathrand.Intn(100) < record.Percentage
244
245 // We reject treat "quarantine" and "reject" the same. Thus, we also don't
246 // "downgrade" from reject to quarantine if this message was sampled out.
247 // ../rfc/7489:1446 ../rfc/7489:1024
248 if recordDomain != from && record.SubdomainPolicy != PolicyEmpty {
249 result.Reject = record.SubdomainPolicy != PolicyNone
250 } else {
251 result.Reject = record.Policy != PolicyNone
252 }
253
254 // ../rfc/7489:1338
255 result.Status = StatusFail
256 if spfResult == spf.StatusTemperror {
257 result.Status = StatusTemperror
258 result.Reject = false
259 }
260
261 // Below we can do a bunch of publicsuffix lookups. Cache the results, mostly to
262 // reduce log pollution.
263 pubsuffixes := map[dns.Domain]dns.Domain{}
264 pubsuffix := func(name dns.Domain) dns.Domain {
265 if r, ok := pubsuffixes[name]; ok {
266 return r
267 }
268 r := publicsuffix.Lookup(ctx, name)
269 pubsuffixes[name] = r
270 return r
271 }
272
273 // ../rfc/7489:1319
274 // ../rfc/7489:544
275 if spfResult == spf.StatusPass && spfIdentity != nil && (*spfIdentity == from || result.Record.ASPF == "r" && pubsuffix(from) == pubsuffix(*spfIdentity)) {
276 result.Reject = false
277 result.Status = StatusPass
278 return
279 }
280
281 for _, dkimResult := range dkimResults {
282 if dkimResult.Status == dkim.StatusTemperror {
283 result.Reject = false
284 result.Status = StatusTemperror
285 continue
286 }
287 // ../rfc/7489:511
288 if dkimResult.Status == dkim.StatusPass && dkimResult.Sig != nil && (dkimResult.Sig.Domain == from || result.Record.ADKIM == "r" && pubsuffix(from) == pubsuffix(dkimResult.Sig.Domain)) {
289 // ../rfc/7489:535
290 result.Reject = false
291 result.Status = StatusPass
292 return
293 }
294 }
295 return
296}
297