dns

package
v0.8.42 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: MIT Imports: 18 Imported by: 1 module, 0 packages

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.

Documentation

Index

Constants

View Source
const (
	ALPNDoT  = "dot" // RFC 7858, via RFC 9461 §4
	ALPNDoH2 = "h2"  // RFC 8484 over HTTP/2
	ALPNDoH3 = "h3"  // RFC 8484 over HTTP/3
	ALPNDoQ  = "doq" // RFC 9250
)

ALPN identifiers for the encrypted DNS transports, from the IANA TLS Application-Layer Protocol Negotiation registry. RFC 9461 §4 specifies which one designates which transport.

View Source
const (
	AlgRSASHA1   uint8 = 5
	AlgRSASHA256 uint8 = 8
	AlgRSASHA512 uint8 = 10
	AlgECDSAP256 uint8 = 13
	AlgECDSAP384 uint8 = 14
	AlgED25519   uint8 = 15
	// AlgED448 is defined so the validator can *name* the algorithm when it
	// declines to use it — an "unsupported algorithm 16" in a log is far
	// more actionable than a bare number, and RFC 6840 §5.2 requires a zone
	// signed only with algorithms we cannot verify to be treated as
	// insecure rather than bogus, which is a decision that needs the
	// constant.
	//
	// It is deliberately absent from dnssec/verify.go. Ed448 is a MAY in
	// RFC 8624 §3.1, the Go standard library has no Ed448 implementation,
	// and x/crypto does not provide one either — so supporting it would
	// mean vendoring a third-party curve implementation to serve a
	// vanishingly small number of zones. A zone signed only with Ed448 is
	// therefore treated as insecure, exactly as the RFC prescribes for an
	// unsupported algorithm.
	AlgED448 uint8 = 16
)

DNSSEC algorithm numbers (RFC 8624).

View Source
const (
	// DigestReserved (0) is the IANA-reserved DS digest type. RFC 4509
	// §2.4 / RFC 8624 §3.3 say a DS RR carrying digest type 0 MUST NOT
	// be used to authenticate the corresponding DNSKEY. If the parent
	// publishes ONLY digest-type-0 DS records for a delegation, the
	// delegation has no usable DS — RFC 4035 §5.2 treats that the same
	// as no DS at all and the validator falls through to Insecure.
	DigestReserved uint8 = 0
	DigestSHA1     uint8 = 1
	DigestSHA256   uint8 = 2
	DigestSHA384   uint8 = 4
)

DNSSEC digest types (RFC 8624).

View Source
const (
	AlgRSAMD5       uint8 = 1
	AlgDSA          uint8 = 3
	AlgDSANSEC3SHA1 uint8 = 6
	AlgRSASHA1NSEC3 uint8 = 7
)

DNSSEC algorithm numbers that this resolver explicitly does NOT validate. The verify-switch in dnssec/verify.go falls through to "unsupported" for any algorithm not enumerated above, so listing these as named constants is for spec-completeness and pin-test readability — never for acceptance.

  • RSAMD5 (1): MD5 is cryptographically broken (RFC 6151) and MUST NOT be used for new signatures (RFC 6944).
  • DSA (3): DSA-SHA1 is deprecated and dropped from the Internet root signing key rollover (RFC 8624 §3.1).
  • DSA-NSEC3 (6): Same DSA constraints, NSEC3 variant.
  • RSASHA1-NSEC3 (7):RSA/SHA-1 in any form is deprecated; we honour the validator's allowSHA1 gate via algorithm 5 only when explicitly opted in. Algorithm 7 is legacy and we leave it strictly off.
View Source
const (
	EDECodeOtherError              uint16 = 0
	EDECodeUnsupportedDNSKEYAlgo   uint16 = 1
	EDECodeUnsupportedDSDigestType uint16 = 2
	EDECodeStaleAnswer             uint16 = 3
	EDECodeForgedAnswer            uint16 = 4
	EDECodeDNSSECIndeterminate     uint16 = 5
	EDECodeDNSSECBogus             uint16 = 6
	EDECodeSignatureExpired        uint16 = 7
	EDECodeSignatureNotYetValid    uint16 = 8
	EDECodeDNSKEYMissing           uint16 = 9
	EDECodeRRSIGsMissing           uint16 = 10
	EDECodeNoZoneKeyBitSet         uint16 = 11
	EDECodeNSECMissing             uint16 = 12
	EDECodeCachedError             uint16 = 13
	EDECodeNotReady                uint16 = 14
	EDECodeBlocked                 uint16 = 15
	EDECodeCensored                uint16 = 16
	EDECodeFiltered                uint16 = 17
	EDECodeProhibited              uint16 = 18
	EDECodeStaleNXDOMAINAnswer     uint16 = 19
	EDECodeNotAuthoritative        uint16 = 20
	EDECodeNotSupported            uint16 = 21
	EDECodeNoReachableAuthority    uint16 = 22
	EDECodeNetworkError            uint16 = 23
	EDECodeInvalidData             uint16 = 24
	// EDECodeSignatureExpiredBeforeValid — RFC 9606. The signer
	// produced an RRSIG whose Expiration timestamp is earlier than
	// its Inception timestamp; under no clock could it ever validate.
	// Distinct from a normal "expired" (7) because this is a signer
	// bug rather than a clock-skew situation.
	EDECodeSignatureExpiredBeforeValid uint16 = 25
	// EDECodeTooEarly — RFC 9539. Used by upstreams that observed
	// the resolver send a 0-RTT query before the TLS handshake
	// completed in a way they could not safely replay. Lets the
	// client know to retry once handshake completes.
	EDECodeTooEarly uint16 = 26
	// EDECodeUnsupportedNSEC3IterationsValue — RFC 9276 §3.2. The
	// resolver refused to walk an NSEC3 chain because its iteration
	// count exceeded the local cap (MaxNSEC3Iterations); the response
	// is reported Insecure rather than Bogus so the client knows to
	// trust it for non-DNSSEC purposes.
	EDECodeUnsupportedNSEC3IterationsValue uint16 = 27
	// EDECodeUnableToConformToPolicy — IANA EDE 28. Signals that the
	// upstream did not return an answer the resolver considers
	// policy-acceptable (e.g. an unsigned answer when the operator
	// requires DO=1 + AD=1). Distinct from "filtered" (17) which is
	// the resolver's OWN policy refusing to forward; code 28 covers
	// the case where the upstream's response itself violates a local
	// policy gate the resolver enforces post-receipt.
	EDECodeUnableToConformToPolicy uint16 = 28
	// EDECodeSynthesized — IANA EDE 29. Signals that the answer was
	// synthesized by the resolver (DNS64 AAAA synthesis, RFC 8198
	// aggressive NSEC NXDOMAIN/NODATA, NSEC3-aggressive synthesis)
	// rather than fetched as-is from the authoritative. Clients that
	// need a verifiable upstream answer can re-query with synthesis
	// disabled or take corrective action.
	EDECodeSynthesized uint16 = 29
)

EDE info codes (RFC 8914).

