dnssec

package
v0.8.11 Latest Latest
Warning

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

Go to latest
Published: May 28, 2026 License: MIT Imports: 22 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 (
	DefaultAddHoldDown    = 30 * 24 * time.Hour
	DefaultRemoveHoldDown = 30 * 24 * time.Hour
)

Default hold-down timers per RFC 5011 §2.4.1.

"MUST be the greater of the addHoldDownTime (30 days) and the active refresh period (per RFC 5011 §2.3). The default we ship is the 30-day floor, which is the right answer for the root KSK which has a long refresh period anyway."

View Source
const MaxDNSKEYCacheEntries = 50_000

MaxDNSKEYCacheEntries caps the validator's keyCache to bound the memory footprint of an attacker who controls many DNSSEC-signed zones. Each cache entry stores the full DNSKEY RRset for one zone — RSA-2048 keys are 256 bytes of wire format, plus RDATA framing and slice headers ~1 KB per entry in practice — so an attacker driving the resolver to fetch DNSKEYs for distinct zones can pin gigabytes of cache with normal query rates. 50k zones is well above any realistic resolver workload (the top of the DNSSEC- signed namespace plus active deep zones rarely exceeds 10k) and small enough that the worst-case footprint stays bounded. LRU eviction on insert past the cap drops the entry with the oldest fetchedAt — a zone we haven't refreshed in the longest is the right one to lose; if we hit it again it just costs one upstream DNSKEY query to re-populate.

View Source
const MaxNSEC3Iterations = 100

MaxNSEC3Iterations is the hard ceiling on the NSEC3 iteration count this resolver will honour, per RFC 9276 §3.2 (August 2022): "validating resolvers SHOULD return an insecure response when processing NSEC3 records with iterations larger than 100." High iteration counts give no real cryptographic benefit but let an attacker amplify CPU cost per query (NSEC3 hash-walk DoS) and slow down legitimate validation. Aligns with BIND 9.18+ and Unbound 1.16+ defaults.

View Source
const MaxNTAEntries = 10_000

MaxNTAEntries caps the size of an NTAStore. /api/dnssec/nta POST is authenticated, but a runaway operator script or a malicious admin with valid credentials could otherwise blow up the in-memory store (consulted on every DNSSEC-validated query through Match) by spamming distinct zone names. Real operator NTA lists are tiny (handful — RFC 7646 §6 explicitly warns NTAs are an exceptional measure, not a normal operating mode). 10k is well above any plausible legitimate workload and tiny enough that the entire map fits in CPU cache.

Variables

View Source
var (
	// ErrCDSEmpty — empty input passed to a CDS/CDNSKEY parser. Distinct
	// from malformed so callers can choose to log differently.
	ErrCDSEmpty = errors.New("dnssec: CDS/CDNSKEY RRset is empty")
	// ErrCDSMalformed — input violates RFC 7344 / 8078 structural rules.
	// The CDSUpdate returned alongside is always Action=Unknown.
	ErrCDSMalformed = errors.New("dnssec: CDS/CDNSKEY RRset malformed")
)
View Source
var ErrNTAStoreFull = errors.New("NTA store is full")

ErrNTAStoreFull is returned by Add when the store has reached MaxNTAEntries. The /api/dnssec/nta admin handler surfaces this as 507 Insufficient Storage so the operator sees the cap rather than a silent no-op.

View Source
var RootDSRecords = []dns.DSRecord{
	{
		KeyTag:     20326,
		Algorithm:  dns.AlgRSASHA256,
		DigestType: dns.DigestSHA256,
		Digest:     hexDecode("E06D44B80B8F1D39A95C0B0D7C65D08458E880409BBC683457104237C7F8EC8D"),
	},
	{
		KeyTag:     38696,
		Algorithm:  dns.AlgRSASHA256,
		DigestType: dns.DigestSHA256,
		Digest:     hexDecode("683D2D0ACB8C9B712A1948B27F741219298D0A450D612C483AF444A4C0FB2B16"),
	},
}

RootDSRecords contains the trust anchors for the DNS root zone. These are the well-known IANA root KSK trust anchors used to anchor the DNSSEC chain of trust.

Key tag 20326: Root KSK (2017), RSA/SHA-256 Key tag 38696: Root KSK (2024), RSA/SHA-256 — added per audit H-7 to avoid a forced validation outage at the next root KSK rollover (the resolver intentionally bypasses fallback on DNSSEC failure, so missing the new anchor would take the entire resolver dark). See: https://data.iana.org/root-anchors/root-anchors.xml

