resolver

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 18 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

resolver

[!NOTE] Forked from this repository. The goal is to insert a cache, add support for other clients, such as DoQ and DoH, and make the configuration flexible. This library will be used for the resolver CoreDNS plugin to turn CoreDNS into a iterative resolver.

A recursive DNS resolver with a Go-based API, designed to handle domain name resolution from the root nameservers. It includes support for DNSSEC validation via the dnssec package, which ensures the authenticity and integrity of DNS responses. Please note that the dnssec package will eventually be moved to its own dedicated project.

[!WARNING] This is an alpha release and remains a work in progress. Users should expect potential changes and improvements as development continues. It is not recommended to rely on this project for security-critical applications at this stage.

Usage

By default, we replace the standard miekg/dns module with mr-torgue/dns which is PQC-enabled. If you don't want this, remove the replace statement in go.mod and it should use the default.

package main

import (
	"context"
	"fmt"
	"github.com/davecgh/go-spew/spew"
	"github.com/miekg/dns"
	"github.com/mr-torgue/resolver-lib"
)

func main() {
	
	// Override the default logging hook on resolver.
	// Query to print each outgoing query to stdout.
	// (So you can see what's happening.)
	resolver.Query = func(s string) {
		fmt.Println("Query: " + s)
	}


	r := resolver.NewResolver()

	// Prepare a new DNS message struct.
	msg := new(dns.Msg)
	
	// Set it up as a question for the A record of “test.qazz.uk.” (Fqdn adds trailing dot).
	msg.SetQuestion(dns.Fqdn("test.qazz.uk"), dns.TypeA)

	// Add an OPT record to enable EDNS0 with a 4096‐byte UDP payload and DNSSEC OK bit.
	msg.SetEdns0(4096, true)

	// Perform the DNS query, using a background Context (no timeout/cancel).
	// Returns a resolver.Result, or error info embedded inside it.
	result := r.Exchange(context.Background(), msg)

	// Dump the full Result struct (including Response Msg, error, timings, etc.)
	// to stdout in a human-readable form.
	spew.Dump(result)
}

Outputs something along the lines of:

Query: 649949c-1: 12.616666ms taken querying [test.qazz.uk.] A in zone [.] on udp://a.root-servers.net. ([2001:503:ba3e::2:30]:53)
Query: 649949c-1: 5.895667ms taken querying [uk.] DNSKEY in zone [uk.] on udp://dns3.nic.uk. ([2a01:618:404::1]:53)
Query: 649949c-1: 6.14325ms taken querying [test.qazz.uk.] A in zone [uk.] on udp://dns1.nic.uk. ([2a01:618:400::1]:53)
Query: 649949c-1: 15.660209ms taken querying [qazz.uk.] DNSKEY in zone [qazz.uk.] on udp://ns2.qazz.uk. ([2600:9000:5300:7d00::1]:53)
Query: 649949c-1: 16.85725ms taken querying [test.qazz.uk.] A in zone [qazz.uk.] on udp://ns1.qazz.uk. ([2600:9000:5303:4800::1]:53)
Query: 649949c-1: 87.384083ms taken querying [.] DNSKEY in zone [.] on udp://c.root-servers.net. ([2001:500:2::c]:53)
Query: 649949c-1: 82.208416ms taken querying [.] DNSKEY in zone [.] on tcp://c.root-servers.net. ([2001:500:2::c]:53)

(*resolver.Response)(0x140000a82a0)({
 Msg: (*dns.Msg)(0x140000982d0)(;; opcode: QUERY, status: NOERROR, id: 44134
;; flags: qr aa rd ra ad; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version 0; flags: do; udp: 4096

;; QUESTION SECTION:
;test.qazz.uk.  IN       A

;; ANSWER SECTION:
test.qazz.uk.   60      IN      A       192.0.2.53
test.qazz.uk.   60      IN      RRSIG   A 13 3 60 20250623072623 20250623052523 6938 qazz.uk. zMzm+gyHbQGc8D3pZYmcQ/r6UGoh2VZEjNHfqAHrHsupYvr2/hKzUC4XIA3H7JM4gTz0YnZDT6u25eSFKVsztw==
),
 Err: (error) <nil>,
 Duration: (time.Duration) 258.376875ms,
 Doe: (dnssec.DenialOfExistenceState) NotFound,
 Auth: (dnssec.AuthenticationResult) Secure
})