View Source
const (
	// EDNSOptionCodeNSID is the Name Server Identifier option (RFC 5001).
	// A client sends it with zero-length data to ask "which instance am I
	// actually talking to?"; the server answers with an opaque identifier.
	// On an anycast deployment this is the only in-band way to tell which
	// node served a query, which is why it is the first thing an operator
	// reaches for when one node in a cluster misbehaves.
	EDNSOptionCodeNSID uint16 = 3
	EDNSOptionCodeECS  uint16 = 8
	// EDNSOptionCodeEXPIRE is the EDNS EXPIRE option (RFC 7314). A
	// secondary uses it to learn the remaining lifetime of the zone it
	// holds, so a zone can expire consistently across a chain of
	// secondaries rather than each restarting the clock. Not acted on:
	// Labyrinth has no secondary-zone role yet (see RFC 9103 in
	// docs/rfc-compliance-matrix.md).
	EDNSOptionCodeEXPIRE       uint16 = 9
	EDNSOptionCodeCookie       uint16 = 10
	EDNSOptionCodeTCPKeepalive uint16 = 11
	EDNSOptionCodePadding      uint16 = 12
	// EDNSOptionCodeCHAIN is the CHAIN query option (RFC 7901), by which a
	// validating client asks for the whole DNSSEC chain in one response.
	// Not acted on: Labyrinth validates on the client's behalf, so the
	// chain-shipping case only arises for stubs that validate themselves.
	EDNSOptionCodeCHAIN uint16 = 13
	// EDNSOptionCodeKeyTag is edns-key-tag (RFC 8145 §4), by which a
	// validator reports which trust anchors it holds. It is the mechanism
	// that made the 2018 root KSK rollover measurable. Not acted on:
	// Labyrinth tracks anchors via RFC 5011 but does not report them.
	EDNSOptionCodeKeyTag uint16 = 14
	EDNSOptionCodeEDE    uint16 = 15
	// EDNSOptionCodeReportChannel is the Report-Channel option (RFC 9567
	// §6.1). An authoritative server attaches it to advertise an agent
	// domain that resolvers should send error reports to. See
	// errorreport.go.
	EDNSOptionCodeReportChannel uint16 = 18
	// EDNSOptionCodeZoneVersion is the ZONEVERSION option (RFC 9660), by
	// which an authoritative server discloses which version of a zone
	// produced an answer. Not acted on: useful to zone operators
	// debugging propagation, not to a recursive resolver.
	EDNSOptionCodeZoneVersion uint16 = 19
	// EDNSOptionCodeDAU is the "DNSSEC Algorithm Understood" option
	// (RFC 6975 §3). The option data is the list of DNSKEY/RRSIG
	// algorithm numbers the resolver can validate. Multi-signed zones
	// (a zone published with multiple algorithms during a rollover)
	// use this to decide which signature to return; without DAU they
	// must send all signatures, wasting bandwidth and amplification.
	EDNSOptionCodeDAU uint16 = 5
	// EDNSOptionCodeDHU is the "DS Hash Understood" option. Same idea
	// but for DS digest types (RFC 6975 §3, option code 6).
	EDNSOptionCodeDHU uint16 = 6
	// EDNSOptionCodeN3U is the "NSEC3 Hash Understood" option. NSEC3
	// hash algorithms — only SHA-1 (algorithm 1) is currently defined
	// (RFC 6975 §3, option code 7).
	EDNSOptionCodeN3U uint16 = 7
)

EDNS option codes, as assigned in the IANA "DNS EDNS0 Option Codes (OPT)" registry. Codes are listed here even when Labyrinth does not act on them: an unrecognised option in a query is silently ignored per RFC 6891 §6.1.2, and having the constant means a log line or a metric can name the option instead of printing a bare integer.

View Source
const (
	SvcParamMandatory     uint16 = 0
	SvcParamALPN          uint16 = 1
	SvcParamNoDefaultALPN uint16 = 2
	SvcParamPort          uint16 = 3
	SvcParamIPv4Hint      uint16 = 4
	SvcParamECH           uint16 = 5
	SvcParamIPv6Hint      uint16 = 6
	// SvcParamDoHPath is the "dohpath" key (RFC 9461 §5): the URI template
	// of a DoH endpoint, e.g. "/dns-query{?dns}". Required for a DoH
	// designation, since unlike DoT and DoQ a DoH endpoint is not fully
	// identified by a host and port.
	SvcParamDoHPath uint16 = 7
)

SvcParamKey values from the IANA "Service Parameter Keys (SvcParamKeys)" registry (RFC 9460 §14.3.2).

View Source
const (
	TSIGErrorNoError  uint16 = 0
	TSIGErrorBadSig   uint16 = 16
	TSIGErrorBadKey   uint16 = 17
	TSIGErrorBadTime  uint16 = 18
	TSIGErrorBadTrunc uint16 = 22
)

TSIG error codes (RFC 8945 §4.3 / §5.2). These live in the TSIG RDATA's Error field, which is a distinct registry from the DNS RCODE and the EDNS extended RCODE — value 16 is BADSIG here and BADVERS in the EDNS space.

View Source
const (
	TSIGHMACSHA1   = "hmac-sha1"
	TSIGHMACSHA224 = "hmac-sha224"
	TSIGHMACSHA256 = "hmac-sha256"
	TSIGHMACSHA384 = "hmac-sha384"
	TSIGHMACSHA512 = "hmac-sha512"
)

TSIG algorithm names, as they appear on the wire (RFC 8945 §6). They are domain names, compared case-insensitively.

View Source
const (
	TypeA     uint16 = 1
	TypeNS    uint16 = 2
	TypeCNAME uint16 = 5
	TypeSOA   uint16 = 6
	TypePTR   uint16 = 12
	TypeMX    uint16 = 15
	TypeTXT   uint16 = 16
	TypeAAAA  uint16 = 28
	TypeSRV   uint16 = 33
	TypeHINFO uint16 = 13
	TypeDNAME uint16 = 39
	TypeOPT   uint16 = 41
	TypeANY   uint16 = 255

	// DNSSEC types
	TypeDS         uint16 = 43
	TypeRRSIG      uint16 = 46
	TypeNSEC       uint16 = 47
	TypeDNSKEY     uint16 = 48
	TypeNSEC3      uint16 = 50
	TypeNSEC3PARAM uint16 = 51
	// RFC 7344 — child-published DS/DNSKEY records the parent zone uses
	// to update the child's delegation. CDS RDATA is byte-identical to
	// DS; CDNSKEY RDATA is byte-identical to DNSKEY. Distinct types
	// only at the owner-side semantics: present at the apex of the
	// CHILD zone, signed by the child's keys, instructing the parent.
	TypeCDS     uint16 = 59
	TypeCDNSKEY uint16 = 60

	// Zone transfer types (RFC 5936 AXFR, RFC 1995 IXFR)
	TypeAXFR uint16 = 252
	TypeIXFR uint16 = 251

	// Meta types used by transaction security. TSIG travels as the last
	// record of a message and is stripped before the message is otherwise
	// interpreted; TKEY negotiates the shared secret TSIG uses.
	TypeTKEY uint16 = 249 // RFC 2930
	TypeTSIG uint16 = 250 // RFC 8945

	// Types below are recognised but not parsed into Go structs. RFC 3597
	// §3 is explicit that the correct handling for an RR type an
	// implementation does not implement is to treat the RDATA as an opaque
	// block, and for a recursive resolver that is not a limitation — it is
	// the whole point. Rewriting RDATA we do not understand would break the
	// signatures over it.
	//
	// What registering them buys is naming. Before this, a TLSA record in
	// the cache viewer showed as blank and a `dig`-style query for it from
	// the dashboard was rejected outright as an "unsupported query type",
	// even though the resolver had been resolving them correctly all
	// along. An operator could not inspect what the resolver already held.
	TypeLOC        uint16 = 29  // RFC 1876 — geographic location
	TypeNAPTR      uint16 = 35  // RFC 3403 — naming authority pointer (ENUM, SIP)
	TypeCERT       uint16 = 37  // RFC 4398 — certificates
	TypeSSHFP      uint16 = 44  // RFC 4255 — SSH host key fingerprints
	TypeIPSECKEY   uint16 = 45  // RFC 4025 — IPsec keying material
	TypeDHCID      uint16 = 49  // RFC 4701 — DHCP identifier
	TypeTLSA       uint16 = 52  // RFC 6698 — DANE TLS anchors
	TypeSMIMEA     uint16 = 53  // RFC 8162 — S/MIME cert association
	TypeHIP        uint16 = 55  // RFC 8005 — host identity protocol
	TypeOPENPGPKEY uint16 = 61  // RFC 7929 — OpenPGP public keys
	TypeCSYNC      uint16 = 62  // RFC 7477 — child-to-parent synchronization
	TypeZONEMD     uint16 = 63  // RFC 8976 — message digest for zone files
	TypeSPF        uint16 = 99  // RFC 7208 — deprecated in favour of TXT
	TypeNID        uint16 = 104 // RFC 6742 — ILNP node identifier
	TypeL32        uint16 = 105 // RFC 6742
	TypeL64        uint16 = 106 // RFC 6742
	TypeLP         uint16 = 107 // RFC 6742
	TypeEUI48      uint16 = 108 // RFC 7043
	TypeEUI64      uint16 = 109 // RFC 7043
	TypeURI        uint16 = 256 // RFC 7553 — URI mapping
	TypeRESINFO    uint16 = 261 // RFC 9606 — resolver information
	TypeTA         uint16 = 32768
	TypeDLV        uint16 = 32769 // RFC 4431; the protocol is deprecated by RFC 8749

	// Modern service-discovery types. We do not parse their RDATA into
	// rich Go structs (the wire layer treats them as opaque, which is
	// the right behaviour for a forwarding recursive resolver per RFC
	// 3597 — pass unknown RDATA through verbatim so signatures remain
	// verifiable downstream). But registering them in TypeToString so
	// logs, the queries UI, and DNSSEC trace events show "HTTPS" and
	// "SVCB" instead of "TYPE65"/"TYPE64" is important for operators
	// chasing real-world traffic on networks where these dominate
	// (Apple devices, HTTP/3 / QUIC clients, ECH-enabled browsers).
	TypeSVCB  uint16 = 64 // RFC 9460 §2.1 — service binding
	TypeHTTPS uint16 = 65 // RFC 9460 §9   — HTTPS specialisation of SVCB
	// RFC 8659 (obsoletes 6844). DNS-based authorization for X.509
	// issuance — every CA on the public PKI MUST honour CAA, so
	// resolvers that mangle this RDATA can silently break cert renewal.
	TypeCAA uint16 = 257
)