Functions

func ComputeNSEC3Hash

func ComputeNSEC3Hash(name string, algorithm uint8, iterations uint16, salt []byte) ([]byte, error)

ComputeNSEC3Hash computes the NSEC3 hash for a domain name. Algorithm 1 is SHA-1 (the only defined algorithm per RFC 5155). The result is the raw hash bytes (not base32-encoded).

func HasType

func HasType(nsec3 *dns.NSEC3Record, rrtype uint16) bool

HasType checks whether the NSEC3 type bitmap includes the given RR type.

func MaxRRSIGVerifyAttempts added in v0.7.19

func MaxRRSIGVerifyAttempts() int

MaxRRSIGVerifyAttempts exposes the verify-cap value for the observability UI. Operators reading the DNSSEC page can confirm the safety-net value without having to grep the source.

func MaxTrustChainDepth added in v0.7.19

func MaxTrustChainDepth() int

MaxTrustChainDepth exposes the chain-depth cap value (see the constant above). Surfaced through /api/dnssec so the UI's safety- net panel can reflect the value the resolver is actually enforcing.

func NSEC3HashToString

func NSEC3HashToString(hash []byte) string

NSEC3HashToString encodes raw NSEC3 hash bytes to the base32hex string representation used in NSEC3 owner names.

func VerifyClosestEncloser

func VerifyClosestEncloser(qname string, nsec3Records []*dns.NSEC3Record) (string, error)

VerifyClosestEncloser finds the closest encloser for the queried name by looking for an NSEC3 record whose hash matches a parent of qname. Returns the closest encloser name if found.

func VerifyDS

func VerifyDS(dnskey *dns.DNSKEYRecord, ds *dns.DSRecord, ownerName string) bool

VerifyDS checks if a DNSKEY matches a DS record by computing the DS digest over the canonical owner name + DNSKEY RDATA and comparing it to the DS digest. The ownerName is the domain name that owns the DNSKEY (e.g., "example.com.").

func VerifyNSEC3Denial

func VerifyNSEC3Denial(qname string, nsec3Records []*dns.NSEC3Record) (bool, error)

VerifyNSEC3Denial verifies that a queried name falls within an NSEC3 hash gap, proving the name does not exist (NXDOMAIN) or the type does not exist (NODATA). Returns true if the denial proof is valid.

func VerifyNSEC3Denial5155 added in v0.6.12

func VerifyNSEC3Denial5155(qname string, qtype uint16, rcode uint8, records []NSEC3RecordWithOwner) (bool, error)

VerifyNSEC3Denial5155 verifies a NXDOMAIN or NODATA denial proof per RFC 5155 §8.4–8.7 and RFC 6840 §4.8. Unlike the loose VerifyNSEC3DenialFull (which only checks that some NSEC3 covers H(qname) and is correct only for the next-closer-coverage step in isolation), this function requires the full three-record proof for NXDOMAIN:

  1. Closest-encloser MATCH: an NSEC3 whose owner hash equals H(CE), where CE is the deepest ancestor of qname proven to exist.
  2. Next-closer COVER: an NSEC3 whose interval contains H(next_closer), where next_closer is CE's immediate child label on the path to qname.
  3. Wildcard-at-CE COVER: an NSEC3 whose interval contains H(*.CE), proving that the synthetic wildcard does not exist either.

For NODATA the function accepts either:

  • Direct NODATA: an NSEC3 matching H(qname) whose type bitmap omits qtype (and CNAME).
  • Wildcard NODATA: CE-match + NC-cover + wildcard-MATCH whose bitmap omits qtype.

Opt-out semantics (RFC 5155 §6): if the next-closer-covering NSEC3 has the opt-out flag set, the next closer name could be an unsigned delegation, and the NXDOMAIN proof is therefore inconclusive (return false). A caller receiving false here treats the response as Bogus (signed denial without a verifiable proof) rather than Secure NXDOMAIN.

Without this strict layering, a forged single covering NSEC3 over H(qname) can fake NXDOMAIN for any name whose true closest-encloser differs from what the attacker claims — exactly the proof-substitution attack RFC 5155 is designed to prevent.

func VerifyNSEC3DenialDSAbsent added in v0.6.12

func VerifyNSEC3DenialDSAbsent(childZone string, records []NSEC3RecordWithOwner) (bool, error)

