Full Toolkit for Next-Level Domain Analysis
Verify DNSKEY signatures along the DNSSEC chain 🔗✍️ (#112)
Felix Wotschofsky35f448509adb
diff --git a/app/(landing)/dnssec/page.tsx b/app/(landing)/dnssec/page.tsxindex 1e82402..13da305 100644--- a/app/(landing)/dnssec/page.tsx+++ b/app/(landing)/dnssec/page.tsx@@ -9,9 +9,9 @@ import { TrustSection } from '../_components/trust-section';export const revalidate = 86400;export const metadata: Metadata = {- title: 'DNSSEC DS Chain Lookup',+ title: 'DNSSEC Lookup',openGraph: {- title: 'DNSSEC DS Chain Lookup',+ title: 'DNSSEC Lookup',url: '/dnssec',},alternates: { canonical: '/dnssec' },@@ -24,14 +24,14 @@ const DnssecLandingPage: FC = () => (<div className="flex min-h-[40vh] flex-col justify-center pt-24 pb-12"><section><h1 className="mb-16 scroll-m-20 text-center text-2xl font-semibold tracking-tight sm:text-3xl">- Check the DNSSEC DS chain for any domain+ Check the DNSSEC chain of trust for any domain</h1><div className="mx-auto w-full max-w-2xl"><SearchForm subpage="dnssec" autofocus /></div><p className="mt-4 mb-20 text-center text-sm/6 text-zinc-500 dark:text-zinc-400">- Follow DS digest links from the IANA root anchors to the name you- enter. This is not full DNSSEC validation.+ Follow DS digest links and DNSKEY signatures from the IANA root+ anchors to the name you enter. This is not full DNSSEC validation.</p></section><SponsorsSection />@@ -48,10 +48,10 @@ const DnssecLandingPage: FC = () => (About this DNSSEC lookup</h2><p>- A parent zone publishes a DS digest for a child zone’s DNSKEY. This- lookup compares those digests from the IANA root anchors down to the- queried name and shows where the chain stops. It does not check DNSSEC- signatures or other records.+ A parent zone publishes a DS digest for a child zone’s DNSKEY, and that+ key signs the child’s DNSKEY set. This lookup checks both from the IANA+ root anchors down to the queried name and shows where the chain stops.+ It does not yet check signatures over DS records or other records.</p></div></div>diff --git a/app/lookup/[domain]/dnssec/page.tsx b/app/lookup/[domain]/dnssec/page.tsxindex 67bb4ef..7ae6e64 100644--- a/app/lookup/[domain]/dnssec/page.tsx+++ b/app/lookup/[domain]/dnssec/page.tsx@@ -2,10 +2,11 @@ import type { Metadata } from 'next';import { notFound } from 'next/navigation';import type { FC } from 'react';+import { digestName } from '@/lib/dnssec/algorithms';import {DsChainNameNotFoundError,type DsChainVerdict,- dsDigestName,+ type DsChainZone,resolveDsChain,} from '@/lib/dnssec/ds-chain';import { AuthoritativeResolver } from '@/lib/resolvers/authoritative';@@ -20,9 +21,9 @@ export const generateMetadata = async ({}: DnssecResultsPageProps): Promise<Metadata> => {const { domain } = await params;return {- title: `DNSSEC DS Chain for ${domain}`,+ title: `DNSSEC Lookup for ${domain}`,openGraph: {- title: `DNSSEC DS Chain for ${domain}`,+ title: `DNSSEC Lookup for ${domain}`,url: `/lookup/${domain}/dnssec`,},alternates: { canonical: `/lookup/${domain}/dnssec` },@@ -30,17 +31,45 @@ export const generateMetadata = async ({};const VERDICT_LABELS: Record<DsChainVerdict, string> = {- intact: 'DS chain intact',+ intact: 'Chain intact',unsigned: 'Unsigned',mismatch: 'DS mismatch',+ 'bad-signature': 'Bad DNSKEY signature',};+const formatDate = (unixSeconds: number): string =>+ new Date(unixSeconds * 1000).toISOString().slice(0, 10);++const describeKeySignature = ({+ outcome,+ inception,+ expiration,+}: NonNullable<DsChainZone['keySignature']>): string => {+ switch (outcome) {+ case 'valid':+ return `Valid until ${formatDate(expiration!)}`;+ case 'expired':+ return `Expired on ${formatDate(expiration!)}`;+ case 'not-yet-valid':+ return `Not valid before ${formatDate(inception!)}`;+ case 'missing':+ return 'Missing';+ case 'unauthenticated-signer':+ return 'Not made by a DS-linked key';+ case 'invalid':+ return 'Invalid';+ }+};++const isBroken = (status: DsChainVerdict): boolean =>+ status === 'mismatch' || status === 'bad-signature';+const shortFingerprint = (hex: string): string =>hex.length > 24 ? `${hex.slice(0, 16)}…${hex.slice(-8)}` : hex;const DnssecResultsPage: FC<DnssecResultsPageProps> = async ({ params }) => {const { domain } = await params;- const resolver = new AuthoritativeResolver();+ const resolver = new AuthoritativeResolver({ dnssecOk: true });let chain;try {chain = await resolveDsChain(domain, (name, type) =>@@ -61,7 +90,7 @@ const DnssecResultsPage: FC<DnssecResultsPageProps> = async ({ params }) => {<div className="space-y-8"><header className="space-y-2"><h2- className={`text-2xl font-semibold tracking-tight ${chain.verdict === 'mismatch' ? 'text-red-700 dark:text-red-400' : ''}`}+ className={`text-2xl font-semibold tracking-tight ${isBroken(chain.verdict) ? 'text-red-700 dark:text-red-400' : ''}`}>{VERDICT_LABELS[chain.verdict]}{chain.breakAt ? ` at ${chain.breakAt}` : ''}@@ -73,7 +102,7 @@ const DnssecResultsPage: FC<DnssecResultsPageProps> = async ({ params }) => {</p>)}<p className="text-sm text-zinc-500 dark:text-zinc-400">- This view checks digest linkage without verifying signatures.+ This view checks DS digest links and DNSKEY signatures.</p></header>@@ -86,7 +115,7 @@ const DnssecResultsPage: FC<DnssecResultsPageProps> = async ({ params }) => {<div className="mb-5 flex flex-wrap items-baseline justify-between gap-2"><h3 className="text-lg font-semibold break-all">{zone.name}</h3><span- className={`text-sm font-medium ${zone.status === 'mismatch' ? 'text-red-700 dark:text-red-400' : 'text-zinc-600 dark:text-zinc-300'}`}+ className={`text-sm font-medium ${isBroken(zone.status) ? 'text-red-700 dark:text-red-400' : 'text-zinc-600 dark:text-zinc-300'}`}>{zone.status === 'intact'? 'Intact'@@ -116,6 +145,13 @@ const DnssecResultsPage: FC<DnssecResultsPageProps> = async ({ params }) => {No DNSKEYs</p>)}+ {zone.keySignature && (+ <p+ className={`mt-3 text-sm ${zone.keySignature.outcome === 'valid' ? 'text-zinc-600 dark:text-zinc-300' : 'text-red-700 dark:text-red-400'}`}+ >+ Signature: {describeKeySignature(zone.keySignature)}+ </p>+ )}</div><div>@@ -132,7 +168,7 @@ const DnssecResultsPage: FC<DnssecResultsPageProps> = async ({ params }) => {<div className="flex flex-wrap items-center gap-x-2 gap-y-1"><span className="font-mono">{ds.keyTag}</span><span className="text-zinc-600 dark:text-zinc-300">- {dsDigestName(ds.digestType)}+ {digestName(ds.digestType)}</span>{ds.weakDigest && (<span className="rounded bg-zinc-100 px-1.5 py-0.5 text-xs text-zinc-500 dark:bg-zinc-800 dark:text-zinc-400">@@ -167,8 +203,8 @@ const DnssecResultsPage: FC<DnssecResultsPageProps> = async ({ params }) => {</div><p className="text-sm text-zinc-500 dark:text-zinc-400">- This checks DS digest linkage only, not signatures; expired or forged- signatures are not detected.+ Signatures over DS records and the queried name’s own records are not+ verified yet, so a forged DS or record is not detected.</p></div>);diff --git a/lib/dnssec/algorithms.test.ts b/lib/dnssec/algorithms.test.tsindex 0a8ad04..1aaa688 100644--- a/lib/dnssec/algorithms.test.ts+++ b/lib/dnssec/algorithms.test.ts@@ -1,11 +1,20 @@import { describe, expect, it } from 'vitest';-import { algorithmName, isWeakDigest } from './algorithms';+import {+ algorithmName,+ digestName,+ isSupportedSigningAlgorithm,+ isWeakDigest,+ verifyWithDnskey,+} from './algorithms';+import { genKey, signData } from './test-helpers';-describe('algorithm policy', () => {- it('names known algorithms and falls back for unknown ones', () => {+describe('algorithm registry', () => {+ it('names known algorithms and digests and falls back for unknown ones', () => {expect(algorithmName(8)).toBe('RSASHA256');expect(algorithmName(99)).toBe('Algorithm 99');+ expect(digestName(2)).toBe('SHA-256');+ expect(digestName(99)).toBe('Digest 99');});it('flags weak digests', () => {@@ -13,4 +22,39 @@ describe('algorithm policy', () => {expect(isWeakDigest(2)).toBe(false); // SHA-256expect(isWeakDigest(3)).toBe(true); // GOST});++ it('supports exactly the signing algorithms it can verify', () => {+ expect(isSupportedSigningAlgorithm(8)).toBe(true);+ expect(isSupportedSigningAlgorithm(1)).toBe(false); // RSAMD5+ expect(isSupportedSigningAlgorithm(3)).toBe(false); // DSA+ });+});++// Real-world keys and signatures are covered by the golden vectors in+// rrsig.test.ts; this pins the per-algorithm plumbing and its failure modes.+describe('verifyWithDnskey', () => {+ const data = Buffer.from('canonical signed data');++ it('verifies RSA, ECDSA, and Ed25519 signatures', () => {+ for (const algorithm of [8, 13, 15]) {+ const signer = genKey(algorithm);+ const signature = signData(signer, data);++ expect(verifyWithDnskey(signer.dnskey, data, signature)).toBe(true);+ expect(+ verifyWithDnskey(signer.dnskey, Buffer.from('other data'), signature),+ ).toBe(false);+ }+ });++ it('rejects unknown algorithms and malformed keys instead of throwing', () => {+ const signer = genKey(13);+ const signature = signData(signer, data);+ const verifyWith = (algorithm: number, key: Buffer) =>+ verifyWithDnskey({ algorithm, key }, data, signature);++ expect(verifyWith(99, signer.dnskey.key)).toBe(false); // unknown alg+ expect(verifyWith(13, Buffer.alloc(10))).toBe(false); // wrong EC size+ expect(verifyWith(8, Buffer.alloc(0))).toBe(false); // empty RSA+ });});diff --git a/lib/dnssec/algorithms.ts b/lib/dnssec/algorithms.tsindex 87d74ec..126d8e4 100644--- a/lib/dnssec/algorithms.ts+++ b/lib/dnssec/algorithms.ts@@ -1,40 +1,154 @@-// Algorithm and DS digest names, plus which digests are too weak to count-// as a strong match. Signing-algorithm verify policy lives with the-// signature checker and is not needed for digest-linkage.--const ALGORITHM_NAMES: Record<number, string> = {- 1: 'RSAMD5',- 3: 'DSA',- 5: 'RSASHA1',- 6: 'DSA-NSEC3-SHA1',- 7: 'RSASHA1-NSEC3-SHA1',- 8: 'RSASHA256',- 10: 'RSASHA512',- 12: 'ECC-GOST',- 13: 'ECDSAP256SHA256',- 14: 'ECDSAP384SHA384',- 15: 'ED25519',- 16: 'ED448',-};+import { createPublicKey, verify as cryptoVerify } from 'node:crypto';-export const algorithmName = (algorithm: number): string =>- ALGORITHM_NAMES[algorithm] ?? `Algorithm ${algorithm}`;+import type { DnskeyData } from 'dns-packet';++// Algorithm registry: the DNSSEC signing algorithms and DS digest types this+// lookup knows, with what it can do with each. One row per algorithm, so+// whether an algorithm is supported can never drift from whether it can be+// verified.++// How to turn a DNSKEY's wire-format public key into a node crypto key and+// verify an RRSIG with it (EdDSA hashes internally).+type Verifier =+ | { kty: 'RSA'; hash: string }+ | { kty: 'EC'; hash: string; crv: string; coordBytes: number }+ | { kty: 'OKP'; crv: string };-export const DIGEST_NAMES: Record<number, string> = {- 1: 'SHA-1',- 2: 'SHA-256',- 3: 'GOST R 34.11-94',- 4: 'SHA-384',+// Algorithms without a verifier cannot be validated here: a DS pointing at+// one must make the zone insecure, not bogus (RFC 4035 §5.2). RSAMD5 has+// none: validators must not validate it (RFC 8624 §3.1).+const SIGNING: Record<number, { name: string; verifier?: Verifier }> = {+ 1: { name: 'RSAMD5' },+ 3: { name: 'DSA' },+ 5: { name: 'RSASHA1', verifier: { kty: 'RSA', hash: 'sha1' } },+ 6: { name: 'DSA-NSEC3-SHA1' },+ 7: { name: 'RSASHA1-NSEC3-SHA1', verifier: { kty: 'RSA', hash: 'sha1' } },+ 8: { name: 'RSASHA256', verifier: { kty: 'RSA', hash: 'sha256' } },+ 10: { name: 'RSASHA512', verifier: { kty: 'RSA', hash: 'sha512' } },+ 12: { name: 'ECC-GOST' },+ 13: {+ name: 'ECDSAP256SHA256',+ verifier: { kty: 'EC', hash: 'sha256', crv: 'P-256', coordBytes: 32 },+ },+ 14: {+ name: 'ECDSAP384SHA384',+ verifier: { kty: 'EC', hash: 'sha384', crv: 'P-384', coordBytes: 48 },+ },+ 15: { name: 'ED25519', verifier: { kty: 'OKP', crv: 'Ed25519' } },+ 16: { name: 'ED448', verifier: { kty: 'OKP', crv: 'Ed448' } },};-export const DIGEST_HASH_ALGOS: Record<number, string> = {- 1: 'sha1',- 2: 'sha256',- 4: 'sha384',+// `hash` is absent for digest types this validator cannot compute. SHA-1 and+// GOST are no longer considered safe.+const DIGESTS: Record<number, { name: string; hash?: string; weak?: true }> = {+ 1: { name: 'SHA-1', hash: 'sha1', weak: true },+ 2: { name: 'SHA-256', hash: 'sha256' },+ 3: { name: 'GOST R 34.11-94', weak: true },+ 4: { name: 'SHA-384', hash: 'sha384' },};-// DS digest algorithms no longer considered safe: SHA-1 and GOST.-const WEAK_DIGEST_TYPES = new Set([1, 3]);+export const algorithmName = (algorithm: number): string =>+ SIGNING[algorithm]?.name ?? `Algorithm ${algorithm}`;++export const isSupportedSigningAlgorithm = (algorithm: number): boolean =>+ Boolean(SIGNING[algorithm]?.verifier);++export const digestName = (digestType: number): string =>+ DIGESTS[digestType]?.name ?? `Digest ${digestType}`;++/** Node hash name for a DS digest type; undefined if unsupported. */+export const digestHash = (digestType: number): string | undefined =>+ DIGESTS[digestType]?.hash;export const isWeakDigest = (digestType: number): boolean =>- WEAK_DIGEST_TYPES.has(digestType);+ Boolean(DIGESTS[digestType]?.weak);++/** Split an RFC 3110 RSA public key into its exponent and modulus. */+const rsaKeyParts = (+ key: Buffer,+): { exponent: Buffer; modulus: Buffer } | null => {+ if (key.length < 1) return null;+ let offset: number;+ let expLen = key[0];+ if (expLen === 0) {+ if (key.length < 3) return null;+ expLen = key.readUInt16BE(1);+ offset = 3;+ } else {+ offset = 1;+ }+ const exponent = key.subarray(offset, offset + expLen);+ const modulus = key.subarray(offset + expLen);+ if (exponent.length === 0 || modulus.length === 0) return null;+ return { exponent, modulus };+};++/**+ * A DNSKEY's public key as a JWK, so no DER hand-encoding is needed. Null for+ * key material that is malformed for its algorithm.+ */+const dnskeyJwk = (+ verifier: Verifier,+ key: Buffer,+): Record<string, string> | null => {+ switch (verifier.kty) {+ case 'RSA': {+ const parts = rsaKeyParts(key);+ return (+ parts && {+ kty: 'RSA',+ n: parts.modulus.toString('base64url'),+ e: parts.exponent.toString('base64url'),+ }+ );+ }+ case 'EC':+ if (key.length !== verifier.coordBytes * 2) return null;+ return {+ kty: 'EC',+ crv: verifier.crv,+ x: key.subarray(0, verifier.coordBytes).toString('base64url'),+ y: key.subarray(verifier.coordBytes).toString('base64url'),+ };+ case 'OKP':+ return { kty: 'OKP', crv: verifier.crv, x: key.toString('base64url') };+ }+};++/**+ * Whether `signature` over `data` was made by the private half of `dnskey`.+ * False -- never a throw -- for an unsupported algorithm (classified+ * unvalidatable upstream, RFC 4035 §5.2) and for a malformed key of a+ * supported one: that key is genuinely unusable, so it can never verify and+ * the data it was meant to sign reads as bogus.+ */+export const verifyWithDnskey = (+ dnskey: Pick<DnskeyData, 'algorithm' | 'key'>,+ data: Buffer,+ signature: Buffer,+): boolean => {+ const verifier = SIGNING[dnskey.algorithm]?.verifier;+ if (!verifier) return false;+ try {+ const jwk = dnskeyJwk(verifier, dnskey.key);+ if (!jwk) return false;+ const publicKey = createPublicKey({ key: jwk, format: 'jwk' });+ switch (verifier.kty) {+ // EdDSA is a one-shot verify with no separate hash.+ case 'OKP':+ return cryptoVerify(null, data, publicKey, signature);+ // DNSSEC ECDSA signatures are raw r||s (IEEE P1363), not DER-wrapped.+ case 'EC':+ return cryptoVerify(+ verifier.hash,+ data,+ { key: publicKey, dsaEncoding: 'ieee-p1363' },+ signature,+ );+ case 'RSA':+ return cryptoVerify(verifier.hash, data, publicKey, signature);+ }+ } catch {+ return false;+ }+};diff --git a/lib/dnssec/ds-chain.test.ts b/lib/dnssec/ds-chain.test.tsindex 1176162..ed70f55 100644--- a/lib/dnssec/ds-chain.test.ts+++ b/lib/dnssec/ds-chain.test.ts@@ -1,24 +1,25 @@-import { createHash } from 'node:crypto';-import type { Answer } from 'dns-packet';-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';import { UserFacingError } from '@/lib/user-facing-error';+import { dsDigest } from './ds';import {DsChainNameNotFoundError,type DsChainQuery,resolveDsChain,} from './ds-chain';--// IANA root KSK public keys, used as fixed offline fixtures. The first is-// KSK-2017 (20326), the second KSK-2024 (38696).-const ROOT_KEYS = [- 'AwEAAaz/tAm8yTn4Mfeh5eyI96WSVexTBAvkMgJzkKTOiW1vkIbzxeF3+/4RgWOq7HrxRixHlFlExOLAJr5emLvN7SWXgnLh4+B5xQlNVz8Og8kvArMtNROxVQuCaSnIDdD5LKyWbRd2n9WGe2R8PzgCmr3EgVLrjyBxWezF0jLHwVN8efS3rCj/EWgvIWgb9tarpVUDK/b58Da+sqqls3eNbuv7pr+eoZG+SrDK6nWeL3c6H5Apxz7LjVc1uTIdsIXxuOLYA4/ilBmSVIzuDWfdRUfhHdY6+cn8HFRm+2hM8AnXGXws9555KrUB5qihylGa8subX2Nn6UwNR1AkUTV74bU=',- 'AwEAAa96jeuknZlaeSrvyAJj6ZHv28hhOKkx3rLGXVaC6rXTsDc449/cidltpkyGwCJNnOAlFNKF2jBosZBU5eeHspaQWOmOElZsjICMQMC3aeHbGiShvZsx4wMYSjH8e7Vrhbu6irwCzVBApESjbUdpWWmEnhathWu1jo+siFUiRAAxm9qyJNg/wOZqqzL/dL/q8PkcRU5oUKEpUge71M3ej2/7CPqpdVwuMoTvoB+ZOT4YeGyxMvHmbrxlFzGOHOijtzN+u1TQNatX2XBuzZNQ1K+s2CXkPIZo7s6JgZyvaBevYtxPvYLw4z9mR7K2vaF18UYH9Z9GNUUeayffKC73PYc=',-];--const testKey = 'AQIDBAUGBwgJCgsMDQ4PEA==';+import { genKey, signDnskeyRrset } from './test-helpers';+import { ROOT_DNSKEY_RRSIG, ROOT_DNSKEYS, ROOT_NOW } from './test-vectors';+import { dnskeyKeyTag } from './wire';++// Every walk is judged at ROOT_NOW, inside the captured root signature's+// validity window. Zones below the root sign with one generated key.+const NOW = ROOT_NOW;+const DAY = 86_400;+const WINDOW = { inception: NOW - DAY, expiration: NOW + DAY };+type Signer = ReturnType<typeof genKey>;+const KSK = genKey(13);const soa = (name: string): Answer => ({name,@@ -50,59 +51,41 @@ const host = (name: string): Answer => ({data: '192.0.2.1',});-const keyRecord = (name: string, key = testKey, flags = 257): Answer => ({+const keyRecord = (name: string, key = KSK.dnskey): Answer => ({name,type: 'DNSKEY',ttl: 60,- data: { flags, algorithm: 8, key: Buffer.from(key, 'base64') },+ data: key,});-const keyTag = (key: string, flags = 257): number => {- const rdata = Buffer.concat([- Buffer.from([flags >> 8, flags & 0xff, 3, 8]),- Buffer.from(key, 'base64'),- ]);- let sum = 0;- for (const [i, octet] of rdata.entries()) {- sum += i % 2 ? octet : octet << 8;- }- sum += (sum >> 16) & 0xffff;- return sum & 0xffff;-};+// The RRSIG over a zone's DNSKEY RRset `keys`, made by `signer`.+const keySig = (+ name: string,+ keys = [KSK.dnskey],+ signer: Signer = KSK,+ window = WINDOW,+): Answer => ({+ name,+ type: 'RRSIG',+ ttl: 60,+ data: signDnskeyRrset(name, keys, signer, window),+});const dsRecord = (name: string,- key = testKey,+ key = KSK.dnskey,digestType = 2,corrupt = false,- flags = 257,): Answer => {- const labels = name.split('.');- const owner = Buffer.concat([- ...labels.flatMap((label) => [- Buffer.from([label.length]),- Buffer.from(label),- ]),- Buffer.from([0]),- ]);- const rdata = Buffer.concat([- Buffer.from([flags >> 8, flags & 0xff, 3, 8]),- Buffer.from(key, 'base64'),- ]);// Digest types without a hash here (e.g. 3, GOST) get a SHA-256 stand-in.- const digest = createHash(- ({ 1: 'sha1', 4: 'sha384' } as Record<number, string>)[digestType] ??- 'sha256',- )- .update(Buffer.concat([owner, rdata]))- .digest();+ const digest = dsDigest(name, key, digestType) ?? dsDigest(name, key, 2)!;return {name,type: 'DS',ttl: 60,data: {- keyTag: keyTag(key, flags),- algorithm: 8,+ keyTag: dnskeyKeyTag(key),+ algorithm: key.algorithm,digestType,digest: corrupt ? Buffer.alloc(digest.length) : digest,},@@ -110,13 +93,18 @@ const dsRecord = (};// A delegated, signed zone apex whose parent publishes a matching DS.-const signedZone = (name: string, key = testKey): Answer[] => [+const signedZone = (name: string): Answer[] => [ns(name),soa(name),- keyRecord(name, key),- dsRecord(name, key),+ keyRecord(name),+ dsRecord(name),+ keySig(name),];+// com with its own SOA and validly signed KSK, under the parent DS `ds`.+const com = (...ds: Answer[]): Answer[] =>+ [root(), soa('com'), keyRecord('com'), keySig('com'), ...ds].flat();+// Answers like AuthoritativeResolver.resolveAnswers over a small DNS tree:// a query returns the records its name owns, a name that owns nothing but// has descendants is an empty non-terminal (NODATA), and anything else is@@ -137,6 +125,13 @@ const dnsTree =answers: records.filter((record) => record.name === name && record.type === type,),+ coveringRrsigs: records.flatMap((record) =>+ record.name === name &&+ record.type === 'RRSIG' &&+ record.data.typeCovered === type+ ? [record.data]+ : [],+ ),rcode:name === '.' ||records.some(@@ -148,17 +143,23 @@ const dnsTree =};};-const root = (key = ROOT_KEYS[0]) => keyRecord('.', key);+// The real root DNSKEY RRset, both IANA KSKs included, and its RRSIG.+const root = (): Answer[] => [+ ...ROOT_DNSKEYS.map((key) => keyRecord('.', key)),+ { name: '.', type: 'RRSIG', ttl: 60, data: ROOT_DNSKEY_RRSIG },+];++const walk = (name: string, records: (Answer | Answer[])[]) =>+ resolveDsChain(name, dnsTree(records.flat()), NOW);describe('resolveDsChain', () => {it('follows matching DS digests to the full queried name', async () => {- const query = dnsTree([+ const chain = await walk('WWW.Example.COM.', [root(),- ...signedZone('com'),- ...signedZone('example.com'),- ...signedZone('www.example.com'),+ signedZone('com'),+ signedZone('example.com'),+ signedZone('www.example.com'),]);- const chain = await resolveDsChain('WWW.Example.COM.', query);expect(chain.verdict).toBe('intact');expect(chain.breakAt).toBeUndefined();expect(chain.name).toBe('www.example.com');@@ -169,18 +170,24 @@ describe('resolveDsChain', () => {'www.example.com',]);expect(chain.zones.every((zone) => zone.status === 'intact')).toBe(true);+ expect(chain.zones.map((zone) => zone.keySignature?.outcome)).toEqual([+ 'valid',+ 'valid',+ 'valid',+ 'valid',+ ]);+ expect(chain.zones[1].keySignature).toMatchObject({+ expiration: WINDOW.expiration,+ });});it('keeps a host inside its signed zone instead of calling it unsigned', async () => {- const chain = await resolveDsChain(- 'www.example.com',- dnsTree([- root(),- ...signedZone('com'),- ...signedZone('example.com'),- host('www.example.com'),- ]),- );+ const chain = await walk('www.example.com', [+ root(),+ signedZone('com'),+ signedZone('example.com'),+ host('www.example.com'),+ ]);expect(chain.verdict).toBe('intact');expect(chain.breakAt).toBeUndefined();expect(chain.name).toBe('www.example.com');@@ -192,15 +199,12 @@ describe('resolveDsChain', () => {});it('skips empty non-terminals between zone apexes', async () => {- const chain = await resolveDsChain(- 'a.b.example.com',- dnsTree([- root(),- ...signedZone('com'),- ...signedZone('example.com'),- ...signedZone('a.b.example.com'),- ]),- );+ const chain = await walk('a.b.example.com', [+ root(),+ signedZone('com'),+ signedZone('example.com'),+ signedZone('a.b.example.com'),+ ]);expect(chain.verdict).toBe('intact');expect(chain.zones.map((zone) => zone.name)).toEqual(['.',@@ -213,15 +217,12 @@ describe('resolveDsChain', () => {it('finds an unsigned child by its own SOA when it shares the parent servers', async () => {// No NS for example.com: the com servers host the child too, so the walk// is never referred and only the owned SOA marks the apex.- const chain = await resolveDsChain(- 'www.example.com',- dnsTree([- root(),- ...signedZone('com'),- soa('example.com'),- host('www.example.com'),- ]),- );+ const chain = await walk('www.example.com', [+ root(),+ signedZone('com'),+ soa('example.com'),+ host('www.example.com'),+ ]);expect(chain.verdict).toBe('unsigned');expect(chain.breakAt).toBe('example.com');expect(chain.zones.map((zone) => zone.name)).toEqual([@@ -235,16 +236,13 @@ describe('resolveDsChain', () => {// Like www.archives.gov: the parent delegates the name without a DS, but// the child servers answer from the parent's zone, so the child has no// SOA of its own and only the referral marks the cut.- const chain = await resolveDsChain(- 'www.example.com',- dnsTree([- root(),- ...signedZone('com'),- ...signedZone('example.com'),- ns('www.example.com'),- host('www.example.com'),- ]),- );+ const chain = await walk('www.example.com', [+ root(),+ signedZone('com'),+ signedZone('example.com'),+ ns('www.example.com'),+ host('www.example.com'),+ ]);expect(chain.verdict).toBe('unsigned');expect(chain.breakAt).toBe('www.example.com');expect(chain.zones.map((zone) => zone.name)).toEqual([@@ -256,25 +254,18 @@ describe('resolveDsChain', () => {});it('keeps a wildcard query name and covers it by its zone', async () => {- const chain = await resolveDsChain(- '*.example.com',- dnsTree([root(), ...signedZone('com'), ...signedZone('example.com')]),- );+ const chain = await walk('*.example.com', [+ root(),+ signedZone('com'),+ signedZone('example.com'),+ ]);expect(chain.verdict).toBe('intact');expect(chain.name).toBe('*.example.com');expect(chain.zones.at(-1)?.name).toBe('example.com');});it('marks an unsigned TLD and its descendants unsigned', async () => {- const chain = await resolveDsChain(- 'example.com',- dnsTree([- root(),- soa('com'),- keyRecord('com'),- ...signedZone('example.com'),- ]),- );+ const chain = await walk('example.com', [com(), signedZone('example.com')]);expect(chain.verdict).toBe('unsigned');expect(chain.breakAt).toBe('com');expect(chain.zones.map((zone) => zone.status)).toEqual([@@ -282,43 +273,40 @@ describe('resolveDsChain', () => {'unsigned','unsigned',]);+ // Nothing above vouches for example.com's DS, so its keys are not checked.+ expect(chain.zones[2].keySignature).toBeUndefined();});it('reports a published DS with no matching DNSKEY as a mismatch', async () => {- const chain = await resolveDsChain(- 'com',- dnsTree([- root(),- soa('com'),- keyRecord('com'),- dsRecord('com', testKey, 2, true),- ]),- );+ const chain = await walk('com', com(dsRecord('com', KSK.dnskey, 2, true)));expect(chain.verdict).toBe('mismatch');expect(chain.breakAt).toBe('com');expect(chain.zones[1].dsRecords[0].matched).toBe(false);});- it.each(ROOT_KEYS)('accepts each pinned IANA root KSK', async (key) => {- const chain = await resolveDsChain('.', dnsTree([root(key)]));+ it('links both pinned IANA root KSKs and verifies the root key set', async () => {+ const chain = await walk('.', root());expect(chain.verdict).toBe('intact');- expect(chain.zones[0].dsRecords.filter((ds) => ds.matched)).toHaveLength(1);+ expect(chain.zones[0].dsRecords.map((ds) => ds.matched)).toEqual([+ true,+ true,+ ]);+ expect(chain.zones[0].keySignature?.outcome).toBe('valid');});it('throws a retryable error when root DNSKEYs are empty', async () => {- await expect(- resolveDsChain('example.com', dnsTree([])),- ).rejects.toMatchObject({+ await expect(walk('example.com', [])).rejects.toMatchObject({payload: { retryable: true },});});it('treats NXDOMAIN at the queried name as not found', async () => {await expect(- resolveDsChain(- 'missing.example.com',- dnsTree([root(), ...signedZone('com'), ...signedZone('example.com')]),- ),+ walk('missing.example.com', [+ root(),+ signedZone('com'),+ signedZone('example.com'),+ ]),).rejects.toBeInstanceOf(DsChainNameNotFoundError);});@@ -337,10 +325,9 @@ describe('resolveDsChain', () => {});it('prefers SHA-256 when SHA-1 and SHA-256 DS records coexist', async () => {- const records = [root(), soa('com'), keyRecord('com'), dsRecord('com')];- const chain = await resolveDsChain(+ const chain = await walk('com',- dnsTree([...records, dsRecord('com', testKey, 1, true)]),+ com(dsRecord('com'), dsRecord('com', KSK.dnskey, 1, true)),);expect(chain.verdict).toBe('intact');expect(chain.zones[1].dsRecords).toEqual([@@ -356,85 +343,99 @@ describe('resolveDsChain', () => {}),]);- const reverse = await resolveDsChain(+ const reverse = await walk('com',- dnsTree([- root(),- soa('com'),- keyRecord('com'),- dsRecord('com', testKey, 1),- dsRecord('com', testKey, 2, true),- ]),+ com(dsRecord('com', KSK.dnskey, 1), dsRecord('com', KSK.dnskey, 2, true)),);expect(reverse.verdict).toBe('mismatch');});- it('accepts a matching SHA-384 DS next to a stale SHA-256 DS', async () => {- const chain = await resolveDsChain(- 'com',- dnsTree([- root(),- soa('com'),- keyRecord('com'),- dsRecord('com', testKey, 2, true),- dsRecord('com', testKey, 4),- ]),- );+ it('does not treat a DNSKEY owned by a host as a zone cut', async () => {+ const chain = await walk('www.example.com', [+ root(),+ signedZone('com'),+ signedZone('example.com'),+ keyRecord('www.example.com'),+ ]);expect(chain.verdict).toBe('intact');+ expect(chain.zones.at(-1)?.name).toBe('example.com');});- it('ignores a matching SHA-1 DS when SHA-384 is present', async () => {- const chain = await resolveDsChain(- 'com',- dnsTree([- root(),- soa('com'),- keyRecord('com'),- dsRecord('com', testKey, 1),- dsRecord('com', testKey, 4, true),- ]),- );- expect(chain.verdict).toBe('mismatch');+ it('breaks on an expired DNSKEY signature and propagates it down', async () => {+ const expired = { inception: NOW - 2 * DAY, expiration: NOW - DAY };+ const chain = await walk('www.example.com', [+ root(),+ signedZone('com'),+ ns('example.com'),+ soa('example.com'),+ keyRecord('example.com'),+ dsRecord('example.com'),+ keySig('example.com', [KSK.dnskey], KSK, expired),+ signedZone('www.example.com'),+ ]);+ expect(chain.verdict).toBe('bad-signature');+ expect(chain.breakAt).toBe('example.com');+ expect(chain.zones[2].keySignature).toEqual({+ outcome: 'expired',+ ...expired,+ });+ expect(chain.zones[3].status).toBe('bad-signature');+ expect(chain.zones[3].keySignature).toBeUndefined();});- it('treats a DS set with only unsupported digests as unsigned', async () => {- const chain = await resolveDsChain(- 'com',- dnsTree([- root(),- soa('com'),- keyRecord('com'),- dsRecord('com', testKey, 3),- ]),- );- expect(chain.verdict).toBe('unsigned');- expect(chain.breakAt).toBe('com');+ it('judges each signature when it is checked, not when the walk started', async () => {+ // Only Date is faked, so the walk's own awaits still run.+ vi.useFakeTimers({ toFake: ['Date'] });+ try {+ vi.setSystemTime(NOW * 1000);+ const tree = dnsTree([root(), signedZone('com')].flat());+ const chain = await resolveDsChain('com', async (name, type) => {+ // com's key-set signature expires while the walk is under way.+ if (name === 'com') vi.setSystemTime((WINDOW.expiration + 1) * 1000);+ return tree(name, type);+ });+ expect(chain.zones[0].keySignature?.outcome).toBe('valid');+ expect(chain.zones[1].keySignature?.outcome).toBe('expired');+ } finally {+ vi.useRealTimers();+ }});- it('does not match a DS against a DNSKEY without the Zone Key flag', async () => {- const chain = await resolveDsChain(+ it('breaks when the DNSKEY RRSIG is missing', async () => {+ const chain = await walk('com', [+ root(),+ soa('com'),+ keyRecord('com'),+ dsRecord('com'),+ ]);+ expect(chain.verdict).toBe('bad-signature');+ expect(chain.zones[1].keySignature).toEqual({ outcome: 'missing' });+ });++ it('breaks when only a key no DS links signed the key set', async () => {+ const zsk = genKey(13);+ const keys = [KSK.dnskey, zsk.dnskey];+ const chain = await walk('com',- dnsTree([+ [root(),soa('com'),- keyRecord('com', testKey, 1),- dsRecord('com', testKey, 2, false, 1),- ]),+ keys.map((key) => keyRecord('com', key)),+ dsRecord('com'),+ keySig('com', keys, zsk),+ ].flat(),);- expect(chain.verdict).toBe('mismatch');+ expect(chain.verdict).toBe('bad-signature');+ expect(chain.zones[1].keySignature?.outcome).toBe('unauthenticated-signer');});- it('does not treat a DNSKEY owned by a host as a zone cut', async () => {- const chain = await resolveDsChain(- 'www.example.com',- dnsTree([- root(),- ...signedZone('com'),- ...signedZone('example.com'),- keyRecord('www.example.com'),- ]),- );- expect(chain.verdict).toBe('intact');- expect(chain.zones.at(-1)?.name).toBe('example.com');+ it('breaks when the served key set is not the one that was signed', async () => {+ const extra = genKey(13).dnskey;+ const chain = await walk('com', [+ com(dsRecord('com')),+ keyRecord('com', extra),+ ]);+ expect(chain.verdict).toBe('bad-signature');+ expect(chain.zones[1].keySignature?.outcome).toBe('invalid');});});diff --git a/lib/dnssec/ds-chain.ts b/lib/dnssec/ds-chain.tsindex 722b5ef..e9c4d2b 100644--- a/lib/dnssec/ds-chain.ts+++ b/lib/dnssec/ds-chain.ts@@ -1,18 +1,21 @@-import type { Answer, DnskeyData, DsData } from 'dns-packet';+import type { Answer, DnskeyData, DsData, RrsigData } from 'dns-packet';-import type { RecordType } from '@/lib/resolvers/base';+import { canonicalDnsName, type RecordType } from '@/lib/resolvers/base';import { UserFacingError } from '@/lib/user-facing-error';-import {- algorithmName,- DIGEST_HASH_ALGOS,- DIGEST_NAMES,- isWeakDigest,-} from './algorithms';-import { dsMatchesKey } from './ds';-import { dnskeyKeyTag } from './wire';+import { algorithmName, isWeakDigest } from './algorithms';+import { linkKeys } from './ds';+import { checkRrsetSignatures, type RrsetSignatureOutcome } from './rrsig';+import { dnskeyKeyTag, dnskeyRdata, isSepKey } from './wire';-export type DsChainVerdict = 'intact' | 'unsigned' | 'mismatch';+export type DsChainVerdict =+ | 'intact'+ | 'unsigned'+ | 'mismatch'+ // A DS links a key, but that key has not validly signed the zone's DNSKEY+ // RRset: missing, expired, not yet valid, forged, or signed only by a key no+ // DS links.+ | 'bad-signature';export type DsChainZone = {name: string;@@ -29,6 +32,15 @@ export type DsChainZone = {matched: boolean;weakDigest: boolean;}>;+ // What the RRSIGs over the zone's DNSKEY RRset establish, checked against+ // the DS-linked keys. Only set while the chain above is intact and a DS+ // links a key: anywhere else there is no trusted key to check against.+ keySignature?: {+ outcome: RrsetSignatureOutcome;+ // Unix seconds, from the signature that explains the outcome.+ inception?: number;+ expiration?: number;+ };status: DsChainVerdict;};@@ -45,11 +57,17 @@ export type DsChain = {// Answers must be decoded rdata owned by the queried name, as an// authoritative server returns them; rcode tells NXDOMAIN from NODATA for// the queried name itself. zone is the zone cut whose servers answered (the-// deepest delegation followed, '.' for the root).+// deepest delegation followed, '.' for the root). coveringRrsigs are the+// RRSIGs over the answered RRset, so the query must set the DNSSEC OK bit.export type DsChainQuery = (name: string,type: Extract<RecordType, 'SOA' | 'DNSKEY' | 'DS'>,-) => Promise<{ answers: Answer[]; rcode?: string; zone: string }>;+) => Promise<{+ answers: Answer[];+ rcode?: string;+ zone: string;+ coveringRrsigs?: RrsigData[];+}>;export class DsChainNameNotFoundError extends Error {}@@ -76,13 +94,6 @@ const ROOT_ANCHORS: DsData[] = [},];-export const dnssecAlgorithmName = algorithmName;--export const dsDigestName = (digestType: number): string =>- DIGEST_NAMES[digestType] ?? `Digest ${digestType}`;--const keyTag = dnskeyKeyTag;-const dnskeysOf = ({ answers }: { answers: Answer[] }): DnskeyData[] =>answers.flatMap((answer) => (answer.type === 'DNSKEY' ? [answer.data] : []));@@ -101,11 +112,15 @@ const suffixesFor = (name: string): string[] => {return ['.', ...labels.map((_, index) => labels.slice(-index - 1).join('.'))];};+// `now` (Unix seconds) pins the instant every signature is judged against.+// Without it each signature is judged when it is checked, so a signature that+// expires while the walk is under way is not reported valid.export const resolveDsChain = async (domain: string,query: DsChainQuery,+ now?: number,): Promise<DsChain> => {- const queried = domain.toLowerCase().replace(/\.$/, '') || '.';+ const queried = canonicalDnsName(domain) || '.';const names = suffixesFor(queried);const zones: DsChainZone[] = [];let verdict: DsChainVerdict = 'intact';@@ -152,26 +167,34 @@ export const resolveDsChain = async () ||soaResponse!.answers.some((answer) => answer.type === 'SOA');if (!isApex) continue;- const matches = dsRecords.map((ds) =>- keys.some((key) => dsMatchesKey(ds, key, name)),- );- // Only supported digests decide, and SHA-1 is ignored next to a stronger- // one (RFC 4509 section 3), so a matching SHA-1 record cannot hide a- // broken stronger digest. With no supported digest the zone cannot be- // authenticated and counts as unsigned (RFC 4035 section 5.2).- const supported = dsRecords.flatMap((ds, i) =>- DIGEST_HASH_ALGOS[ds.digestType] ? [{ ds, matched: matches[i] }] : [],- );- const hasStrong = supported.some(({ ds }) => ds.digestType !== 1);- const deciding = supported.filter(- ({ ds }) => !hasStrong || ds.digestType !== 1,- );- const ownStatus: DsChainVerdict =- deciding.length === 0- ? 'unsigned'- : deciding.some(({ matched }) => matched)- ? 'intact'- : 'mismatch';+ const link = linkKeys(name, dsRecords, keys);++ let ownStatus: DsChainVerdict =+ link.status === 'linked' ? 'intact' : link.status;+ let keySignature: DsChainZone['keySignature'];+ if (link.status === 'linked' && verdict === 'intact') {+ // Only DS-linked keys may vouch for the key set: a zone must not+ // authenticate its DNSKEY RRset with a key nothing above it links.+ // Below a break nothing vouches for the DS itself, so there is no+ // trusted key to check against.+ const { outcome, rrsig } = checkRrsetSignatures({+ type: 'DNSKEY',+ rdatas: keys.map((key) => dnskeyRdata(key)),+ rrsigs: keyResponse.coveringRrsigs ?? [],+ ownerName: name,+ signerName: name,+ keys: link.linkedKeys,+ now: now ?? Math.floor(Date.now() / 1000),+ });+ keySignature = {+ outcome,+ ...(rrsig && {+ inception: rrsig.inception,+ expiration: rrsig.expiration,+ }),+ };+ ownStatus = outcome === 'valid' ? 'intact' : 'bad-signature';+ }if (verdict === 'intact' && ownStatus !== 'intact') {verdict = ownStatus;breakAt = name;@@ -180,18 +203,19 @@ export const resolveDsChain = async (zones.push({name,keys: keys.map((key) => ({- keyTag: keyTag(key),+ keyTag: dnskeyKeyTag(key),algorithm: key.algorithm,- algorithmName: dnssecAlgorithmName(key.algorithm),- isSep: (key.flags & 1) !== 0,+ algorithmName: algorithmName(key.algorithm),+ isSep: isSepKey(key),})),dsRecords: dsRecords.map((ds, i) => ({keyTag: ds.keyTag,digestType: ds.digestType,digestHex: ds.digest.toString('hex').toUpperCase(),- matched: matches[i],+ matched: link.matched[i],weakDigest: isWeakDigest(ds.digestType),})),+ ...(keySignature && { keySignature }),status: verdict,});}diff --git a/lib/dnssec/ds.test.ts b/lib/dnssec/ds.test.tsindex ed41af5..e55a02b 100644--- a/lib/dnssec/ds.test.ts+++ b/lib/dnssec/ds.test.ts@@ -1,65 +1,107 @@+import type { DnskeyData } from 'dns-packet';import { describe, expect, it } from 'vitest';-import { dsDigest, dsMatchesKey } from './ds';+import { dsDigest, linkKeys } from './ds';import { RFC_DS, RFC_KEY } from './test-vectors';-import { computeKeyTag, dnskeyKeyTag, dnskeyRdata } from './wire';+import { dnskeyKeyTag } from './wire';++const ZONE = 'dskey.example.com';++// A DS for `key` at ZONE, optionally with a zeroed (non-matching) digest.+const dsFor = (digestType: number, key = RFC_KEY, corrupt = false) => {+ // Digest types without a hash here (e.g. 3, GOST) get a SHA-256 stand-in.+ const digest = dsDigest(ZONE, key, digestType) ?? dsDigest(ZONE, key, 2)!;+ return {+ keyTag: dnskeyKeyTag(key),+ algorithm: key.algorithm,+ digestType,+ digest: corrupt ? Buffer.alloc(digest.length) : digest,+ };+};describe('DS digest linkage', () => {it('computes the RFC 4034 DS digest (SHA-1)', () => {- expect(- dsDigest('dskey.example.com', RFC_KEY, 1)?.toString('hex').toUpperCase(),- ).toBe('2BB183AF5F22588179A53B0A98631FAD1A292118');+ expect(dsDigest(ZONE, RFC_KEY, 1)?.toString('hex').toUpperCase()).toBe(+ '2BB183AF5F22588179A53B0A98631FAD1A292118',+ );});- it('matches a DS to its DNSKEY', () => {- expect(dsMatchesKey(RFC_DS, RFC_KEY, 'dskey.example.com')).toBe(true);+ it('returns null for an unsupported digest type', () => {+ expect(dsDigest(ZONE, RFC_KEY, 99)).toBeNull();});- it('rejects a DS for the wrong owner name', () => {- expect(dsMatchesKey(RFC_DS, RFC_KEY, 'other.example.com')).toBe(false);+ it('links a DS to its DNSKEY', () => {+ expect(linkKeys(ZONE, [RFC_DS], [RFC_KEY])).toEqual({+ status: 'linked',+ linkedKeys: [RFC_KEY],+ matched: [true],+ });});- it('returns null for an unsupported digest type', () => {- expect(dsDigest('dskey.example.com', RFC_KEY, 99)).toBeNull();+ it('rejects a DS for the wrong owner name', () => {+ expect(linkKeys('other.example.com', [RFC_DS], [RFC_KEY])).toMatchObject({+ status: 'mismatch',+ matched: [false],+ });});- it('matches an RSAMD5 DS using the Appendix B.1 key tag', () => {+ it('matches an RSAMD5 DS by the Appendix B.1 key tag only', () => {const key = {flags: 256,algorithm: 1,key: Buffer.from([0x01, 0xaa, 0xbb, 0xcc]),};const ds = {- keyTag: dnskeyKeyTag(key),+ keyTag: 0xaabb,algorithm: 1,digestType: 1,digest: dsDigest('example.com', key, 1)!,};- expect(ds.keyTag).toBe(0xaabb);- expect(dsMatchesKey(ds, key, 'example.com')).toBe(true);+ expect(linkKeys('example.com', [ds], [key]).matched).toEqual([true]);+ // 0xc177: the general-case checksum, which RSAMD5 does not use.expect(- dsMatchesKey(- { ...ds, keyTag: computeKeyTag(dnskeyRdata(key)) },- key,- 'example.com',- ),- ).toBe(false);+ linkKeys('example.com', [{ ...ds, keyTag: 0xc177 }], [key]).matched,+ ).toEqual([false]);});it('rejects a DNSKEY without the Zone Key flag', () => {const key = { ...RFC_KEY, flags: RFC_KEY.flags & ~0x0100 };- expect(dsMatchesKey(RFC_DS, key, 'dskey.example.com')).toBe(false);+ expect(linkKeys(ZONE, [RFC_DS], [key]).status).toBe('mismatch');});it('rejects a DS whose key tag does not match the DNSKEY', () => {// Correct digest + algorithm but a deliberately wrong key tag: a validator// would never select this key, so it must not count as a match.- const good = {- ...RFC_DS,- keyTag: dnskeyKeyTag(RFC_KEY),- digest: dsDigest('example', RFC_KEY, 1)!,- };- const tagMismatch = { ...good, keyTag: good.keyTag + 1 };- expect(dsMatchesKey(tagMismatch, RFC_KEY, 'example')).toBe(false);+ const ds = dsFor(1);+ expect(+ linkKeys(ZONE, [{ ...ds, keyTag: ds.keyTag + 1 }], [RFC_KEY]).status,+ ).toBe('mismatch');+ });++ it('ignores SHA-1 next to a stronger digest', () => {+ const link = (...ds: ReturnType<typeof dsFor>[]) =>+ linkKeys(ZONE, ds, [RFC_KEY]);++ expect(link(dsFor(2), dsFor(1, RFC_KEY, true))).toMatchObject({+ status: 'linked',+ matched: [true, false],+ });+ expect(link(dsFor(1), dsFor(2, RFC_KEY, true)).status).toBe('mismatch');+ expect(link(dsFor(1), dsFor(4, RFC_KEY, true)).status).toBe('mismatch');+ expect(link(dsFor(2, RFC_KEY, true), dsFor(4)).status).toBe('linked');+ });++ it('treats a DS set with only unsupported digests as unsigned', () => {+ expect(linkKeys(ZONE, [dsFor(3)], [RFC_KEY]).status).toBe('unsigned');+ });++ it('treats a DS for an unsupported signing algorithm as unsigned', () => {+ // DSA (3): the digest links, but no signature by it can be verified.+ const dsa: DnskeyData = { flags: 257, algorithm: 3, key: Buffer.alloc(64) };+ expect(linkKeys(ZONE, [dsFor(2, dsa)], [dsa])).toEqual({+ status: 'unsigned',+ linkedKeys: [],+ matched: [true],+ });});});diff --git a/lib/dnssec/ds.ts b/lib/dnssec/ds.tsindex 850a5ad..3dc2e93 100644--- a/lib/dnssec/ds.ts+++ b/lib/dnssec/ds.ts@@ -2,11 +2,11 @@ import { createHash } from 'node:crypto';import type { DnskeyData, DsData } from 'dns-packet';-import { DIGEST_HASH_ALGOS } from './algorithms';-import { dnskeyKeyTag, dnskeyRdata, wireName } from './wire';+import { digestHash, isSupportedSigningAlgorithm } from './algorithms';+import { dnskeyKeyTag, dnskeyRdata, isZoneKey, wireName } from './wire';-// DS digest linkage (RFC 4034 §5.1.4): does a parent's DS record actually-// hash to one of the child zone's DNSKEYs?+// DS digest linkage (RFC 4034 §5.1.4): which of a child zone's DNSKEYs do the+// parent's DS records actually hash to, and which of those DS records count?/** DS digest of a DNSKEY: hash(ownerName || DNSKEY RDATA). Null if digest type unsupported. */export const dsDigest = (@@ -14,7 +14,7 @@ export const dsDigest = (key: Pick<DnskeyData, 'flags' | 'algorithm' | 'key'>,digestType: number,): Buffer | null => {- const algo = DIGEST_HASH_ALGOS[digestType];+ const algo = digestHash(digestType);if (!algo) return null;return createHash(algo).update(Buffer.concat([wireName(zoneName), dnskeyRdata(key)]))@@ -29,15 +29,60 @@ export const dsDigest = (* tag is wrong, so a malformed DS (right digest, wrong tag) is correctly treated* as a non-match here too.*/-export const dsMatchesKey = (+const dsMatchesKey = (ds: DsData,key: DnskeyData,zoneName: string,): boolean => {// RFC 4034 §5.2: a DS may only point at a Zone Key (bit 7).- if ((key.flags & 0x0100) === 0) return false;+ if (!isZoneKey(key)) return false;if (ds.algorithm !== key.algorithm) return false;if (ds.keyTag !== dnskeyKeyTag(key)) return false;const digest = dsDigest(zoneName, key, ds.digestType);return digest !== null && digest.equals(ds.digest);};++export type DsLink = {+ // unsigned: no DS this validator can use, so the zone cannot be+ // authenticated (RFC 4035 §5.2). mismatch: the deciding DS records link no+ // key. linked: linkedKeys are the keys the deciding DS records vouch for.+ status: 'unsigned' | 'mismatch' | 'linked';+ linkedKeys: DnskeyData[];+ // Per DS record, in input order: whether it hashes to one of the keys,+ // deciding or not.+ matched: boolean[];+};++/**+ * Link a zone's DS set to its DNSKEYs. Only supported digests and signing+ * algorithms decide, and SHA-1 is ignored next to a stronger digest (RFC 4509+ * section 3), so a matching SHA-1 record cannot hide a broken stronger digest.+ */+export const linkKeys = (+ zoneName: string,+ dsRecords: DsData[],+ keys: DnskeyData[],+): DsLink => {+ const matchedKeys = dsRecords.map((ds) =>+ keys.filter((key) => dsMatchesKey(ds, key, zoneName)),+ );+ const supported = dsRecords.flatMap((ds, i) =>+ digestHash(ds.digestType) && isSupportedSigningAlgorithm(ds.algorithm)+ ? [{ ds, keys: matchedKeys[i] }]+ : [],+ );+ const hasStrong = supported.some(({ ds }) => ds.digestType !== 1);+ const linkedKeys = supported+ .filter(({ ds }) => !hasStrong || ds.digestType !== 1)+ .flatMap((deciding) => deciding.keys);+ return {+ status:+ supported.length === 0+ ? 'unsigned'+ : linkedKeys.length === 0+ ? 'mismatch'+ : 'linked',+ linkedKeys,+ matched: matchedKeys.map((matches) => matches.length > 0),+ };+};diff --git a/lib/dnssec/rrsig.test.ts b/lib/dnssec/rrsig.test.tsnew file mode 100644index 0000000..902d86f--- /dev/null+++ b/lib/dnssec/rrsig.test.ts@@ -0,0 +1,344 @@+import type { DnskeyData, RrsigData } from 'dns-packet';+import { describe, expect, it, vi } from 'vitest';++import type * as Algorithms from './algorithms';+import { verifyWithDnskey } from './algorithms';+import { checkRrsetSignatures } from './rrsig';+import { genKey, signDnskeyRrset } from './test-helpers';+import {+ ROOT_DNSKEY_RRSIG,+ ROOT_DNSKEYS,+ ROOT_NOW,+ WSKY_DNSKEY_RRSIG,+ WSKY_DNSKEYS,+ WSKY_NOW,+} from './test-vectors';+import { dnskeyKeyTag, dnskeyRdata } from './wire';++// Count signature verifications while keeping the real crypto.+vi.mock('./algorithms', async (importOriginal) => {+ const actual = await importOriginal<typeof Algorithms>();+ return { ...actual, verifyWithDnskey: vi.fn(actual.verifyWithDnskey) };+});++// Different key material with the same RFC 4034 key tag: moving `n` between+// two odd-offset bytes leaves the checksum unchanged.+const sameTagKey = (key: Buffer, n: number): Buffer => {+ const odd = [...key.keys()].filter((i) => i % 2 === 1);+ const up = odd.find((i) => key[i] + n <= 255)!;+ const down = odd.find((i) => i !== up && key[i] - n >= 0)!;+ const variant = Buffer.from(key);+ variant[up] += n;+ variant[down] -= n;+ return variant;+};++// A zone's DNSKEY RRset vouched for by its own keys, the way resolveDsChain checks+// it (there, narrowed to the DS-linked keys).+const dnskeyOutcome = (params: {+ rrsig: RrsigData;+ keys: DnskeyData[];+ ownerName: string;+ now: number;+}) =>+ checkRrsetSignatures({+ type: 'DNSKEY',+ rdatas: params.keys.map((key) => dnskeyRdata(key)),+ rrsigs: [params.rrsig],+ ownerName: params.ownerName,+ signerName: params.ownerName,+ keys: params.keys,+ now: params.now,+ }).outcome;++describe('checkRrsetSignatures over DNSKEY RRsets (golden vectors)', () => {+ it('verifies the real root DNSKEY RRSIG (RSASHA256)', () => {+ expect(+ dnskeyOutcome({+ rrsig: ROOT_DNSKEY_RRSIG,+ keys: ROOT_DNSKEYS,+ ownerName: '.',+ now: ROOT_NOW,+ }),+ ).toBe('valid');+ });++ it('verifies the real wsky.dev DNSKEY RRSIG (ECDSAP256SHA256)', () => {+ expect(+ dnskeyOutcome({+ rrsig: WSKY_DNSKEY_RRSIG,+ keys: WSKY_DNSKEYS,+ ownerName: 'wsky.dev',+ now: WSKY_NOW,+ }),+ ).toBe('valid');+ });++ it('rejects an expired signature', () => {+ expect(+ dnskeyOutcome({+ rrsig: ROOT_DNSKEY_RRSIG,+ keys: ROOT_DNSKEYS,+ ownerName: '.',+ now: ROOT_DNSKEY_RRSIG.expiration + 1,+ }),+ ).toBe('expired');+ });++ it('rejects a not-yet-valid signature', () => {+ expect(+ dnskeyOutcome({+ rrsig: ROOT_DNSKEY_RRSIG,+ keys: ROOT_DNSKEYS,+ ownerName: '.',+ now: ROOT_DNSKEY_RRSIG.inception - 1,+ }),+ ).toBe('not-yet-valid');+ });++ it('rejects a tampered signature', () => {+ const signature = Buffer.from(ROOT_DNSKEY_RRSIG.signature);+ signature[0] ^= 0xff;+ expect(+ dnskeyOutcome({+ rrsig: { ...ROOT_DNSKEY_RRSIG, signature },+ keys: ROOT_DNSKEYS,+ ownerName: '.',+ now: ROOT_NOW,+ }),+ ).toBe('invalid');+ });++ it('rejects when the RRset is altered (a DNSKEY dropped)', () => {+ // The RRSIG covers the whole DNSKEY RRset; removing any key changes the+ // canonical bytes and the signature no longer matches.+ expect(+ dnskeyOutcome({+ rrsig: ROOT_DNSKEY_RRSIG,+ keys: ROOT_DNSKEYS.slice(1),+ ownerName: '.',+ now: ROOT_NOW,+ }),+ ).toBe('invalid');+ });++ it('rejects the wrong owner name', () => {+ expect(+ dnskeyOutcome({+ rrsig: WSKY_DNSKEY_RRSIG,+ keys: WSKY_DNSKEYS,+ ownerName: 'other.dev',+ now: WSKY_NOW,+ }),+ ).toBe('invalid');+ });++ it('rejects when no served key has the signing tag', () => {+ expect(+ dnskeyOutcome({+ rrsig: { ...ROOT_DNSKEY_RRSIG, keyTag: 11111 },+ keys: ROOT_DNSKEYS,+ ownerName: '.',+ now: ROOT_NOW,+ }),+ ).toBe('unauthenticated-signer');+ });++ it('rejects a DNSKEY RRSIG whose signer name is not the zone apex', () => {+ const k = genKey(13);+ const rrsig = signDnskeyRrset('example', [k.dnskey], k, {+ inception: 1000,+ expiration: 2000,+ });+ // Crypto-valid signature, but the declared signer is a different zone --+ // validating resolvers reject this (RFC 4035 §5.3.1).+ const wrongSigner = { ...rrsig, signersName: 'other' };+ expect(+ dnskeyOutcome({+ rrsig: wrongSigner,+ keys: [k.dnskey],+ ownerName: 'example',+ now: 1500,+ }),+ ).toBe('invalid');+ });++ it('rejects a DNSKEY RRSIG made by a revoked key (RFC 5011)', () => {+ const k = genKey(13);+ const revoked: DnskeyData = { ...k.dnskey, flags: k.dnskey.flags | 0x0080 };+ const rrsig = signDnskeyRrset(+ 'example',+ [revoked],+ { ...k, dnskey: revoked },+ { inception: 1000, expiration: 2000 },+ );+ expect(+ dnskeyOutcome({+ rrsig,+ keys: [revoked],+ ownerName: 'example',+ now: 1500,+ }),+ ).toBe('unauthenticated-signer');+ });++ it('rejects a DNSKEY RRSIG made by a key without the ZONE flag', () => {+ const k = genKey(13);+ const nonZone: DnskeyData = { ...k.dnskey, flags: 1 };+ const rrsig = signDnskeyRrset(+ 'example',+ [nonZone],+ { ...k, dnskey: nonZone },+ { inception: 1000, expiration: 2000 },+ );+ expect(+ dnskeyOutcome({+ rrsig,+ keys: [nonZone],+ ownerName: 'example',+ now: 1500,+ }),+ ).toBe('unauthenticated-signer');+ });++ it('rejects a crypto-valid DNSKEY RRSIG with an invalid Labels count', () => {+ const signer = genKey(13);+ const rrsig = signDnskeyRrset('example', [signer.dnskey], signer, {+ inception: 1000,+ expiration: 2000,+ labels: 2,+ });++ expect(+ dnskeyOutcome({+ rrsig,+ keys: [signer.dnskey],+ ownerName: 'example',+ now: 1500,+ }),+ ).toBe('invalid');+ });+ it('tries every key sharing the signer tag, so a legitimate collision verifies', () => {+ const signer = genKey(13);+ const decoy = { ...signer.dnskey, key: sameTagKey(signer.dnskey.key, 1) };+ expect(dnskeyKeyTag(decoy)).toBe(dnskeyKeyTag(signer.dnskey));+ const keys = [decoy, signer.dnskey];+ const rrsig = signDnskeyRrset('example', keys, signer, {+ inception: 1000,+ expiration: 2000,+ });++ expect(+ dnskeyOutcome({ rrsig, keys, ownerName: 'example', now: 1500 }),+ ).toBe('valid');+ });++ it('bounds signature checks when many linked keys share a key tag (KeyTrap)', () => {+ const base = { flags: 257, algorithm: 13, key: Buffer.alloc(64, 0x40) };+ const keys = Array.from({ length: 16 }, (_, n) => ({+ ...base,+ key: sameTagKey(base.key, n),+ }));+ expect(new Set(keys.map((key) => dnskeyKeyTag(key))).size).toBe(1);+ const rrsigs = keys.map(+ (_, n): RrsigData => ({+ typeCovered: 'DNSKEY',+ algorithm: 13,+ labels: 1,+ originalTTL: 3600,+ expiration: 2000,+ inception: 1000,+ keyTag: dnskeyKeyTag(base),+ signersName: 'example',+ signature: Buffer.alloc(64, n),+ }),+ );+ vi.mocked(verifyWithDnskey).mockClear();++ const { outcome } = checkRrsetSignatures({+ type: 'DNSKEY',+ rdatas: keys.map((key) => dnskeyRdata(key)),+ rrsigs,+ ownerName: 'example',+ signerName: 'example',+ keys,+ now: 1500,+ });++ expect(outcome).toBe('invalid');+ expect(vi.mocked(verifyWithDnskey).mock.calls.length).toBeLessThanOrEqual(+ 8,+ );+ });++ it('tries the longest-lived RRSIG first, whatever the answer order', () => {+ const signer = genKey(13);+ const keys = [signer.dnskey];+ const genuine = signDnskeyRrset('example', keys, signer, {+ inception: 1000,+ expiration: 3000,+ });+ // Enough shorter-lived forgeries to spend the whole budget.+ const forged = Array.from(+ { length: 8 },+ (_, n): RrsigData => ({+ ...genuine,+ expiration: 2000 + n,+ signature: Buffer.alloc(64, n + 1),+ }),+ );+ const outcome = (rrsigs: RrsigData[]) =>+ checkRrsetSignatures({+ type: 'DNSKEY',+ rdatas: keys.map((key) => dnskeyRdata(key)),+ rrsigs,+ ownerName: 'example',+ signerName: 'example',+ keys,+ now: 1500,+ }).outcome;++ expect(outcome([...forged, genuine])).toBe('valid');+ expect(outcome([genuine, ...forged])).toBe('valid');+ });++ it('checks a key linked twice only once', () => {+ // E.g. one key linked by both a SHA-256 and a SHA-384 DS record.+ const signer = genKey(13);+ const rrsig = {+ ...signDnskeyRrset('example', [signer.dnskey], signer, {+ inception: 1000,+ expiration: 2000,+ }),+ signature: Buffer.alloc(64, 1),+ };+ vi.mocked(verifyWithDnskey).mockClear();++ expect(+ dnskeyOutcome({+ rrsig,+ keys: [signer.dnskey, { ...signer.dnskey }],+ ownerName: 'example',+ now: 1500,+ }),+ ).toBe('invalid');+ expect(vi.mocked(verifyWithDnskey)).toHaveBeenCalledTimes(1);+ });++ it('verifies a DNSKEY RRSIG despite a duplicated DNSKEY record', () => {+ const key = genKey(13);+ const rrsig = signDnskeyRrset('example', [key.dnskey], key, {+ inception: 1000,+ expiration: 2000,+ });++ expect(+ dnskeyOutcome({+ rrsig,+ keys: [key.dnskey, key.dnskey],+ ownerName: 'example',+ now: 1500,+ }),+ ).toBe('valid');+ });+});diff --git a/lib/dnssec/rrsig.ts b/lib/dnssec/rrsig.tsnew file mode 100644index 0000000..0888e83--- /dev/null+++ b/lib/dnssec/rrsig.ts@@ -0,0 +1,222 @@+import type { DnskeyData, RrsigData } from 'dns-packet';+import { toType } from 'dns-packet/types';++import { canonicalDnsName } from '@/lib/resolvers/base';++import { verifyWithDnskey } from './algorithms';+import {+ canonicalRr,+ dnskeyKeyTag,+ dnskeyRdata,+ isEligibleSigner,+ rrsigSigningPrefix,+} from './wire';++// RRSIG verification (RFC 4034 §3.1.8.1): decide what an RRset's covering+// signatures establish.++type Signer = { key: DnskeyData; tag: number };++// Keys carrying the REVOKE bit are excluded: validators must not accept+// signatures from a key that revokes itself (RFC 5011 §2.1). A key listed+// twice (say, linked by both a SHA-256 and a SHA-384 DS) is kept once, so it+// is never checked twice. Tags are computed once per RRset, not once per+// (RRSIG, key) pair.+const eligibleSigners = (keys: DnskeyData[]): Signer[] => {+ const seen = new Set<string>();+ return keys.filter(isEligibleSigner).flatMap((key) => {+ const rdata = dnskeyRdata(key).toString('hex');+ if (seen.has(rdata)) return [];+ seen.add(rdata);+ return [{ key, tag: dnskeyKeyTag(key) }];+ });+};++/**+ * A 16-bit key tag is a checksum, not an identifier: distinct keys can share a+ * tag (and an attacker can craft one that does), so signer selection must try+ * every candidate matching the RRSIG's (algorithm, key tag) pair, within+ * MAX_VERIFICATIONS -- gating on the pair alone would let a colliding key+ * impersonate the real signer, and picking only the first match would falsely+ * reject the second of two legitimately colliding keys.+ */+const signerCandidates = (signers: Signer[], rrsig: RrsigData): DnskeyData[] =>+ signers+ .filter(+ ({ key, tag }) =>+ key.algorithm === rrsig.algorithm && tag === rrsig.keyTag,+ )+ .map(({ key }) => key);++// KeyTrap (CVE-2023-50387): colliding key tags and stacks of RRSIGs let one+// answer demand a signature check per (RRSIG, key) pair. Like validating+// resolvers, stop after a small budget: signature checks past it are skipped+// and count as invalid, so a valid signature the budget never reaches does not+// make the RRset valid. RRSIGs are tried longest-lived first, so the outcome+// does not depend on answer order. Honest zones need one check per RRSIG and+// signing key, a few during a rollover.+const MAX_VERIFICATIONS = 8;++export type RrsetSignatureOutcome =+ | 'valid'+ // No RRSIG covers the type at all.+ | 'missing'+ // RRSIGs exist, but none was made by a trusted key.+ | 'unauthenticated-signer'+ | 'expired'+ | 'not-yet-valid'+ | 'invalid';++type RrsetSignatureCheck = {+ outcome: RrsetSignatureOutcome;+ // The signature that explains the outcome. Its fields are observed claims+ // unless the outcome is `valid`. Absent only when `missing`.+ rrsig?: RrsigData;+};++type RrsetSignatureParams = {+ type: string;+ // Canonical RDATA of each record in the RRset (RFC 4034 §6.2).+ rdatas: Buffer[];+ // RRSIGs served with the answer; only those covering `type` count.+ rrsigs: RrsigData[];+ ownerName: string;+ signerName: string;+ // Keys trusted to sign this RRset. Signatures by any other key (including+ // revoked ones, which RFC 5011 §2.1 strips from the trusted set) carry no+ // weight at all.+ keys: DnskeyData[];+ // Unix seconds the validity window is judged against.+ now: number;+};++const labelCount = (name: string): number => {+ const normalized = canonicalDnsName(name);+ return normalized ? normalized.split('.').length : 0;+};++/** Every RRSIG condition that does not require running its signing algorithm. */+const metadataFailure = (+ rrsig: RrsigData,+ { ownerName, signerName, now }: RrsetSignatureParams,+): 'expired' | 'not-yet-valid' | 'invalid' | null => {+ if (canonicalDnsName(rrsig.signersName) !== canonicalDnsName(signerName)) {+ return 'invalid';+ }+ // ponytail: exact label count, so no wildcard expansions; add RFC 4035+ // §5.3.4 handling when leaf RRsets (which can be expansions) get checked.+ if (rrsig.labels !== labelCount(ownerName)) return 'invalid';+ if (now < rrsig.inception) return 'not-yet-valid';+ if (now > rrsig.expiration) return 'expired';+ return null;+};++// An RRset is a set: duplicate copies of an identical RR in a packet must+// contribute one canonical entry, or the signed data diverges from what the+// signer hashed and a valid signature reads as bogus (RFC 4034 §6.3). Sorted+// first, so duplicates are neighbours.+const canonicalRdataSet = (rdatas: Buffer[]): Buffer[] =>+ [...rdatas]+ .sort(Buffer.compare)+ .filter((rdata, i, sorted) => i === 0 || !rdata.equals(sorted[i - 1]));++/**+ * Whether `rrsig` cryptographically checks out over the canonical RRset. Each+ * verification spends one unit of `budget`; with none left it is false.+ */+const verifies = (+ rrsig: RrsigData,+ candidates: DnskeyData[],+ { type, rdatas, ownerName }: RrsetSignatureParams,+ budget: { remaining: number },+): boolean => {+ if (budget.remaining <= 0) return false;+ const rrType = toType(type);+ const prefix = rrsigSigningPrefix(rrsig);+ if (!rrType || !prefix) return false;++ const rrset = canonicalRdataSet(rdatas).map((rdata) =>+ canonicalRr(ownerName, rrType, rrsig.originalTTL, rdata),+ );++ const signedData = Buffer.concat([prefix, ...rrset]);+ return candidates.some((signer) => {+ if (budget.remaining <= 0) return false;+ budget.remaining--;+ return verifyWithDnskey(signer, signedData, rrsig.signature);+ });+};++// Total order over every field a caller may display, longest-lived first, so+// the same DNS answer in any order reports the same signature. (Rollovers+// legitimately publish several RRSIGs at once.)+const evidenceOrder = (a: RrsigData, b: RrsigData): number =>+ b.expiration - a.expiration ||+ a.keyTag - b.keyTag ||+ a.algorithm - b.algorithm ||+ a.signersName.localeCompare(b.signersName) ||+ b.inception - a.inception ||+ a.originalTTL - b.originalTTL;++const pick = (+ outcome: RrsetSignatureOutcome,+ rrsigs: RrsigData[],+): RrsetSignatureCheck => ({+ outcome,+ rrsig: [...rrsigs].sort(+ (a, b) =>+ // What matters about a not-yet-valid RRset is when it becomes valid.+ (outcome === 'not-yet-valid' ? a.inception - b.inception : 0) ||+ evidenceOrder(a, b),+ )[0],+});++/**+ * What the RRSIGs covering one RRset establish. The longest-lived signature+ * that verifies within MAX_VERIFICATIONS wins; with none verifying, the+ * outcome names the failure that best explains why: expired before+ * not-yet-valid before invalid.+ */+export const checkRrsetSignatures = (+ params: RrsetSignatureParams,+): RrsetSignatureCheck => {+ const { type, rrsigs, keys } = params;+ // Longest-lived first, so the budget goes to the signatures that would win;+ // the signature bytes break ties the displayed fields leave.+ const covering = rrsigs+ .filter((rrsig) => rrsig.typeCovered === type)+ .sort(+ (a, b) => evidenceOrder(a, b) || Buffer.compare(a.signature, b.signature),+ );+ if (!covering.length) return { outcome: 'missing' };++ const valid: RrsigData[] = [];+ const failures = {+ expired: [] as RrsigData[],+ 'not-yet-valid': [] as RrsigData[],+ invalid: [] as RrsigData[],+ };+ let sawTrustedSigner = false;+ const signers = eligibleSigners(keys);+ const budget = { remaining: MAX_VERIFICATIONS };++ for (const rrsig of covering) {+ const candidates = signerCandidates(signers, rrsig);+ if (!candidates.length) continue;+ sawTrustedSigner = true;++ const failure = metadataFailure(rrsig, params);+ if (failure) failures[failure].push(rrsig);+ else if (verifies(rrsig, candidates, params, budget)) valid.push(rrsig);+ else failures.invalid.push(rrsig);+ }++ if (valid.length) return pick('valid', valid);+ if (!sawTrustedSigner) return pick('unauthenticated-signer', covering);+ const outcome = failures.expired.length+ ? 'expired'+ : failures['not-yet-valid'].length+ ? 'not-yet-valid'+ : 'invalid';+ return pick(outcome, failures[outcome]);+};diff --git a/lib/dnssec/test-helpers.ts b/lib/dnssec/test-helpers.tsnew file mode 100644index 0000000..a2cc356--- /dev/null+++ b/lib/dnssec/test-helpers.ts@@ -0,0 +1,139 @@+import {+ sign as cryptoSign,+ generateKeyPairSync,+ type KeyObject,+} from 'node:crypto';++import type { DnskeyData, RrsigData } from 'dns-packet';++import { dnskeyKeyTag, dnskeyRdata, wireName } from './wire';++// Signing-side test helpers: generated keypairs plus canonical RRSIG+// construction (RFC 4034 §3.1.8.1 / §6), so tests can exercise the real verify+// path for keys we hold the private half of. The RRSIG prefix and the RR+// framing are encoded here independently of the verifier, so a bug in those+// cannot pass on both sides. Name encoding, DNSKEY RDATA and the+// key tag are shared with wire.ts; the captured real-world records in+// test-vectors.ts are what prove those against independent signers.++const u16 = (n: number): Buffer => {+ const b = Buffer.alloc(2);+ b.writeUInt16BE(n);+ return b;+};+const u32 = (n: number): Buffer => {+ const b = Buffer.alloc(4);+ b.writeUInt32BE(n >>> 0);+ return b;+};++// A live keypair whose DNSKEY we can sign with.+export const genKey = (+ algorithm: number,+): { priv: KeyObject; dnskey: DnskeyData } => {+ if (algorithm === 8) {+ const { privateKey, publicKey } = generateKeyPairSync('rsa', {+ modulusLength: 2048,+ });+ const jwk = publicKey.export({ format: 'jwk' }) as { n: string; e: string };+ const n = Buffer.from(jwk.n, 'base64url');+ const e = Buffer.from(jwk.e, 'base64url');+ return {+ priv: privateKey,+ dnskey: {+ flags: 257,+ algorithm,+ key: Buffer.concat([Buffer.from([e.length]), e, n]),+ },+ };+ }+ if (algorithm === 13) {+ const { privateKey, publicKey } = generateKeyPairSync('ec', {+ namedCurve: 'P-256',+ });+ const jwk = publicKey.export({ format: 'jwk' }) as { x: string; y: string };+ return {+ priv: privateKey,+ dnskey: {+ flags: 257,+ algorithm,+ key: Buffer.concat([+ Buffer.from(jwk.x, 'base64url'),+ Buffer.from(jwk.y, 'base64url'),+ ]),+ },+ };+ }+ // 15 Ed25519+ const { privateKey, publicKey } = generateKeyPairSync('ed25519');+ const jwk = publicKey.export({ format: 'jwk' }) as { x: string };+ return {+ priv: privateKey,+ dnskey: { flags: 257, algorithm, key: Buffer.from(jwk.x, 'base64url') },+ };+};++type Signer = { priv: KeyObject; dnskey: DnskeyData };++export const signData = (signer: Signer, data: Buffer): Buffer =>+ signer.dnskey.algorithm === 15+ ? cryptoSign(null, data, signer.priv)+ : signer.dnskey.algorithm === 13+ ? cryptoSign('sha256', data, {+ key: signer.priv,+ dsaEncoding: 'ieee-p1363',+ })+ : cryptoSign('sha256', data, signer.priv);++// Sign a zone's DNSKEY RRset with `signer`. `rrset` is every DNSKEY at the apex.+export const signDnskeyRrset = (+ name: string,+ rrset: DnskeyData[],+ signer: Signer,+ opts: {+ inception: number;+ expiration: number;+ // Defaults to the owner's label count.+ labels?: number;+ },+): RrsigData => {+ const type = 48; // DNSKEY+ const ttl = 3600;+ const { algorithm } = signer.dnskey;+ const keyTag = dnskeyKeyTag(signer.dnskey);+ const labels = opts.labels ?? name.split('.').filter(Boolean).length;+ const prefix = Buffer.concat([+ u16(type),+ Buffer.from([algorithm, labels]),+ u32(ttl),+ u32(opts.expiration),+ u32(opts.inception),+ u16(keyTag),+ wireName(name),+ ]);+ const owner = wireName(name);+ const records = rrset+ .map((key) => dnskeyRdata(key))+ .sort(Buffer.compare)+ .map((rdata) =>+ Buffer.concat([+ owner,+ u16(type),+ u16(1), // class IN+ u32(ttl),+ u16(rdata.length),+ rdata,+ ]),+ );+ return {+ typeCovered: 'DNSKEY',+ algorithm,+ labels,+ originalTTL: ttl,+ expiration: opts.expiration,+ inception: opts.inception,+ keyTag,+ signersName: name,+ signature: signData(signer, Buffer.concat([prefix, ...records])),+ };+};diff --git a/lib/dnssec/test-vectors.ts b/lib/dnssec/test-vectors.tsindex 52a61d2..88e2871 100644--- a/lib/dnssec/test-vectors.ts+++ b/lib/dnssec/test-vectors.ts@@ -1,4 +1,87 @@-import type { DnskeyData, DsData } from 'dns-packet';+import type { DnskeyData, DsData, RrsigData } from 'dns-packet';++// Golden vectors: real DNSKEY RRsets + their DNSKEY RRSIGs, captured with+// `dig +dnssec DNSKEY`. `now` is pinned inside each signature's validity window+// so these never flake. They verify the canonical encoding against independent,+// real-world signers (RSASHA256, ECDSAP256).++const dnskey = (+ flags: number,+ algorithm: number,+ keyB64: string,+): DnskeyData => ({+ flags,+ algorithm,+ key: Buffer.from(keyB64, 'base64'),+});++// Root zone (RSASHA256), signed by the IANA KSK, key tag 20326.+export const ROOT_DNSKEYS: DnskeyData[] = [+ dnskey(+ 256,+ 8,+ 'AwEAAeCYD6Z7WWKVLeuWgowKP+3g+Gs1cnLKq7a3CaQxQpv8bfuFVI0WnG33qaSH/Mw9IBgifrdzf4XY/DQLnyBJ9MfaOyAWuEaEmYJ+GQPiwVVfstGwSA1McfFJUttTgq2Huu74KARhtA8wPo/N3XcyYQtNhz+qCM5NBb3ecx/naw6sYab9LxS6f2cU0q03++BP5Ks0Uef8WJCa/1izCYE+vMkwoltV+tENa3hpXiZ7jle/xdgaZrPi5ZGmyLVI34g1XVYrNlsCCTmNvFQIfzW5STFQFsQpizczyFn9r3LzSxxPCNwdlCG84bER0BmdwqbF6Tanv+FxMOavrahkj4wIy5k=',+ ),+ dnskey(+ 257,+ 8,+ 'AwEAAaz/tAm8yTn4Mfeh5eyI96WSVexTBAvkMgJzkKTOiW1vkIbzxeF3+/4RgWOq7HrxRixHlFlExOLAJr5emLvN7SWXgnLh4+B5xQlNVz8Og8kvArMtNROxVQuCaSnIDdD5LKyWbRd2n9WGe2R8PzgCmr3EgVLrjyBxWezF0jLHwVN8efS3rCj/EWgvIWgb9tarpVUDK/b58Da+sqqls3eNbuv7pr+eoZG+SrDK6nWeL3c6H5Apxz7LjVc1uTIdsIXxuOLYA4/ilBmSVIzuDWfdRUfhHdY6+cn8HFRm+2hM8AnXGXws9555KrUB5qihylGa8subX2Nn6UwNR1AkUTV74bU=',+ ),+ dnskey(+ 256,+ 8,+ 'AwEAAb5dDYffpgAJ8VUGLwQtWXPlQWsjIFJtCM00/XaKU+8ln+ofah3q2KxEIjvzQg+nqdxRj+8emtPne1mtYcbFWP4Q9E+DniOJLK09R05FuzvGbrG7DDdRDUX/cedFdV7O8pFEAYpJqYNR9BCTIAV973DO2biauKSA31b7I2lK/woxoR1tf5cqJ4SMbJUviuHicAEoUi2ATswloZNWd5T5thmEFZnxFx7D5UgKCY7oflS7+GU7dNJwEtmFnWYVETHN0kHXVz6aguouaAZp706YXNIoR/iTgQhmsR7XX+wL0Z8QM2LxQIyU6vRZ06IyuJMGRMiwkSuGElbumyBt12JZbrU=',+ ),+ dnskey(+ 257,+ 8,+ 'AwEAAa96jeuknZlaeSrvyAJj6ZHv28hhOKkx3rLGXVaC6rXTsDc449/cidltpkyGwCJNnOAlFNKF2jBosZBU5eeHspaQWOmOElZsjICMQMC3aeHbGiShvZsx4wMYSjH8e7Vrhbu6irwCzVBApESjbUdpWWmEnhathWu1jo+siFUiRAAxm9qyJNg/wOZqqzL/dL/q8PkcRU5oUKEpUge71M3ej2/7CPqpdVwuMoTvoB+ZOT4YeGyxMvHmbrxlFzGOHOijtzN+u1TQNatX2XBuzZNQ1K+s2CXkPIZo7s6JgZyvaBevYtxPvYLw4z9mR7K2vaF18UYH9Z9GNUUeayffKC73PYc=',+ ),+];+export const ROOT_DNSKEY_RRSIG: RrsigData = {+ typeCovered: 'DNSKEY',+ algorithm: 8,+ labels: 0,+ originalTTL: 172800,+ expiration: 1784678400, // 2026-07-22 00:00:00 UTC+ inception: 1782864000, // 2026-07-01 00:00:00 UTC+ keyTag: 20326,+ signersName: '.',+ signature: Buffer.from(+ 'PIWRr97cYGmtOj+ITFeA8BqCHizd3FW/RykfcnMqVXQ7OqcE3lACjOoYfj+aj1iZfAP59iNsOWJz/J7AUAqxb7CpPIO9bJxllbhHyRkKEJhCO4M/MvlYAMmc6G8gnI4yBZEIiRPaFOP0Ux04kX/CMk4KoM89Rv4sQy02hsF7HeQb7GAowyKSW3hy0TazdwGeRyC00SjDCVZMVNCc8gPF4ZZsWgSmkpDDj3H1V5JSzLiu/mtf0k/6oHTi0IrsaBKywdQO9JgAOvayfW0hhySQ2FoQSrZC5Hb1btjvkzj49LxGTy0qvoRdHLjmnrsk8BqNlekAhJoLtIB+HEla/s1/DQ==',+ 'base64',+ ),+};+export const ROOT_NOW = 1782950400; // within the window++// wsky.dev (ECDSAP256SHA256), signed by its KSK, key tag 2371.+export const WSKY_DNSKEYS: DnskeyData[] = [+ dnskey(+ 257,+ 13,+ 'mdsswUyr3DPW132mOi8V9xESWE8jTo0dxCjjnopKl+GqJxpVXckHAeF+KkxLbxILfDLUT0rAK9iUzy1L53eKGQ==',+ ),+ dnskey(+ 256,+ 13,+ 'oJMRESz5E4gYzS/q6XDrvU1qMPYIjCWzJaOau8XNEZeqCYKD5ar0IRd8KqXXFJkqmVfRvMGPmM1x8fGAa2XhSA==',+ ),+];+export const WSKY_DNSKEY_RRSIG: RrsigData = {+ typeCovered: 'DNSKEY',+ algorithm: 13,+ labels: 2,+ originalTTL: 3600,+ expiration: 1787564388,+ inception: 1782293988,+ keyTag: 2371,+ signersName: 'wsky.dev',+ signature: Buffer.from(+ 'bWnpt80RbJPgeMeaIM+Q+XMuXAgewTsW04P9ltGSdyZEtexlICuObJiACCFjcH4lhVZjza37kRluO+CvtZtruw==',+ 'base64',+ ),+};+export const WSKY_NOW = 1782380388; // within the window// RFC 4034 Appendix B worked example: dskey.example.com.export const RFC_KEY: DnskeyData = {diff --git a/lib/dnssec/wire.test.ts b/lib/dnssec/wire.test.tsindex c813f9d..e9293ef 100644--- a/lib/dnssec/wire.test.ts+++ b/lib/dnssec/wire.test.ts@@ -1,11 +1,10 @@import { describe, expect, it } from 'vitest';import { RFC_KEY } from './test-vectors';-import { computeKeyTag, dnskeyKeyTag, dnskeyRdata } from './wire';+import { dnskeyKeyTag } from './wire';describe('canonical wire encoding', () => {it('computes the RFC 4034 key tag', () => {- expect(computeKeyTag(dnskeyRdata(RFC_KEY))).toBe(60485);expect(dnskeyKeyTag(RFC_KEY)).toBe(60485);});@@ -15,7 +14,7 @@ describe('canonical wire encoding', () => {algorithm: 1,key: Buffer.from([0x01, 0xaa, 0xbb, 0xcc]),};+ // The general-case checksum over this RDATA would be 0xc177.expect(dnskeyKeyTag(key)).toBe(0xaabb);- expect(dnskeyKeyTag(key)).not.toBe(computeKeyTag(dnskeyRdata(key)));});});diff --git a/lib/dnssec/wire.ts b/lib/dnssec/wire.tsindex a1d0d99..0e82943 100644--- a/lib/dnssec/wire.ts+++ b/lib/dnssec/wire.ts@@ -1,14 +1,17 @@-import type { DnskeyData } from 'dns-packet';+import type { DnskeyData, RrsigData } from 'dns-packet';+import { toType } from 'dns-packet/types';-// Wire-format pieces the DS digest needs (RFC 4034 §5.1.4 / Appendix B).-// RRSIG canonicalization stays with the signature checker.+import { canonicalDnsName } from '@/lib/resolvers/base';++// Canonical wire-format encoding (RFC 4034 §6): domain names, DNSKEY RDATA, and+// the exact byte layout an RRSIG signature is computed over./** Canonical wire-format encoding of a domain name (lowercase, length-prefixed). */export const wireName = (name: string): Buffer => {- const clean = name.replace(/\.$/, '');+ const clean = canonicalDnsName(name);if (clean === '') return Buffer.from([0]); // rootconst parts: Buffer[] = [];- for (const label of clean.toLowerCase().split('.')) {+ for (const label of clean.split('.')) {const labelBuf = Buffer.from(label, 'ascii');parts.push(Buffer.from([labelBuf.length]), labelBuf);}@@ -27,8 +30,64 @@ export const dnskeyRdata = (return Buffer.concat([head, key.key]);};+// DNSKEY flags (RFC 4034 §2.1.1, RFC 5011 §7). Decoded here so the bit+// positions live in exactly one place: every caller asks a named question+// instead of re-spelling a mask.+const DNSKEY_ZONE = 0x0100;+const DNSKEY_REVOKE = 0x0080;+const DNSKEY_SEP = 0x0001;++type KeyFlags = Pick<DnskeyData, 'flags'>;++/** Bit 7: the key may sign records in this zone (RFC 4034 §2.1.1). */+export const isZoneKey = (key: KeyFlags): boolean =>+ (key.flags & DNSKEY_ZONE) !== 0;++/** Bit 15: Secure Entry Point, conventionally the KSK a DS points at. */+export const isSepKey = (key: KeyFlags): boolean =>+ (key.flags & DNSKEY_SEP) !== 0;++/**+ * A key eligible to make a signature: a zone key that has not revoked itself+ * (bit 8; validators must not trust a revoked key, RFC 5011 §2.1).+ */+export const isEligibleSigner = (key: KeyFlags): boolean =>+ isZoneKey(key) && (key.flags & DNSKEY_REVOKE) === 0;++/** RRSIG RDATA up to (but excluding) the signature, per RFC 4034 §3.1.8.1. */+export const rrsigSigningPrefix = (rrsig: RrsigData): Buffer | null => {+ // dns-packet's toType returns 0 for names it doesn't know.+ const typeCovered = toType(rrsig.typeCovered);+ if (!typeCovered) return null;+ const head = Buffer.alloc(18);+ head.writeUInt16BE(typeCovered, 0);+ head.writeUInt8(rrsig.algorithm, 2);+ head.writeUInt8(rrsig.labels, 3);+ head.writeUInt32BE(rrsig.originalTTL >>> 0, 4);+ head.writeUInt32BE(rrsig.expiration >>> 0, 8);+ head.writeUInt32BE(rrsig.inception >>> 0, 12);+ head.writeUInt16BE(rrsig.keyTag, 16);+ // Signer's name in canonical (lowercase, uncompressed) wire form.+ return Buffer.concat([head, wireName(rrsig.signersName)]);+};++/** One canonical RR: owner | type | class(IN) | originalTTL | rdlen | rdata. */+export const canonicalRr = (+ owner: string,+ type: number,+ originalTTL: number,+ rdata: Buffer,+): Buffer => {+ const head = Buffer.alloc(10);+ head.writeUInt16BE(type, 0);+ head.writeUInt16BE(1, 2); // class IN+ head.writeUInt32BE(originalTTL >>> 0, 4);+ head.writeUInt16BE(rdata.length, 8);+ return Buffer.concat([wireName(owner), head, rdata]);+};+/** Key tag computation per RFC 4034 Appendix B (general case). */-export const computeKeyTag = (rdata: Buffer): number => {+const computeKeyTag = (rdata: Buffer): number => {let ac = 0;for (let i = 0; i < rdata.length; i++) {ac += i & 1 ? rdata[i] : rdata[i] << 8;diff --git a/lib/resolvers/authoritative.test.ts b/lib/resolvers/authoritative.test.tsindex 63c4ca3..6c2e545 100644--- a/lib/resolvers/authoritative.test.ts+++ b/lib/resolvers/authoritative.test.ts@@ -219,6 +219,63 @@ describe('AuthoritativeResolver transport policy', () => {);});+ it('keeps the DO bit across a referral and returns only covering RRSIGs', async () => {+ const rrsig = (name: string, typeCovered: string) =>+ ({ name, type: 'RRSIG', ttl: 300, data: { typeCovered } }) as Answer;+ const udpTransport = vi.fn<AuthoritativeUdpTransport>(+ async ({ domain, recordType, nameserver }) =>+ nameserver === '192.0.2.1'+ ? ({+ ...response(domain, recordType, 'NOERROR'),+ authorities: [+ {+ name: 'example.com',+ type: 'NS',+ ttl: 300,+ data: 'ns1.example.net',+ },+ ],+ additionals: [+ {+ name: 'ns1.example.net',+ type: 'A',+ ttl: 300,+ data: '8.8.8.8',+ },+ ],+ } as DecodedPacket)+ : ({+ ...response(domain, recordType, 'NOERROR', [+ {+ name: domain,+ type: 'DNSKEY',+ ttl: 300,+ data: { flags: 257, algorithm: 13, key: Buffer.alloc(64) },+ },+ // Owner names are case-insensitive.+ rrsig('Example.COM', 'DNSKEY'),+ rrsig(domain, 'SOA'),+ rrsig('www.example.com', 'DNSKEY'),+ ]),+ flag_aa: true,+ } as DecodedPacket),+ );+ const resolver = new AuthoritativeResolver({+ udpTransport,+ rootServers: async () => ['192.0.2.1'],+ dnssecOk: true,+ });++ const result = await resolver.resolveAnswers('example.com', 'DNSKEY');++ expect(result.answers).toHaveLength(1);+ expect(result.coveringRrsigs).toEqual([{ typeCovered: 'DNSKEY' }]);+ expect(udpTransport).toHaveBeenCalledTimes(2);+ expect(udpTransport.mock.calls.every(([request]) => request.dnssecOk)).toBe(+ true,+ );+ });+it('does not report a dangling CNAME target as NXDOMAIN for the queried name', async () => {// RFC 6604: the rcode describes the end of the chain, not the owner.const resolver = new AuthoritativeResolver({diff --git a/lib/resolvers/authoritative.ts b/lib/resolvers/authoritative.tsindex 947a9b5..b312dd7 100644--- a/lib/resolvers/authoritative.ts+++ b/lib/resolvers/authoritative.ts@@ -7,6 +7,7 @@ import dnsPacket, {type DecodedPacket,type Packet,type Question,+ type RrsigData,type StringAnswer,} from 'dns-packet';@@ -14,6 +15,7 @@ import { retry } from '@/lib/utils';import { UserFacingError } from '../user-facing-error';import {+ canonicalDnsName,DnsResolver,type RawRecord,type RecordType,@@ -23,8 +25,20 @@ import { isPublicIp } from './ip-filter';type RawAnswer = Extract<Answer, { type: RecordType }>;-const canonicalDnsName = (name: string): string =>- name.replace(/\.$/, '').toLowerCase();+// EDNS OPT pseudo-record carrying the DNSSEC OK (DO) bit, so the server+// returns RRSIG records alongside the answer. 1232 bytes keeps UDP answers+// unfragmented on any path (DNS Flag Day 2020); larger ones come back with TC+// and are retried over TCP instead of being lost to dropped fragments.+const DNSSEC_OPT_RECORD = {+ type: 'OPT' as const,+ name: '.',+ udpPayloadSize: 1232,+ extendedRcode: 0,+ ednsVersion: 0,+ flags: dnsPacket.DNSSEC_OK,+ flag_do: true,+ options: [],+};// A legitimate referral delegates a zone the queried name lives under.// Anything else -- an upward referral to the root ('' is never a match) or@@ -81,6 +95,7 @@ export type AuthoritativeRequest = {domain: string;recordType: RecordType;nameserver: string;+ dnssecOk: boolean;};export type AuthoritativeUdpTransport = (@@ -98,6 +113,9 @@ export type AuthoritativeResolverOptions = {// Time budget for trying fallback nameservers, shared across the whole// walk (see fetchRecordsRaw). Injectable for tests.fallbackDeadlineMs?: number;+ // Set the EDNS DNSSEC OK (DO) bit on every query of this instance, so+ // authoritative servers include RRSIGs.+ dnssecOk?: boolean;};export const isMatchingDnsResponse = (@@ -123,6 +141,9 @@ type WalkResult = {trace: string[];rcode?: string;zone: string;+ // RRSIGs covering the queried type; servers only send them when the+ // resolver sets the dnssecOk option.+ coveringRrsigs?: RrsigData[];};type FetchRecordsParams = {@@ -279,6 +300,7 @@ export class AuthoritativeResolver extends DnsResolver {domain,recordType,nameserver,+ dnssecOk,}: AuthoritativeRequest) {const id = Math.floor(Math.random() * 65535);const packetBuffer = dnsPacket.encode({@@ -286,6 +308,7 @@ export class AuthoritativeResolver extends DnsResolver {// Randomize ID to avoid response mismatchid,questions: [{ type: recordType, name: domain } as Question],+ ...(dnssecOk && { additionals: [DNSSEC_OPT_RECORD] }),});return new Promise<DecodedPacket>((resolve, reject) => {@@ -333,12 +356,14 @@ export class AuthoritativeResolver extends DnsResolver {domain,recordType,nameserver,+ dnssecOk,}: AuthoritativeRequest) {const id = Math.floor(Math.random() * 65535);const packetBuffer = dnsPacket.streamEncode({type: 'query',id,questions: [{ type: recordType, name: domain } as Question],+ ...(dnssecOk && { additionals: [DNSSEC_OPT_RECORD] }),});return new Promise<Packet>((resolve, reject) => {@@ -392,11 +417,12 @@ export class AuthoritativeResolver extends DnsResolver {private async sendRequest(request: AuthoritativeRequest,): Promise<DnsResponse> {- // DNS queries are first attempted over UDP per convention. However, UDP- // responses are limited to 512 bytes (RFC 1035). When the answer exceeds- // that limit the server truncates the response and sets the TC flag,- // signaling the client to retry over TCP where the full response (up to- // 64 KB) can be delivered.+ // DNS queries are first attempted over UDP per convention. UDP responses+ // are limited to 512 bytes (RFC 1035), or to the advertised EDNS payload+ // size when the query carries an OPT record (dnssecOk). When the answer+ // exceeds that limit the server truncates the response and sets the TC+ // flag, signaling the client to retry over TCP where the full response+ // (up to 64 KB) can be delivered.const udpResponse = this.options.udpTransport? await this.options.udpTransport(request): await this.sendUdpRequest(request);@@ -543,6 +569,7 @@ export class AuthoritativeResolver extends DnsResolver {domain,recordType,nameserver: candidate,+ dnssecOk: this.options.dnssecOk ?? false,};let result: DnsResponse;try {@@ -731,6 +758,15 @@ export class AuthoritativeResolver extends DnsResolver {answer.type === recordType,) as RawAnswer[];+ const coveringRrsigs = packet.answers+ .filter(+ (answer): answer is Extract<Answer, { type: 'RRSIG' }> =>+ answer.type === 'RRSIG' &&+ canonicalDnsName(answer.name) === wantName &&+ answer.data.typeCovered === recordType,+ )+ .map((sig) => sig.data);+return {answers: filteredAnswers,// The name owns a record, so it exists: an NXDOMAIN here describes@@ -741,6 +777,7 @@ export class AuthoritativeResolver extends DnsResolver {...trace,`${recordType} ${domain} @ ${candidate} (${protocol}) -> answer: ${filteredAnswers.map(this.recordToString).join(', ')}`,],+ coveringRrsigs,};}@@ -942,7 +979,8 @@ export class AuthoritativeResolver extends DnsResolver {// Decoded answers owned by the queried name, the response code (NXDOMAIN// stays distinct from NODATA) and the zone cut whose servers answered. For// callers that need structured rdata (DNSSEC) rather than presentation- // strings.+ // strings. With the dnssecOk option, the RRSIGs covering the answer come+ // back too.public resolveAnswers(domain: string,recordType: RecordType,diff --git a/lib/resolvers/base.ts b/lib/resolvers/base.tsindex 8064c2e..09c268f 100644--- a/lib/resolvers/base.ts+++ b/lib/resolvers/base.ts@@ -2,6 +2,10 @@ import type { ALL_RECORD_TYPES } from '@/lib/data';export type RecordType = (typeof ALL_RECORD_TYPES)[number];+// Case-insensitive, trailing-dot-free form for comparing DNS names.+export const canonicalDnsName = (name: string): string =>+ name.replace(/\.$/, '').toLowerCase();+export type RawRecord = {name: string;type: RecordType;diff --git a/types/dns-packet-types.d.ts b/types/dns-packet-types.d.tsnew file mode 100644index 0000000..59330d2--- /dev/null+++ b/types/dns-packet-types.d.ts@@ -0,0 +1,5 @@+// dns-packet's types submodule ships no declarations (@types/dns-packet only+// covers the main entry).+declare module 'dns-packet/types' {+ export function toType(name: string): number;+}