Record types

View Source
const (
	RCodeNoError  uint8 = 0
	RCodeFormErr  uint8 = 1
	RCodeServFail uint8 = 2
	RCodeNXDomain uint8 = 3
	RCodeNotImp   uint8 = 4
	RCodeRefused  uint8 = 5
	// RCodeBadCookie is the extended RCODE 23 (RFC 7873 §5.2). It must be
	// transmitted using the EDNS0 ExtRCODE split: the low 4 bits (0x07) go
	// into the DNS header RCODE field, the high 8 bits (0x01) go into the
	// OPT pseudo-RR TTL byte 0. See buildBadCookieResponse.
	RCodeBadCookie uint8 = 23
)

Response codes

View Source
const (
	OpcodeQuery  uint8 = 0
	OpcodeIQuery uint8 = 1
	OpcodeStatus uint8 = 2
	// OpcodeNotify (RFC 1996) and OpcodeUpdate (RFC 2136) are recognised
	// so the handler can name what it is refusing. Labyrinth answers both
	// with NOTIMP — it is a recursive resolver with no zone to be notified
	// about or updated — but "NOTIMP for OPCODE 5" in a log is a far
	// better lead for an operator who misconfigured a primary than a bare
	// counter increment.
	OpcodeNotify uint8 = 4
	OpcodeUpdate uint8 = 5
	OpcodeDSO    uint8 = 6 // RFC 8490 — DNS Stateful Operations
)

Opcodes

View Source
const (
	ClassIN uint16 = 1
)

Classes

View Source
const DDRQueryName = "_dns.resolver.arpa"

DDRQueryName is the special-use name a client queries to discover designated resolvers by IP address (RFC 9462 §4). It is served locally and must never be forwarded — resolver.arpa has no delegation in the global DNS, so a forwarded query would leak the client's discovery attempt and return NXDOMAIN.

View Source
const DDRTTL uint32 = 7200

DDRTTL is the TTL on designation records. RFC 9462 §4.1 uses 7200 in its examples; the value trades off how fast an endpoint change propagates against how often clients re-query for something that rarely changes.

View Source
const DefaultTSIGAlgorithm = TSIGHMACSHA256

DefaultTSIGAlgorithm is what a configuration that does not say gets. RFC 8945 §6 lists HMAC-SHA256 as mandatory to implement, and it is the de-facto default across BIND, Knot and PowerDNS.

View Source
const DefaultTSIGFudge uint16 = 300

DefaultTSIGFudge is the permitted clock skew in seconds (RFC 8945 §5.2.3 recommends 300). It bounds how far apart the two clocks may be before signatures start failing, and equally how long a captured message stays replayable.

View Source
const MaxNSIDLength = 64

MaxNSIDLength bounds the identifier a server will emit. RFC 5001 puts no ceiling on NSID length, but the option travels in every response to a client that asked for it, and an operator who pastes a long string into the config should not silently start pushing responses over the UDP buffer into TCP fallback. 64 bytes is comfortably more than the hostname-or-site-code that real deployments use.

View Source
const PaddingBlockSize = 468

PaddingBlockSize is the recommended response padding block (RFC 8467 §4.1: "the server SHOULD pad the response packet to a multiple of 468 bytes"). The number is empirical: it avoids most common MTUs while still being a single power-of-two-friendly value that hides most short answers in the same length bucket as longer ones.

View Source
const ReportQueryLabel = "_er"

ReportQueryLabel is the "_er" label that brackets a report QNAME on both sides (RFC 9567 §6.2). It appears twice: once leading the encoded query details, once immediately before the agent domain. Recognising it is also how a resolver avoids reporting on its own reports.

Variables

View Source
var (
	ErrTSIGNotSigned       = errors.New("tsig: message carries no TSIG record")
	ErrTSIGNotLast         = errors.New("tsig: TSIG record is not the last record in the additional section")
	ErrTSIGBadKey          = errors.New("tsig: unknown key name")
	ErrTSIGBadAlgorithm    = errors.New("tsig: unsupported algorithm")
	ErrTSIGBadSig          = errors.New("tsig: MAC verification failed")
	ErrTSIGBadTime         = errors.New("tsig: time signed outside the fudge window")
	ErrTSIGBadTrunc        = errors.New("tsig: MAC truncated below the permitted minimum")
	ErrTSIGMalformed       = errors.New("tsig: malformed TSIG record")
	ErrTSIGWrongClassOrTTL = errors.New("tsig: TSIG record must have class ANY and TTL 0")
)
View Source
var RCodeToString = map[uint8]string{
	RCodeNoError:   "NOERROR",
	RCodeFormErr:   "FORMERR",
	RCodeServFail:  "SERVFAIL",
	RCodeNXDomain:  "NXDOMAIN",
	RCodeNotImp:    "NOTIMP",
	RCodeRefused:   "REFUSED",
	RCodeBadCookie: "BADCOOKIE",
}

RCodeToString maps response codes to human-readable names.

View Source
var StringToType = func() map[string]uint16 {
	m := make(map[string]uint16, len(TypeToString))
	for t, s := range TypeToString {
		m[s] = t
	}
	return m
}()

StringToType is the inverse of TypeToString, built once at init so the two can never disagree. Adding a type to TypeToString automatically makes it queryable from the dashboard and the diagnostics endpoint.

It previously did not exist, and three hand-maintained partial copies stood in for it — one in the cache API, one in the trace API, one implied by the UI. They had drifted to different subsets, so which record types you could inspect depended on which page you were looking at.

