1// Package mtasts implements MTA-STS (SMTP MTA Strict Transport Security, RFC 8461)
2// which allows a domain to specify SMTP TLS requirements.
4// SMTP for message delivery to a remote mail server always starts out unencrypted,
5// in plain text. STARTTLS allows upgrading the connection to TLS, but is optional
6// and by default mail servers will fall back to plain text communication if
7// STARTTLS does not work (which can be sabotaged by DNS manipulation or SMTP
8// connection manipulation). MTA-STS can specify a policy for requiring STARTTLS to
9// be used for message delivery. A TXT DNS record at "_mta-sts.<domain>" specifies
10// the version of the policy, and
11// "https://mta-sts.<domain>/.well-known/mta-sts.txt" serves the policy.
24 "github.com/mjl-/adns"
26 "github.com/mjl-/mox/dns"
27 "github.com/mjl-/mox/mlog"
28 "github.com/mjl-/mox/moxio"
29 "github.com/mjl-/mox/stub"
33 MetricGet stub.HistogramVec = stub.HistogramVecIgnore{}
34 HTTPClientObserve func(ctx context.Context, log *slog.Logger, pkg, method string, statusCode int, err error, start time.Time) = stub.HTTPClientObserveIgnore
37// Pair is an extension key/value pair in a MTA-STS DNS record or policy.
43// Record is an MTA-STS DNS record, served under "_mta-sts.<domain>" as a TXT
48// v=STSv1; id=20160831085700Z
50 Version string // "STSv1", for "v=". Required.
51 ID string // Record version, for "id=". Required.
52 Extensions []Pair // Optional extensions.
55// String returns a textual version of the MTA-STS record for use as DNS TXT
57func (r Record) String() string {
58 b := &strings.Builder{}
59 fmt.Fprint(b, "v="+r.Version)
60 fmt.Fprint(b, "; id="+r.ID)
61 for _, p := range r.Extensions {
62 fmt.Fprint(b, "; "+p.Key+"="+p.Value)
67// Mode indicates how the policy should be interpreted.
73 ModeEnforce Mode = "enforce" // Policy must be followed, i.e. deliveries must fail if a TLS connection cannot be made.
74 ModeTesting Mode = "testing" // In case TLS cannot be negotiated, plain SMTP can be used, but failures must be reported, e.g. with TLSRPT.
75 ModeNone Mode = "none" // In case MTA-STS is not or no longer implemented.
78// MX is an allowlisted MX host name/pattern.
80 // "*." wildcard, e.g. if a subdomain matches. A wildcard must match exactly one
81 // label. *.example.com matches mail.example.com, but not example.com, and not
82 // foor.bar.example.com.
88// LogString returns a loggable string representing the host, with both unicode
89// and ascii version for IDNA domains.
90func (s MX) LogString() string {
95 if s.Domain.Unicode == "" {
96 return pre + s.Domain.ASCII
98 return pre + s.Domain.Unicode + "/" + pre + s.Domain.ASCII
101// Policy is an MTA-STS policy as served at "https://mta-sts.<domain>/.well-known/mta-sts.txt".
103 Version string // "STSv1"
106 MaxAgeSeconds int // How long this policy can be cached. Suggested values are in weeks or more.
110// String returns a textual representation for serving at the well-known URL.
111func (p Policy) String() string {
112 b := &strings.Builder{}
113 line := func(k, v string) {
114 fmt.Fprint(b, k+": "+v+"\n")
116 line("version", p.Version)
117 line("mode", string(p.Mode))
118 line("max_age", fmt.Sprintf("%d", p.MaxAgeSeconds))
119 for _, mx := range p.MX {
120 s := mx.Domain.Name()
129// Matches returns whether the hostname matches the mx list in the policy.
130func (p *Policy) Matches(host dns.Domain) bool {
132 for _, mx := range p.MX {
134 v := strings.SplitN(host.ASCII, ".", 2)
135 if len(v) == 2 && v[1] == mx.Domain.ASCII {
138 } else if host == mx.Domain {
145// TLSReportFailureReason returns a concise error for known error types, or an
146// empty string. For use in TLSRPT.
147func TLSReportFailureReason(err error) string {
148 // If this is a DNSSEC authentication error, we'll collect it for TLS reporting.
150 var errCode adns.ErrorCode
151 if errors.As(err, &errCode) && errCode.IsAuthentication() {
152 return fmt.Sprintf("dns-extended-error-%d-%s", errCode, strings.ReplaceAll(errCode.String(), " ", "-"))
155 for _, e := range mtastsErrors {
156 if errors.Is(err, e) {
157 s := strings.TrimPrefix(e.Error(), "mtasts: ")
158 return strings.ReplaceAll(s, " ", "-")
164var mtastsErrors = []error{
165 ErrNoRecord, ErrMultipleRecords, ErrDNS, ErrRecordSyntax, // Lookup
166 ErrNoPolicy, ErrPolicyFetch, ErrPolicySyntax, // Fetch
171 ErrNoRecord = errors.New("mtasts: no mta-sts dns txt record") // Domain does not implement MTA-STS. If a cached non-expired policy is available, it should still be used.
172 ErrMultipleRecords = errors.New("mtasts: multiple mta-sts records") // Should be treated as if domain does not implement MTA-STS, unless a cached non-expired policy is available.
173 ErrDNS = errors.New("mtasts: dns lookup") // For temporary DNS errors.
174 ErrRecordSyntax = errors.New("mtasts: record syntax error")
177// LookupRecord looks up the MTA-STS TXT DNS record at "_mta-sts.<domain>",
178// following CNAME records, and returns the parsed MTA-STS record and the DNS TXT
180func LookupRecord(ctx context.Context, elog *slog.Logger, resolver dns.Resolver, domain dns.Domain) (rrecord *Record, rtxt string, rerr error) {
181 log := mlog.New("mtasts", elog)
184 log.Debugx("mtasts lookup result", rerr,
185 slog.Any("domain", domain),
186 slog.Any("record", rrecord),
187 slog.Duration("duration", time.Since(start)))
192 // We lookup the txt record, but must follow CNAME records when the TXT does not
193 // exist. LookupTXT follows CNAMEs.
194 name := "_mta-sts." + domain.ASCII + "."
196 txts, _, err := dns.WithPackage(resolver, "mtasts").LookupTXT(ctx, name)
197 if dns.IsNotFound(err) {
198 return nil, "", ErrNoRecord
199 } else if err != nil {
200 return nil, "", fmt.Errorf("%w: %s", ErrDNS, err)
205 for _, txt := range txts {
206 r, ismtasts, err := ParseRecord(txt)
209 // "v=STSv1 ;" (note the space) as a non-STS record too in case of multiple TXT
210 // records. We treat it as an STS record that is invalid, which is possibly more
218 return nil, "", ErrMultipleRecords
224 return nil, "", ErrNoRecord
226 return record, text, nil
229// Policy fetch errors.
231 ErrNoPolicy = errors.New("mtasts: no policy served") // If the name "mta-sts.<domain>" does not exist in DNS or if webserver returns HTTP status 404 "File not found".
232 ErrPolicyFetch = errors.New("mtasts: cannot fetch policy") // E.g. for HTTP request errors.
233 ErrPolicySyntax = errors.New("mtasts: policy syntax error")
236// HTTPClient is used by FetchPolicy for HTTP requests.
237var HTTPClient = &http.Client{
238 CheckRedirect: func(req *http.Request, via []*http.Request) error {
243// FetchPolicy fetches a new policy for the domain, at
244// https://mta-sts.<domain>/.well-known/mta-sts.txt.
246// FetchPolicy returns the parsed policy and the literal policy text as fetched
247// from the server. If a policy was fetched but could not be parsed, the policyText
248// return value will be set.
250// Policies longer than 64KB result in a syntax error.
252// If an error is returned, callers should back off for 5 minutes until the next
254func FetchPolicy(ctx context.Context, elog *slog.Logger, domain dns.Domain) (policy *Policy, policyText string, rerr error) {
255 log := mlog.New("mtasts", elog)
258 log.Debugx("mtasts fetch policy result", rerr,
259 slog.Any("domain", domain),
260 slog.Any("policy", policy),
261 slog.String("policytext", policyText),
262 slog.Duration("duration", time.Since(start)))
266 ctx, cancel := context.WithTimeout(ctx, time.Minute)
269 // TLS requirements are what the Go standard library checks: trusted, non-expired,
271 url := "https://mta-sts." + domain.Name() + "/.well-known/mta-sts.txt"
272 req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
274 return nil, "", fmt.Errorf("%w: http request: %s", ErrPolicyFetch, err)
276 // We are not likely to reuse a connection: we cache policies and negative DNS
277 // responses. So don't keep connections open unnecessarily.
280 resp, err := HTTPClient.Do(req)
281 if dns.IsNotFound(err) {
282 return nil, "", ErrNoPolicy
285 // We pass along underlying TLS certificate errors.
286 return nil, "", fmt.Errorf("%w: http get: %w", ErrPolicyFetch, err)
288 HTTPClientObserve(ctx, log.Logger, "mtasts", req.Method, resp.StatusCode, err, start)
289 defer resp.Body.Close()
290 if resp.StatusCode == http.StatusNotFound {
291 return nil, "", ErrNoPolicy
293 if resp.StatusCode != http.StatusOK {
295 return nil, "", fmt.Errorf("%w: http status %s while status 200 is required", ErrPolicyFetch, resp.Status)
298 // We don't look at Content-Type and charset. It should be ASCII or UTF-8, we'll
302 buf, err := io.ReadAll(&moxio.LimitReader{R: resp.Body, Limit: 64 * 1024})
304 return nil, "", fmt.Errorf("%w: reading policy: %s", ErrPolicySyntax, err)
306 policyText = string(buf)
307 policy, err = ParsePolicy(policyText)
309 return nil, policyText, fmt.Errorf("parsing policy: %w", err)
311 return policy, policyText, nil
314// Get looks up the MTA-STS DNS record and fetches the policy.
316// Errors can be those returned by LookupRecord and FetchPolicy.
318// If a valid policy cannot be retrieved, a sender must treat the domain as not
319// implementing MTA-STS. If a sender has a non-expired cached policy, that policy
322// If a record was retrieved, but a policy could not be retrieved/parsed, the
323// record is still returned.
325// Also see Get in package mtastsdb.
326func Get(ctx context.Context, elog *slog.Logger, resolver dns.Resolver, domain dns.Domain) (record *Record, policy *Policy, policyText string, err error) {
327 log := mlog.New("mtasts", elog)
329 result := "lookuperror"
331 MetricGet.ObserveLabels(float64(time.Since(start))/float64(time.Second), result)
332 log.Debugx("mtasts get result", err,
333 slog.Any("domain", domain),
334 slog.Any("record", record),
335 slog.Any("policy", policy),
336 slog.Duration("duration", time.Since(start)))
339 record, _, err = LookupRecord(ctx, log.Logger, resolver, domain)
341 return nil, nil, "", err
344 result = "fetcherror"
345 policy, policyText, err = FetchPolicy(ctx, log.Logger, domain)
347 return record, nil, "", err
351 return record, policy, policyText, nil