diff --git a/src/lib/constants/icon-map.ts b/src/lib/constants/icon-map.ts index 46226e3..d9287b0 100644 --- a/src/lib/constants/icon-map.ts +++ b/src/lib/constants/icon-map.ts @@ -254,6 +254,7 @@ export const iconMap: Record = { signature: ``, blacklist: ``, 'info-circle': ``, + 'zone-transfer-safe': ``, // '': ``, // 'pie-chart': ``, diff --git a/src/lib/constants/nav.ts b/src/lib/constants/nav.ts index ea30bb9..cdca91c 100644 --- a/src/lib/constants/nav.ts +++ b/src/lib/constants/nav.ts @@ -1188,6 +1188,13 @@ export const SUB_NAV: Record = { 'delisting', ], }, + { + href: makePath('/diagnostics/dns/axfr-tester'), + label: 'AXFR Security Tester', + description: 'Test if DNS zone transfers are improperly exposed - detect critical security vulnerabilities', + icon: 'zone-transfer-safe', + keywords: ['axfr', 'zone', 'transfer', 'security', 'vulnerability', 'dns', 'leak', 'audit', 'test', 'nameserver'], + }, { href: makePath('/diagnostics/dns/query-performance'), label: 'DNS Query Performance', diff --git a/src/lib/content/axfr.ts b/src/lib/content/axfr.ts new file mode 100644 index 0000000..41edccf --- /dev/null +++ b/src/lib/content/axfr.ts @@ -0,0 +1,298 @@ +export const axfrContent = { + title: 'DNS Zone Transfer (AXFR) Security Tester', + description: + 'Test if your DNS zone transfers are improperly exposed. AXFR vulnerabilities can leak entire DNS records to unauthorized parties.', + + sections: { + whatIsAXFR: { + title: 'What is DNS Zone Transfer (AXFR)?', + content: `DNS Zone Transfer (AXFR) is a mechanism for replicating DNS zone data between authoritative nameservers. When configured properly, it allows secondary nameservers to maintain synchronized copies of zone data from primary servers. + +However, if AXFR is misconfigured to allow transfers from any source, it becomes a serious security vulnerability. Attackers can download your entire DNS zone, revealing all subdomains, internal hostnames, IP addresses, and infrastructure details that should remain private.`, + }, + + security: { + title: 'Security Implications', + risks: [ + { + risk: 'Information Disclosure', + severity: 'High', + description: + 'Entire DNS zone exposed, revealing all subdomains, internal hostnames, IP addresses, mail servers, and infrastructure topology.', + impact: 'Provides attackers with complete map of your DNS infrastructure', + }, + { + risk: 'Reconnaissance for Attacks', + severity: 'High', + description: + 'Leaked zone data enables targeted attacks on discovered internal systems, dev/staging environments, and admin interfaces.', + impact: 'Significantly increases attack surface and enables focused exploitation', + }, + { + risk: 'Subdomain Enumeration', + severity: 'Medium', + description: + 'Discovery of hidden subdomains like admin.example.com, staging.example.com, vpn.example.com that attackers can target.', + impact: 'Exposes systems intended to be hidden from public knowledge', + }, + { + risk: 'Internal IP Exposure', + severity: 'Medium', + description: + 'Private IP addresses and internal network topology revealed through zone records.', + impact: 'Helps attackers understand internal network architecture', + }, + ], + }, + + howItWorks: { + title: 'How AXFR Testing Works', + steps: [ + 'Query nameservers (NS records) for the target domain', + 'Resolve each nameserver to its IP address', + 'Attempt AXFR query against each nameserver using dig', + 'Analyze response to determine if transfer succeeded', + 'Parse and count zone records if transfer allowed', + 'Report vulnerability status for each nameserver', + ], + }, + + interpretation: { + title: 'Understanding Test Results', + statuses: [ + { + status: 'Vulnerable', + color: 'error', + meaning: 'Zone transfer succeeded', + description: + 'The nameserver allowed unrestricted zone transfer and returned DNS records. This is a critical security vulnerability.', + action: 'Immediately restrict AXFR to authorized secondary nameservers only', + }, + { + status: 'Secure', + color: 'success', + meaning: 'Transfer refused', + description: + 'The nameserver properly rejected the zone transfer request. This is the correct configuration for public queries.', + action: 'No action needed - nameserver is properly configured', + }, + { + status: 'Error', + color: 'warning', + meaning: 'Query failed', + description: + 'Could not complete the AXFR test due to timeout, connection failure, or other error. Nameserver may be unreachable.', + action: 'Verify nameserver is functioning properly', + }, + ], + }, + + properConfiguration: { + title: 'Proper AXFR Configuration', + configurations: [ + { + server: 'BIND', + syntax: `zone "example.com" { + type master; + file "/etc/bind/zones/example.com"; + allow-transfer { + 192.0.2.1; // Secondary NS IP + 203.0.113.5; // Another authorized secondary + }; +};`, + description: 'Restrict transfers to specific IP addresses of secondary nameservers', + }, + { + server: 'NSD', + syntax: `zone: + name: "example.com" + zonefile: "example.com.zone" + provide-xfr: 192.0.2.1 NOKEY + provide-xfr: 203.0.113.5 NOKEY`, + description: 'Explicitly list authorized IPs for zone transfers', + }, + { + server: 'PowerDNS', + syntax: `allow-axfr-ips=192.0.2.1,203.0.113.5 +# Or in SQL zone metadata: +INSERT INTO domainmetadata (domain_id, kind, content) +VALUES (1, 'ALLOW-AXFR-FROM', '192.0.2.1');`, + description: 'Configure allowed transfer IPs in configuration or database', + }, + { + server: 'Microsoft DNS', + syntax: `Right-click zone → Properties → Zone Transfers: +☑ Allow zone transfers + ○ Only to servers listed on the Name Servers tab + ○ Only to the following servers: [Add IPs] + ☐ To any server`, + description: 'Use GUI to restrict transfers to specific servers only', + }, + ], + }, + + bestPractices: { + title: 'DNS Security Best Practices', + practices: [ + { + practice: 'Restrict Zone Transfers', + description: + 'Only allow AXFR from authorized secondary nameservers. Never allow unrestricted transfers.', + priority: 'Critical', + }, + { + practice: 'Use TSIG Authentication', + description: + 'Implement TSIG (Transaction Signature) for authenticated zone transfers between servers.', + priority: 'High', + }, + { + practice: 'Regular Security Audits', + description: + 'Periodically test your nameservers for AXFR vulnerabilities using tools like this one.', + priority: 'High', + }, + { + practice: 'Minimize Public DNS Records', + description: + "Don't publish internal hostnames or private infrastructure details in public DNS zones.", + priority: 'Medium', + }, + { + practice: 'Split-Horizon DNS', + description: + 'Use separate internal and external DNS zones. Internal zone contains private records, external only public ones.', + priority: 'Medium', + }, + { + practice: 'Monitor DNS Query Logs', + description: 'Log and monitor AXFR requests to detect unauthorized transfer attempts.', + priority: 'Medium', + }, + ], + }, + + remediation: { + title: 'Fixing AXFR Vulnerabilities', + steps: [ + { + step: 'Identify Vulnerable Nameservers', + details: 'Use this tool or manual dig commands to test all authoritative nameservers', + command: 'dig @nameserver.example.com example.com AXFR', + }, + { + step: 'Configure Transfer Restrictions', + details: 'Edit nameserver config to allow transfers only from secondary NS IP addresses', + command: 'allow-transfer { 192.0.2.1; 203.0.113.5; };', + }, + { + step: 'Reload DNS Configuration', + details: 'Apply configuration changes and reload the nameserver', + command: 'rndc reload (BIND) or service nsd reload (NSD)', + }, + { + step: 'Verify Fix', + details: + 'Test from external IP to confirm AXFR is now refused, and from secondary to confirm authorized transfers still work', + command: 'dig @nameserver.example.com example.com AXFR', + }, + { + step: 'Implement TSIG', + details: 'Add TSIG keys for cryptographic authentication of zone transfers', + command: 'tsig-keygen -a hmac-sha256 transfer-key', + }, + ], + }, + + commonMisconfigurations: { + title: 'Common AXFR Misconfigurations', + misconfigurations: [ + { + issue: 'No Transfer Restrictions', + example: 'allow-transfer { any; };', + problem: 'Allows anyone to download entire zone', + fix: 'Replace "any" with specific secondary NS IPs', + }, + { + issue: 'Network-Based Trust', + example: 'allow-transfer { 192.168.0.0/16; };', + problem: 'Trusts entire network range - too permissive', + fix: 'Specify exact IP addresses of secondary nameservers', + }, + { + issue: 'Default Permit Configuration', + example: 'Zone transfers enabled by default without restrictions', + problem: 'Many DNS servers default to allowing transfers', + fix: 'Explicitly configure allow-transfer directive', + }, + { + issue: 'Forgotten Test Nameserver', + example: 'Old test/dev nameserver still in production with open AXFR', + problem: 'Test servers often have relaxed security', + fix: 'Remove or properly secure all nameservers', + }, + ], + }, + + detectionMethods: { + title: 'How Attackers Exploit AXFR', + methods: [ + { + method: 'Manual dig Query', + command: 'dig @ns1.target.com target.com AXFR', + description: 'Direct zone transfer request to each nameserver', + }, + { + method: 'Automated Scanning', + command: 'fierce --domain target.com', + description: 'Tools like fierce, dnsrecon automatically test AXFR', + }, + { + method: 'Subdomain Enumeration', + command: 'After successful AXFR, extract all A/AAAA records for subdomain list', + description: 'Parse zone file to discover all subdomains and targets', + }, + { + method: 'Infrastructure Mapping', + command: 'grep "IN A\\|IN AAAA\\|IN MX\\|IN CNAME" zone_dump.txt', + description: 'Map entire infrastructure from leaked zone data', + }, + ], + }, + + compliance: { + title: 'Compliance & Standards', + standards: [ + { + standard: 'CIS DNS Benchmark', + requirement: 'Restrict zone transfers to authorized secondary nameservers', + reference: 'Section 3.7', + }, + { + standard: 'PCI DSS', + requirement: 'Secure DNS configuration to prevent information disclosure', + reference: 'Requirement 2.2', + }, + { + standard: 'NIST 800-81-2', + requirement: 'DNS Security Recommendations - Restrict AXFR', + reference: 'Section 3.1.1', + }, + { + standard: 'ISO 27001', + requirement: 'Protection against information leakage', + reference: 'A.13.2.1', + }, + ], + }, + }, + + quickTips: [ + 'Zone transfers should only work from authorized secondary nameservers', + 'Test all your nameservers - one misconfigured server compromises the entire zone', + 'Use TSIG authentication for additional transfer security', + 'Monitor DNS logs for unauthorized AXFR attempts', + 'Regular security audits help catch configuration drift', + 'Split internal and external DNS to minimize exposure', + ], +}; diff --git a/src/routes/api/internal/diagnostics/axfr/+server.ts b/src/routes/api/internal/diagnostics/axfr/+server.ts new file mode 100644 index 0000000..bf105b2 --- /dev/null +++ b/src/routes/api/internal/diagnostics/axfr/+server.ts @@ -0,0 +1,255 @@ +import { json, error } from '@sveltejs/kit'; +import type { RequestHandler } from './$types'; +import { exec } from 'node:child_process'; +import { promisify } from 'node:util'; +import { promises as dns } from 'node:dns'; + +const execAsync = promisify(exec); + +interface AXFRRequest { + domain: string; + nameserver?: string; +} + +interface NameserverResult { + nameserver: string; + ip: string; + vulnerable: boolean; + recordCount?: number; + records?: string[]; + error?: string; + responseTime: number; +} + +interface AXFRResponse { + domain: string; + nameservers: NameserverResult[]; + summary: { + total: number; + vulnerable: number; + secure: number; + errors: number; + }; + timestamp: string; +} + +const DOMAIN_PATTERN = /^([a-zA-Z0-9_]([a-zA-Z0-9_-]{0,61}[a-zA-Z0-9_])?\.)+[a-zA-Z]{2,}$/; +const MAX_DOMAIN_LENGTH = 253; +const AXFR_TIMEOUT_MS = 10000; +const MAX_RECORDS_DISPLAY = 50; + +function validateDomain(domain: string): boolean { + if (!domain || domain.length > MAX_DOMAIN_LENGTH) return false; + return DOMAIN_PATTERN.test(domain); +} + +async function resolveNameserverIP(nameserver: string): Promise { + try { + const addresses = await dns.resolve4(nameserver); + return addresses[0]; + } catch { + try { + const addresses = await dns.resolve6(nameserver); + return addresses[0]; + } catch { + throw new Error(`Failed to resolve nameserver: ${nameserver}`); + } + } +} + +async function testAXFR(domain: string, nameserver: string, ip: string): Promise { + const startTime = performance.now(); + + try { + // Use dig for AXFR query with timeout + const command = `dig @${ip} ${domain} AXFR +time=5 +retry=1 +noidnout 2>&1`; + + const { stdout, stderr } = await Promise.race([ + execAsync(command, { maxBuffer: 1024 * 1024 * 5 }), // 5MB max + new Promise((_, reject) => + setTimeout(() => reject(new Error('AXFR query timeout')), AXFR_TIMEOUT_MS) + ), + ]); + + const endTime = performance.now(); + const responseTime = Math.round((endTime - startTime) * 100) / 100; + + const output = stdout + stderr; + + // Check for transfer success indicators + if (output.includes('Transfer failed') || output.includes('failed')) { + return { + nameserver, + ip, + vulnerable: false, + error: 'Transfer refused (secure)', + responseTime, + }; + } + + // Check for timeout + if (output.includes('connection timed out') || output.includes('no servers could be reached')) { + return { + nameserver, + ip, + vulnerable: false, + error: 'Connection timeout', + responseTime, + }; + } + + // Parse records from output + const lines = output.split('\n').filter((line: string) => { + const trimmed = line.trim(); + return ( + trimmed && + !trimmed.startsWith(';') && + !trimmed.startsWith('<<>>') && + !trimmed.match(/^(DiG|global|Query|Transfer|connection|WARNING)/) + ); + }); + + // If we got actual zone records, it's vulnerable + if (lines.length > 0) { + // Filter out metadata lines + const zoneRecords = lines.filter((line: string) => { + return line.match(/^\S+\s+\d+\s+IN\s+\w+\s+/); + }); + + if (zoneRecords.length > 0) { + return { + nameserver, + ip, + vulnerable: true, + recordCount: zoneRecords.length, + records: zoneRecords.slice(0, MAX_RECORDS_DISPLAY), + responseTime, + }; + } + } + + // No records returned - secure + return { + nameserver, + ip, + vulnerable: false, + error: 'Transfer refused (secure)', + responseTime, + }; + } catch (err: any) { + const endTime = performance.now(); + const responseTime = Math.round((endTime - startTime) * 100) / 100; + + let errorMsg = 'Unknown error'; + if (err.message?.includes('timeout')) { + errorMsg = 'Query timeout'; + } else if (err.message?.includes('not found')) { + errorMsg = 'Nameserver not found'; + } else if (err.code === 'ENOENT') { + errorMsg = 'dig command not available'; + } else if (err.message) { + errorMsg = err.message.split('\n')[0].substring(0, 100); + } + + return { + nameserver, + ip, + vulnerable: false, + error: errorMsg, + responseTime, + }; + } +} + +export const POST: RequestHandler = async ({ request }) => { + try { + let body: AXFRRequest; + try { + body = await request.json(); + } catch { + throw error(400, 'Invalid JSON in request body'); + } + + const { domain, nameserver } = body; + + if (!domain || typeof domain !== 'string' || !domain.trim()) { + throw error(400, 'Domain is required'); + } + + const trimmedDomain = domain.trim().toLowerCase(); + + if (!validateDomain(trimmedDomain)) { + throw error(400, 'Invalid domain name format'); + } + + // Get nameservers to test + let nameserversToTest: string[] = []; + + if (nameserver && typeof nameserver === 'string' && nameserver.trim()) { + // Single nameserver specified + nameserversToTest = [nameserver.trim()]; + } else { + // Get all nameservers for domain + try { + nameserversToTest = await dns.resolveNs(trimmedDomain); + } catch (err: any) { + if (err.code === 'ENOTFOUND') { + throw error(400, 'Domain not found or has no nameservers'); + } + throw error(500, `Failed to resolve nameservers: ${err.message}`); + } + } + + if (nameserversToTest.length === 0) { + throw error(400, 'No nameservers found for domain'); + } + + // Limit to 10 nameservers for safety + if (nameserversToTest.length > 10) { + nameserversToTest = nameserversToTest.slice(0, 10); + } + + // Test AXFR on all nameservers + const results = await Promise.all( + nameserversToTest.map(async (ns): Promise => { + try { + const ip = await resolveNameserverIP(ns); + return await testAXFR(trimmedDomain, ns, ip); + } catch (err: any) { + return { + nameserver: ns, + ip: 'N/A', + vulnerable: false, + error: err.message || 'Failed to resolve nameserver', + responseTime: 0, + }; + } + }) + ); + + // Calculate summary + const vulnerable = results.filter((r) => r.vulnerable).length; + const secure = results.filter((r) => !r.vulnerable && !r.error).length; + const errors = results.filter((r) => r.error).length; + + const response: AXFRResponse = { + domain: trimmedDomain, + nameservers: results, + summary: { + total: results.length, + vulnerable, + secure, + errors, + }, + timestamp: new Date().toISOString(), + }; + + return json(response); + } catch (err) { + console.error('AXFR test error:', err); + if (err && typeof err === 'object' && 'status' in err) { + throw err; + } + throw error(500, `AXFR test failed: ${err instanceof Error ? err.message : 'Unknown error'}`); + } +}; diff --git a/src/routes/diagnostics/dns/axfr-tester/+page.svelte b/src/routes/diagnostics/dns/axfr-tester/+page.svelte new file mode 100644 index 0000000..27e109e --- /dev/null +++ b/src/routes/diagnostics/dns/axfr-tester/+page.svelte @@ -0,0 +1,1023 @@ + + +
+
+

DNS Zone Transfer (AXFR) Security Tester

+

Test if zone transfers are improperly exposed - a critical DNS security vulnerability

+
+ + +
+
+ + +

Quick Examples

+
+
+ {#each examples as example, i (i)} + + {/each} +
+
+
+ + +
{ e.preventDefault(); testAXFR(); }}> +
+ + { selectedExampleIndex = null; }} + aria-invalid={!isInputValid} + /> +
+ + +
+ + + {#if error} + + {/if} + + + {#if results} + + {#if results.summary.vulnerable > 0} + + {:else if results.summary.secure > 0} +
+ +
+ All Nameservers Secure +

Zone transfers are properly restricted. No AXFR vulnerabilities detected.

+
+
+ {/if} + + +
+
+ +
+ Total Nameservers + {results.summary.total} +
+
+ +
+ +
+ Vulnerable + {results.summary.vulnerable} +
+
+ +
+ +
+ Secure + {results.summary.secure} +
+
+ +
+ +
+ Errors + {results.summary.errors} +
+
+
+ + +
+

Nameserver Test Results

+ +
+ {#each results.nameservers as ns (ns.nameserver)} +
+
+
+ +
+

{ns.nameserver}

+ {ns.ip} +
+
+
+ + {getStatusText(ns)} + + {ns.responseTime}ms +
+
+ + {#if ns.vulnerable && ns.recordCount} +
+
+ + Zone transfer succeeded! Exposed {ns.recordCount} DNS records +
+ + {#if ns.records && ns.records.length > 0} + + + {#if expandedRecords.has(ns.nameserver)} +
+
{ns.records.join('\n')}
+ {#if ns.recordCount > ns.records.length} +

+ Showing first {ns.records.length} of {ns.recordCount} total records +

+ {/if} +
+ {/if} + {/if} +
+ {:else if ns.error} +
+ + {ns.error} +
+ {:else} +
+ + Zone transfer properly refused +
+ {/if} +
+ {/each} +
+
+ + + + {/if} +
+ + +
+
+

{axfrContent.sections.whatIsAXFR.title}

+

{axfrContent.sections.whatIsAXFR.content}

+
+ +
+

{axfrContent.sections.security.title}

+
+ {#each axfrContent.sections.security.risks as risk (risk.risk)} +
+
+

{risk.risk}

+ {risk.severity} +
+

{risk.description}

+
+ + {risk.impact} +
+
+ {/each} +
+
+ +
+

{axfrContent.sections.interpretation.title}

+
+ {#each axfrContent.sections.interpretation.statuses as status (status.status)} +
+
+ +

{status.status}: {status.meaning}

+
+

{status.description}

+
+ + Action: {status.action} +
+
+ {/each} +
+
+ +
+

{axfrContent.sections.properConfiguration.title}

+ {#each axfrContent.sections.properConfiguration.configurations as config (config.server)} +
+

{config.server}

+

{config.description}

+
{config.syntax}
+
+ {/each} +
+ +
+

{axfrContent.sections.remediation.title}

+
+ {#each axfrContent.sections.remediation.steps as step, i (step.step)} +
+
{i + 1}
+
+

{step.step}

+

{step.details}

+ {#if step.command} +
{step.command}
+ {/if} +
+
+ {/each} +
+
+ +
+

{axfrContent.sections.bestPractices.title}

+
+ {#each axfrContent.sections.bestPractices.practices as practice (practice.practice)} +
+
+ +

{practice.practice}

+ {practice.priority} +
+

{practice.description}

+
+ {/each} +
+
+
+ + diff --git a/tests/api/internal-endpoints/axfr.test.ts b/tests/api/internal-endpoints/axfr.test.ts new file mode 100644 index 0000000..b1818e0 --- /dev/null +++ b/tests/api/internal-endpoints/axfr.test.ts @@ -0,0 +1,325 @@ +import { describe, it, expect } from 'vitest'; + +describe('AXFR Security Tester API', () => { + const BASE_URL = 'http://localhost:5173'; + + async function makeRequest(domain: string, nameserver?: string) { + const response = await fetch(`${BASE_URL}/api/internal/diagnostics/axfr`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ domain, nameserver }), + }); + const data = await response.json(); + return { status: response.status, data }; + } + + describe('Basic Functionality', () => { + it('should test domain for AXFR vulnerability', async () => { + const { status, data } = await makeRequest('example.com'); + + expect(status).toBe(200); + expect(data.domain).toBe('example.com'); + expect(data.nameservers).toBeInstanceOf(Array); + expect(data.nameservers.length).toBeGreaterThan(0); + expect(data.summary).toBeDefined(); + expect(data.summary.total).toBe(data.nameservers.length); + expect(data.timestamp).toBeDefined(); + }); + + it('should include all required fields in nameserver results', async () => { + const { status, data } = await makeRequest('example.com'); + + expect(status).toBe(200); + + for (const ns of data.nameservers) { + expect(ns).toHaveProperty('nameserver'); + expect(ns).toHaveProperty('ip'); + expect(ns).toHaveProperty('vulnerable'); + expect(ns).toHaveProperty('responseTime'); + expect(typeof ns.nameserver).toBe('string'); + expect(typeof ns.vulnerable).toBe('boolean'); + expect(typeof ns.responseTime).toBe('number'); + } + }); + + it('should calculate correct summary counts', async () => { + const { status, data } = await makeRequest('example.com'); + + expect(status).toBe(200); + + const vulnerable = data.nameservers.filter((ns: any) => ns.vulnerable).length; + const secure = data.nameservers.filter((ns: any) => !ns.vulnerable && !ns.error).length; + const errors = data.nameservers.filter((ns: any) => ns.error).length; + + expect(data.summary.vulnerable).toBe(vulnerable); + expect(data.summary.secure).toBe(secure); + expect(data.summary.errors).toBe(errors); + expect(data.summary.total).toBe(data.nameservers.length); + }); + }); + + describe('Secure Domains', () => { + it('should report google.com as secure', async () => { + const { status, data } = await makeRequest('google.com'); + + expect(status).toBe(200); + expect(data.domain).toBe('google.com'); + expect(data.summary.vulnerable).toBe(0); + // Most/all should be secure (AXFR properly refused) + expect(data.summary.secure + data.summary.errors).toBeGreaterThan(0); + }); + + it('should report cloudflare.com as secure', async () => { + const { status, data } = await makeRequest('cloudflare.com'); + + expect(status).toBe(200); + expect(data.summary.vulnerable).toBe(0); + }); + + it('should report github.com as secure', async () => { + const { status, data } = await makeRequest('github.com'); + + expect(status).toBe(200); + expect(data.summary.vulnerable).toBe(0); + }); + }); + + describe('Vulnerable Test Domain', () => { + it('should detect vulnerability on zonetransfer.me', async () => { + const { status, data } = await makeRequest('zonetransfer.me'); + + expect(status).toBe(200); + expect(data.domain).toBe('zonetransfer.me'); + + // This domain is intentionally vulnerable for testing + // It should have at least one vulnerable nameserver + const vulnerableNS = data.nameservers.find((ns: any) => ns.vulnerable); + + if (vulnerableNS) { + expect(vulnerableNS.vulnerable).toBe(true); + expect(vulnerableNS.recordCount).toBeGreaterThan(0); + expect(vulnerableNS.records).toBeInstanceOf(Array); + expect(vulnerableNS.records.length).toBeGreaterThan(0); + } + }); + + it('should include zone records when vulnerable', async () => { + const { status, data } = await makeRequest('zonetransfer.me'); + + expect(status).toBe(200); + + const vulnerableNS = data.nameservers.find((ns: any) => ns.vulnerable); + + if (vulnerableNS) { + expect(vulnerableNS.records).toBeInstanceOf(Array); + expect(vulnerableNS.recordCount).toBeGreaterThan(0); + + // Records should be DNS zone format + if (vulnerableNS.records.length > 0) { + const firstRecord = vulnerableNS.records[0]; + expect(typeof firstRecord).toBe('string'); + // Should contain IN and record type + expect(firstRecord).toMatch(/\s+IN\s+/); + } + } + }); + }); + + describe('Single Nameserver Testing', () => { + it('should test single nameserver when specified', async () => { + const { status, data } = await makeRequest('example.com', 'a.iana-servers.net'); + + expect(status).toBe(200); + expect(data.nameservers.length).toBe(1); + expect(data.nameservers[0].nameserver).toBe('a.iana-servers.net'); + }); + + it('should handle invalid nameserver gracefully', async () => { + const { status, data } = await makeRequest('example.com', 'nonexistent-ns.example.com'); + + expect(status).toBe(200); + expect(data.nameservers.length).toBe(1); + expect(data.nameservers[0].error).toBeDefined(); + expect(data.nameservers[0].vulnerable).toBe(false); + }); + }); + + describe('Domain Normalization', () => { + it('should normalize domain to lowercase', async () => { + const { status, data } = await makeRequest('Example.COM'); + + expect(status).toBe(200); + expect(data.domain).toBe('example.com'); + }); + + it('should trim whitespace from domain', async () => { + const { status, data } = await makeRequest(' example.com '); + + expect(status).toBe(200); + expect(data.domain).toBe('example.com'); + }); + }); + + describe('Error Handling', () => { + it('should reject empty domain', async () => { + const { status, data } = await makeRequest(''); + + expect(status).toBe(400); + expect(data.message).toMatch(/required/i); + }); + + it('should reject missing domain', async () => { + const response = await fetch(`${BASE_URL}/api/internal/diagnostics/axfr`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({}), + }); + + expect(response.status).toBe(400); + const data = await response.json(); + expect(data.message).toMatch(/required/i); + }); + + it('should reject whitespace-only domain', async () => { + const { status, data } = await makeRequest(' '); + + expect(status).toBe(400); + expect(data.message).toMatch(/required/i); + }); + + it('should reject invalid domain format', async () => { + const { status, data } = await makeRequest('invalid domain with spaces'); + + expect(status).toBe(400); + expect(data.message).toMatch(/invalid|format/i); + }); + + it('should handle domain with no nameservers', async () => { + const { status, data } = await makeRequest('this-domain-definitely-does-not-exist-12345.com'); + + expect(status).toBeGreaterThanOrEqual(400); + expect(data.message).toMatch(/not found|nameserver/i); + }); + + it('should reject invalid JSON', async () => { + const response = await fetch(`${BASE_URL}/api/internal/diagnostics/axfr`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: 'not valid json', + }); + + expect(response.status).toBe(400); + const data = await response.json(); + expect(data.message).toMatch(/json/i); + }); + }); + + describe('Response Time Tracking', () => { + it('should include response times for all nameservers', async () => { + const { status, data } = await makeRequest('example.com'); + + expect(status).toBe(200); + + for (const ns of data.nameservers) { + expect(ns.responseTime).toBeGreaterThanOrEqual(0); + expect(typeof ns.responseTime).toBe('number'); + } + }); + + it('should complete within reasonable time', async () => { + const startTime = Date.now(); + const { status } = await makeRequest('example.com'); + const duration = Date.now() - startTime; + + expect(status).toBe(200); + // Should complete within 30 seconds (generous timeout for multiple NS) + expect(duration).toBeLessThan(30000); + }); + }); + + describe('Nameserver Limits', () => { + it('should limit to 10 nameservers', async () => { + const { status, data } = await makeRequest('example.com'); + + expect(status).toBe(200); + // Should not exceed 10 nameservers even if domain has more + expect(data.nameservers.length).toBeLessThanOrEqual(10); + }); + }); + + describe('Record Count Limits', () => { + it('should limit exposed records to 50', async () => { + const { status, data } = await makeRequest('zonetransfer.me'); + + expect(status).toBe(200); + + const vulnerableNS = data.nameservers.find((ns: any) => ns.vulnerable); + + if (vulnerableNS && vulnerableNS.records) { + // Should not return more than 50 records + expect(vulnerableNS.records.length).toBeLessThanOrEqual(50); + + // But recordCount can be higher + if (vulnerableNS.recordCount > 50) { + expect(vulnerableNS.records.length).toBe(50); + } + } + }); + }); + + describe('IP Resolution', () => { + it('should resolve nameserver IPs', async () => { + const { status, data } = await makeRequest('example.com'); + + expect(status).toBe(200); + + for (const ns of data.nameservers) { + // IP should be present (unless resolution failed) + if (!ns.error || !ns.error.includes('resolve')) { + expect(ns.ip).toBeDefined(); + expect(ns.ip).not.toBe('N/A'); + // Should be valid IP format (simplified check) + expect(ns.ip).toMatch(/[\d.:a-fA-F]+/); + } + } + }); + }); + + describe('Timestamp Validation', () => { + it('should include valid timestamp', async () => { + const { status, data } = await makeRequest('example.com'); + + expect(status).toBe(200); + expect(data.timestamp).toBeDefined(); + + const timestamp = new Date(data.timestamp); + expect(timestamp.getTime()).toBeLessThanOrEqual(Date.now()); + expect(timestamp.getTime()).toBeGreaterThan(Date.now() - 60000); // Within last minute + }); + }); + + describe('Different Domain TLDs', () => { + it('should handle .org domains', async () => { + const { status, data } = await makeRequest('wikipedia.org'); + + expect(status).toBe(200); + expect(data.domain).toBe('wikipedia.org'); + expect(data.nameservers.length).toBeGreaterThan(0); + }); + + it('should handle .net domains', async () => { + const { status, data } = await makeRequest('cloudflare.net'); + + expect(status).toBe(200); + expect(data.domain).toBe('cloudflare.net'); + }); + + it('should handle country code TLDs', async () => { + const { status, data } = await makeRequest('bbc.co.uk'); + + expect(status).toBe(200); + expect(data.domain).toBe('bbc.co.uk'); + expect(data.nameservers.length).toBeGreaterThan(0); + }); + }); +});