View Source
var TypeToString = map[uint16]string{
	TypeA: "A", TypeNS: "NS", TypeCNAME: "CNAME", TypeSOA: "SOA",
	TypeHINFO: "HINFO", TypePTR: "PTR", TypeMX: "MX", TypeTXT: "TXT",
	TypeAAAA: "AAAA", TypeSRV: "SRV", TypeDNAME: "DNAME", TypeOPT: "OPT",
	TypeDS: "DS", TypeRRSIG: "RRSIG", TypeNSEC: "NSEC",
	TypeDNSKEY: "DNSKEY", TypeNSEC3: "NSEC3", TypeNSEC3PARAM: "NSEC3PARAM",
	TypeCDS: "CDS", TypeCDNSKEY: "CDNSKEY",
	TypeANY:  "ANY",
	TypeSVCB: "SVCB", TypeHTTPS: "HTTPS", TypeCAA: "CAA",
	TypeAXFR: "AXFR", TypeIXFR: "IXFR",
	TypeTKEY: "TKEY", TypeTSIG: "TSIG",
	TypeLOC: "LOC", TypeNAPTR: "NAPTR", TypeCERT: "CERT",
	TypeSSHFP: "SSHFP", TypeIPSECKEY: "IPSECKEY", TypeDHCID: "DHCID",
	TypeTLSA: "TLSA", TypeSMIMEA: "SMIMEA", TypeHIP: "HIP",
	TypeOPENPGPKEY: "OPENPGPKEY", TypeCSYNC: "CSYNC", TypeZONEMD: "ZONEMD",
	TypeSPF: "SPF",
	TypeNID: "NID", TypeL32: "L32", TypeL64: "L64", TypeLP: "LP",
	TypeEUI48: "EUI48", TypeEUI64: "EUI64",
	TypeURI: "URI", TypeRESINFO: "RESINFO",
	TypeTA: "TA", TypeDLV: "DLV",
}

TypeToString maps type values to human-readable names. Use TypeName for lookups that must always yield a string — it falls back to the RFC 3597 §5 generic "TYPE<n>" form for anything not listed here.

Functions

func AddNSIDToRawResponse added in v0.8.33

func AddNSIDToRawResponse(resp []byte, id []byte) []byte

AddNSIDToRawResponse parses a wire-format response and attaches an NSID option carrying `id` (RFC 5001 §2.3). Used by every transport rather than just the stateful ones: an operator debugging an anycast cluster is most often doing it over UDP, which is where the misrouting happens.

Idempotent — a response that already carries NSID is returned unchanged, since RFC 6891 §6.1.1 allows each option code to appear only once. Returns the original bytes on any parse/pack error or for an empty id.

Like AddTCPKeepaliveToRawResponse, this appends to the existing OPT RR's RData rather than rebuilding the record, so ExtRCODE/Version/DO bits set by earlier stages survive.

func AddTCPKeepaliveToRawResponse added in v0.6.20

func AddTCPKeepaliveToRawResponse(resp []byte, timeoutUnits100ms uint16) []byte

AddTCPKeepaliveToRawResponse parses a wire-format response and adds an edns-tcp-keepalive option (RFC 7828 §3.1) carrying the server's idle timeout in 100ms units. Used by TCP/DoT/DoH servers when the client signalled keepalive interest. Idempotent — if the response already carries a keepalive option, the original bytes are returned unchanged. Returns the original bytes on any parse/pack error.

func BogusReasonToEDE added in v0.8.33

func BogusReasonToEDE(reason string) (uint16, string)

BogusReasonToEDE maps a dnssec.FailureReason token (carried through resolver.ResolveResult.DNSSECReason as a stable string) to the most informative RFC 8914 §4 Extended DNS Error info code we can emit. The generic EDE 6 (DNSSEC Bogus) is the fallback when the validator did not classify the cause more specifically. Granular codes help operators and clients distinguish "the auth's signature expired" (an operational failure at the auth side, retry later) from "we saw a cryptographic forgery" (a security event worth investigating).

The token-string indirection — instead of a typed enum across packages — lets resolver.ResolveResult avoid importing dnssec just for the type.

This lives in the dns package rather than next to its original caller in server/ because there are now two consumers with no import path between them: the server picks the EDE it sends *downstream* to the client, and the resolver picks the EDE it puts in an RFC 9567 report sent *upstream* to the zone's agent domain. Both must name the same failure the same way, or an operator correlating their agent-domain logs against a client's error would see two different codes for one event.

func BuildPlainName

func BuildPlainName(name string) []byte

BuildPlainName encodes a domain name as uncompressed wire-format label sequence. Exported for use in tests and delegation handling.

func BuildRESINFORData added in v0.8.33

func BuildRESINFORData(info ResolverInfo) []byte

RESINFOName is the owner name under which a resolver publishes RESINFO: its own name, queried directly (RFC 9606 §4).

Empty ResolverInfo produces no record at all rather than an empty one — a resolver that has nothing to declare should not claim to have declared nothing.

func BuildReportQName added in v0.8.33

func BuildReportQName(agentDomain, qname string, qtype uint16, edeCode uint16) (string, bool)

BuildReportQName constructs the report query name for a failure, per RFC 9567 §6.2:

_er.<qtype>.<qname>.<extended-error>._er.<agent-domain>

So a DNSSEC-bogus (EDE 6) failure on an A query for broken.test., reported to agent domain a.example., becomes:

_er.1.broken.test.6._er.a.example.

The QTYPE and EDE code are decimal, not the mnemonic — the agent's log pipeline parses labels, not names.

Returns ok=false when the report should not be sent:

  • the agent domain or qname is empty;
  • the qname is itself a report (§6.3 loop guard — see IsReportQName);
  • the assembled name would exceed the 255-octet DNS limit, which happens for legitimately deep qnames since reporting adds the agent domain plus four labels of overhead. A name that cannot be encoded must be dropped rather than truncated: a truncated report names the *wrong* zone.

func BuildSVCBRData added in v0.8.33

func BuildSVCBRData(priority uint16, target string, params []SvcParam) ([]byte, error)

BuildSVCBRData assembles SVCB/HTTPS RDATA: a 2-octet priority, an uncompressed target name, and the parameter list.

Parameters are sorted by key before encoding. RFC 9460 §2.2 requires them to appear in strictly increasing key order, and a receiver is entitled to reject a record that violates it — sorting here means a caller cannot produce an invalid record by listing parameters in a natural reading order rather than a numeric one.

A priority of 0 marks AliasMode, in which §2.4.2 forbids any parameters; callers building DDR records always use ServiceMode (priority >= 1).

func DecodeName

func DecodeName(msg []byte, offset int) (string, int, error)

DecodeName reads a domain name from the wire format. It returns the decoded name and the number of bytes consumed from the ORIGINAL position (before any pointer jumps).

func EncodeName

func EncodeName(w *wireWriter, name string) error

EncodeName writes a domain name in wire format with optional compression.

func EncodeNameToBytes added in v0.6.15

func EncodeNameToBytes(name string) ([]byte, error)

EncodeNameToBytes returns the uncompressed wire-format encoding of a domain name: a sequence of length-prefixed labels terminated by a zero byte (e.g. "foo.example.com" → 3 'f' 'o' 'o' 7 'e'...'m' 0). Used for callers that need to produce stand-alone RData bytes — DNAME→CNAME synthesis, hand-built test fixtures — without the message-level compression dictionary that EncodeName depends on. Returns an error on labels longer than 63 octets (RFC 1035 §2.3.4) or full names longer than 255 octets including the root terminator.

func ExtractReportChannel added in v0.8.33

func ExtractReportChannel(e *EDNS0) string

ExtractReportChannel returns the agent domain advertised in a response's Report-Channel option, or "" when the responder did not advertise one (which is the common case — the option is opt-in per zone).

func FormatRData added in v0.8.33

func FormatRData(r ResourceRecord) (string, error)

FormatRData is the BIND master-file presentation encoder for one RR's RDATA. It dispatches on the RR type and returns the textual form ready to be appended after the TYPE column on a zone-file line.

Types Labyrinth does not model as a Go struct (TLSA, LOC, NAPTR, CERT, DHCID, ZONEMD, …) are emitted in RFC 3597 §5 generic form:

TYPE<n> \# <rdlength> <hex>

which is exact round-trip — the parser reads it back to the same RDATA bytes. The hex form is the canonical one BIND itself uses for unknown types, because it does not require the writer to know the type's RDATA grammar.

Types that *are* modelled get their presentation form from the type- specific encoder. Adding a new type means implementing an encoder here and a parser in zonefile_parser.go; the dispatcher is a single switch.

