Full Toolkit for Next-Level Domain Analysis
Add a DNSSEC DS-chain tab (digest linkage only) 🔗🔑 (#109)
Felix Wotschofskya6e3a9b8a97d
diff --git a/app/(landing)/dnssec/page.tsx b/app/(landing)/dnssec/page.tsxnew file mode 100644index 0000000..1e82402--- /dev/null+++ b/app/(landing)/dnssec/page.tsx@@ -0,0 +1,60 @@+import type { Metadata } from 'next';+import type { FC } from 'react';++import { SearchForm } from '../../_components/search-form';+import { AuthorSection } from '../_components/author-section';+import { SponsorsSection } from '../_components/sponsors-section';+import { TrustSection } from '../_components/trust-section';++export const revalidate = 86400;++export const metadata: Metadata = {+ title: 'DNSSEC DS Chain Lookup',+ openGraph: {+ title: 'DNSSEC DS Chain Lookup',+ url: '/dnssec',+ },+ alternates: { canonical: '/dnssec' },+};++const DnssecLandingPage: FC = () => (+ <div className="container space-y-16">+ <div className="flex min-h-[calc(100vh-4.5rem-2rem)] flex-col gap-16 pb-12">+ <div className="flex flex-col gap-20">+ <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+ </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.+ </p>+ </section>+ <SponsorsSection />+ </div>++ <AuthorSection />+ </div>++ <TrustSection subpage="dnssec" />+ </div>++ <div className="mx-auto max-w-4xl space-y-4 pt-16 text-center">+ <h2 className="scroll-m-20 text-2xl font-semibold tracking-tight">+ 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.+ </p>+ </div>+ </div>+);++export default DnssecLandingPage;diff --git a/app/lookup/[domain]/dnssec/error.tsx b/app/lookup/[domain]/dnssec/error.tsxnew file mode 100644index 0000000..a91299b--- /dev/null+++ b/app/lookup/[domain]/dnssec/error.tsx@@ -0,0 +1,16 @@+'use client';++import type { FC } from 'react';++import { BoundaryError } from '@/components/boundary-error';++type DnssecErrorProps = {+ error: Error & { digest?: string };+ retry: () => void;+};++const DnssecError: FC<DnssecErrorProps> = ({ error, retry }) => (+ <BoundaryError error={error} retry={retry} />+);++export default DnssecError;diff --git a/app/lookup/[domain]/dnssec/loading.tsx b/app/lookup/[domain]/dnssec/loading.tsxnew file mode 100644index 0000000..98ab1e8--- /dev/null+++ b/app/lookup/[domain]/dnssec/loading.tsx@@ -0,0 +1,62 @@+import type { FC } from 'react';++import { Skeleton } from '@/components/ui/skeleton';++const zones = [+ { nameWidth: 'w-8', keys: 2, ds: 2 },+ { nameWidth: 'w-16', keys: 2, ds: 1 },+ { nameWidth: 'w-36', keys: 1, ds: 1 },+] as const;++const DnssecLoading: FC = () => (+ <div className="space-y-8">+ <p className="sr-only" role="status">+ Loading DNSSEC chain+ </p>+ <div aria-hidden="true" className="space-y-8">+ <header className="space-y-2">+ <Skeleton className="h-8 w-48 rounded-sm" />+ <Skeleton className="h-5 w-full max-w-sm rounded-sm" />+ </header>++ <div className="space-y-4">+ {zones.map((zone, index) => (+ <section+ key={index}+ className="rounded-lg border border-zinc-200 p-5 dark:border-zinc-800"+ >+ <div className="mb-5 flex flex-wrap items-baseline justify-between gap-2">+ <Skeleton className={`h-7 ${zone.nameWidth} rounded-sm`} />+ <Skeleton className="h-5 w-16 rounded-sm" />+ </div>++ <div className="grid gap-6 md:grid-cols-2">+ <div className="space-y-2">+ <Skeleton className="h-5 w-20 rounded-sm" />+ {Array.from({ length: zone.keys }).map((_, keyIndex) => (+ <Skeleton+ key={keyIndex}+ className="h-5 w-44 max-w-full rounded-sm"+ />+ ))}+ </div>+ <div className="space-y-3">+ <Skeleton className="h-5 w-28 rounded-sm" />+ {Array.from({ length: zone.ds }).map((_, dsIndex) => (+ <div key={dsIndex} className="space-y-1">+ <Skeleton className="h-5 w-48 max-w-full rounded-sm" />+ <Skeleton className="h-3 w-36 rounded-sm" />+ </div>+ ))}+ </div>+ </div>+ </section>+ ))}+ </div>++ <Skeleton className="h-5 w-full max-w-xl rounded-sm" />+ </div>+ </div>+);++export default DnssecLoading;diff --git a/app/lookup/[domain]/dnssec/not-found.tsx b/app/lookup/[domain]/dnssec/not-found.tsxnew file mode 100644index 0000000..95cead1--- /dev/null+++ b/app/lookup/[domain]/dnssec/not-found.tsx@@ -0,0 +1,7 @@+export default function DnssecNotFound() {+ return (+ <p className="mt-24 text-center text-zinc-500 dark:text-zinc-400">+ Domain not found.+ </p>+ );+}diff --git a/app/lookup/[domain]/dnssec/opengraph-image.tsx b/app/lookup/[domain]/dnssec/opengraph-image.tsxnew file mode 100644index 0000000..e3cc2dd--- /dev/null+++ b/app/lookup/[domain]/dnssec/opengraph-image.tsx@@ -0,0 +1,6 @@+import handler from '../(dns)/opengraph-image';++export const runtime = 'edge';+export const contentType = 'image/png';++export default handler;diff --git a/app/lookup/[domain]/dnssec/page.tsx b/app/lookup/[domain]/dnssec/page.tsxnew file mode 100644index 0000000..67bb4ef--- /dev/null+++ b/app/lookup/[domain]/dnssec/page.tsx@@ -0,0 +1,177 @@+import type { Metadata } from 'next';+import { notFound } from 'next/navigation';+import type { FC } from 'react';++import {+ DsChainNameNotFoundError,+ type DsChainVerdict,+ dsDigestName,+ resolveDsChain,+} from '@/lib/dnssec/ds-chain';+import { AuthoritativeResolver } from '@/lib/resolvers/authoritative';+import { recordLookupAfter } from '@/lib/search';++type DnssecResultsPageProps = {+ params: Promise<{ domain: string }>;+};++export const generateMetadata = async ({+ params,+}: DnssecResultsPageProps): Promise<Metadata> => {+ const { domain } = await params;+ return {+ title: `DNSSEC DS Chain for ${domain}`,+ openGraph: {+ title: `DNSSEC DS Chain for ${domain}`,+ url: `/lookup/${domain}/dnssec`,+ },+ alternates: { canonical: `/lookup/${domain}/dnssec` },+ };+};++const VERDICT_LABELS: Record<DsChainVerdict, string> = {+ intact: 'DS chain intact',+ unsigned: 'Unsigned',+ mismatch: 'DS mismatch',+};++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();+ let chain;+ try {+ chain = await resolveDsChain(domain, (name, type) =>+ resolver.resolveAnswers(name, type),+ );+ } catch (error) {+ if (error instanceof DsChainNameNotFoundError) {+ await recordLookupAfter(domain, 'dnssec', false);+ notFound();+ }+ throw error;+ }++ await recordLookupAfter(domain, 'dnssec', chain.zones.length > 0);+ const coveringZone = chain.zones.at(-1)!.name;++ return (+ <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' : ''}`}+ >+ {VERDICT_LABELS[chain.verdict]}+ {chain.breakAt ? ` at ${chain.breakAt}` : ''}+ </h2>+ {coveringZone !== chain.name && (+ <p className="text-sm">+ {chain.name} is not a zone of its own; it is covered by{' '}+ <span className="font-medium">{coveringZone}</span>.+ </p>+ )}+ <p className="text-sm text-zinc-500 dark:text-zinc-400">+ This view checks digest linkage without verifying signatures.+ </p>+ </header>++ <div className="space-y-4">+ {chain.zones.map((zone) => (+ <section+ key={zone.name}+ className="rounded-lg border border-zinc-200 p-5 dark:border-zinc-800"+ >+ <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'}`}+ >+ {zone.status === 'intact'+ ? 'Intact'+ : VERDICT_LABELS[zone.status]}+ </span>+ </div>++ <div className="grid gap-6 md:grid-cols-2">+ <div>+ <h4 className="mb-2 text-sm font-semibold">DNSKEYs</h4>+ {zone.keys.length ? (+ <ul className="space-y-2 text-sm">+ {zone.keys.map((key, index) => (+ <li+ key={`${key.keyTag}-${key.algorithm}-${index}`}+ className="break-words"+ >+ <span className="font-mono">{key.keyTag}</span>{' '}+ <span className="text-zinc-600 dark:text-zinc-300">+ {key.algorithmName} · {key.isSep ? 'KSK' : 'ZSK'}+ </span>+ </li>+ ))}+ </ul>+ ) : (+ <p className="text-sm text-zinc-500 dark:text-zinc-400">+ No DNSKEYs+ </p>+ )}+ </div>++ <div>+ <h4 className="mb-2 text-sm font-semibold">+ {zone.name === '.' ? 'IANA trust anchor' : 'Parent DS'}+ </h4>+ {zone.dsRecords.length ? (+ <ul className="space-y-3 text-sm">+ {zone.dsRecords.map((ds, index) => (+ <li+ key={`${ds.keyTag}-${ds.digestHex}-${index}`}+ className="space-y-1"+ >+ <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)}+ </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">+ Weak digest+ </span>+ )}+ <span+ className={+ !ds.matched && zone.status === 'mismatch'+ ? 'text-red-700 dark:text-red-400'+ : 'text-zinc-600 dark:text-zinc-300'+ }+ >+ {ds.matched ? 'Matched' : 'No match'}+ </span>+ </div>+ <code className="block text-xs break-all text-zinc-500 dark:text-zinc-400">+ {shortFingerprint(ds.digestHex)}+ </code>+ </li>+ ))}+ </ul>+ ) : (+ <p className="text-sm text-zinc-500 dark:text-zinc-400">+ No DS records+ </p>+ )}+ </div>+ </div>+ </section>+ ))}+ </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.+ </p>+ </div>+ );+};++export default DnssecResultsPage;diff --git a/lib/dnssec/ds-chain.test.ts b/lib/dnssec/ds-chain.test.tsnew file mode 100644index 0000000..1176162--- /dev/null+++ b/lib/dnssec/ds-chain.test.ts@@ -0,0 +1,440 @@+import { createHash } from 'node:crypto';++import type { Answer } from 'dns-packet';+import { describe, expect, it } from 'vitest';++import { UserFacingError } from '@/lib/user-facing-error';++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==';++const soa = (name: string): Answer => ({+ name,+ type: 'SOA',+ ttl: 60,+ data: {+ mname: `ns.${name}`,+ rname: `hostmaster.${name}`,+ serial: 1,+ refresh: 3600,+ retry: 600,+ expire: 86400,+ minimum: 60,+ },+});++// A delegation: the parent's NS RRset for a child zone cut.+const ns = (name: string): Answer => ({+ name,+ type: 'NS',+ ttl: 60,+ data: `ns.${name}`,+});++const host = (name: string): Answer => ({+ name,+ type: 'A',+ ttl: 60,+ data: '192.0.2.1',+});++const keyRecord = (name: string, key = testKey, flags = 257): Answer => ({+ name,+ type: 'DNSKEY',+ ttl: 60,+ data: { flags, algorithm: 8, key: Buffer.from(key, 'base64') },+});++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;+};++const dsRecord = (+ name: string,+ key = testKey,+ 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();+ return {+ name,+ type: 'DS',+ ttl: 60,+ data: {+ keyTag: keyTag(key, flags),+ algorithm: 8,+ digestType,+ digest: corrupt ? Buffer.alloc(digest.length) : digest,+ },+ };+};++// A delegated, signed zone apex whose parent publishes a matching DS.+const signedZone = (name: string, key = testKey): Answer[] => [+ ns(name),+ soa(name),+ keyRecord(name, key),+ dsRecord(name, key),+];++// 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+// NXDOMAIN. The zone is the deepest delegation (NS owner) at or above the+// name; DS is answered from the parent side of a cut.+const dnsTree =+ (records: Answer[]): DsChainQuery =>+ async (name, type) => {+ const labels = name === '.' ? [] : name.split('.');+ const zone =+ labels+ .map((_, i) => labels.slice(i).join('.'))+ .slice(type === 'DS' ? 1 : 0)+ .find((cut) =>+ records.some((record) => record.name === cut && record.type === 'NS'),+ ) ?? '.';+ return {+ answers: records.filter(+ (record) => record.name === name && record.type === type,+ ),+ rcode:+ name === '.' ||+ records.some(+ (record) => record.name === name || record.name.endsWith(`.${name}`),+ )+ ? 'NOERROR'+ : 'NXDOMAIN',+ zone,+ };+ };++const root = (key = ROOT_KEYS[0]) => keyRecord('.', key);++describe('resolveDsChain', () => {+ it('follows matching DS digests to the full queried name', async () => {+ const query = dnsTree([+ root(),+ ...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');+ expect(chain.zones.map((zone) => zone.name)).toEqual([+ '.',+ 'com',+ 'example.com',+ 'www.example.com',+ ]);+ expect(chain.zones.every((zone) => zone.status === 'intact')).toBe(true);+ });++ 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'),+ ]),+ );+ expect(chain.verdict).toBe('intact');+ expect(chain.breakAt).toBeUndefined();+ expect(chain.name).toBe('www.example.com');+ expect(chain.zones.map((zone) => zone.name)).toEqual([+ '.',+ 'com',+ 'example.com',+ ]);+ });++ 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'),+ ]),+ );+ expect(chain.verdict).toBe('intact');+ expect(chain.zones.map((zone) => zone.name)).toEqual([+ '.',+ 'com',+ 'example.com',+ 'a.b.example.com',+ ]);+ });++ 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'),+ ]),+ );+ expect(chain.verdict).toBe('unsigned');+ expect(chain.breakAt).toBe('example.com');+ expect(chain.zones.map((zone) => zone.name)).toEqual([+ '.',+ 'com',+ 'example.com',+ ]);+ });++ it('finds an unsigned delegation whose servers host no zone at the cut', async () => {+ // 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'),+ ]),+ );+ expect(chain.verdict).toBe('unsigned');+ expect(chain.breakAt).toBe('www.example.com');+ expect(chain.zones.map((zone) => zone.name)).toEqual([+ '.',+ 'com',+ 'example.com',+ 'www.example.com',+ ]);+ });++ 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')]),+ );+ 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'),+ ]),+ );+ expect(chain.verdict).toBe('unsigned');+ expect(chain.breakAt).toBe('com');+ expect(chain.zones.map((zone) => zone.status)).toEqual([+ 'intact',+ 'unsigned',+ 'unsigned',+ ]);+ });++ 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),+ ]),+ );+ 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)]));+ expect(chain.verdict).toBe('intact');+ expect(chain.zones[0].dsRecords.filter((ds) => ds.matched)).toHaveLength(1);+ });++ it('throws a retryable error when root DNSKEYs are empty', async () => {+ await expect(+ resolveDsChain('example.com', dnsTree([])),+ ).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')]),+ ),+ ).rejects.toBeInstanceOf(DsChainNameNotFoundError);+ });++ it('rejects names over 16 labels before querying', async () => {+ let queried = false;+ await expect(+ resolveDsChain(+ Array.from({ length: 17 }, () => 'a').join('.'),+ async () => {+ queried = true;+ return { answers: [], zone: '.' };+ },+ ),+ ).rejects.toBeInstanceOf(UserFacingError);+ expect(queried).toBe(false);+ });++ 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(+ 'com',+ dnsTree([...records, dsRecord('com', testKey, 1, true)]),+ );+ expect(chain.verdict).toBe('intact');+ expect(chain.zones[1].dsRecords).toEqual([+ expect.objectContaining({+ digestType: 2,+ matched: true,+ weakDigest: false,+ }),+ expect.objectContaining({+ digestType: 1,+ matched: false,+ weakDigest: true,+ }),+ ]);++ const reverse = await resolveDsChain(+ 'com',+ dnsTree([+ root(),+ soa('com'),+ keyRecord('com'),+ dsRecord('com', testKey, 1),+ dsRecord('com', testKey, 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),+ ]),+ );+ expect(chain.verdict).toBe('intact');+ });++ 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('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('does not match a DS against a DNSKEY without the Zone Key flag', async () => {+ const chain = await resolveDsChain(+ 'com',+ dnsTree([+ root(),+ soa('com'),+ keyRecord('com', testKey, 1),+ dsRecord('com', testKey, 2, false, 1),+ ]),+ );+ expect(chain.verdict).toBe('mismatch');+ });++ 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');+ });+});diff --git a/lib/dnssec/ds-chain.ts b/lib/dnssec/ds-chain.tsnew file mode 100644index 0000000..4a8029a--- /dev/null+++ b/lib/dnssec/ds-chain.ts@@ -0,0 +1,266 @@+import { createHash } from 'node:crypto';++import type { Answer, DnskeyData, DsData } from 'dns-packet';++import type { RecordType } from '@/lib/resolvers/base';+import { UserFacingError } from '@/lib/user-facing-error';++export type DsChainVerdict = 'intact' | 'unsigned' | 'mismatch';++export type DsChainZone = {+ name: string;+ keys: Array<{+ keyTag: number;+ algorithm: number;+ algorithmName: string;+ isSep: boolean;+ }>;+ dsRecords: Array<{+ keyTag: number;+ digestType: number;+ digestHex: string;+ matched: boolean;+ weakDigest: boolean;+ }>;+ status: DsChainVerdict;+};++export type DsChain = {+ // The queried name, lowercased and without a trailing dot. When it is not+ // a zone apex itself (a host, a wildcard, ...), the last zone is the one+ // it lives in.+ name: string;+ zones: DsChainZone[];+ verdict: DsChainVerdict;+ breakAt?: string;+};++// 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).+export type DsChainQuery = (+ name: string,+ type: Extract<RecordType, 'SOA' | 'DNSKEY' | 'DS'>,+) => Promise<{ answers: Answer[]; rcode?: string; zone: string }>;++export class DsChainNameNotFoundError extends Error {}++// IANA root trust anchors: KSK-2017 and KSK-2024.+// https://data.iana.org/root-anchors/root-anchors.xml+const ROOT_ANCHORS: DsData[] = [+ {+ keyTag: 20326,+ algorithm: 8,+ digestType: 2,+ digest: Buffer.from(+ 'E06D44B80B8F1D39A95C0B0D7C65D08458E880409BBC683457104237C7F8EC8D',+ 'hex',+ ),+ },+ {+ keyTag: 38696,+ algorithm: 8,+ digestType: 2,+ digest: Buffer.from(+ '683D2D0ACB8C9B712A1948B27F741219298D0A450D612C483AF444A4C0FB2B16',+ 'hex',+ ),+ },+];++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',+};++export const dnssecAlgorithmName = (algorithm: number): string =>+ ALGORITHM_NAMES[algorithm] ?? `Algorithm ${algorithm}`;++export const dsDigestName = (digestType: number): string =>+ ({ 1: 'SHA-1', 2: 'SHA-256', 3: 'GOST R 34.11-94', 4: 'SHA-384' })[+ digestType+ ] ?? `Digest ${digestType}`;++const HASH_ALGORITHMS: Record<number, string> = {+ 1: 'sha1',+ 2: 'sha256',+ 4: 'sha384',+};++const wireName = (name: string): Buffer => {+ if (name === '.') return Buffer.from([0]);+ return Buffer.concat([+ ...name+ .toLowerCase()+ .split('.')+ .flatMap((label) => [+ Buffer.from([Buffer.byteLength(label, 'ascii')]),+ Buffer.from(label, 'ascii'),+ ]),+ Buffer.from([0]),+ ]);+};++const dnskeyRdata = (key: DnskeyData): Buffer => {+ const header = Buffer.alloc(4);+ header.writeUInt16BE(key.flags, 0);+ header.writeUInt8(3, 2);+ header.writeUInt8(key.algorithm, 3);+ return Buffer.concat([header, key.key]);+};++const keyTag = (key: DnskeyData): number => {+ const rdata = dnskeyRdata(key);+ // RFC 4034 Appendix B.1 has a special case for the obsolete RSAMD5 key.+ if (key.algorithm === 1) return (rdata.at(-3)! << 8) | rdata.at(-2)!;+ let sum = 0;+ for (let i = 0; i < rdata.length; i++) {+ sum += i & 1 ? rdata[i] : rdata[i] << 8;+ }+ sum += (sum >> 16) & 0xffff;+ return sum & 0xffff;+};++const dsMatchesKey = (ds: DsData, key: DnskeyData, name: string): boolean => {+ // A DS may only point at a key with the Zone Key flag (RFC 4034 section 5.2).+ if ((key.flags & 0x0100) === 0) return false;+ if (ds.keyTag !== keyTag(key) || ds.algorithm !== key.algorithm) return false;+ const hash = HASH_ALGORITHMS[ds.digestType];+ if (!hash) return false;+ return createHash(hash)+ .update(Buffer.concat([wireName(name), dnskeyRdata(key)]))+ .digest()+ .equals(ds.digest);+};++const dnskeysOf = ({ answers }: { answers: Answer[] }): DnskeyData[] =>+ answers.flatMap((answer) => (answer.type === 'DNSKEY' ? [answer.data] : []));++const dsOf = ({ answers }: { answers: Answer[] }): DsData[] =>+ answers.flatMap((answer) => (answer.type === 'DS' ? [answer.data] : []));++const suffixesFor = (name: string): string[] => {+ const clean = name.replace(/^\*\./, '');+ const labels = clean && clean !== '.' ? clean.split('.') : [];+ if (labels.length > 16) {+ throw new UserFacingError({+ title: 'Domain name is too deep',+ description: 'DNSSEC chain lookups support up to 16 labels.',+ });+ }+ return ['.', ...labels.map((_, index) => labels.slice(-index - 1).join('.'))];+};++export const resolveDsChain = async (+ domain: string,+ query: DsChainQuery,+): Promise<DsChain> => {+ const queried = domain.toLowerCase().replace(/\.$/, '') || '.';+ const names = suffixesFor(queried);+ const zones: DsChainZone[] = [];+ let verdict: DsChainVerdict = 'intact';+ let breakAt: string | undefined;++ for (const [index, name] of names.entries()) {+ const isRoot = index === 0;+ const [soaResponse, keyResponse, dsResponse] = await Promise.all([+ isRoot ? null : query(name, 'SOA'),+ query(name, 'DNSKEY'),+ isRoot ? null : query(name, 'DS'),+ ]);+ if (+ index === names.length - 1 &&+ [soaResponse, keyResponse, dsResponse].some(+ (response) => response?.rcode === 'NXDOMAIN',+ )+ ) {+ throw new DsChainNameNotFoundError(name);+ }++ const keys = dnskeysOf(keyResponse);+ if (isRoot && keys.length === 0) {+ throw new UserFacingError({+ title: 'Root DNSKEY records unavailable',+ description:+ 'The root DNSKEY lookup returned no keys. Please try again shortly.',+ retryable: true,+ });+ }+ const dsRecords = isRoot ? ROOT_ANCHORS : dsOf(dsResponse!);+ // Only zone apexes link the chain. A name is one when a parent delegates+ // it (the lookup was referred to its servers) or it has its own SOA or a+ // parent DS; a DNSKEY RRset alone does not make a zone cut. The SOA+ // covers parent and child sharing servers, where no referral happens; the+ // referral covers child servers that host no zone at the cut. Anything+ // else (a host, a CNAME, an empty non-terminal) lives inside the zone+ // above.+ const isApex =+ isRoot ||+ dsRecords.length > 0 ||+ [soaResponse, keyResponse, dsResponse].some(+ (response) => response?.zone === name,+ ) ||+ 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) =>+ HASH_ALGORITHMS[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';+ if (verdict === 'intact' && ownStatus !== 'intact') {+ verdict = ownStatus;+ breakAt = name;+ }++ zones.push({+ name,+ keys: keys.map((key) => ({+ keyTag: keyTag(key),+ algorithm: key.algorithm,+ algorithmName: dnssecAlgorithmName(key.algorithm),+ isSep: (key.flags & 1) !== 0,+ })),+ dsRecords: dsRecords.map((ds, i) => ({+ keyTag: ds.keyTag,+ digestType: ds.digestType,+ digestHex: ds.digest.toString('hex').toUpperCase(),+ matched: matches[i],+ weakDigest: ds.digestType === 1 || ds.digestType === 3,+ })),+ status: verdict,+ });+ }++ return {+ name: queried,+ zones,+ verdict,+ ...(breakAt ? { breakAt } : {}),+ };+};diff --git a/lib/lookup-features.ts b/lib/lookup-features.tsindex 658071e..f417e1a 100644--- a/lib/lookup-features.ts+++ b/lib/lookup-features.ts@@ -17,6 +17,15 @@ export const LOOKUP_FEATURES = [footerLabel: 'Global DNS Lookup',lookupType: 'dns',},+ {+ id: 'dnssec',+ label: 'DNSSEC',+ segment: 'dnssec',+ path: '/dnssec',+ landingPath: '/dnssec',+ footerLabel: 'DNSSEC Lookup',+ lookupType: 'dnssec',+ },{id: 'whois',label: 'Whois',diff --git a/lib/resolvers/authoritative.test.ts b/lib/resolvers/authoritative.test.tsindex 08a3b43..63c4ca3 100644--- a/lib/resolvers/authoritative.test.ts+++ b/lib/resolvers/authoritative.test.ts@@ -125,6 +125,125 @@ describe('AuthoritativeResolver transport policy', () => {expect(udpTransport).toHaveBeenCalledTimes(1);});+ it('exposes NXDOMAIN separately from an empty NOERROR answer', async () => {+ const resolver = new AuthoritativeResolver({+ udpTransport: async ({ domain, recordType }) =>+ ({+ ...response(+ domain,+ recordType,+ domain === 'missing.example' ? 'NXDOMAIN' : 'NOERROR',+ ),+ flag_aa: true,+ }) as DecodedPacket,+ rootServers: async () => ['192.0.2.1'],+ });++ await expect(+ resolver.resolveAnswers('missing.example', 'DNSKEY'),+ ).resolves.toEqual(+ expect.objectContaining({ answers: [], rcode: 'NXDOMAIN' }),+ );+ await expect(+ resolver.resolveAnswers('empty.example', 'DNSKEY'),+ ).resolves.toEqual(+ expect.objectContaining({ answers: [], rcode: 'NOERROR' }),+ );+ });++ it('returns decoded DNSKEY rdata from resolveAnswers', async () => {+ const key = {+ flags: 257,+ algorithm: 13,+ key: Buffer.from('AQIDBA==', 'base64'),+ };+ const resolver = new AuthoritativeResolver({+ udpTransport: async ({ domain, recordType }) =>+ ({+ ...response(domain, recordType, 'NOERROR', [+ { name: domain, type: 'DNSKEY', ttl: 60, data: key },+ ]),+ flag_aa: true,+ }) as DecodedPacket,+ rootServers: async () => ['192.0.2.1'],+ });++ await expect(+ resolver.resolveAnswers('example.com', 'DNSKEY'),+ ).resolves.toEqual(+ expect.objectContaining({+ answers: [expect.objectContaining({ type: 'DNSKEY', data: key })],+ zone: '.',+ }),+ );+ });++ it('reports the zone cut a referral led to, even when its servers answer NODATA', async () => {+ const resolver = new AuthoritativeResolver({+ udpTransport: async ({ domain, recordType, nameserver }) =>+ nameserver === '192.0.2.1'+ ? ({+ ...response(domain, recordType, 'NOERROR'),+ authorities: [+ {+ name: 'www.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'),+ flag_aa: true,+ } as DecodedPacket),+ rootServers: async () => ['192.0.2.1'],+ });++ await expect(+ resolver.resolveAnswers('www.example.com', 'SOA'),+ ).resolves.toEqual(+ expect.objectContaining({+ answers: [],+ rcode: 'NOERROR',+ zone: 'www.example.com',+ }),+ );+ });++ 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({+ udpTransport: async ({ domain, recordType }) =>+ ({+ ...response(domain, recordType, 'NXDOMAIN', [+ {+ name: domain,+ type: 'CNAME',+ ttl: 60,+ data: 'gone.example.com',+ },+ ]),+ flag_aa: true,+ }) as DecodedPacket,+ rootServers: async () => ['192.0.2.1'],+ });++ await expect(+ resolver.resolveAnswers('dangling.example.com', 'SOA'),+ ).resolves.toEqual(+ expect.objectContaining({ answers: [], rcode: 'NOERROR' }),+ );+ });+it('surfaces all-REFUSED plain non-RRSIG queries as retryable failures', async () => {// The REFUSED-as-empty tolerance exists for RRSIG browsing only; a domain// whose nameservers refuse ordinary lookups must not render "no records".diff --git a/lib/resolvers/authoritative.ts b/lib/resolvers/authoritative.tsindex 6147ce9..947a9b5 100644--- a/lib/resolvers/authoritative.ts+++ b/lib/resolvers/authoritative.ts@@ -116,10 +116,21 @@ export const isMatchingDnsResponse = (),);+// A walk's final answer. `zone` is the zone cut whose servers gave it: the+// deepest delegation followed, or the root.+type WalkResult = {+ answers: RawAnswer[];+ trace: string[];+ rcode?: string;+ zone: string;+};+type FetchRecordsParams = {domain: string;recordType: RecordType;nameservers?: string[];+ // The zone cut `nameservers` were delegated for.+ zone?: string;trace?: string[];depth?: number;deadlineAt?: number;@@ -458,6 +469,7 @@ export class AuthoritativeResolver extends DnsResolver {domain,recordType,nameservers,+ zone: delegatedZone,trace = [],depth = 0,// The deadline and query budget span the whole walk -- referrals and@@ -467,10 +479,7 @@ export class AuthoritativeResolver extends DnsResolver {(this.options.fallbackDeadlineMs ??AuthoritativeResolver.FALLBACK_DEADLINE_MS),budget = { remaining: AuthoritativeResolver.MAX_CANDIDATES_PER_WALK },- }: FetchRecordsParams): Promise<{- answers: RawAnswer[];- trace: string[];- }> {+ }: FetchRecordsParams): Promise<WalkResult> {if (depth > AuthoritativeResolver.MAX_RECURSION_DEPTH) {throw new Error(`Max recursion depth exceeded while resolving ${domain} (type ${recordType})`,@@ -484,6 +493,7 @@ export class AuthoritativeResolver extends DnsResolver {nameservers && nameservers.length? nameservers: (cached?.ips ?? (await this.getRootServers()).slice(0, 4));+ const zone = (nameservers?.length ? delegatedZone : cached?.zone) || '.';const wantName = canonicalDnsName(domain);let lastResort: { result: DnsResponse; candidate: string } | null = null;const failedNameservers: string[] = [];@@ -580,6 +590,7 @@ export class AuthoritativeResolver extends DnsResolver {domain,recordType,wantName,+ zone,trace: acceptedTrace,depth,deadlineAt,@@ -633,6 +644,7 @@ export class AuthoritativeResolver extends DnsResolver {domain,recordType,wantName,+ zone,trace: lastResortTrace,depth,deadlineAt,@@ -649,6 +661,7 @@ export class AuthoritativeResolver extends DnsResolver {if (allRefused && recordType === 'RRSIG') {return {answers: [],+ zone,trace: [...trace,`${recordType} ${domain} -> all nameservers returned an error: ${failedNameservers.join('; ')}`,@@ -681,6 +694,7 @@ export class AuthoritativeResolver extends DnsResolver {domain,recordType,wantName,+ zone,trace,depth,deadlineAt,@@ -692,11 +706,12 @@ export class AuthoritativeResolver extends DnsResolver {domain: string;recordType: RecordType;wantName: string;+ zone: string;trace: string[];depth: number;deadlineAt: number;budget: { remaining: number };- }): Promise<{ answers: RawAnswer[]; trace: string[] }> {+ }): Promise<WalkResult> {// Only records owned by the queried name (any type, e.g. a CNAME alias)// make this a terminal answer. An answer section carrying nothing but// unrelated records (e.g. glue promoted into it by a quirky server) must@@ -718,6 +733,10 @@ export class AuthoritativeResolver extends DnsResolver {return {answers: filteredAnswers,+ // The name owns a record, so it exists: an NXDOMAIN here describes+ // the end of a CNAME/DNAME chain (RFC 6604), not the queried name.+ rcode: packet.rcode === 'NXDOMAIN' ? 'NOERROR' : packet.rcode,+ zone,trace: [...trace,`${recordType} ${domain} @ ${candidate} (${protocol}) -> answer: ${filteredAnswers.map(this.recordToString).join(', ')}`,@@ -774,6 +793,7 @@ export class AuthoritativeResolver extends DnsResolver {domain,recordType,nameservers: addresses,+ zone: canonicalDnsName(nsRedirects[0].name),trace: [...trace,`${recordType} ${domain} @ ${candidate} (${protocol}) -> redirect to ${aRedirects.map((r) => r.data).join(', ')}`,@@ -798,7 +818,7 @@ export class AuthoritativeResolver extends DnsResolver {});}- return { answers: [], trace };+ return { answers: [], trace, rcode: packet.rcode, zone };}// Follow a glueless referral: resolve the delegated NS hostnames to public@@ -824,7 +844,8 @@ export class AuthoritativeResolver extends DnsResolver {depth: number;deadlineAt: number;budget: { remaining: number };- }): Promise<{ answers: RawAnswer[]; trace: string[] }> {+ }): Promise<WalkResult> {+ const zone = canonicalDnsName(nsRedirects[0].name);const subTrace: string[] = [];// Resolve the candidate NS hostnames concurrently and proceed with// the first usable result: done serially (or awaited jointly), a@@ -883,6 +904,7 @@ export class AuthoritativeResolver extends DnsResolver {domain,recordType,nameservers: tried,+ zone,trace: redirectTrace,depth: depth + 1,deadlineAt,@@ -899,12 +921,13 @@ export class AuthoritativeResolver extends DnsResolver {.filter((ip) => !tried.includes(ip)).slice(0, 4);if (!late.length) throw error;- this.delegationCache.delete(canonicalDnsName(nsRedirects[0].name));+ this.delegationCache.delete(zone);this.cacheDelegation(nsRedirects[0].name, domain, late);return this.fetchRecordsRaw({domain,recordType,nameservers: late,+ zone,trace: [...redirectTrace,`${recordType} ${domain} -> retrying with late sibling nameservers: ${late.join(', ')}`,@@ -916,14 +939,22 @@ 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.+ public resolveAnswers(+ domain: string,+ recordType: RecordType,+ ): Promise<WalkResult> {+ return this.fetchRecordsRaw({ domain, recordType });+ }+public async resolveRecordType(domain: string,recordType: RecordType,): Promise<ResolverResponse> {- const { answers, trace } = await this.fetchRecordsRaw({- domain,- recordType,- });+ const { answers, trace } = await this.resolveAnswers(domain, recordType);const records: RawRecord[] = answers.map((answer) => ({name: answer.name,