checker-email-keys/checker/dns.go

132 lines
3.8 KiB
Go

package checker
import (
"context"
"fmt"
"net"
"strings"
"time"
"github.com/miekg/dns"
)
// dnsTimeout is the per-query deadline used by every helper here.
const dnsTimeout = 5 * time.Second
// maxAnswerRecords caps how many answer RRs of the requested type are
// retained from a single DNS response. A DANE owner serving more than a
// handful of keys is already abnormal; bounding the count keeps later
// per-record work (parsing, comparison) from blowing up if a zone (or a
// hostile resolver) returns a pathological answer set.
const maxAnswerRecords = 64
// dnsLookupAnswer is the subset of a DNS answer this checker cares about.
type dnsLookupAnswer struct {
// Records are the answer records of the requested type.
Records []dns.RR
// AD reports whether the response header has the Authenticated Data
// flag set, i.e. the validating resolver confirmed DNSSEC.
AD bool
// Rcode is the response code from the answering resolver.
Rcode int
// Server is the address of the resolver that answered.
Server string
}
// resolvers returns the list of resolver addresses to try. If resolverOpt
// is non-empty it is parsed (comma-separated allowed) into a host:port
// list. Otherwise /etc/resolv.conf is read; if that fails we fall back to
// public validating resolvers.
func resolvers(resolverOpt string) []string {
if s := strings.TrimSpace(resolverOpt); s != "" {
var out []string
for part := range strings.SplitSeq(s, ",") {
part = strings.TrimSpace(part)
if part == "" {
continue
}
if !strings.Contains(part, ":") {
part = net.JoinHostPort(part, "53")
}
out = append(out, part)
}
if len(out) > 0 {
return out
}
}
if cfg, err := dns.ClientConfigFromFile("/etc/resolv.conf"); err == nil && cfg != nil && len(cfg.Servers) > 0 {
out := make([]string, 0, len(cfg.Servers))
for _, s := range cfg.Servers {
out = append(out, net.JoinHostPort(s, cfg.Port))
}
return out
}
// Fall back to known validating resolvers.
return []string{"1.1.1.1:53", "9.9.9.9:53", "8.8.8.8:53"}
}
// lookup queries qtype at owner against each resolver in order until one
// answers. The first resolver whose answer has a non-error Rcode wins.
// DNSSEC validation is requested via EDNS0 DO=1; the AD flag is read back
// from the response header.
func lookup(ctx context.Context, servers []string, owner string, qtype uint16) (*dnsLookupAnswer, error) {
m := new(dns.Msg)
m.SetQuestion(dns.Fqdn(owner), qtype)
m.SetEdns0(4096, true)
m.RecursionDesired = true
m.AuthenticatedData = true
c := &dns.Client{Timeout: dnsTimeout}
var lastErr error
for _, srv := range servers {
in, _, err := c.ExchangeContext(ctx, m, srv)
if err != nil {
lastErr = err
continue
}
if in == nil {
lastErr = fmt.Errorf("nil response from %s", srv)
continue
}
ans := &dnsLookupAnswer{
Rcode: in.Rcode,
AD: in.AuthenticatedData,
Server: srv,
}
for _, rr := range in.Answer {
if rr.Header().Rrtype != qtype {
continue
}
if len(ans.Records) >= maxAnswerRecords {
break
}
ans.Records = append(ans.Records, rr)
}
if in.Rcode == dns.RcodeSuccess || in.Rcode == dns.RcodeNameError {
return ans, nil
}
lastErr = fmt.Errorf("rcode %s from %s", dns.RcodeToString[in.Rcode], srv)
}
if lastErr == nil {
lastErr = fmt.Errorf("no resolver available")
}
return nil, lastErr
}
// joinSubdomain composes the FQDN of a subdomain within a zone. Both
// arguments are accepted in any of their canonical forms (trailing dot
// optional, empty subdomain allowed).
func joinSubdomain(subdomain, origin string) string {
origin = strings.TrimSuffix(origin, ".")
subdomain = strings.TrimSuffix(subdomain, ".")
if subdomain == "" || subdomain == "@" {
return dns.Fqdn(origin)
}
if strings.HasSuffix(subdomain, "."+origin) || subdomain == origin {
return dns.Fqdn(subdomain)
}
return dns.Fqdn(subdomain + "." + origin)
}