VerifyNSEC3DenialDSAbsent verifies an NSEC3 proof that the queried zone has no DS record at its parent — required for authenticating "insecure delegation" responses (RFC 5155 §10.4). Three forms are accepted:

  • NSEC3 at H(childZone) with DS absent from the bitmap (and NS present, so we're at a real delegation point rather than a synthesized empty name).
  • Opt-out next-closer-cover: the NC-covering NSEC3 has the opt-out flag set, asserting that the child is an unsigned delegation that the parent zone has not enumerated.

The function returns true only when one of these proofs holds. A caller that gets `true` from this function may safely treat the delegation as Insecure; `false` means the denial of DS is unproven and the response must NOT downgrade a previously-Secure chain to Insecure.

func VerifyNSEC3DenialFull

func VerifyNSEC3DenialFull(qname string, nsec3Records []NSEC3RecordWithOwner) (bool, error)

VerifyNSEC3DenialFull verifies NSEC3 denial with full owner hash information. This is the proper implementation that checks hash ranges correctly.

func VerifyNSECDenial added in v0.6.4

func VerifyNSECDenial(qname string, qtype uint16, rcode uint8, records []NSECRecordWithOwner) (bool, error)

VerifyNSECDenial verifies an NSEC denial proof for a NODATA or NXDOMAIN response. Returns true if the records authenticate the negative answer.

Three forms are accepted:

  1. NODATA (RFC 4035 §5.4) — an NSEC at owner == qname whose type bitmap does not include qtype or CNAME. A delegation-style NSEC (NS bit set without SOA) is rejected: it belongs to the parent zone and proves nothing about types served at the child.

  2. NXDOMAIN — covering NSEC for qname plus covering NSEC for the wildcard `*.closest_encloser` derived from the qname-covering NSEC. This is the standard two-NSEC name-error proof.

  3. Compact denial of existence (draft-ietf-dnsop-compact-denial-of-existence, widely deployed by Cloudflare as "black lies"). For an NXDOMAIN response the auth server returns an NSEC at owner == qname whose bitmap excludes CNAME and DNAME, asserting the name has no useful records. Treated as a valid NXDOMAIN proof: the RCODE is signer-authenticated via the SOA RRSIG and the NSEC bitmap denies every type the client could have wanted.

func VerifyRRSIG

func VerifyRRSIG(rrset []dns.ResourceRecord, rrsig *dns.RRSIGRecord, dnskey *dns.DNSKEYRecord) error

VerifyRRSIG verifies an RRSIG signature over an RRset using a DNSKEY. It builds the signed data (RRSIG RDATA without signature + canonical RRset) and verifies the cryptographic signature according to the algorithm.

Types

type AnchorCandidate added in v0.6.43

type AnchorCandidate struct {
	// Owner is the zone the KSK belongs to (typically "." for the
	// root). Pinned to the entry so a multi-zone deployment can
	// share one TrustAnchorStore.
	Owner string
	// KeyTag is the RFC 4034 App B.1 key tag of the DNSKEY.
	KeyTag uint16
	// Algorithm + Flags are pinned so a refresh that returned a
	// different DNSKEY at the same key tag (collision or attacker
	// substitution) is treated as a different candidate.
	Algorithm uint8
	Flags     uint16
	// PublicKeyHash is SHA-256 over the DNSKEY RDATA wire form. We
	// keep a hash rather than the raw key so the store is cheap to
	// serialise and so equality checks don't need to deal with
	// variable-length wire bytes.
	PublicKeyHash [32]byte

	State TrustAnchorState
	// FirstSeen is when this candidate first appeared in a refresh.
	// AddPending → Valid transition fires when wall-time exceeds
	// FirstSeen + AddHoldDown AND the candidate was still observed
	// in the latest refresh.
	FirstSeen time.Time
	// MissingSince is set when the candidate transitions to Missing.
	// Zero in any other state. Missing → Removed transition fires
	// when wall-time exceeds MissingSince + RemoveHoldDown AND the
	// candidate was NOT in the latest refresh.
	MissingSince time.Time
	// RevokedAt is when the REVOKE bit was first observed. Once
	// non-zero, the candidate is in TAStateRevoked permanently.
	RevokedAt time.Time
	// LastObserved is the time of the most recent refresh that
	// included this candidate.
	LastObserved time.Time
}

AnchorCandidate is one KSK tracked by the lifecycle machine.

type CDSUpdate added in v0.6.43

type CDSUpdate struct {
	// Action says what the RRset signals (publish, delete, unknown).
	Action CDSUpdateAction
	// DSRecords is the list of DS records carried in the CDS RRset
	// (one DSRecord per CDS RR). For CDSActionDelete this still
	// contains the single Algorithm=0 sentinel record so the caller
	// can log exactly what was received.
	DSRecords []*dns.DSRecord
}

CDSUpdate is the parsed-and-classified view of a CDS RRset.

func ParseCDSRRset added in v0.6.43

func ParseCDSRRset(rrs []dns.ResourceRecord) (CDSUpdate, error)

ParseCDSRRset extracts and classifies the action signalled by a CDS RRset. The owner of the records is not validated here — the caller must ensure they came from the apex of the child zone in question.

Wire format: CDS RDATA == DS RDATA (RFC 7344 §3.1), so ParseDS is reused directly.

Errors:

  • errors.Is(err, ErrCDSEmpty) — empty input (no records).
  • errors.Is(err, ErrCDSMalformed) — at least one CDS RR failed to parse as DS wire form. The Action returned alongside is CDSActionUnknown; well-formed siblings are NOT silently honoured because RFC 8078 §3.1 makes the RRset a single atomic intent — partial trust would defeat the purpose.

func (CDSUpdate) CDSMatchesParentDS added in v0.6.43

func (u CDSUpdate) CDSMatchesParentDS(parentDS []*dns.DSRecord) bool

CDSMatchesParentDS reports whether the CDSUpdate's DS records are a SUPERSET of the parent's current DS RRset under structural equality (KeyTag + Algorithm + DigestType + Digest bytes). A "publish" CDS whose set equals the parent's existing DS is a no-op — useful to distinguish from a real rollover when surfacing the signal to an operator.

Returns false unconditionally for CDSActionDelete (the parent's DS is supposed to disappear, not be matched).

type CDSUpdateAction added in v0.6.43

type CDSUpdateAction int

CDSUpdateAction is the action a CDS RRset is signalling.

const (
	// CDSActionUnknown — RRset is malformed or empty.
	CDSActionUnknown CDSUpdateAction = iota
	// CDSActionPublish — the child wants the parent to publish the DS
	// records carried in the CDS RRset. May be a no-op (matches the
	// existing DS), a key add, a key remove, or an algorithm rollover.
	CDSActionPublish
	// CDSActionDelete — RFC 8078 §4: a single CDS record with
	// Algorithm = 0 means "delete the DS, take this delegation
	// insecure". This is the canonical signal for a child operator
	// who wants to take their zone out of DNSSEC entirely.
	CDSActionDelete
)

func ParseCDNSKEYRRset added in v0.6.43

func ParseCDNSKEYRRset(rrs []dns.ResourceRecord) ([]*dns.DNSKEYRecord, CDSUpdateAction, error)

ParseCDNSKEYRRset is the dual of ParseCDSRRset for CDNSKEY records. The classification logic mirrors RFC 8078 §4: a single record with Algorithm=0 (and protocol=3, flags=0 per §4) means "delete". Otherwise the records carry the child's desired DNSKEY set for the next delegation. Wire format == DNSKEY (RFC 7344 §3.2).

func (CDSUpdateAction) String added in v0.6.43

func (a CDSUpdateAction) String() string

String returns a stable token for logs/metrics.

type FailureReason added in v0.6.15

type FailureReason int

FailureReason classifies why DNSSEC validation produced a non-Secure verdict. Designed to be mapped by callers to RFC 8914 Extended DNS Error (EDE) info codes so that clients and operators can distinguish, for example, "the auth's signature expired" (operational issue on the auth side) from "we saw a cryptographically forged signature" (security event). Without this distinction every Bogus collapses into the generic EDE 6 and the cause is lost.

Suggested EDE mapping (RFC 8914 §4):

ReasonSignatureExpired      → EDE  7 (Signature Expired)
ReasonSignatureNotYetValid  → EDE  8 (Signature Not Yet Valid)
ReasonDNSKEYMissing         → EDE  9 (DNSKEY Missing)
ReasonNoMatchingDNSKEY      → EDE  9 (DNSKEY Missing — no key by tag/alg)
ReasonRRSIGsMissing         → EDE 10 (RRSIGs Missing)
ReasonUnsupportedDNSKEYAlgo → EDE  1 (Unsupported DNSKEY Algorithm)
ReasonUnsupportedDSDigest   → EDE  2 (Unsupported DS Digest Type)
ReasonOther                 → EDE  6 (DNSSEC Bogus, generic)
const (
	// ReasonNone means no specific failure reason was recorded (verdict
	// is Secure, or the validator didn't tag a specific cause).
	ReasonNone FailureReason = iota
	// ReasonSignatureExpired — an RRSIG's expiration is in the past.
	ReasonSignatureExpired
	// ReasonSignatureNotYetValid — an RRSIG's inception is in the future.
	ReasonSignatureNotYetValid
	// ReasonDNSKEYMissing — no DNSKEY rrset could be fetched for the signer.
	ReasonDNSKEYMissing
	// ReasonNoMatchingDNSKEY — DNSKEYs were fetched but none matched the
	// RRSIG's key-tag/algorithm.
	ReasonNoMatchingDNSKEY
	// ReasonRRSIGsMissing — the response is in a signed zone but lacks RRSIG.
	ReasonRRSIGsMissing
	// ReasonUnsupportedDNSKEYAlgo — every RRSIG used an algorithm this
	// resolver cannot verify.
	ReasonUnsupportedDNSKEYAlgo
	// ReasonUnsupportedDSDigest — every DS digest type was unsupported.
	ReasonUnsupportedDSDigest
	// ReasonOther — cryptographic verify failed, bailiwick failed, or some
	// other Bogus cause the validator has not classified further.
	ReasonOther
	// ReasonNTAOverride — a Negative Trust Anchor (RFC 7646) is active for
	// the queried zone subtree, suppressing the validation verdict to
	// Insecure regardless of what the chain would have produced. The
	// operator installed the NTA explicitly; this is the audit trail.
	ReasonNTAOverride
)

func FailureReasonFromString added in v0.6.15

func FailureReasonFromString(s string) FailureReason

FailureReasonFromString is the inverse of FailureReason.String. Returns ReasonNone for the empty string and ReasonOther for unrecognised tokens (we'd rather fall through to the generic EDE 6 than drop the signal).

func (FailureReason) String added in v0.6.15

func (r FailureReason) String() string

String returns a stable token for the reason — used in logs, metrics, and ResolveResult.DNSSECReason so the value crosses package boundaries without leaking the int representation.

type NSEC3RecordWithOwner

type NSEC3RecordWithOwner struct {
	dns.NSEC3Record
	OwnerHash []byte // raw hash bytes from the NSEC3 RR owner name
}

NSEC3RecordWithOwner extends NSEC3Record with the owner hash for proper range checking in denial proofs.

type NSECRecordWithOwner added in v0.6.4

type NSECRecordWithOwner struct {
	dns.NSECRecord
	OwnerName string
}

NSECRecordWithOwner pairs a parsed NSEC RDATA with the owner name from the resource record. The owner is required for both canonical range coverage checks and NODATA proofs (which compare owner against qname).

type NTAStore added in v0.6.42

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

NTAStore is a thread-safe collection of negative trust anchors. Construct via NewNTAStore. The zero value is NOT ready for use — callers must use the constructor so the internal map is allocated.

func LoadNTAStoreFromStrings added in v0.6.42

func LoadNTAStoreFromStrings(entries []string) (*NTAStore, []string)

LoadNTAStoreFromStrings builds a store from operator config lines of the form "<zone>|<RFC3339-expiry>|<reason>". Empty lines are skipped. Lines that fail to parse (bad format, unparseable timestamp, expiry already past) are returned in the second result so the caller can log them but the store remains usable with the entries that did parse. Returns a non-nil store even on total parse failure.

func NewNTAStore added in v0.6.42

func NewNTAStore() *NTAStore

NewNTAStore returns an empty store backed by the wall clock.

func (*NTAStore) Add added in v0.6.42

func (s *NTAStore) Add(zone string, expiry time.Time, reason string) error

Add installs an NTA for the given zone. If an NTA already exists for the same zone it is replaced (typical "extend or shorten the window" operator action). Expiry MUST be in the future at the moment of the call; an Expiry already in the past is silently ignored — the caller should detect this and surface an error if it matters.

Returns ErrNTAStoreFull when the store is at MaxNTAEntries capacity and the call would create a NEW entry (replacements of existing zones continue to succeed at the cap because they do not grow the map). nil on success, including the silent no-ops for empty zone names and past-expiry entries (those are not error states).

func (*NTAStore) Cleanup added in v0.6.42

func (s *NTAStore) Cleanup() int

Cleanup removes expired NTAs from the store. Returns the number of entries removed. Safe to call on a schedule (e.g. once per minute) from a background goroutine.

func (*NTAStore) List added in v0.6.42

func (s *NTAStore) List() []NegativeTrustAnchor

List returns a snapshot of all currently-stored NTAs (active OR expired — for operator-facing UI it is useful to surface expired entries until Cleanup runs). Order is not specified.

func (*NTAStore) Match added in v0.6.42

func (s *NTAStore) Match(qname string) (NegativeTrustAnchor, bool)

Match reports whether the given qname is covered by any active (unexpired) NTA. The walk is suffix-based: the NTA at `example.test` matches `example.test`, `foo.example.test`, and so on, but NOT `other.test`. Cousins outside the NTA subtree always fall through to normal validation.

Expired entries are treated as absent; they are not eagerly evicted here (that would require a write lock on the hot path). Use Cleanup() periodically to reclaim memory.

func (*NTAStore) Remove added in v0.6.42

func (s *NTAStore) Remove(zone string) bool

Remove deletes the NTA for the given zone. No-op if the zone is not covered. Returns true iff an entry was actually removed.

func (*NTAStore) SetClock added in v0.6.42

func (s *NTAStore) SetClock(fn func() time.Time)

SetClock replaces the store's clock for tests. Not safe to call concurrently with Match — wire it before publishing the store.

type NegativeTrustAnchor added in v0.6.42

type NegativeTrustAnchor struct {
	// Zone is the apex name of the zone for which validation is
	// suppressed. Always stored normalized (lowercase, trailing dot).
	Zone string

	// Expiry is the wall-clock time after which this NTA is treated
	// as removed. RFC 7646 §6 requires a bounded lifetime.
	Expiry time.Time

	// Reason is an operator-supplied free-text note. Surfaced via the
	// observability API so the operator can later answer "why did I
	// add this NTA". Not used by the matcher.
	Reason string
}

NegativeTrustAnchor (NTA, RFC 7646) is an operator-installed override that suppresses DNSSEC validation for a specific zone subtree for a bounded time window.

Motivation: a major TLD or a frequently-used domain misconfigures its signatures (expired RRSIG, broken DS rollover, KSK lost). Every validating resolver in front of that zone goes SERVFAIL. The operator — who knows the zone is broken but the operator of the broken zone has not yet fixed it — wants to keep their users working without disabling DNSSEC globally. RFC 7646 §1 defines an NTA as exactly that: a per-zone, time-bounded local override that downgrades validation to Insecure for matching qnames.

Safety design:

  • NTAs are bounded by expiry. RFC 7646 §6 stresses that NTAs MUST NOT be open-ended; an entry past its expiry is treated as removed. The store enforces this on every Match call.
  • The expiry is operator-set (no implicit duration), so the operational team takes the explicit decision of how long to tolerate the broken zone.
  • Match uses strict suffix semantics: an NTA at `example.test` covers `example.test` itself and any descendant (`foo.example.test`, `bar.foo.example.test`), but NOT sibling zones like `other.test`. This matches the bailiwick rule used everywhere else in the validator.

Match is read-side hot path (every DNSSEC-validated query passes through it), so the store uses RWMutex with the read path under RLock only.

type Querier

type Querier interface {
	// QueryDNSSEC sends a DNS query with the DO (DNSSEC OK) bit set
	// and returns the response.
	QueryDNSSEC(name string, qtype uint16, qclass uint16) (*dns.Message, error)
}

Querier is the interface the validator uses to fetch DNSKEY and DS records needed for DNSSEC chain-of-trust validation.

type TrustAnchorState added in v0.6.43

type TrustAnchorState int

TrustAnchorState is the lifecycle position of a KSK candidate.

const (
	// TAStateAddPending — observed but the add hold-down has not elapsed.
	// MUST NOT be used to validate signatures yet.
	TAStateAddPending TrustAnchorState = iota
	// TAStateValid — passed the add hold-down and is currently
	// published in the parent's DNSKEY RRset. Use to validate.
	TAStateValid
	// TAStateMissing — was Valid, now absent from the RRset. The
	// remove hold-down is counting down. We KEEP using this anchor
	// for validation during the hold-down — RFC 5011 §2.2: "an
	// anchor that has not been formally revoked SHOULD continue to
	// be used until the remove hold-down timer expires".
	TAStateMissing
	// TAStateRemoved — remove hold-down elapsed without the key
	// reappearing. No longer a usable trust anchor. We keep the
	// entry in the store so a future reappearance restarts the
	// AddPending timer rather than instantly trusting it.
	TAStateRemoved
	// TAStateRevoked — RFC 5011 §2.1: the operator published the
	// key with the REVOKE bit set. Immediate transition; bypasses
	// hold-down timers. Never trust this key again.
	TAStateRevoked
)

func (TrustAnchorState) String added in v0.6.43

func (s TrustAnchorState) String() string

String returns a stable token for logs and the observability API.

type TrustAnchorStore added in v0.6.43

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

TrustAnchorStore is the RFC 5011 lifecycle machine. Safe for concurrent use. Construct via NewTrustAnchorStore.

func NewTrustAnchorStore added in v0.6.43

func NewTrustAnchorStore() *TrustAnchorStore

NewTrustAnchorStore returns an empty store with the RFC defaults.

func (*TrustAnchorStore) All added in v0.6.43

func (s *TrustAnchorStore) All() []AnchorCandidate

All returns every tracked candidate regardless of state. Used by the operator-facing UI to surface the full lifecycle picture.

func (*TrustAnchorStore) SetClock added in v0.6.43

func (s *TrustAnchorStore) SetClock(fn func() time.Time)

SetClock injects a mocked clock for tests.

func (*TrustAnchorStore) SetHoldDowns added in v0.6.43

func (s *TrustAnchorStore) SetHoldDowns(addHold, removeHold time.Duration)

SetHoldDowns overrides the default RFC timers. Tests use this to shrink the 30-day windows to milliseconds. Not safe to call concurrently with TrackRefresh — wire it before publication.

func (*TrustAnchorStore) TrackRefresh added in v0.6.43

func (s *TrustAnchorStore) TrackRefresh(owner string, dnskeys []*dns.DNSKEYRecord)

TrackRefresh processes one refresh of the published DNSKEY RRset at the given owner zone. It updates the lifecycle state of every candidate (existing + newly-observed):

  • A new candidate enters AddPending with FirstSeen = now.
  • An AddPending candidate observed again has its observation timestamp refreshed; if the elapsed time since FirstSeen >= addHoldDown, transitions to Valid.
  • A Valid candidate observed again stays Valid (LastObserved updated).
  • A Valid candidate absent from THIS refresh transitions to Missing (MissingSince = now). It REMAINS usable during the remove hold-down.
  • A Missing candidate observed again resurrects to Valid.
  • A Missing candidate still absent and now past MissingSince + removeHoldDown transitions to Removed.
  • Any candidate seen with the REVOKE bit set transitions to Revoked immediately.
  • A Revoked or Removed candidate that reappears as a fresh DNSKEY restarts at AddPending (RFC 5011 §2.1: a once-revoked key never bypasses hold-down again).

The caller passes the DNSKEY records from the refresh. The store recomputes the canonical (KeyTag, Algorithm, hash) tuple from each.

func (*TrustAnchorStore) ValidAnchors added in v0.6.43

func (s *TrustAnchorStore) ValidAnchors() []AnchorCandidate

ValidAnchors returns the candidates currently usable for chain validation: Valid + Missing (the latter still in remove hold-down per RFC 5011 §2.2).

type ValidationResult

type ValidationResult int

ValidationResult represents the outcome of DNSSEC validation.

const (
	// Secure means all signatures validated and the chain of trust is intact.
	Secure ValidationResult = iota
	// Insecure means the zone does not have DNSSEC (no RRSIG/DS records).
	Insecure
	// Bogus means signature validation failed - the response cannot be trusted.
	Bogus
	// Indeterminate means validation could not be completed (e.g., missing keys).
	Indeterminate
)

func (ValidationResult) String

func (v ValidationResult) String() string

String returns a human-readable name for the validation result.

type ValidationStep added in v0.6.7

type ValidationStep struct {
	Stage       string // "skip-weak", "skip-unsupported", "no-rrset", "expired", "not-yet", "out-of-bailiwick", "no-dnskey", "no-matching-key", "verify-failed", "verify-ok", "trust-chain"
	Signer      string
	Owner       string
	KeyTag      uint16
	Algorithm   uint8
	TypeCovered uint16
	Labels      uint8
	Outcome     string // "ok", "bogus", "insecure", "indeterminate", "skipped"
	Detail      string
}

ValidationStep captures one RRSIG-attempt outcome inside a validation pass. It is produced by ValidateResponseDetailed and exposed to diagnostic tools (the DNS lookup trace UI) so an operator can see exactly which signature the validator considered, what it covered, and why it was accepted or rejected. Plain ValidateResponse callers do not pay for this — they get the same single verdict as before.

type Validator

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

Validator performs DNSSEC signature verification and trust chain validation.

func NewValidator

func NewValidator(querier Querier, logger *slog.Logger) *Validator

NewValidator creates a new DNSSEC Validator that uses the given Querier to fetch DNSKEY/DS records and the root trust anchors for chain validation.

func (*Validator) AllowSHA1 added in v0.6.2

func (v *Validator) AllowSHA1(allow bool)

AllowSHA1 toggles acceptance of RSASHA1 RRSIGs and SHA1 DS digests. When false (the default), responses that depend on SHA1 are treated as insecure (as if the zone published no signatures we can validate).

func (*Validator) GetOrCreateNTAStore added in v0.7.59

func (v *Validator) GetOrCreateNTAStore() *NTAStore

GetOrCreateNTAStore returns the configured NTA store, creating an empty one and wiring it in atomically if none is set. Safe to call from multiple goroutines: the first caller wins the CAS, losers observe the winner's store. This closes the lazy-init TOCTOU on the /api/dnssec/nta admin handler where two concurrent POSTs could each create a fresh store, the loser's store.Add would write to an orphaned store, and the NTA would silently never take effect.

func (*Validator) NTAMatches added in v0.6.42

func (v *Validator) NTAMatches() int64

NTAMatches reports the cumulative count of validations short- circuited by an NTA match. Surfaced via /api/stats so operators can see whether an NTA is actually doing anything.

func (*Validator) NTAStore added in v0.6.42

func (v *Validator) NTAStore() *NTAStore

NTAStore returns the configured store, or nil if none is wired. Operator-facing UI reads from here.

func (*Validator) SHA1Allowed added in v0.6.14

func (v *Validator) SHA1Allowed() bool

SHA1Allowed reports the current allowSHA1 setting. Used by callers that advertise their accepted primitives via RFC 6975 DAU/DHU options — the advertised list must match what the validator will actually accept.

func (*Validator) SetNTAStore added in v0.6.42

func (v *Validator) SetNTAStore(store *NTAStore)

SetNTAStore wires a Negative Trust Anchor (RFC 7646) registry into the validator. Pass nil to disable NTA enforcement. Once set, every ValidateResponse call consults the store first; matching qnames are short-circuited to Insecure with ReasonNTAOverride before any chain work runs.

func (*Validator) ValidateResponse

func (v *Validator) ValidateResponse(response *dns.Message, qname string, qtype uint16) ValidationResult

ValidateResponse validates DNSSEC signatures in a DNS response. It checks RRSIG records in the answer section and validates the trust chain from the signer back to the root trust anchors. For NXDOMAIN/NODATA responses, it also validates NSEC3 proofs.

func (*Validator) ValidateResponseDetailed added in v0.6.7

func (v *Validator) ValidateResponseDetailed(response *dns.Message, qname string, qtype uint16) (ValidationResult, []ValidationStep)

ValidateResponseDetailed returns the same verdict as ValidateResponse plus a per-RRSIG step log for diagnostic UIs. Each step records the algorithm, key tag, signer, type covered, labels, and outcome so a human can see why the validator settled on Secure / Insecure / Bogus / Indeterminate.

Plain ValidateResponse callers do not pay for this — they get the same single verdict and no allocated step slice.

func (*Validator) ValidateResponseWithReason added in v0.6.15

func (v *Validator) ValidateResponseWithReason(response *dns.Message, qname string, qtype uint16) (ValidationResult, FailureReason)

ValidateResponseWithReason returns the same verdict as ValidateResponse plus a FailureReason that classifies why a Bogus / Indeterminate verdict was reached. Callers can map the reason to an RFC 8914 EDE info code so that "RRSIG expired" and "no DNSKEY by key tag" don't collapse into the generic EDE 6. For Secure verdicts the reason is ReasonNone.

Like ValidateResponse, this path does not allocate per-RRSIG steps.

Jump to

Keyboard shortcuts

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