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.
20 "github.com/prometheus/client_golang/prometheus"
21 "github.com/prometheus/client_golang/prometheus/promauto"
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"
30var xlog = mlog.New("dmarc")
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},
42 "use", // yes/no, if policy is used after random selection
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")
58// Status is the result of DMARC policy evaluation, for use in an Authentication-Results header.
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.
71// Result is a DMARC policy evaluation.
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.
76 // Result of DMARC validation. A message can fail validation, but still
77 // not be rejected, e.g. if the policy is "none".
79 // Domain with the DMARC DNS record. May be the organizational domain instead of
80 // the domain in the From-header.
82 // Parsed DMARC record.
84 // Details about possible error condition, e.g. when parsing the DMARC record failed.
88// Lookup looks up the DMARC TXT record at "_dmarc.<domain>" for the domain in the
89// "From"-header of a message.
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)
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)))
105 status, record, txt, err := lookupRecord(ctx, resolver, domain)
106 if status != StatusNone {
107 return status, domain, record, txt, err
111 domain = publicsuffix.Lookup(ctx, from)
113 return StatusNone, domain, nil, txt, err
116 status, record, txt, err = lookupRecord(ctx, resolver, domain)
118 return status, domain, record, txt, err
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)
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, fmt.Errorf("%w: %s", ErrSyntax, err)
140 return StatusNone, nil, "", ErrMultipleRecords
146 return StatusNone, record, text, rerr
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)
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.
163 if !isdmarc && txt == "v=DMARC1" {
165 r, isdmarc, err = &xr, true, nil
170 } else if err != nil {
171 return StatusPermerror, nil, text, fmt.Errorf("%w: %s", ErrSyntax, err)
175 return StatusNone, nil, "", ErrMultipleRecords
181 return StatusNone, record, text, rerr
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.
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).
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)
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)))
201 status, record, txt, rerr = lookupReportsRecord(ctx, resolver, dmarcDomain, extDestDomain)
202 accepts = rerr == nil
203 return accepts, status, record, txt, rerr
206// Verify evaluates the DMARC policy for the domain in the From-header of a
207// message given the DKIM and SPF evaluation results.
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
214// Verify always returns the result of verifying the DMARC policy
215// against the message (for inclusion in Authentication-Result headers).
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)
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)))
234 status, recordDomain, record, _, err := Lookup(ctx, resolver, from)
236 return false, Result{false, status, recordDomain, record, err}
238 result.Domain = recordDomain
239 result.Record = record
241 // Record can request sampling of messages to apply policy.
243 useResult = !applyRandomPercentage || record.Percentage == 100 || mathrand.Intn(100) < record.Percentage
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.
248 if recordDomain != from && record.SubdomainPolicy != PolicyEmpty {
249 result.Reject = record.SubdomainPolicy != PolicyNone
251 result.Reject = record.Policy != PolicyNone
255 result.Status = StatusFail
256 if spfResult == spf.StatusTemperror {
257 result.Status = StatusTemperror
258 result.Reject = false
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 {
268 r := publicsuffix.Lookup(ctx, name)
269 pubsuffixes[name] = r
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
281 for _, dkimResult := range dkimResults {
282 if dkimResult.Status == dkim.StatusTemperror {
283 result.Reject = false
284 result.Status = StatusTemperror
288 if dkimResult.Status == dkim.StatusPass && dkimResult.Sig != nil && (dkimResult.Sig.Domain == from || result.Record.ADKIM == "r" && pubsuffix(from) == pubsuffix(dkimResult.Sig.Domain)) {
290 result.Reject = false
291 result.Status = StatusPass