Licence

This project is licensed under the MIT License - see the LICENSE file for details.

Also see:

Documentation

Index

Constants

View Source
const (
	DefaultMaxAllowedTTL = uint32(60 * 60 * 48) // 48 Hours

	DefaultMaxQueriesPerRequest = uint32(100)

	DefaultDesireNumberOfNameserversPerZone = 3

	DefaultLazyEnrichment = false

	DefaultSuppressBogusResponseSections = true

	DefaultRemoveAuthoritySectionForPositiveAnswers  = true
	DefaultRemoveAdditionalSectionForPositiveAnswers = true

	DefaultUDPSize    uint16 = 8192
	DefaultTimeoutUDP        = 400 * time.Millisecond
	DefaultTimeoutTCP        = 1000 * time.Millisecond
	DefaultTimeoutDOQ        = 600 * time.Millisecond
	DefaultTimeoutDOT        = 1500 * time.Millisecond
	DefaultDNSPort           = "53"
	DefaultDoQPort           = "853"
	DefaultDoTPort           = "8853"

	DefaultRootzone    = "named.root"
	DefaultRootanchors = "root-anchors.xml"

	// just some random values. no real thought went into this.
	DefaultTLSCacheSize = 1024
	DefaultCacheSize    = 2048
)
View Source
const (
	CtxTrace ctxKey = iota
)

Variables

View Source
var (
	ErrNotRecursionDesired         = errors.New("only recursive queries are supported via this server")
	ErrNilMessageSentToExchange    = errors.New("nil message sent to exchange")
	ErrNoPoolConfiguredForZone     = errors.New("no nameserver pool configured for zone")
	ErrFailedToGetDNSKEYs          = errors.New("failed looking up DNSKEY records")
	ErrFailedCreatingZoneAndPool   = errors.New("failed creating nameserver pool for zone")
	ErrFailedEnrichingPool         = errors.New("failed enriching nameserver pool for zone")
	ErrUnableToResolveAnswer       = errors.New("failed resolving answer")
	ErrNextNameserversNotFound     = errors.New("the onward nameservers cannot be found")
	ErrEmptyResponse               = errors.New("the received response is empty")
	ErrInternalError               = errors.New("internal error")
	ErrMaxQueriesPerRequestReached = errors.New("max queries per request reached")
)
View Source
var DefaultConfig = Config{
	// contains filtered or unexported fields
}

DefaultConfig is a working default configuration.

Log is the package-level default logger. It defaults to doing nothing.

Functions

func IPv6Available

func IPv6Available() bool

IPv6Available return true if IPv6 Internet connectivity is found. If the check has not been performed, it won't block, and (initially) will return false.

func RcodeToString

func RcodeToString(rcode int) string

func SetLogger added in v1.0.4

func SetLogger(l log.Logger)

SetLogger allows external users to override the package-level default logger. It only affects Configs built afterwards (see ConfigBuilder).

func TypeToString

func TypeToString(rrtype uint16) string

func UpdateIPv6Availability

func UpdateIPv6Availability()

UpdateIPv6Availability sense checks if we can get a DNS response from an IPv6 address.

Types

type CacheInterface

type CacheInterface interface {
	Get(qmsg *dns.Msg) (*dns.Msg, error)
	// Update inserts msg into the cache with the validation status that was
	// determined for it (Indeterminate when no validation was performed).
	// It is called once, after validation. A Bogus status evicts any existing
	// entries instead of caching: bogus data must never be served.
	Update(question dns.Question, msg *dns.Msg, status cache.ValidationStatus) error
}

type Config

type Config struct {
	// contains filtered or unexported fields
}

func ConfigBuilder

func ConfigBuilder(options ...Option) *Config

ConfigBuilder builds a configuration based on the provided options. The package-level default variables are snapshotted here; later changes to them do not affect the returned Config.

type NameserverPoolStatus

type NameserverPoolStatus uint8
const (
	PoolEmpty NameserverPoolStatus = iota
	PoolExpired
	PoolHasHostnamesButNoIpAddresses
	PrimedButNeedsEnhancing
	PoolPrimed
)

type Option

type Option func(*Config)

func WithCache added in v0.2.0

func WithCache(size int) Option

WithCache sets the DNS cache. If set to 0, it gets disabled. Note: this is the DNS cache, not the TLS session cache.

func WithClient

func WithClient(client string, fallback bool) Option