SOA is special-cased: the wire RDATA is a structured tuple, but the BIND form is a parenthesised keyword list with a serial/y/ref/r/exp/min header on the same line:

@ IN SOA ns.example. hostmaster.example. ( 2024010101 7200 3600 1209600 3600 )

The "(..." continuation is what `dnsview` and friends display by default. The writer emits exactly that layout.

func FormatRDataBase64 added in v0.8.33

func FormatRDataBase64(r ResourceRecord) string

FormatRDataBase64 is the unsupported convenience form `BIND` will also accept for unknown types but no other master-file reader guarantees. Kept for operator convenience when re-pasting a record someone gave them as `<base64>`. Provided here so the writer can pick: hex (default, RFC 3597 §5) or base64 (operator preference).

func FormatSOARecord added in v0.8.33

func FormatSOARecord(rec *SOARecord) string

FormatSOARecord is the public entry point for callers that already have a parsed SOARecord (e.g. from a transfer response) and want to render it without going through wire RDATA. Same output format as formatSOA.

func FormatZone added in v0.8.33

func FormatZone(apex string, records []ResourceRecord) ([]byte, error)

FormatZone writes a zone file in BIND master-file format.

The records do not need to be sorted; the writer groups them by owner name. SOA records are emitted first at the apex (the zone's own name as the first Record argument), then NS, then everything else. Within one owner the records are emitted in the order given, except DNSSEC types (DNSKEY, DS, RRSIG, NSEC, NSEC3) which are emitted at the end of the owner block because BIND readers and tooling do not care about the ordering inside an owner but DNSKEY/DS precede RRSIG/NSEC/NSEC3 in DNSSEC-aware tooling.

apex is the zone apex (e.g. "example.com." — the trailing dot is the presentation form). The writer starts the zone with a $TTL directive synthesised from the SOA's minimum TTL (or 86400 if no SOA is present) only if the caller has not supplied a $TTL; we do not synthesise one here because every record carries its own TTL.

FormatZone returns the formatted text. Errors are only returned for RDATA the writer recognises as structurally broken (e.g. an SOA with fewer than five space-separated fields). Unknown RR types are emitted in RFC 3597 §5 generic form; the parser is responsible for round-trip.

func HasNSIDOption added in v0.8.33

func HasNSIDOption(e *EDNS0) bool

HasNSIDOption reports whether the parsed EDNS0 record carries an NSID option — the client's request for the server's identity (RFC 5001 §2.1). The request form has zero-length data; we treat presence alone as the signal, since a client that sent data is still unambiguously asking.

func HasPaddingOption added in v0.6.20

func HasPaddingOption(e *EDNS0) bool

HasPaddingOption reports whether the parsed EDNS0 record carries a PADDING option (used as the client's signal that it wants the response padded — RFC 8467 §4).

func HasTCPKeepaliveOption added in v0.6.20

func HasTCPKeepaliveOption(e *EDNS0) bool

HasTCPKeepaliveOption reports whether the parsed EDNS0 record carries an edns-tcp-keepalive option — the client's signal that it wants to negotiate a TCP idle timeout (RFC 7828 §3.2). Per the RFC the client form has zero-length data; we accept any length and treat the option's presence alone as the signal.

func IsDDRQuery added in v0.8.33

func IsDDRQuery(name string, qtype uint16) bool

IsDDRQuery reports whether a question is the RFC 9462 §4 discovery query. Matching is case-insensitive per RFC 4343 and tolerates a trailing dot.

func IsReportQName added in v0.8.33

func IsReportQName(name string) bool

IsReportQName reports whether a name is itself an error report, i.e. it contains the "_er" bracket label. RFC 9567 §6.3 requires a resolver not to send reports about failures encountered while resolving a report — without that check a broken agent domain would trigger a report about the report, which fails, which triggers another, and the resolver amplifies its own error into a loop against the very server that is already struggling.

func Pack

func Pack(msg *Message, buf []byte) ([]byte, error)

Pack serializes a DNS message to wire format.

func PadRawResponse added in v0.6.20

func PadRawResponse(resp []byte, block int) []byte

PadRawResponse parses a wire-format response and adds an EDNS PADDING option (RFC 7830 §3) sized so that the total wire length becomes the next multiple of `block` bytes (RFC 8467 §4.1 recommends 468). Used by DoT/DoH servers when the client signalled padding interest, so a passive observer cannot infer the queried name from response length alone. Returns the original bytes unchanged on any parse/pack error or when `block <= 0`.

Implementation note: we deliberately mutate the existing OPT RR's RData (rather than rebuilding via BuildOPTWithOptions) so OPT TTL bits — ExtRCODE, Version, DO-flag — are preserved verbatim. The caller's resolver may have set ExtRCODE for BADVERS/BADKEY signalling and we must not lose it.

func ParseA

func ParseA(rdata []byte) (net.IP, error)

ParseA extracts an IPv4 address from A record RDATA.

func ParseAAAA

func ParseAAAA(rdata []byte) (net.IP, error)

ParseAAAA extracts an IPv6 address from AAAA record RDATA.

func ParseCNAME

func ParseCNAME(msg []byte, rdataOffset int) (string, error)

ParseCNAME extracts the canonical name from CNAME record RDATA.

func ParseCookieOption

func ParseCookieOption(data []byte) (clientCookie []byte, serverCookie []byte)

ParseCookieOption parses a DNS Cookie option (RFC 7873, option code 10). Returns the client cookie (8 bytes) and optional server cookie (8-32 bytes).

func ParseDNAME

func ParseDNAME(msg []byte, rdataOffset int) (string, error)

ParseDNAME extracts the delegation name from DNAME record RDATA (RFC 6672).

func ParseEDEOption

func ParseEDEOption(data []byte) (infoCode uint16, extraText string, err error)

ParseEDEOption parses an Extended DNS Error option from EDNS0 option data. Returns the info code and extra text.

func ParseNS

func ParseNS(msg []byte, rdataOffset int) (string, error)

ParseNS extracts the nameserver hostname from NS record RDATA.

func ParsePTR

func ParsePTR(msg []byte, rdataOffset int) (string, error)

ParsePTR extracts the pointer domain name from PTR record RDATA.

func ParseReportChannelOption added in v0.8.33

func ParseReportChannelOption(data []byte) string

ParseReportChannelOption decodes the agent domain from a Report-Channel option's data (RFC 9567 §6.1). The payload is a domain name in uncompressed DNS wire format.

The name is decoded with the ordinary wire decoder, which rejects compression pointers here for free: a pointer must target an offset strictly earlier than its own, and inside a standalone RDATA buffer the earliest possible offset is 0, so no pointer can ever be valid. That matters because the option arrives from an authoritative server we do not trust — a pointer that escaped into the surrounding message buffer would be an out-of-bounds read primitive.

Returns "" for a malformed or empty payload, and for the root name, which cannot be a usable agent domain.

func ParseTXT

func ParseTXT(rdata []byte) ([]string, error)

ParseTXT extracts character strings from TXT record RDATA.

func ParseType added in v0.8.33

func ParseType(s string) (uint16, bool)

ParseType resolves a presentation type name to its numeric value. It accepts both mnemonics ("TLSA") and the RFC 3597 §5 generic form ("TYPE52"), case-insensitively and ignoring surrounding whitespace.

Accepting the generic form matters: it means an operator can inspect a record type this build has never heard of, which is exactly the situation RFC 3597 exists to handle. The resolver already caches such records correctly; without this it just could not show them.

func TSIGSign added in v0.8.33

func TSIGSign(msg []byte, key TSIGKey, timeSigned time.Time, fudge uint16, requestMAC []byte) ([]byte, []byte, error)

TSIGSign appends a TSIG record to a packed DNS message and returns the new message together with the MAC it carries.

requestMAC is empty when signing a request. When signing a *response*, it must be the MAC from the request being answered: RFC 8945 §5.3 folds it into the digest so a response cannot be lifted from one exchange and replayed into another. Omitting it produces a signature the peer will reject, which is the correct failure — but it is silent on this side, so callers signing responses must thread it through.

func TSIGSignStream added in v0.8.33

func TSIGSignStream(msg []byte, key TSIGKey, timeSigned time.Time, fudge uint16, priorMAC []byte, unsigned ...[]byte) ([]byte, []byte, error)

TSIGSignStream signs a subsequent message of a multi-message stream, such as the second and later messages of an AXFR (RFC 8945 §5.3.1).

The digest for these is deliberately different: it covers the *previous* message's MAC, then the message, then only the Time Signed and Fudge fields rather than the full TSIG variables block. That is what chains the messages together — a stream cannot be reordered or have messages dropped from the middle without the chain breaking.

unsigned holds the messages sent without a TSIG since the last signed one, in order. RFC 8945 §5.3.1 lets a sender sign only every Nth message; the next signature then digests those messages too, which is all that authenticates them.

func ToASCII added in v0.8.33

func ToASCII(name string) string

ToASCII converts a domain name to its A-label (Punycode) form.

Names that are already pure ASCII pass through with only case folding, so this is safe to call unconditionally on any name arriving from a human. Conversion failures return the input unchanged rather than an error: the caller is about to look the name up, and a name that cannot be converted is better sent as typed — the resolver will reject it and say why — than replaced by an error message that hides what the operator actually asked for.

func ToUnicode added in v0.8.33

func ToUnicode(name string) string

ToUnicode converts an A-label name back to its Unicode presentation form, for display. Failures return the input unchanged — showing the Punycode is worse than showing Unicode, but far better than showing nothing.

func TruncateIP

func TruncateIP(ip net.IP, prefixLen uint8) net.IP

TruncateIP truncates an IP address to the given prefix length, zeroing out any bits beyond the prefix.

func TypeName added in v0.8.33

func TypeName(t uint16) string

TypeName returns the presentation name for an RR type, falling back to the RFC 3597 §5 generic form "TYPE<n>" for types with no mnemonic. Every display path should use this rather than indexing TypeToString directly, which yields "" for unknown types and renders as a blank column.

Types

type DDRConfig added in v0.8.33

type DDRConfig struct {
	// TargetName is the DNS name clients should connect to. Empty disables
	// DDR entirely: without a name whose certificate covers this resolver's
	// address, every designation we published would fail the client's
	// RFC 9462 §4.2 verification, and we would be spending a round trip to
	// hand out something guaranteed not to work.
	TargetName string

	DoTEnabled bool
	DoTPort    uint16

	DoQEnabled bool
	DoQPort    uint16

	DoHEnabled bool
	DoHPort    uint16
	DoHPath    string
	// DoH3Enabled adds "h3" to the DoH designation's ALPN list.
	DoH3Enabled bool
}

DDRConfig describes which transports to advertise.

func (DDRConfig) Designations added in v0.8.33

func (c DDRConfig) Designations() []DesignatedResolver

Designations turns the config into the endpoint list to publish, ordered by SVCB priority.

The priority ordering encodes a preference, and the one chosen here is DoH first, then DoT, then DoQ. The reasoning is reachability rather than merit: DoH on 443 traverses restrictive middleboxes that drop 853 outright, so a client that tries it first is least likely to fall back to plaintext. DoQ is last only because it is the least widely deployed.

func (DDRConfig) Enabled added in v0.8.33

func (c DDRConfig) Enabled() bool

Enabled reports whether there is anything to advertise. A DDR query gets NODATA rather than a designation when this is false — which is the honest answer, and distinct from NXDOMAIN, since the name does exist.

type DNSKEYRecord

type DNSKEYRecord struct {
	Flags     uint16
	Protocol  uint8
	Algorithm uint8
	PublicKey []byte
}

DNSKEYRecord holds parsed DNSKEY RDATA fields (RFC 4034 Section 2).

func ParseDNSKEY

func ParseDNSKEY(rdata []byte) (*DNSKEYRecord, error)

ParseDNSKEY extracts DNSKEY fields from RDATA.

func (*DNSKEYRecord) IsKSK

func (k *DNSKEYRecord) IsKSK() bool

IsKSK reports whether the key-signing-key flag (SEP bit) is set.

func (*DNSKEYRecord) IsRevoked added in v0.6.13

func (k *DNSKEYRecord) IsRevoked() bool

IsRevoked reports whether the REVOKE flag (RFC 5011 §3, bit 8) is set. A revoked DNSKEY MUST NOT be used to validate signatures or to match DS records — the operator has explicitly disowned that key and the chain must rebuild from the unrevoked siblings. Resolvers that ignore the bit keep accepting signatures from compromised or rolled-out keys.

func (*DNSKEYRecord) IsZoneKey added in v0.6.32

func (k *DNSKEYRecord) IsZoneKey() bool

IsZoneKey reports whether the Zone Key flag (bit 7, value 0x0100) is set. Per RFC 4034 §2.1.1, a DNSKEY whose Zone Key bit is clear holds some other kind of public key (e.g. SIG(0) host keys) and MUST NOT be used to verify RRSIGs that cover RRsets. The validator gates VerifyRRSIG on this.

func (*DNSKEYRecord) KeyTag

func (k *DNSKEYRecord) KeyTag() uint16

KeyTag computes the key tag per RFC 4034 Appendix B.

type DSRecord

type DSRecord struct {
	KeyTag     uint16
	Algorithm  uint8
	DigestType uint8
	Digest     []byte
}

DSRecord holds parsed DS RDATA fields (RFC 4034 Section 5).

func ParseDS

func ParseDS(rdata []byte) (*DSRecord, error)

ParseDS extracts DS fields from RDATA.

type DesignatedResolver added in v0.8.33

type DesignatedResolver struct {
	// Priority is the SVCB priority. Lower is preferred; RFC 9460 §2.4.2
	// reserves 0 for AliasMode, so a designation is always >= 1.
	Priority uint16
	// Target is the DNS name of the endpoint. Its certificate must cover
	// the address the client already has for this resolver, or the client
	// will reject the designation per RFC 9462 §4.2.
	Target string
	// ALPNs are the protocols this endpoint speaks.
	ALPNs []string
	// Port is the endpoint port. Zero omits the parameter, which tells the
	// client to use the default for the ALPN (853 for dot/doq, 443 for
	// h2/h3).
	Port uint16
	// DoHPath is the RFC 9461 §5 URI template, required for h2/h3
	// designations and meaningless otherwise.
	DoHPath string
}

DesignatedResolver describes one encrypted endpoint to advertise.

type ECSOption

type ECSOption struct {
	Family          uint16 // 1=IPv4, 2=IPv6
	SourcePrefixLen uint8
	ScopePrefixLen  uint8
	Address         net.IP
}

ECSOption represents an EDNS Client Subnet option (RFC 7871, option code 8).

func ExtractECSFromOPT added in v0.6.9

func ExtractECSFromOPT(opt *EDNS0) (*ECSOption, error)

ExtractECSFromOPT walks the OPT record options and returns the first EDNS Client Subnet option found, or nil if none is present. Parse errors are reported so callers can FORMERR-fail a malformed option per RFC 7871 §6 (unrecognized FAMILY → SERVFAIL). Missing-ECS is the common case and returns (nil, nil).

func ParseECS

func ParseECS(data []byte) (*ECSOption, error)

ParseECS parses an EDNS Client Subnet option from EDNS0 option data.

func (*ECSOption) CacheKey added in v0.6.9

func (ecs *ECSOption) CacheKey() string

CacheKey returns the canonical string used to key ECS-scoped cache entries: "<address>/<prefix>" where address is truncated to prefix. Returns "" when ecs is nil or SourcePrefixLen is 0 (global scope), so callers can distinguish global from ECS-scoped entries by emptiness.

type EDNS0

type EDNS0 struct {
	UDPSize  uint16
	ExtRCODE uint8
	Version  uint8
	DOFlag   bool
	Options  []EDNSOption
}

EDNS0 represents parsed EDNS0 extension data.

func ParseOPT

func ParseOPT(rr *ResourceRecord) (*EDNS0, error)

ParseOPT extracts EDNS0 information from an OPT pseudo-record.

type EDNSOption

type EDNSOption struct {
	Code uint16
	Data []byte
}

EDNSOption represents a single EDNS0 option.

func BuildDAUOption added in v0.6.14

func BuildDAUOption(algorithms []uint8) EDNSOption

BuildDAUOption constructs the DNSSEC Algorithm Understood option (RFC 6975) carrying the list of DNSKEY/RRSIG algorithm numbers this resolver can validate. Algorithms we deliberately refuse (RSASHA1 when allowSHA1=false, ED448 until we ship a verifier) are omitted — the spec is explicit that DAU advertises ONLY algorithms the resolver will actually accept.

func BuildDHUOption added in v0.6.14

func BuildDHUOption(digests []uint8) EDNSOption

BuildDHUOption is the DS-hash counterpart of BuildDAUOption.

func BuildECS

func BuildECS(ecs *ECSOption) EDNSOption

BuildECS constructs an EDNS Client Subnet option (RFC 7871, option code 8).

func BuildEDEOption

func BuildEDEOption(infoCode uint16, extraText string) EDNSOption

BuildEDEOption constructs an Extended DNS Error option (RFC 8914, option code 15). infoCode is the EDE info code, extraText is an optional UTF-8 string.

func BuildN3UOption added in v0.6.14

func BuildN3UOption(hashes []uint8) EDNSOption

BuildN3UOption is the NSEC3-hash counterpart of BuildDAUOption.

func BuildNSIDOption added in v0.8.33

func BuildNSIDOption(id []byte) EDNSOption

BuildNSIDOption constructs an NSID option (RFC 5001 §2.3) carrying the server's identifier. RFC 5001 §2.3 is explicit that the payload is an opaque byte string with no imposed structure or encoding — so the identifier is emitted verbatim rather than being hex-encoded or null-terminated. Identifiers longer than MaxNSIDLength are truncated.

func BuildPaddingOption added in v0.6.20

func BuildPaddingOption(n int) EDNSOption

BuildPaddingOption constructs an EDNS(0) PADDING option (RFC 7830, option code 12) carrying `n` zero bytes. The option SHOULD be the last option in the OPT RR per RFC 7830 §3 so receivers can ignore trailing zeros without parsing the rest. Only meaningful on encrypted transports (DoT/DoH) — RFC 8467 §6 explicitly disallows padding on plain UDP/TCP since it gives no privacy benefit and wastes bandwidth.

func BuildTCPKeepaliveOption added in v0.6.20

func BuildTCPKeepaliveOption(timeoutUnits100ms uint16) EDNSOption

BuildTCPKeepaliveOption constructs an EDNS(0) edns-tcp-keepalive option (RFC 7828, option code 11). `timeoutUnits100ms` is the idle timeout the server is willing to keep the connection open, expressed in 100-millisecond units (RFC 7828 §3.1). A zero-length data field (length=0) is the client form ("I want to use keepalive"); the server response form MUST carry the 2-byte timeout. This builder produces the server form.

type FlagBuilder

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

FlagBuilder provides a builder pattern for constructing DNS header flags.

func NewFlagBuilder

func NewFlagBuilder() *FlagBuilder

func (*FlagBuilder) Build

func (fb *FlagBuilder) Build() uint16

func (*FlagBuilder) SetAA

func (fb *FlagBuilder) SetAA(v bool) *FlagBuilder

func (*FlagBuilder) SetAD

func (fb *FlagBuilder) SetAD(v bool) *FlagBuilder

func (*FlagBuilder) SetCD

func (fb *FlagBuilder) SetCD(v bool) *FlagBuilder

func (*FlagBuilder) SetOpcode

func (fb *FlagBuilder) SetOpcode(v uint8) *FlagBuilder

func (*FlagBuilder) SetQR

func (fb *FlagBuilder) SetQR(v bool) *FlagBuilder

func (*FlagBuilder) SetRA

func (fb *FlagBuilder) SetRA(v bool) *FlagBuilder

func (*FlagBuilder) SetRCODE

func (fb *FlagBuilder) SetRCODE(v uint8) *FlagBuilder

func (*FlagBuilder) SetRD

func (fb *FlagBuilder) SetRD(v bool) *FlagBuilder

func (*FlagBuilder) SetTC

func (fb *FlagBuilder) SetTC(v bool) *FlagBuilder
type Header struct {
	ID      uint16
	Flags   uint16
	QDCount uint16
	ANCount uint16
	NSCount uint16
	ARCount uint16
}

Header represents the fixed 12-byte DNS message header.

func (*Header) AA

func (h *Header) AA() bool

func (*Header) AD

func (h *Header) AD() bool

func (*Header) CD

func (h *Header) CD() bool

func (*Header) Opcode

func (h *Header) Opcode() uint8

func (*Header) Pack

func (h *Header) Pack(w *wireWriter) error

Pack writes the header to a wireWriter.

func (*Header) QR

func (h *Header) QR() bool

func (*Header) RA

func (h *Header) RA() bool

func (*Header) RCODE

func (h *Header) RCODE() uint8

func (*Header) RD

func (h *Header) RD() bool

func (*Header) TC

func (h *Header) TC() bool

func (*Header) Unpack

func (h *Header) Unpack(r *wireReader) error

Unpack reads the header from a wireReader.

type MXRecord

type MXRecord struct {
	Preference uint16
	Exchange   string
}

MXRecord holds parsed MX RDATA fields.

func ParseMX

func ParseMX(msg []byte, rdataOffset int) (*MXRecord, error)

ParseMX extracts preference and exchange from MX record RDATA.

type Message

type Message struct {
	Header     Header
	Questions  []Question
	Answers    []ResourceRecord
	Authority  []ResourceRecord
	Additional []ResourceRecord
	EDNS0      *EDNS0
	// Raw holds the original wire-format bytes (needed for RDATA decompression)
	Raw []byte
}

Message represents a complete DNS message.

func Unpack

func Unpack(buf []byte) (*Message, error)

Unpack parses a DNS message from wire format.

type NSEC3Record

type NSEC3Record struct {
	HashAlgorithm uint8
	Flags         uint8
	Iterations    uint16
	Salt          []byte
	NextHash      []byte
	TypeBitMaps   []uint16
}

NSEC3Record holds parsed NSEC3 RDATA fields (RFC 5155).

func ParseNSEC3

func ParseNSEC3(rdata []byte) (*NSEC3Record, error)

ParseNSEC3 extracts NSEC3 fields from RDATA.

type NSECRecord

type NSECRecord struct {
	NextDomainName string
	TypeBitMaps    []uint16
}

NSECRecord holds parsed NSEC RDATA fields (RFC 4034 Section 4).

func ParseNSEC

func ParseNSEC(rdata []byte, offset int) (*NSECRecord, error)

ParseNSEC extracts NSEC fields from RDATA. The rdata slice must be self-contained (next domain name not compressed). The offset parameter is unused but kept for API consistency; pass 0.

type Question

type Question struct {
	Name  string
	Type  uint16
	Class uint16
}

Question represents a DNS question entry.

func UnpackQuestion

func UnpackQuestion(msg []byte, offset int) (Question, int, error)

UnpackQuestion decodes a question entry from the wire format.

type RRSIGRecord

type RRSIGRecord struct {
	TypeCovered uint16
	Algorithm   uint8
	Labels      uint8
	OrigTTL     uint32
	Expiration  uint32
	Inception   uint32
	KeyTag      uint16
	SignerName  string
	Signature   []byte
}

RRSIGRecord holds parsed RRSIG RDATA fields (RFC 4034 Section 3).

func ParseRRSIG

func ParseRRSIG(rdata []byte, offset int) (*RRSIGRecord, error)

ParseRRSIG extracts RRSIG fields from RDATA. The rdata slice must be self-contained (signer name not compressed). The offset parameter is unused but kept for API consistency with other name-bearing parsers; pass 0.

type ResolverInfo added in v0.8.33

type ResolverInfo struct {
	// QnameMinimisation reports RFC 9156 QNAME minimisation, published as
	// the bare key "qnamemin" (RFC 9606 §6.1). It is a presence flag, not
	// a key=value pair.
	QnameMinimisation bool
	// ExtendedErrors lists the RFC 8914 EDE codes this resolver may emit
	// for filtered answers, published as "exterr=15,16,17" (§6.2). It tells
	// a client which codes carry a policy meaning here, so a filtered
	// answer can be surfaced to the user as a block rather than a failure.
	ExtendedErrors []uint16
	// InfoURL is a human-readable policy page, published as "infourl=..."
	// (§6.3).
	InfoURL string
}

ResolverInfoKey/Value pairs describe resolver behaviour for RFC 9606 RESINFO. The record shares TXT's wire format: a sequence of length-prefixed character-strings.

type ResourceRecord

type ResourceRecord struct {
	Name     string
	Type     uint16
	Class    uint16
	TTL      uint32
	RDLength uint16
	RData    []byte

	// RDataOffset is the offset of this RR's RDATA in the original wire message.
	// Used by type-specific parsers that need the full message for name decompression.
	RDataOffset int
}

ResourceRecord represents a DNS resource record.

func BuildDDRAnswer added in v0.8.33

func BuildDDRAnswer(cfg DDRConfig) ([]ResourceRecord, error)

BuildDDRAnswer returns the SVCB records answering a `_dns.resolver.arpa` query. An empty slice means NODATA.

func BuildOPT

func BuildOPT(udpSize uint16, doFlag bool) ResourceRecord

BuildOPT creates an OPT pseudo-record for outgoing queries.

func BuildOPTWithOptions

func BuildOPTWithOptions(udpSize uint16, doFlag bool, options []EDNSOption) ResourceRecord

BuildOPTWithOptions creates an OPT pseudo-record with EDNS0 options.

func ParseZone added in v0.8.33

func ParseZone(name string, text []byte) ([]ResourceRecord, error)

ParseZone parses a BIND master-file and returns the records it contains.

name is the file's logical zone name (used for error messages and to validate that the apex is present). It does not have to match the $ORIGIN — the parser will overwrite it if the file sets one explicitly.

The returned slice has records in file order. Owner names are absolute (with trailing dot) and lowercased.

func ReadZone added in v0.8.33

func ReadZone(name string, r io.Reader) ([]ResourceRecord, error)

ReadZone reads a BIND master-file from an io.Reader and returns the records it contains. Convenience wrapper around ParseZone for the common case where the file is on disk or being piped in.

func UnpackRR

func UnpackRR(msg []byte, offset int) (ResourceRecord, int, error)

UnpackRR decodes a resource record from the wire format. For types with compressed domain names in RDATA (NS, CNAME, PTR, MX, SOA, SRV), the names are decompressed during unpack so stored RDATA is self-contained.

type SOARecord

type SOARecord struct {
	MName   string
	RName   string
	Serial  uint32
	Refresh uint32
	Retry   uint32
	Expire  uint32
	Minimum uint32
}

SOARecord holds parsed SOA RDATA fields.

func ParseSOA

func ParseSOA(msg []byte, rdataOffset int) (*SOARecord, error)

ParseSOA extracts all SOA fields from SOA record RDATA.

type SRVRecord

type SRVRecord struct {
	Priority uint16
	Weight   uint16
	Port     uint16
	Target   string
}

SRVRecord holds parsed SRV RDATA fields.

func ParseSRV

func ParseSRV(msg []byte, rdataOffset int) (*SRVRecord, error)

ParseSRV extracts all SRV fields from SRV record RDATA.

type SvcParam added in v0.8.33

type SvcParam struct {
	Key   uint16
	Value []byte
}

SvcParam is one key/value pair in an SVCB record's parameter list.

func ParseSVCBParams added in v0.8.33

func ParseSVCBParams(rdata []byte) ([]SvcParam, error)

ParseSVCBParams reads the parameter list out of SVCB RDATA, skipping the priority and target name. Used by tests and by the dashboard to show what a designation actually advertises.

It is strict about the ordering rule so a malformed record is reported rather than silently half-read.

func SvcParamALPNValue added in v0.8.33

func SvcParamALPNValue(protocols ...string) SvcParam

SvcParamALPNValue encodes an "alpn" parameter value (RFC 9460 §7.1.1): a sequence of length-prefixed protocol identifiers, e.g. {"h2", "h3"}.

The one-octet length prefix is per protocol id, not for the whole list — a detail worth stating because the encoding otherwise looks like it could be a simple concatenation, and a receiver reading a mis-encoded value gets garbage protocol names rather than a parse error.

func SvcParamDoHPathValue added in v0.8.33

func SvcParamDoHPathValue(path string) SvcParam

SvcParamDoHPathValue encodes a "dohpath" parameter (RFC 9461 §5). The value is the raw UTF-8 URI template with no length prefix — the parameter's own length field delimits it.

func SvcParamIPv4HintValue added in v0.8.33

func SvcParamIPv4HintValue(ips []net.IP) SvcParam

SvcParamIPv4HintValue encodes an "ipv4hint" parameter (RFC 9460 §7.3) as a concatenation of 4-octet addresses. Non-IPv4 entries are skipped rather than encoded as something the receiver would misread.

func SvcParamIPv6HintValue added in v0.8.33

func SvcParamIPv6HintValue(ips []net.IP) SvcParam

SvcParamIPv6HintValue encodes an "ipv6hint" parameter (RFC 9460 §7.3) as a concatenation of 16-octet addresses. IPv4 addresses are skipped: an IPv4-mapped IPv6 address here would tell the client to open an IPv6 connection to an address that only exists in v4.

func SvcParamPortValue added in v0.8.33

func SvcParamPortValue(port uint16) SvcParam

SvcParamPortValue encodes a "port" parameter (RFC 9460 §7.2).

type TSIGKey added in v0.8.33

type TSIGKey struct {
	// Name is the key name, which travels as the TSIG record's owner name.
	// Both parties must use the same name; it is how the receiver selects
	// which secret to verify against.
	Name string
	// Algorithm is one of the TSIGHMAC* constants. Empty means
	// DefaultTSIGAlgorithm.
	Algorithm string
	// Secret is the raw shared secret. Configuration usually carries it
	// base64-encoded; decoding happens at the config boundary so a secret
	// never sits in memory in two representations.
	Secret []byte
}

TSIGKey is a shared secret and the algorithm it is used with.

type TSIGRecord added in v0.8.33

type TSIGRecord struct {
	KeyName    string
	Algorithm  string
	TimeSigned uint64 // 48-bit seconds since the Unix epoch
	Fudge      uint16
	MAC        []byte
	OriginalID uint16
	Error      uint16
	OtherData  []byte
}

TSIGRecord is a parsed TSIG RDATA (RFC 8945 §4.2).

func TSIGVerify added in v0.8.33

func TSIGVerify(msg []byte, keyFor func(name string) (TSIGKey, bool), requestMAC []byte, now time.Time) (*TSIGRecord, []byte, error)

TSIGVerify checks the TSIG record on a packed message and returns its MAC, which the caller needs in order to sign the response (or the next message of a multi-message stream).

keyFor resolves a key name to its secret. Taking a lookup function rather than a single key is what lets a server hold several keys and select by the name the client presented — the normal deployment, where each peer has its own secret.

`now` is passed in rather than read from the clock so the fudge-window check is testable; production callers pass time.Now().

func TSIGVerifyStream added in v0.8.33

func TSIGVerifyStream(msg []byte, key TSIGKey, priorMAC []byte, now time.Time, unsigned ...[]byte) (*TSIGRecord, []byte, error)

TSIGVerifyStream is the verification counterpart of TSIGSignStream. unsigned must hold every message received without a TSIG since the last signed one, as received; leaving one out fails verification.

Jump to

Keyboard shortcuts

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