1package smtpclient
2
3import (
4 "context"
5 "crypto/sha256"
6 "crypto/sha512"
7 "crypto/x509"
8 "errors"
9 "fmt"
10 "log/slog"
11 "net"
12 "sort"
13 "strings"
14 "time"
15
16 "github.com/mjl-/adns"
17
18 "github.com/mjl-/mox/dns"
19 "github.com/mjl-/mox/mlog"
20)
21
22var (
23 errCNAMELoop = errors.New("cname loop")
24 errCNAMELimit = errors.New("too many cname records")
25 errDNS = errors.New("dns lookup error")
26 errNoMail = errors.New("domain does not accept email as indicated with single dot for mx record")
27)
28
29// GatherDestinations looks up the hosts to deliver email to a domain ("next-hop").
30// If it is an IP address, it is the only destination to try. Otherwise CNAMEs of
31// the domain are followed. Then MX records for the expanded CNAME are looked up.
32// If no MX record is present, the original domain is returned. If an MX record is
33// present but indicates the domain does not accept email, ErrNoMail is returned.
34// If valid MX records were found, the MX target hosts are returned.
35//
36// haveMX indicates if an MX record was found.
37//
38// origNextHopAuthentic indicates if the DNS record for the initial domain name was
39// DNSSEC secure (CNAME, MX).
40//
41// expandedNextHopAuthentic indicates if the DNS records after following CNAMEs were
42// DNSSEC secure.
43//
44// These authentic results are needed for DANE, to determine where to look up TLSA
45// records, and which names to allow in the remote TLS certificate. If MX records
46// were found, both the original and expanded next-hops must be authentic for DANE
47// to be option. For a non-IP with no MX records found, the authentic result can
48// be used to decide which of the names to use as TLSA base domain.
49func GatherDestinations(ctx context.Context, elog *slog.Logger, resolver dns.Resolver, origNextHop dns.IPDomain) (haveMX, origNextHopAuthentic, expandedNextHopAuthentic bool, expandedNextHop dns.Domain, hosts []dns.IPDomain, permanent bool, err error) {
50 // ../rfc/5321:3824
51
52 log := mlog.New("smtpclient", elog)
53
54 // IP addresses are dialed directly, and don't have TLSA records.
55 if len(origNextHop.IP) > 0 {
56 return false, false, false, expandedNextHop, []dns.IPDomain{origNextHop}, false, nil
57 }
58
59 // We start out assuming the result is authentic. Updated with each lookup.
60 origNextHopAuthentic = true
61 expandedNextHopAuthentic = true
62
63 // We start out delivering to the recipient domain. We follow CNAMEs.
64 rcptDomain := origNextHop.Domain
65 // Domain we are actually delivering to, after following CNAME record(s).
66 expandedNextHop = rcptDomain
67 // Keep track of CNAMEs we have followed, to detect loops.
68 domainsSeen := map[string]bool{}
69 for i := 0; ; i++ {
70 if domainsSeen[expandedNextHop.ASCII] {
71 // todo: only mark as permanent failure if TTLs for all records are beyond latest possibly delivery retry we would do.
72 err := fmt.Errorf("%w: recipient domain %s: already saw %s", errCNAMELoop, rcptDomain, expandedNextHop)
73 return false, origNextHopAuthentic, expandedNextHopAuthentic, expandedNextHop, nil, false, err
74 }
75 domainsSeen[expandedNextHop.ASCII] = true
76
77 // note: The Go resolver returns the requested name if the domain has no CNAME
78 // record but has a host record.
79 if i == 16 {
80 // We have a maximum number of CNAME records we follow. There is no hard limit for
81 // DNS, and you might think folks wouldn't configure CNAME chains at all, but for
82 // (non-mail) domains, CNAME chains of 10 records have been encountered according
83 // to the internet.
84 // todo: only mark as permanent failure if TTLs for all records are beyond latest possibly delivery retry we would do.
85 err := fmt.Errorf("%w: recipient domain %s, last resolved domain %s", errCNAMELimit, rcptDomain, expandedNextHop)
86 return false, origNextHopAuthentic, expandedNextHopAuthentic, expandedNextHop, nil, false, err
87 }
88
89 // Do explicit CNAME lookup. Go's LookupMX also resolves CNAMEs, but we want to
90 // know the final name, and we're interested in learning if the first vs later
91 // results were DNSSEC-(in)secure.
92 // ../rfc/5321:3838 ../rfc/3974:197
93 cctx, ccancel := context.WithTimeout(ctx, 30*time.Second)
94 defer ccancel()
95 cname, cnameResult, err := resolver.LookupCNAME(cctx, expandedNextHop.ASCII+".")
96 ccancel()
97 if i == 0 {
98 origNextHopAuthentic = origNextHopAuthentic && cnameResult.Authentic
99 }
100 expandedNextHopAuthentic = expandedNextHopAuthentic && cnameResult.Authentic
101 if err != nil && !dns.IsNotFound(err) {
102 err = fmt.Errorf("%w: cname lookup for %s: %v", errDNS, expandedNextHop, err)
103 return false, origNextHopAuthentic, expandedNextHopAuthentic, expandedNextHop, nil, false, err
104 }
105 if err == nil && cname != expandedNextHop.ASCII+"." {
106 d, err := dns.ParseDomain(strings.TrimSuffix(cname, "."))
107 if err != nil {
108 // todo: only mark as permanent failure if TTLs for all records are beyond latest possibly delivery retry we would do.
109 err = fmt.Errorf("%w: parsing cname domain %s: %v", errDNS, expandedNextHop, err)
110 return false, origNextHopAuthentic, expandedNextHopAuthentic, expandedNextHop, nil, false, err
111 }
112 expandedNextHop = d
113 // Start again with new domain.
114 continue
115 }
116
117 // Not a CNAME, so lookup MX record.
118 mctx, mcancel := context.WithTimeout(ctx, 30*time.Second)
119 defer mcancel()
120 // Note: LookupMX can return an error and still return records: Invalid records are
121 // filtered out and an error returned. We must process any records that are valid.
122 // Only if all are unusable will we return an error. ../rfc/5321:3851
123 mxl, mxResult, err := resolver.LookupMX(mctx, expandedNextHop.ASCII+".")
124 mcancel()
125 if i == 0 {
126 origNextHopAuthentic = origNextHopAuthentic && mxResult.Authentic
127 }
128 expandedNextHopAuthentic = expandedNextHopAuthentic && mxResult.Authentic
129 if err != nil && len(mxl) == 0 {
130 if !dns.IsNotFound(err) {
131 err = fmt.Errorf("%w: mx lookup for %s: %v", errDNS, expandedNextHop, err)
132 return false, origNextHopAuthentic, expandedNextHopAuthentic, expandedNextHop, nil, false, err
133 }
134
135 // No MX record, attempt delivery directly to host. ../rfc/5321:3842
136 hosts = []dns.IPDomain{{Domain: expandedNextHop}}
137 return false, origNextHopAuthentic, expandedNextHopAuthentic, expandedNextHop, hosts, false, nil
138 } else if err != nil {
139 log.Infox("mx record has some invalid records, keeping only the valid mx records", err)
140 }
141
142 // ../rfc/7505:122
143 if err == nil && len(mxl) == 1 && mxl[0].Host == "." {
144 // Note: Depending on MX record TTL, this record may be replaced with a more
145 // receptive MX record before our final delivery attempt. But it's clearly the
146 // explicit desire not to be bothered with email delivery attempts, so mark failure
147 // as permanent.
148 return true, origNextHopAuthentic, expandedNextHopAuthentic, expandedNextHop, nil, true, errNoMail
149 }
150
151 // The Go resolver already sorts by preference, randomizing records of same
152 // preference. ../rfc/5321:3885
153 for _, mx := range mxl {
154 // Parsing lax (unless pedantic mode) for MX targets with underscores as seen in the wild.
155 host, err := dns.ParseDomainLax(strings.TrimSuffix(mx.Host, "."))
156 if err != nil {
157 // note: should not happen because Go resolver already filters these out.
158 err = fmt.Errorf("%w: invalid host name in mx record %q: %v", errDNS, mx.Host, err)
159 return true, origNextHopAuthentic, expandedNextHopAuthentic, expandedNextHop, nil, true, err
160 }
161 hosts = append(hosts, dns.IPDomain{Domain: host})
162 }
163 if len(hosts) > 0 {
164 err = nil
165 }
166 return true, origNextHopAuthentic, expandedNextHopAuthentic, expandedNextHop, hosts, false, err
167 }
168}
169
170// GatherIPs looks up the IPs to try for connecting to host, with the IPs ordered
171// to take previous attempts into account. For use with DANE, the CNAME-expanded
172// name is returned, and whether the DNS responses were authentic.
173func GatherIPs(ctx context.Context, elog *slog.Logger, resolver dns.Resolver, network string, host dns.IPDomain, dialedIPs map[string][]net.IP) (authentic bool, expandedAuthentic bool, expandedHost dns.Domain, ips []net.IP, dualstack bool, rerr error) {
174 log := mlog.New("smtpclient", elog)
175
176 if len(host.IP) > 0 {
177 return false, false, dns.Domain{}, []net.IP{host.IP}, false, nil
178 }
179
180 authentic = true
181 expandedAuthentic = true
182
183 // The Go resolver automatically follows CNAMEs, which is not allowed for host
184 // names in MX records, but seems to be accepted and is documented for DANE SMTP
185 // behaviour. We resolve CNAMEs explicitly, so we can return the final name, which
186 // DANE needs. ../rfc/7671:246
187 // ../rfc/5321:3861 ../rfc/2181:661 ../rfc/7672:1382 ../rfc/7671:1030
188 name := host.Domain.ASCII + "."
189
190 for i := 0; ; i++ {
191 cname, result, err := resolver.LookupCNAME(ctx, name)
192 if i == 0 {
193 authentic = result.Authentic
194 }
195 expandedAuthentic = expandedAuthentic && result.Authentic
196 if dns.IsNotFound(err) {
197 break
198 } else if err != nil {
199 return authentic, expandedAuthentic, dns.Domain{}, nil, dualstack, err
200 } else if strings.TrimSuffix(cname, ".") == strings.TrimSuffix(name, ".") {
201 break
202 }
203 if i > 10 {
204 return authentic, expandedAuthentic, dns.Domain{}, nil, dualstack, fmt.Errorf("mx lookup: %w", errCNAMELimit)
205 }
206 name = strings.TrimSuffix(cname, ".") + "."
207 }
208
209 if name == host.Domain.ASCII+"." {
210 expandedHost = host.Domain
211 } else {
212 var err error
213 expandedHost, err = dns.ParseDomain(strings.TrimSuffix(name, "."))
214 if err != nil {
215 return authentic, expandedAuthentic, dns.Domain{}, nil, dualstack, fmt.Errorf("parsing cname-resolved domain: %w", err)
216 }
217 }
218
219 ipaddrs, result, err := resolver.LookupIP(ctx, network, name)
220 authentic = authentic && result.Authentic
221 expandedAuthentic = expandedAuthentic && result.Authentic
222 if err != nil || len(ipaddrs) == 0 {
223 return authentic, expandedAuthentic, expandedHost, nil, false, fmt.Errorf("looking up %q: %w", name, err)
224 }
225 var have4, have6 bool
226 for _, ipaddr := range ipaddrs {
227 ips = append(ips, ipaddr)
228 if ipaddr.To4() == nil {
229 have6 = true
230 } else {
231 have4 = true
232 }
233 }
234 dualstack = have4 && have6
235 prevIPs := dialedIPs[host.String()]
236 if len(prevIPs) > 0 {
237 prevIP := prevIPs[len(prevIPs)-1]
238 prevIs4 := prevIP.To4() != nil
239 sameFamily := 0
240 for _, ip := range prevIPs {
241 is4 := ip.To4() != nil
242 if prevIs4 == is4 {
243 sameFamily++
244 }
245 }
246 preferPrev := sameFamily == 1
247 // We use stable sort so any preferred/randomized listing from DNS is kept intact.
248 sort.SliceStable(ips, func(i, j int) bool {
249 aIs4 := ips[i].To4() != nil
250 bIs4 := ips[j].To4() != nil
251 if aIs4 != bIs4 {
252 // Prefer "i" if it is not same address family.
253 return aIs4 != prevIs4
254 }
255 // Prefer "i" if it is the same as last and we should be preferring it.
256 return preferPrev && ips[i].Equal(prevIP)
257 })
258 log.Debug("ordered ips for dialing", slog.Any("ips", ips))
259 }
260 return
261}
262
263// GatherTLSA looks up TLSA record for either expandedHost or host, and returns
264// records usable for DANE with SMTP, and host names to allow in DANE-TA
265// certificate name verification.
266//
267// If no records are found, this isn't necessarily an error. It can just indicate
268// the domain/host does not opt-in to DANE, and nil records and a nil error are
269// returned.
270//
271// Only usable records are returned. If any record was found, DANE is required and
272// this is indicated with daneRequired. If no usable records remain, the caller
273// must do TLS, but not verify the remote TLS certificate.
274//
275// Returned values are always meaningful, also when an error was returned.
276func GatherTLSA(ctx context.Context, elog *slog.Logger, resolver dns.Resolver, host dns.Domain, expandedAuthentic bool, expandedHost dns.Domain) (daneRequired bool, daneRecords []adns.TLSA, tlsaBaseDomain dns.Domain, err error) {
277 log := mlog.New("smtpclient", elog)
278
279 // ../rfc/7672:912
280 // This function is only called when the lookup of host was authentic.
281
282 var l []adns.TLSA
283
284 tlsaBaseDomain = host
285 if host == expandedHost || !expandedAuthentic {
286 l, err = lookupTLSACNAME(ctx, log, resolver, 25, "tcp", host)
287 } else if expandedAuthentic {
288 // ../rfc/7672:934
289 tlsaBaseDomain = expandedHost
290 l, err = lookupTLSACNAME(ctx, log, resolver, 25, "tcp", expandedHost)
291 if err == nil && len(l) == 0 {
292 tlsaBaseDomain = host
293 l, err = lookupTLSACNAME(ctx, log, resolver, 25, "tcp", host)
294 }
295 }
296 if len(l) == 0 || err != nil {
297 daneRequired = err != nil
298 log.Debugx("gathering tlsa records failed", err, slog.Bool("danerequired", daneRequired), slog.Any("basedomain", tlsaBaseDomain))
299 return daneRequired, nil, tlsaBaseDomain, err
300 }
301 daneRequired = len(l) > 0
302 l = filterUsableTLSARecords(log, l)
303 log.Debug("tlsa records exist",
304 slog.Bool("danerequired", daneRequired),
305 slog.Any("records", l),
306 slog.Any("basedomain", tlsaBaseDomain))
307 return daneRequired, l, tlsaBaseDomain, err
308}
309
310// lookupTLSACNAME composes a TLSA domain name to lookup, follows CNAMEs and looks
311// up TLSA records. no TLSA records exist, a nil error is returned as it means
312// the host does not opt-in to DANE.
313func lookupTLSACNAME(ctx context.Context, log mlog.Log, resolver dns.Resolver, port int, protocol string, host dns.Domain) (l []adns.TLSA, rerr error) {
314 name := fmt.Sprintf("_%d._%s.%s", port, protocol, host.ASCII+".")
315 for i := 0; ; i++ {
316 cname, result, err := resolver.LookupCNAME(ctx, name)
317 if dns.IsNotFound(err) {
318 if !result.Authentic {
319 log.Debugx("cname nxdomain result during tlsa lookup not authentic, not doing dane for host", err, slog.Any("host", host), slog.String("name", name))
320 return nil, nil
321 }
322 break
323 } else if err != nil {
324 return nil, fmt.Errorf("looking up cname for tlsa candidate base domain: %w", err)
325 } else if !result.Authentic {
326 log.Debugx("cname result during tlsa lookup not authentic, not doing dane for host", err, slog.Any("host", host), slog.String("name", name))
327 return nil, nil
328 }
329 if i == 10 {
330 return nil, fmt.Errorf("looking up cname for tlsa candidate base domain: %w", errCNAMELimit)
331 }
332 name = strings.TrimSuffix(cname, ".") + "."
333 }
334 var result adns.Result
335 var err error
336 l, result, err = resolver.LookupTLSA(ctx, 0, "", name)
337 if dns.IsNotFound(err) || err == nil && len(l) == 0 {
338 log.Debugx("no tlsa records for host, not doing dane", err,
339 slog.Any("host", host),
340 slog.String("name", name),
341 slog.Bool("authentic", result.Authentic))
342 return nil, nil
343 } else if err != nil {
344 return nil, fmt.Errorf("looking up tlsa records for tlsa candidate base domain: %w", err)
345 } else if !result.Authentic {
346 log.Debugx("tlsa lookup not authentic, not doing dane for host", err, slog.Any("host", host), slog.String("name", name))
347 return nil, nil
348 }
349 return l, nil
350}
351
352func filterUsableTLSARecords(log mlog.Log, l []adns.TLSA) []adns.TLSA {
353 // Gather "usable" records. ../rfc/7672:708
354 o := 0
355 for _, r := range l {
356 // A record is not usable when we don't recognize parameters. ../rfc/6698:649
357
358 switch r.Usage {
359 case adns.TLSAUsageDANETA, adns.TLSAUsageDANEEE:
360 default:
361 // We can regard PKIX-TA and PKIX-EE as "unusable" with SMTP DANE. ../rfc/7672:1304
362 continue
363 }
364 switch r.Selector {
365 case adns.TLSASelectorCert, adns.TLSASelectorSPKI:
366 default:
367 continue
368 }
369 switch r.MatchType {
370 case adns.TLSAMatchTypeFull:
371 if r.Selector == adns.TLSASelectorCert {
372 if _, err := x509.ParseCertificate(r.CertAssoc); err != nil {
373 log.Debugx("parsing certificate in dane tlsa record, ignoring", err)
374 continue
375 }
376 } else if r.Selector == adns.TLSASelectorSPKI {
377 if _, err := x509.ParsePKIXPublicKey(r.CertAssoc); err != nil {
378 log.Debugx("parsing certificate in dane tlsa record, ignoring", err)
379 continue
380 }
381 }
382 case adns.TLSAMatchTypeSHA256:
383 if len(r.CertAssoc) != sha256.Size {
384 log.Debug("dane tlsa record with wrong data size for sha2-256", slog.Int("got", len(r.CertAssoc)), slog.Int("expect", sha256.Size))
385 continue
386 }
387 case adns.TLSAMatchTypeSHA512:
388 if len(r.CertAssoc) != sha512.Size {
389 log.Debug("dane tlsa record with wrong data size for sha2-512", slog.Int("got", len(r.CertAssoc)), slog.Int("expect", sha512.Size))
390 continue
391 }
392 default:
393 continue
394 }
395
396 l[o] = r
397 o++
398 }
399 return l[:o]
400}
401
402// GatherTLSANames returns the allowed names in TLS certificates for verification
403// with PKIX-* or DANE-TA. The first name should be used for SNI.
404//
405// If there was no MX record, the next-hop domain parameters (i.e. the original
406// email destination host, and its CNAME-expanded host, that has MX records) are
407// ignored and only the base domain parameters are taken into account.
408func GatherTLSANames(haveMX, expandedNextHopAuthentic, expandedTLSABaseDomainAuthentic bool, origNextHop, expandedNextHop, origTLSABaseDomain, expandedTLSABaseDomain dns.Domain) []dns.Domain {
409 // Gather the names to check against TLS certificate. ../rfc/7672:1318
410 if !haveMX {
411 // ../rfc/7672:1336
412 if !expandedTLSABaseDomainAuthentic || origTLSABaseDomain == expandedTLSABaseDomain {
413 return []dns.Domain{origTLSABaseDomain}
414 }
415 return []dns.Domain{expandedTLSABaseDomain, origTLSABaseDomain}
416 } else if expandedNextHopAuthentic {
417 // ../rfc/7672:1326
418 var l []dns.Domain
419 if expandedTLSABaseDomainAuthentic {
420 l = []dns.Domain{expandedTLSABaseDomain}
421 }
422 if expandedTLSABaseDomain != origTLSABaseDomain {
423 l = append(l, origTLSABaseDomain)
424 }
425 l = append(l, origNextHop)
426 if origNextHop != expandedNextHop {
427 l = append(l, expandedNextHop)
428 }
429 return l
430 } else {
431 // We don't attempt DANE after insecure MX, but behaviour for it is specified.
432 // ../rfc/7672:1332
433 return []dns.Domain{origNextHop}
434 }
435}
436