WithClients specifies which client to use. Supported: doq, doh, dot, udp, and tcp. Fallback can be enabled.

func WithCustomRoot

func WithCustomRoot(filename string, anchorfilename string) Option

WithCustomRoot overwrites the standard rootzone and anchors.

func WithDNSPort added in v0.1.5

func WithDNSPort(dnsPort int) Option

WithCustomDNSPort changes the default port for UDP/TCP.

func WithDesireNumberOfNameserversPerZone added in v1.0.8

func WithDesireNumberOfNameserversPerZone(n int) Option

WithDesireNumberOfNameserversPerZone sets how many nameserver addresses a zone pool should try to know.

func WithDoQPort added in v0.1.5

func WithDoQPort(doqPort int) Option

WithCustomDoQPort changes the default port for DoQ.

func WithDoTPort added in v0.1.5

func WithDoTPort(dotPort int) Option

WithCustomDoTPort changes the default port for DoT.

func WithLazyEnrichment added in v1.0.8

func WithLazyEnrichment(lazy bool) Option

WithLazyEnrichment toggles lazy pool enrichment for this instance.

func WithLogger added in v1.0.8

func WithLogger(l log.Logger) Option

WithLogger sets the logger for this instance.

func WithMaxAllowedTTL added in v1.0.8

func WithMaxAllowedTTL(ttl uint32) Option

WithMaxAllowedTTL sets the maximum TTL cached for any record.

func WithMaxQueriesPerRequest added in v1.0.8

func WithMaxQueriesPerRequest(max uint32) Option

WithMaxQueriesPerRequest sets the maximum number of DNS lookups per Exchange call.

func WithPQCMode added in v0.1.4

func WithPQCMode(pqcMode bool) Option

WithPQCMode turns the pqc mode on or off.

func WithRemoveAdditionalSectionForPositiveAnswers added in v1.0.8

func WithRemoveAdditionalSectionForPositiveAnswers(remove bool) Option

WithRemoveAdditionalSectionForPositiveAnswers toggles removal of the Additional section for positive answers.

func WithRemoveAuthoritySectionForPositiveAnswers added in v1.0.8

func WithRemoveAuthoritySectionForPositiveAnswers(remove bool) Option

WithRemoveAuthoritySectionForPositiveAnswers toggles removal of the Authority section for positive answers.

func WithSuppressBogusResponseSections added in v1.0.8

func WithSuppressBogusResponseSections(suppress bool) Option

WithSuppressBogusResponseSections toggles suppression of response sections for Bogus answers.

func WithTLSCache added in v0.1.4

func WithTLSCache(capacity int) Option

WithTLSCache indicates the cache size.

func WithTLSVerification

func WithTLSVerification(verify bool) Option

WithTLSVerification indicates if TLS verification is enabled. In case of clients that don't use TLS, this option is ignored.

func WithTimeouts

func WithTimeouts(udp, tcp, tls, quic time.Duration) Option

WithTimeouts sets the timeouts for connections.

func WithTrustAnchors added in v1.0.8

func WithTrustAnchors(anchors []*dns.DS) Option

WithTrustAnchors sets the DNSSEC trust anchors for this instance.

func WithUDPSize added in v0.1.5

func WithUDPSize(udpsize uint16) Option

type Resolver

type Resolver struct {
	// contains filtered or unexported fields
}

func NewResolver

func NewResolver(config *Config) *Resolver

func (*Resolver) CountZones

func (resolver *Resolver) CountZones() int

CountZones metrics gathering.

func (*Resolver) Exchange

func (resolver *Resolver) Exchange(ctx context.Context, qmsg *dns.Msg) *Response

type Response

type Response struct {
	Msg      *dns.Msg
	Err      error
	Duration time.Duration
	Doe      dnssec.DenialOfExistenceState
	Auth     dnssec.AuthenticationResult
}

func (*Response) HasError

func (r *Response) HasError() bool

func (*Response) IsEmpty

func (r *Response) IsEmpty() bool

type Trace

type Trace struct {
	Id    uuid.UUID
	Start time.Time

	Iterations atomic.Uint32
}

func NewTrace

func NewTrace() *Trace

func (*Trace) ID

func (t *Trace) ID() string

func (*Trace) Iteration

func (t *Trace) Iteration() uint32

func (*Trace) ShortID

func (t *Trace) ShortID() string

Directories

Path Synopsis
doe

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址