2024-01-10 16:19:20 +00:00
|
|
|
// Copyright (c) HashiCorp, Inc.
|
|
|
|
// SPDX-License-Identifier: BUSL-1.1
|
|
|
|
|
|
|
|
package dns
|
|
|
|
|
|
|
|
import (
|
2024-01-17 03:36:02 +00:00
|
|
|
"errors"
|
2024-01-10 16:19:20 +00:00
|
|
|
"fmt"
|
|
|
|
"net"
|
2024-01-29 22:33:45 +00:00
|
|
|
"regexp"
|
|
|
|
"strings"
|
2024-01-10 16:19:20 +00:00
|
|
|
"sync/atomic"
|
|
|
|
"time"
|
|
|
|
|
2024-02-13 17:08:01 +00:00
|
|
|
"github.com/armon/go-metrics"
|
2024-01-10 16:19:20 +00:00
|
|
|
"github.com/armon/go-radix"
|
2024-02-02 23:29:38 +00:00
|
|
|
"github.com/hashicorp/go-hclog"
|
2024-04-22 18:30:43 +00:00
|
|
|
"github.com/miekg/dns"
|
2024-02-02 23:29:38 +00:00
|
|
|
|
2024-01-10 16:19:20 +00:00
|
|
|
"github.com/hashicorp/consul/agent/config"
|
|
|
|
"github.com/hashicorp/consul/agent/discovery"
|
|
|
|
"github.com/hashicorp/consul/agent/structs"
|
2024-01-29 16:40:10 +00:00
|
|
|
"github.com/hashicorp/consul/internal/dnsutil"
|
2024-01-17 03:36:02 +00:00
|
|
|
"github.com/hashicorp/consul/logging"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
addrLabel = "addr"
|
|
|
|
|
2024-01-29 16:40:10 +00:00
|
|
|
arpaDomain = "arpa."
|
|
|
|
arpaLabel = "arpa"
|
2024-01-17 03:36:02 +00:00
|
|
|
|
2024-01-29 22:33:45 +00:00
|
|
|
suffixFailover = "failover."
|
|
|
|
suffixNoFailover = "no-failover."
|
|
|
|
maxRecursionLevelDefault = 3 // This field comes from the V1 DNS server and affects V1 catalog lookups
|
|
|
|
maxRecurseRecords = 5
|
2024-01-17 03:36:02 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
errInvalidQuestion = fmt.Errorf("invalid question")
|
2024-01-18 23:30:04 +00:00
|
|
|
errNameNotFound = fmt.Errorf("name not found")
|
2024-02-02 23:29:38 +00:00
|
|
|
errNotImplemented = fmt.Errorf("not implemented")
|
2024-01-18 23:30:04 +00:00
|
|
|
errRecursionFailed = fmt.Errorf("recursion failed")
|
2024-01-29 22:33:45 +00:00
|
|
|
|
|
|
|
trailingSpacesRE = regexp.MustCompile(" +$")
|
2024-01-10 16:19:20 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// RouterDynamicConfig is the dynamic configuration that can be hot-reloaded
|
|
|
|
type RouterDynamicConfig struct {
|
2024-02-14 22:38:11 +00:00
|
|
|
ARecordLimit int
|
|
|
|
DisableCompression bool
|
|
|
|
EnableTruncate bool
|
|
|
|
NodeMetaTXT bool
|
|
|
|
NodeTTL time.Duration
|
|
|
|
Recursors []string
|
|
|
|
RecursorTimeout time.Duration
|
|
|
|
RecursorStrategy structs.RecursorStrategy
|
|
|
|
SOAConfig SOAConfig
|
2024-01-10 16:19:20 +00:00
|
|
|
// TTLRadix sets service TTLs by prefix, eg: "database-*"
|
|
|
|
TTLRadix *radix.Tree
|
|
|
|
// TTLStrict sets TTLs to service by full name match. It Has higher priority than TTLRadix
|
|
|
|
TTLStrict map[string]time.Duration
|
|
|
|
UDPAnswerLimit int
|
|
|
|
}
|
|
|
|
|
2024-03-01 15:36:37 +00:00
|
|
|
// GetTTLForService Find the TTL for a given service.
|
|
|
|
// return ttl, true if found, 0, false otherwise
|
|
|
|
func (cfg *RouterDynamicConfig) GetTTLForService(service string) (time.Duration, bool) {
|
|
|
|
if cfg.TTLStrict != nil {
|
|
|
|
ttl, ok := cfg.TTLStrict[service]
|
|
|
|
if ok {
|
|
|
|
return ttl, true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if cfg.TTLRadix != nil {
|
|
|
|
_, ttlRaw, ok := cfg.TTLRadix.LongestPrefix(service)
|
|
|
|
if ok {
|
|
|
|
return ttlRaw.(time.Duration), true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return 0, false
|
|
|
|
}
|
|
|
|
|
2024-01-10 16:19:20 +00:00
|
|
|
type SOAConfig struct {
|
|
|
|
Refresh uint32 // 3600 by default
|
|
|
|
Retry uint32 // 600
|
|
|
|
Expire uint32 // 86400
|
|
|
|
Minttl uint32 // 0
|
|
|
|
}
|
|
|
|
|
|
|
|
// DiscoveryQueryProcessor is an interface that can be used by any consumer requesting Service Discovery results.
|
|
|
|
// This could be attached to a gRPC endpoint in the future in addition to DNS.
|
|
|
|
// Making this an interface means testing the router with a mock is trivial.
|
|
|
|
type DiscoveryQueryProcessor interface {
|
|
|
|
QueryByName(*discovery.Query, discovery.Context) ([]*discovery.Result, error)
|
|
|
|
QueryByIP(net.IP, discovery.Context) ([]*discovery.Result, error)
|
|
|
|
}
|
|
|
|
|
2024-01-18 23:30:04 +00:00
|
|
|
// dnsRecursor is an interface that can be used to mock calls to external DNS servers for unit testing.
|
|
|
|
//
|
|
|
|
//go:generate mockery --name dnsRecursor --inpackage
|
|
|
|
type dnsRecursor interface {
|
2024-02-03 03:23:52 +00:00
|
|
|
handle(req *dns.Msg, cfgCtx *RouterDynamicConfig, remoteAddress net.Addr) (*dns.Msg, error)
|
2024-01-18 23:30:04 +00:00
|
|
|
}
|
|
|
|
|
2024-01-10 16:19:20 +00:00
|
|
|
// Router replaces miekg/dns.ServeMux with a simpler router that only checks for the 2-3 valid domains
|
|
|
|
// that Consul supports and forwards to a single DiscoveryQueryProcessor handler. If there is no match, it will recurse.
|
|
|
|
type Router struct {
|
2024-04-22 18:30:43 +00:00
|
|
|
processor DiscoveryQueryProcessor
|
|
|
|
recursor dnsRecursor
|
|
|
|
domain string
|
|
|
|
altDomain string
|
|
|
|
nodeName string
|
|
|
|
logger hclog.Logger
|
2024-01-10 16:19:20 +00:00
|
|
|
|
2024-02-12 19:27:25 +00:00
|
|
|
tokenFunc func() string
|
|
|
|
translateAddressFunc func(dc string, addr string, taggedAddresses map[string]string, accept dnsutil.TranslateAddressAccept) string
|
|
|
|
translateServiceAddressFunc func(dc string, address string, taggedAddresses map[string]structs.ServiceAddress, accept dnsutil.TranslateAddressAccept) string
|
2024-01-10 16:19:20 +00:00
|
|
|
|
|
|
|
// dynamicConfig stores the config as an atomic value (for hot-reloading).
|
|
|
|
// It is always of type *RouterDynamicConfig
|
|
|
|
dynamicConfig atomic.Value
|
|
|
|
}
|
|
|
|
|
|
|
|
var _ = dns.Handler(&Router{})
|
2024-01-22 15:10:03 +00:00
|
|
|
var _ = DNSRouter(&Router{})
|
2024-01-10 16:19:20 +00:00
|
|
|
|
|
|
|
func NewRouter(cfg Config) (*Router, error) {
|
2024-01-17 03:36:02 +00:00
|
|
|
// Make sure domains are FQDN, make them case-insensitive for DNSRequestRouter
|
|
|
|
domain := dns.CanonicalName(cfg.AgentConfig.DNSDomain)
|
|
|
|
altDomain := dns.CanonicalName(cfg.AgentConfig.DNSAltDomain)
|
|
|
|
|
2024-01-18 23:30:04 +00:00
|
|
|
logger := cfg.Logger.Named(logging.DNS)
|
|
|
|
|
2024-01-10 16:19:20 +00:00
|
|
|
router := &Router{
|
2024-02-12 19:27:25 +00:00
|
|
|
processor: cfg.Processor,
|
|
|
|
recursor: newRecursor(logger),
|
|
|
|
domain: domain,
|
|
|
|
altDomain: altDomain,
|
|
|
|
logger: logger,
|
2024-02-13 17:08:01 +00:00
|
|
|
nodeName: cfg.AgentConfig.NodeName,
|
2024-02-12 19:27:25 +00:00
|
|
|
tokenFunc: cfg.TokenFunc,
|
|
|
|
translateAddressFunc: cfg.TranslateAddressFunc,
|
|
|
|
translateServiceAddressFunc: cfg.TranslateServiceAddressFunc,
|
2024-01-10 16:19:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if err := router.ReloadConfig(cfg.AgentConfig); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return router, nil
|
|
|
|
}
|
|
|
|
|
2024-01-17 23:46:18 +00:00
|
|
|
// HandleRequest is used to process an individual DNS request. It returns a message in success or fail cases.
|
2024-02-02 23:29:38 +00:00
|
|
|
func (r *Router) HandleRequest(req *dns.Msg, reqCtx Context, remoteAddress net.Addr) *dns.Msg {
|
2024-02-13 17:08:01 +00:00
|
|
|
configCtx := r.dynamicConfig.Load().(*RouterDynamicConfig)
|
|
|
|
|
2024-03-01 15:36:37 +00:00
|
|
|
respGenerator := dnsResponseGenerator{}
|
2024-02-13 17:08:01 +00:00
|
|
|
|
|
|
|
err := validateAndNormalizeRequest(req)
|
|
|
|
if err != nil {
|
|
|
|
r.logger.Error("error parsing DNS query", "error", err)
|
|
|
|
if errors.Is(err, errInvalidQuestion) {
|
2024-03-01 15:36:37 +00:00
|
|
|
return respGenerator.createRefusedResponse(req)
|
2024-02-13 17:08:01 +00:00
|
|
|
}
|
2024-03-01 15:36:37 +00:00
|
|
|
return respGenerator.createServerFailureResponse(req, configCtx, false)
|
2024-02-13 17:08:01 +00:00
|
|
|
}
|
|
|
|
|
2024-03-01 15:36:37 +00:00
|
|
|
r.logger.Trace("received request", "question", req.Question[0].Name, "type", dns.Type(req.Question[0].Qtype).String())
|
2024-04-22 18:30:43 +00:00
|
|
|
r.normalizeContext(&reqCtx)
|
2024-03-01 15:36:37 +00:00
|
|
|
|
2024-02-13 17:08:01 +00:00
|
|
|
defer func(s time.Time, q dns.Question) {
|
|
|
|
metrics.MeasureSinceWithLabels([]string{"dns", "query"}, s,
|
|
|
|
[]metrics.Label{
|
|
|
|
{Name: "node", Value: r.nodeName},
|
|
|
|
{Name: "type", Value: dns.Type(q.Qtype).String()},
|
|
|
|
})
|
|
|
|
|
2024-02-14 17:40:38 +00:00
|
|
|
r.logger.Trace("request served from client",
|
2024-02-13 17:08:01 +00:00
|
|
|
"name", q.Name,
|
|
|
|
"type", dns.Type(q.Qtype).String(),
|
|
|
|
"class", dns.Class(q.Qclass).String(),
|
|
|
|
"latency", time.Since(s).String(),
|
|
|
|
"client", remoteAddress.String(),
|
|
|
|
"client_network", remoteAddress.Network(),
|
|
|
|
)
|
|
|
|
}(time.Now(), req.Question[0])
|
|
|
|
|
|
|
|
return r.handleRequestRecursively(req, reqCtx, configCtx, remoteAddress, maxRecursionLevelDefault)
|
2024-01-29 22:33:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// handleRequestRecursively is used to process an individual DNS request. It will recurse as needed
|
|
|
|
// a maximum number of times and returns a message in success or fail cases.
|
2024-02-13 17:08:01 +00:00
|
|
|
func (r *Router) handleRequestRecursively(req *dns.Msg, reqCtx Context, configCtx *RouterDynamicConfig,
|
2024-01-29 22:33:45 +00:00
|
|
|
remoteAddress net.Addr, maxRecursionLevel int) *dns.Msg {
|
2024-03-01 15:36:37 +00:00
|
|
|
respGenerator := dnsResponseGenerator{}
|
2024-01-10 16:19:20 +00:00
|
|
|
|
2024-02-13 17:08:01 +00:00
|
|
|
r.logger.Trace(
|
|
|
|
"received request",
|
|
|
|
"question", req.Question[0].Name,
|
|
|
|
"type", dns.Type(req.Question[0].Qtype).String(),
|
|
|
|
"recursion_remaining", maxRecursionLevel)
|
2024-01-10 16:19:20 +00:00
|
|
|
|
2024-02-03 03:23:52 +00:00
|
|
|
responseDomain, needRecurse := r.parseDomain(req.Question[0].Name)
|
2024-01-18 23:30:04 +00:00
|
|
|
if needRecurse && !canRecurse(configCtx) {
|
2024-01-24 20:32:42 +00:00
|
|
|
// This is the same error as an unmatched domain
|
2024-03-01 15:36:37 +00:00
|
|
|
return respGenerator.createRefusedResponse(req)
|
2024-01-18 23:30:04 +00:00
|
|
|
}
|
2024-01-10 16:19:20 +00:00
|
|
|
|
2024-01-18 23:30:04 +00:00
|
|
|
if needRecurse {
|
2024-02-09 22:41:40 +00:00
|
|
|
r.logger.Trace("checking recursors to handle request", "question", req.Question[0].Name, "type", dns.Type(req.Question[0].Qtype).String())
|
|
|
|
|
2024-01-18 23:30:04 +00:00
|
|
|
// This assumes `canRecurse(configCtx)` is true above
|
|
|
|
resp, err := r.recursor.handle(req, configCtx, remoteAddress)
|
|
|
|
if err != nil && !errors.Is(err, errRecursionFailed) {
|
|
|
|
r.logger.Error("unhandled error recursing DNS query", "error", err)
|
|
|
|
}
|
|
|
|
if err != nil {
|
2024-03-01 15:36:37 +00:00
|
|
|
return respGenerator.createServerFailureResponse(req, configCtx, true)
|
2024-01-18 23:30:04 +00:00
|
|
|
}
|
|
|
|
return resp
|
2024-01-17 03:36:02 +00:00
|
|
|
}
|
2024-01-10 16:19:20 +00:00
|
|
|
|
2024-01-30 22:34:35 +00:00
|
|
|
// Need to pass the question name to properly support recursion and the
|
|
|
|
// trimming of the domain suffixes.
|
|
|
|
qName := dns.CanonicalName(req.Question[0].Name)
|
|
|
|
if maxRecursionLevel < maxRecursionLevelDefault {
|
|
|
|
// Get the QName without the domain suffix
|
|
|
|
qName = r.trimDomain(qName)
|
|
|
|
}
|
|
|
|
|
2024-03-01 15:36:37 +00:00
|
|
|
results, query, err := discoveryResultsFetcher{}.getQueryResults(&getQueryOptions{
|
|
|
|
req: req,
|
|
|
|
reqCtx: reqCtx,
|
|
|
|
qName: qName,
|
|
|
|
remoteAddress: remoteAddress,
|
|
|
|
processor: r.processor,
|
|
|
|
logger: r.logger,
|
|
|
|
domain: r.domain,
|
|
|
|
altDomain: r.altDomain,
|
|
|
|
})
|
2024-02-02 23:29:38 +00:00
|
|
|
|
2024-02-09 02:56:04 +00:00
|
|
|
// in case of the wrapped ECSNotGlobalError, extract the error from it.
|
2024-02-08 04:24:00 +00:00
|
|
|
isECSGlobal := !errors.Is(err, discovery.ErrECSNotGlobal)
|
|
|
|
err = getErrorFromECSNotGlobalError(err)
|
|
|
|
if err != nil {
|
2024-03-01 15:36:37 +00:00
|
|
|
return respGenerator.generateResponseFromError(&generateResponseFromErrorOpts{
|
|
|
|
req: req,
|
|
|
|
err: err,
|
|
|
|
qName: qName,
|
|
|
|
configCtx: configCtx,
|
|
|
|
responseDomain: responseDomain,
|
|
|
|
isECSGlobal: isECSGlobal,
|
|
|
|
query: query,
|
|
|
|
canRecurse: canRecurse(configCtx),
|
|
|
|
logger: r.logger,
|
|
|
|
})
|
2024-01-17 03:36:02 +00:00
|
|
|
}
|
2024-01-10 16:19:20 +00:00
|
|
|
|
2024-02-09 22:41:40 +00:00
|
|
|
r.logger.Trace("serializing results", "question", req.Question[0].Name, "results-found", len(results))
|
|
|
|
|
2024-01-17 03:36:02 +00:00
|
|
|
// This needs the question information because it affects the serialization format.
|
|
|
|
// e.g., the Consul service has the same "results" for both NS and A/AAAA queries, but the serialization differs.
|
2024-03-01 15:36:37 +00:00
|
|
|
serializedOpts := &serializeOptions{
|
|
|
|
req: req,
|
|
|
|
reqCtx: reqCtx,
|
|
|
|
query: query,
|
|
|
|
results: results,
|
|
|
|
cfg: configCtx,
|
|
|
|
responseDomain: responseDomain,
|
|
|
|
remoteAddress: remoteAddress,
|
|
|
|
maxRecursionLevel: maxRecursionLevel,
|
|
|
|
translateAddressFunc: r.translateAddressFunc,
|
|
|
|
translateServiceAddressFunc: r.translateServiceAddressFunc,
|
|
|
|
resolveCnameFunc: r.resolveCNAME,
|
|
|
|
}
|
|
|
|
resp, err := messageSerializer{}.serialize(serializedOpts)
|
2024-01-17 03:36:02 +00:00
|
|
|
if err != nil {
|
|
|
|
r.logger.Error("error serializing DNS results", "error", err)
|
2024-03-01 15:36:37 +00:00
|
|
|
return respGenerator.generateResponseFromError(&generateResponseFromErrorOpts{
|
|
|
|
req: req,
|
|
|
|
err: err,
|
|
|
|
qName: qName,
|
|
|
|
configCtx: configCtx,
|
|
|
|
responseDomain: responseDomain,
|
|
|
|
isECSGlobal: isECSGlobal,
|
|
|
|
query: query,
|
|
|
|
canRecurse: false,
|
|
|
|
logger: r.logger,
|
|
|
|
})
|
2024-02-08 04:24:00 +00:00
|
|
|
}
|
|
|
|
|
2024-03-01 15:36:37 +00:00
|
|
|
respGenerator.trimDNSResponse(configCtx, remoteAddress, req, resp, r.logger)
|
|
|
|
respGenerator.setEDNS(req, resp, isECSGlobal)
|
2024-01-17 03:36:02 +00:00
|
|
|
return resp
|
2024-01-10 16:19:20 +00:00
|
|
|
}
|
|
|
|
|
2024-01-30 22:34:35 +00:00
|
|
|
// trimDomain trims the domain from the question name.
|
|
|
|
func (r *Router) trimDomain(questionName string) string {
|
|
|
|
longer := r.domain
|
|
|
|
shorter := r.altDomain
|
|
|
|
|
|
|
|
if len(shorter) > len(longer) {
|
|
|
|
longer, shorter = shorter, longer
|
|
|
|
}
|
|
|
|
|
|
|
|
if strings.HasSuffix(questionName, "."+strings.TrimLeft(longer, ".")) {
|
|
|
|
return strings.TrimSuffix(questionName, longer)
|
|
|
|
}
|
|
|
|
return strings.TrimSuffix(questionName, shorter)
|
|
|
|
}
|
|
|
|
|
2024-01-17 03:36:02 +00:00
|
|
|
// ServeDNS implements the miekg/dns.Handler interface.
|
2024-04-22 18:30:43 +00:00
|
|
|
// This is a standard DNS listener.
|
2024-01-17 03:36:02 +00:00
|
|
|
func (r *Router) ServeDNS(w dns.ResponseWriter, req *dns.Msg) {
|
2024-04-22 18:30:43 +00:00
|
|
|
out := r.HandleRequest(req, Context{}, w.RemoteAddr())
|
2024-01-10 16:19:20 +00:00
|
|
|
w.WriteMsg(out)
|
|
|
|
}
|
|
|
|
|
|
|
|
// ReloadConfig hot-reloads the router config with new parameters
|
2024-01-17 03:36:02 +00:00
|
|
|
func (r *Router) ReloadConfig(newCfg *config.RuntimeConfig) error {
|
|
|
|
cfg, err := getDynamicRouterConfig(newCfg)
|
2024-01-10 16:19:20 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("error loading DNS config: %w", err)
|
|
|
|
}
|
|
|
|
r.dynamicConfig.Store(cfg)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-03-01 15:36:37 +00:00
|
|
|
// resolveCNAME is used to recursively resolve CNAME records
|
|
|
|
func (r *Router) resolveCNAME(cfgContext *RouterDynamicConfig, name string, reqCtx Context,
|
|
|
|
remoteAddress net.Addr, maxRecursionLevel int) []dns.RR {
|
|
|
|
// If the CNAME record points to a Consul address, resolve it internally
|
|
|
|
// Convert query to lowercase because DNS is case-insensitive; r.domain and
|
|
|
|
// r.altDomain are already converted
|
2024-03-01 12:42:42 +00:00
|
|
|
|
2024-03-01 15:36:37 +00:00
|
|
|
if ln := strings.ToLower(name); strings.HasSuffix(ln, "."+r.domain) || strings.HasSuffix(ln, "."+r.altDomain) {
|
|
|
|
if maxRecursionLevel < 1 {
|
|
|
|
r.logger.Error("Infinite recursion detected for name, won't perform any CNAME resolution.", "name", name)
|
|
|
|
return nil
|
2024-02-02 23:29:38 +00:00
|
|
|
}
|
2024-03-01 15:36:37 +00:00
|
|
|
req := &dns.Msg{}
|
|
|
|
|
|
|
|
req.SetQuestion(name, dns.TypeANY)
|
|
|
|
// TODO: handle error response (this is a comment from the V1 DNS Server)
|
|
|
|
resp := r.handleRequestRecursively(req, reqCtx, cfgContext, nil, maxRecursionLevel-1)
|
|
|
|
|
|
|
|
return resp.Answer
|
2024-02-02 23:29:38 +00:00
|
|
|
}
|
2024-03-01 15:36:37 +00:00
|
|
|
|
|
|
|
// Do nothing if we don't have a recursor
|
|
|
|
if !canRecurse(cfgContext) {
|
|
|
|
return nil
|
2024-02-02 23:29:38 +00:00
|
|
|
}
|
2024-03-01 15:36:37 +00:00
|
|
|
|
|
|
|
// Ask for any A records
|
|
|
|
m := new(dns.Msg)
|
|
|
|
m.SetQuestion(name, dns.TypeA)
|
|
|
|
|
|
|
|
// Make a DNS lookup request
|
|
|
|
recursorResponse, err := r.recursor.handle(m, cfgContext, remoteAddress)
|
|
|
|
if err == nil {
|
|
|
|
return recursorResponse.Answer
|
|
|
|
}
|
|
|
|
|
|
|
|
r.logger.Error("all resolvers failed for name", "name", name)
|
|
|
|
return nil
|
2024-02-02 23:29:38 +00:00
|
|
|
}
|
|
|
|
|
2024-01-17 03:36:02 +00:00
|
|
|
// Request type is similar to miekg/dns.Type, but correlates to the different query processors we might need to invoke.
|
|
|
|
type requestType string
|
|
|
|
|
|
|
|
const (
|
2024-01-24 20:32:42 +00:00
|
|
|
requestTypeName requestType = "NAME" // A/AAAA/CNAME/SRV
|
|
|
|
requestTypeIP requestType = "IP" // PTR
|
|
|
|
requestTypeAddress requestType = "ADDR" // Custom addr. A/AAAA lookups
|
|
|
|
requestTypeConsul requestType = "CONSUL" // SOA/NS
|
2024-01-17 03:36:02 +00:00
|
|
|
)
|
|
|
|
|
2024-01-24 20:32:42 +00:00
|
|
|
// parseDomain converts a DNS message into a generic discovery request.
|
2024-01-17 03:36:02 +00:00
|
|
|
// If the request domain does not match "consul." or the alternative domain,
|
|
|
|
// it will return true for needRecurse. The logic is based on miekg/dns.ServeDNS matcher.
|
|
|
|
// The implementation assumes that the only valid domains are "consul." and the alternative domain, and
|
|
|
|
// that DS query types are not supported.
|
2024-02-03 03:23:52 +00:00
|
|
|
func (r *Router) parseDomain(questionName string) (string, bool) {
|
|
|
|
target := dns.CanonicalName(questionName)
|
2024-03-01 15:36:37 +00:00
|
|
|
target, _ = stripAnyFailoverSuffix(target)
|
2024-01-17 03:36:02 +00:00
|
|
|
|
|
|
|
for offset, overflow := 0, false; !overflow; offset, overflow = dns.NextLabel(target, offset) {
|
|
|
|
subdomain := target[offset:]
|
|
|
|
switch subdomain {
|
2024-01-24 20:32:42 +00:00
|
|
|
case ".":
|
|
|
|
// We don't support consul having a domain or altdomain attached to the root.
|
|
|
|
return "", true
|
2024-01-17 03:36:02 +00:00
|
|
|
case r.domain:
|
2024-01-24 20:32:42 +00:00
|
|
|
return r.domain, false
|
2024-01-17 03:36:02 +00:00
|
|
|
case r.altDomain:
|
2024-01-24 20:32:42 +00:00
|
|
|
return r.altDomain, false
|
2024-01-17 03:36:02 +00:00
|
|
|
case arpaDomain:
|
|
|
|
// PTR queries always respond with the primary domain.
|
2024-01-24 20:32:42 +00:00
|
|
|
return r.domain, false
|
2024-01-17 03:36:02 +00:00
|
|
|
// Default: fallthrough
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// No match found; recurse if possible
|
2024-01-24 20:32:42 +00:00
|
|
|
return "", true
|
|
|
|
}
|
|
|
|
|
2024-03-01 15:36:37 +00:00
|
|
|
// GetConfig returns the current router config
|
|
|
|
func (r *Router) GetConfig() *RouterDynamicConfig {
|
|
|
|
return r.dynamicConfig.Load().(*RouterDynamicConfig)
|
|
|
|
}
|
|
|
|
|
|
|
|
// getErrorFromECSNotGlobalError returns the underlying error from an ECSNotGlobalError, if it exists.
|
|
|
|
func getErrorFromECSNotGlobalError(err error) error {
|
|
|
|
if errors.Is(err, discovery.ErrECSNotGlobal) {
|
|
|
|
return err.(discovery.ECSNotGlobalError).Unwrap()
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2024-01-24 20:32:42 +00:00
|
|
|
// parseRequestType inspects the DNS message type and question name to determine the requestType of request.
|
|
|
|
// We assume by the time this is called, we are responding to a question with a domain we serve.
|
|
|
|
// This is used internally to determine which query processor method (if any) to invoke.
|
|
|
|
func parseRequestType(req *dns.Msg) requestType {
|
|
|
|
switch {
|
|
|
|
case req.Question[0].Qtype == dns.TypeSOA || req.Question[0].Qtype == dns.TypeNS:
|
|
|
|
// SOA and NS type supersede the domain
|
|
|
|
// NOTE!: In V1 of the DNS server it was possible to serve a PTR lookup using the arpa domain but a SOA question type.
|
|
|
|
// This also included the SOA record. This seemed inconsistent and unnecessary - it was removed for simplicity.
|
|
|
|
return requestTypeConsul
|
|
|
|
case isPTRSubdomain(req.Question[0].Name):
|
|
|
|
return requestTypeIP
|
|
|
|
case isAddrSubdomain(req.Question[0].Name):
|
|
|
|
return requestTypeAddress
|
|
|
|
default:
|
|
|
|
return requestTypeName
|
|
|
|
}
|
2024-01-17 03:36:02 +00:00
|
|
|
}
|
|
|
|
|
2024-01-18 23:30:04 +00:00
|
|
|
// validateAndNormalizeRequest validates the DNS request and normalizes the request name.
|
|
|
|
func validateAndNormalizeRequest(req *dns.Msg) error {
|
|
|
|
// like upstream miekg/dns, we require at least one question,
|
|
|
|
// but we will only answer the first.
|
|
|
|
if len(req.Question) == 0 {
|
|
|
|
return errInvalidQuestion
|
|
|
|
}
|
|
|
|
|
|
|
|
// We mutate the request name to respond with the canonical name.
|
|
|
|
// This is Consul convention.
|
|
|
|
req.Question[0].Name = dns.CanonicalName(req.Question[0].Name)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-04-22 18:30:43 +00:00
|
|
|
// normalizeContext makes sure context information is populated with agent defaults as needed.
|
|
|
|
// Right now this is just the ACL token. We do this in the router with the token because DNS doesn't
|
|
|
|
// allow a token to be passed in the request, and we expect ACL tokens upfront in APIs when they are enabled.
|
|
|
|
// Tenancy information is left out because it is safe/expected to assume agent defaults in the backend lookup.
|
|
|
|
func (r *Router) normalizeContext(ctx *Context) {
|
|
|
|
if ctx.Token == "" {
|
|
|
|
ctx.Token = r.tokenFunc()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-03-01 15:36:37 +00:00
|
|
|
// stripAnyFailoverSuffix strips off the suffixes that may have been added to the request name.
|
|
|
|
func stripAnyFailoverSuffix(target string) (string, bool) {
|
2024-01-17 03:36:02 +00:00
|
|
|
enableFailover := false
|
|
|
|
|
|
|
|
// Strip off any suffixes that may have been added.
|
|
|
|
offset, underflow := dns.PrevLabel(target, 1)
|
|
|
|
if !underflow {
|
|
|
|
maybeSuffix := target[offset:]
|
|
|
|
switch maybeSuffix {
|
|
|
|
case suffixFailover:
|
|
|
|
target = target[:offset]
|
|
|
|
enableFailover = true
|
|
|
|
case suffixNoFailover:
|
|
|
|
target = target[:offset]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return target, enableFailover
|
|
|
|
}
|
|
|
|
|
2024-01-17 23:46:18 +00:00
|
|
|
// isAddrSubdomain returns true if the domain is a valid addr subdomain.
|
2024-01-17 03:36:02 +00:00
|
|
|
func isAddrSubdomain(domain string) bool {
|
|
|
|
labels := dns.SplitDomainName(domain)
|
|
|
|
|
|
|
|
// Looking for <hexadecimal-encoded IP>.addr.<optional datacenter>.consul.
|
|
|
|
if len(labels) > 2 {
|
|
|
|
return labels[1] == addrLabel
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2024-01-24 20:32:42 +00:00
|
|
|
// isPTRSubdomain returns true if the domain ends in the PTR domain, "in-addr.arpa.".
|
|
|
|
func isPTRSubdomain(domain string) bool {
|
|
|
|
labels := dns.SplitDomainName(domain)
|
|
|
|
labelCount := len(labels)
|
|
|
|
|
2024-01-29 16:40:10 +00:00
|
|
|
// We keep this check brief so we can have more specific error handling later.
|
|
|
|
if labelCount < 1 {
|
2024-01-24 20:32:42 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2024-01-29 16:40:10 +00:00
|
|
|
return labels[labelCount-1] == arpaLabel
|
2024-01-24 20:32:42 +00:00
|
|
|
}
|
|
|
|
|
2024-01-17 03:36:02 +00:00
|
|
|
// getDynamicRouterConfig takes agent config and creates/resets the config used by DNS Router
|
|
|
|
func getDynamicRouterConfig(conf *config.RuntimeConfig) (*RouterDynamicConfig, error) {
|
|
|
|
cfg := &RouterDynamicConfig{
|
|
|
|
ARecordLimit: conf.DNSARecordLimit,
|
|
|
|
EnableTruncate: conf.DNSEnableTruncate,
|
|
|
|
NodeTTL: conf.DNSNodeTTL,
|
|
|
|
RecursorStrategy: conf.DNSRecursorStrategy,
|
|
|
|
RecursorTimeout: conf.DNSRecursorTimeout,
|
|
|
|
UDPAnswerLimit: conf.DNSUDPAnswerLimit,
|
|
|
|
NodeMetaTXT: conf.DNSNodeMetaTXT,
|
|
|
|
DisableCompression: conf.DNSDisableCompression,
|
|
|
|
SOAConfig: SOAConfig{
|
|
|
|
Expire: conf.DNSSOA.Expire,
|
|
|
|
Minttl: conf.DNSSOA.Minttl,
|
|
|
|
Refresh: conf.DNSSOA.Refresh,
|
|
|
|
Retry: conf.DNSSOA.Retry,
|
|
|
|
},
|
2024-01-10 16:19:20 +00:00
|
|
|
}
|
2024-01-17 03:36:02 +00:00
|
|
|
|
2024-01-29 22:33:45 +00:00
|
|
|
if conf.DNSServiceTTL != nil {
|
|
|
|
cfg.TTLRadix = radix.New()
|
|
|
|
cfg.TTLStrict = make(map[string]time.Duration)
|
|
|
|
|
|
|
|
for key, ttl := range conf.DNSServiceTTL {
|
|
|
|
// All suffix with '*' are put in radix
|
|
|
|
// This include '*' that will match anything
|
|
|
|
if strings.HasSuffix(key, "*") {
|
|
|
|
cfg.TTLRadix.Insert(key[:len(key)-1], ttl)
|
|
|
|
} else {
|
|
|
|
cfg.TTLStrict[key] = ttl
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
cfg.TTLRadix = nil
|
|
|
|
cfg.TTLStrict = nil
|
|
|
|
}
|
2024-01-17 03:36:02 +00:00
|
|
|
|
2024-01-18 23:30:04 +00:00
|
|
|
for _, r := range conf.DNSRecursors {
|
|
|
|
ra, err := formatRecursorAddress(r)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("invalid recursor address: %w", err)
|
|
|
|
}
|
|
|
|
cfg.Recursors = append(cfg.Recursors, ra)
|
|
|
|
}
|
|
|
|
|
2024-01-17 03:36:02 +00:00
|
|
|
return cfg, nil
|
|
|
|
}
|
|
|
|
|
2024-01-17 23:46:18 +00:00
|
|
|
// canRecurse returns true if the router can recurse on the request.
|
2024-01-17 03:36:02 +00:00
|
|
|
func canRecurse(cfg *RouterDynamicConfig) bool {
|
|
|
|
return len(cfg.Recursors) > 0
|
2024-01-10 16:19:20 +00:00
|
|
|
}
|