From 7470a8d92f8366a4ce7e1c3b52cae375e2e85bcf Mon Sep 17 00:00:00 2001 From: Alicia Sykes Date: Mon, 8 Sep 2025 20:50:47 +0100 Subject: [PATCH] DNS Zone diff, lint, stats, parsing, len check --- src/lib/components/global/Icon.svelte | 30 +- .../components/tools/NameLengthChecker.svelte | 942 +++++++++++++++ src/lib/components/tools/ZoneDiff.svelte | 933 +++++++++++++++ src/lib/components/tools/ZoneLinter.svelte | 755 ++++++++++++ src/lib/components/tools/ZoneStats.svelte | 1061 +++++++++++++++++ src/lib/constants/nav.ts | 33 + src/lib/utils/zone-parser.ts | 445 +++++++ src/routes/dns/zone/+page.svelte | 385 ++++++ src/routes/dns/zone/diff/+page.svelte | 10 + src/routes/dns/zone/linter/+page.svelte | 10 + .../dns/zone/name-length-checker/+page.svelte | 10 + src/routes/dns/zone/stats/+page.svelte | 10 + 12 files changed, 4618 insertions(+), 6 deletions(-) create mode 100644 src/lib/components/tools/NameLengthChecker.svelte create mode 100644 src/lib/components/tools/ZoneDiff.svelte create mode 100644 src/lib/components/tools/ZoneLinter.svelte create mode 100644 src/lib/components/tools/ZoneStats.svelte create mode 100644 src/lib/utils/zone-parser.ts create mode 100644 src/routes/dns/zone/+page.svelte create mode 100644 src/routes/dns/zone/diff/+page.svelte create mode 100644 src/routes/dns/zone/linter/+page.svelte create mode 100644 src/routes/dns/zone/name-length-checker/+page.svelte create mode 100644 src/routes/dns/zone/stats/+page.svelte diff --git a/src/lib/components/global/Icon.svelte b/src/lib/components/global/Icon.svelte index f55a502..f53e2aa 100644 --- a/src/lib/components/global/Icon.svelte +++ b/src/lib/components/global/Icon.svelte @@ -45,12 +45,16 @@ + {:else if name === 'shield-check'} + + {:else if name === 'shield-alert'} + + {:else if name === 'maximize'} + + {:else if name === 'pie' || name === 'dns-zone-stats'} + {:else if name === 'layers'} - - - - - + {:else if name === 'warning'} {:else if name === 'info'} @@ -185,6 +189,8 @@ {:else if name === 'dns-label-normalize'} + {:else if name === 'dns-zone-linter'} + {:else if name === 'dns-ttl'} {:else if name === 'alias'} @@ -195,8 +201,12 @@ + {:else if name === 'code-diff' || name === 'dns-zone-diff'} + {:else if name === 'file'} + {:else if name === 'file-tick'} + {:else if name === 'map-pin'} {:else if name === 'arrow-up-down'} @@ -263,16 +273,20 @@ {:else if name === 'sort'} + {:else if name === 'minus'} + {:else if name === 'plus'} {:else if name === 'certified'} - {:else if name === 'ruler'} + {:else if name === 'ruler' || name === 'dns-name-length'} {:else if name === 'wrench'} {:else if name === 'settings'} + {:else if name === 'layout'} + {:else if name === 'calendar'} {:else if name === 'check'} @@ -293,8 +307,12 @@ {:else if name === 'scattered'} + {:else if name === 'hash'} + {:else if name === 'help'} + {:else if name === 'bar-chart'} + {:else if name === 'list-check'} {:else if name === 'list'} diff --git a/src/lib/components/tools/NameLengthChecker.svelte b/src/lib/components/tools/NameLengthChecker.svelte new file mode 100644 index 0000000..02d010a --- /dev/null +++ b/src/lib/components/tools/NameLengthChecker.svelte @@ -0,0 +1,942 @@ + + +
+
+

DNS Name Length Checker

+

Validate DNS names against RFC length limits: 63 bytes per label, 255 bytes per FQDN

+
+ + +
+
+
+ +
+ Label Limits: Each DNS label must be 63 characters or fewer. +
+
+
+ +
+ FQDN Limits: Complete domain names must be 255 characters or fewer. +
+
+
+ +
+ Compliance: Exceeding limits causes DNS resolution failures. +
+
+
+
+ + +
+
+ + +

Name Length Examples

+
+
+ {#each examples as example, index} + + {/each} +
+
+
+ + +
+
+ + +
+
+ + + {#if results} +
+
+

Name Length Validation Results

+ +
+ +
+ +
+
+
+
+ +
+
+
{results.totalNames}
+
Total Names
+
+
+ +
+
+ +
+
+
{results.validNames}
+
Valid Names
+
+
+ +
+
+ +
+
+
{results.violations.length}
+
Violations
+
+
+ +
+
+ +
+
+
+ {results.violations.length === 0 ? '100%' : `${((results.validNames / results.totalNames) * 100).toFixed(1)}%`} +
+
Compliance
+
+
+
+
+ + {#if results.violations.length === 0} + +
+
+ +
+

All Names Valid!

+

All {results.totalNames} domain names in your zone comply with DNS length limits.

+
+
+
+ {:else} + +
+

Length Limit Violations

+ + + {#if results.violations.filter(v => v.type === 'label').length > 0} +
+
+ + Label Length Violations ({results.violations.filter(v => v.type === 'label').length}) +
+
+ {#each results.violations.filter(v => v.type === 'label') as violation} +
+
+
{violation.name}
+
+ + {violation.length} chars + + + (limit: {violation.limit}) + + + +{violation.length - violation.limit} over + +
+
+ {#if violation.labels} +
+ Labels: + {#each violation.labels as label, index} + + {label} ({label.length}) + + {#if index < violation.labels.length - 1}•{/if} + {/each} +
+ {/if} +
+ {/each} +
+
+ {/if} + + + {#if results.violations.filter(v => v.type === 'fqdn').length > 0} +
+
+ + FQDN Length Violations ({results.violations.filter(v => v.type === 'fqdn').length}) +
+
+ {#each results.violations.filter(v => v.type === 'fqdn') as violation} +
+
+
{violation.name}
+
+ + {violation.length} chars + + + (limit: {violation.limit}) + + + +{violation.length - violation.limit} over + +
+
+
+ {/each} +
+
+ {/if} +
+ {/if} +
+
+ {/if} + + +
+
+
+

DNS Name Limits

+

+ DNS names have strict length limits defined by RFC specifications. Each label (part + between dots) must be 63 octets or less, and the complete FQDN must not exceed + 255 octets including the length encoding. +

+
+ +
+

Impact of Violations

+

+ Names exceeding these limits will cause DNS resolution failures. Some resolvers + may truncate names, while others will reject them entirely. This can break + applications and services relying on these names. +

+
+ +
+

Common Causes

+

+ Long names often result from deep subdomain structures, verbose naming conventions, + or automated name generation. Consider shorter alternatives or restructuring + your DNS hierarchy to stay within limits. +

+
+ +
+

Best Practices

+

+ Use concise, descriptive names. Avoid unnecessary subdomains and overly verbose + labels. Regularly validate zone files during development. Consider using aliases + or redirects for shorter public-facing names. +

+
+
+
+
+ + diff --git a/src/lib/components/tools/ZoneDiff.svelte b/src/lib/components/tools/ZoneDiff.svelte new file mode 100644 index 0000000..8e01b0b --- /dev/null +++ b/src/lib/components/tools/ZoneDiff.svelte @@ -0,0 +1,933 @@ + + +
+
+

DNS Zone Diff

+

Compare two zone files and identify added, removed, and changed DNS records

+
+ + +
+
+
+ +
+ Added Records: Identify new DNS records in the updated zone file. +
+
+
+ +
+ Removed Records: Find records that were deleted from the original zone. +
+
+
+ +
+ Changed Records: Detect modifications to existing records' data or TTL. +
+
+
+
+ + +
+
+ + +

Zone Comparison Examples

+
+
+ {#each examples as example, index} + + {/each} +
+
+
+ + +
+
+
+ + +
+ +
+ + +
+
+
+ + + {#if results} +
+
+

Zone Comparison Results

+
+ + +
+
+ +
+ +
+

+ + Change Summary +

+
+
+
{results.added.length}
+
Added
+
+
+
{results.removed.length}
+
Removed
+
+
+
{results.changed.length}
+
Changed
+
+
+
{results.unchanged.length}
+
Unchanged
+
+
+
+ + + {#if showUnified} +
+

+ + Unified Diff +

+
+
{generateUnifiedDiff()}
+
+
+ {:else} +
+ + {#if results.added.length > 0} +
+

+ + Added Records ({results.added.length}) +

+
+ {#each results.added as record} +
+ + {formatRecord(record)} +
+ {/each} +
+
+ {/if} + + + {#if results.removed.length > 0} +
+

+ + Removed Records ({results.removed.length}) +

+
+ {#each results.removed as record} +
+ + {formatRecord(record)} +
+ {/each} +
+
+ {/if} + + + {#if results.changed.length > 0} +
+

+ + Changed Records ({results.changed.length}) +

+
+ {#each results.changed as change} +
+
+ + {formatRecord(change.before)} +
+
+ + {formatRecord(change.after)} +
+
+ {/each} +
+
+ {/if} +
+ {/if} +
+
+ {/if} + + +
+
+
+

Zone File Comparison

+

+ Comparing zone files helps track DNS changes during migrations, updates, or + troubleshooting. It identifies exactly what records were added, removed, or modified + between two zone versions. +

+
+ +
+

Change Types

+

+ Added records are new entries in the updated zone. Removed records exist in the + original but not the updated zone. Changed records have the same owner and type + but different data or TTL values. +

+
+ +
+

Diff Formats

+

+ Structured format groups changes by type for easy review. Unified diff format + follows standard patch conventions, useful for version control systems and + automated processing. +

+
+ +
+

Migration Planning

+

+ Use zone diffs to plan DNS migrations, verify changes before deployment, and + audit modifications. Consider TTL impact on propagation when planning record + updates or deletions. +

+
+
+
+
+ + diff --git a/src/lib/components/tools/ZoneLinter.svelte b/src/lib/components/tools/ZoneLinter.svelte new file mode 100644 index 0000000..eefe513 --- /dev/null +++ b/src/lib/components/tools/ZoneLinter.svelte @@ -0,0 +1,755 @@ + + +
+
+

DNS Zone Linter

+

Normalize and canonicalize BIND zone files with error checking and formatting

+
+ + +
+
+
+ +
+ Normalization: Sort records, remove duplicates, and apply consistent formatting. +
+
+
+ +
+ Error Detection: Identify syntax errors, missing records, and configuration issues. +
+
+
+ +
+ Canonicalization: Apply standard ordering and TTL defaults for clean output. +
+
+
+
+ + +
+
+ + +

Zone File Examples

+
+
+ {#each examples as example, index} + + {/each} +
+
+
+ + +
+
+ + +
+
+ + + {#if results} +
+

Linting Results

+
+ + + {#if results.normalized.errors.length > 0 || results.normalized.warnings.length > 0} +
+

+ + Issues Found +

+ + {#if results.normalized.errors.length > 0} +
+
Errors ({results.normalized.errors.length})
+ {#each results.normalized.errors as error} +
+ +
+ Line {error.line}: + {error.message} +
+
+ {/each} +
+ {/if} + + {#if results.normalized.warnings.length > 0} +
+
Warnings ({results.normalized.warnings.length})
+ {#each results.normalized.warnings as warning} +
+ +
+ Line {warning.line || 'General'}: + {warning.message} +
+
+ {/each} +
+ {/if} +
+ {/if} + + +
+

+ + Zone Summary +

+
+
+
Total Records
+
{results.normalized.records.length}
+
+
+
Origin
+
{results.normalized.origin || 'Not specified'}
+
+
+
Default TTL
+
{results.normalized.defaultTTL || 'Not specified'}
+
+
+
Has SOA
+
+ {results.normalized.soa ? 'Yes' : 'No'} +
+
+
+
+ + +
+
+

+ + Normalized Zone File +

+
+ + +
+
+ +
+
{results.formattedZone}
+
+
+
+
+ {/if} + + +
+
+
+

Zone File Format

+

+ BIND zone files define DNS records for a domain. They include resource records (RRs) + with owner names, TTL values, classes, types, and data. Proper formatting ensures + reliable DNS operation. +

+
+ +
+

Normalization Benefits

+

+ Normalizing zone files improves readability, reduces errors, and ensures consistent + formatting. It also helps identify duplicate records and missing essential records + like SOA and NS. +

+
+ +
+

Common Issues

+

+ Watch for missing trailing dots in FQDNs, duplicate records, incorrect TTL values, + and missing SOA or NS records. The linter helps catch these configuration problems + early. +

+
+ +
+

Best Practices

+

+ Use consistent TTL values, maintain proper record ordering, include comprehensive + NS records, and regularly validate your zones. Consider using shorter TTLs during + transitions. +

+
+
+
+
+ + diff --git a/src/lib/components/tools/ZoneStats.svelte b/src/lib/components/tools/ZoneStats.svelte new file mode 100644 index 0000000..9fc6776 --- /dev/null +++ b/src/lib/components/tools/ZoneStats.svelte @@ -0,0 +1,1061 @@ + + +
+
+

DNS Zone Statistics

+

Analyze zone file structure, record distribution, and configuration health

+
+ + +
+
+
+ +
+ Record Analysis: Count and categorize all DNS records by type and TTL. +
+
+
+ +
+ Size Metrics: Identify largest records and analyze name length distribution. +
+
+
+ +
+ Health Checks: Validate zone structure and identify potential issues. +
+
+
+
+ + +
+
+ + +

Zone Analysis Examples

+
+
+ {#each examples as example, index} + + {/each} +
+
+
+ + +
+
+ + +
+
+ + + {#if results} +
+
+

Zone Analysis Report

+ +
+ +
+ +
+
+
+ +
+
+
{results.totalRecords}
+
Total Records
+
+
+ +
+
+ +
+
+
{Object.keys(results.recordsByType).length}
+
Record Types
+
+
+ +
+
+ +
+
+
{Object.keys(results.ttlDistribution).length}
+
Unique TTLs
+
+
+ +
+
+ +
+
+
{results.nameDepths.average.toFixed(1)}
+
Avg Name Length
+
+
+
+ + +
+

+ + Record Type Distribution +

+
+ {#each Object.entries(results.recordsByType).sort(([,a], [,b]) => b - a) as [type, count]} +
+
+ {type} + {count} record{count !== 1 ? 's' : ''} +
+
+
+
+
+ {((count / results.totalRecords) * 100).toFixed(1)}% +
+
+ {/each} +
+
+ + +
+

+ + TTL Distribution +

+
+ {#each Object.entries(results.ttlDistribution).sort(([a], [b]) => parseInt(a) - parseInt(b)) as [ttl, count]} +
+
+ + {parseInt(ttl)}s + + ({getTTLLabel(parseInt(ttl))}) +
+
{count} record{count !== 1 ? 's' : ''}
+
+ {/each} +
+
+ + +
+

+ + Name Length Analysis +

+
+
+
Shortest Name
+
{results.nameDepths.min} chars
+
+
+
Longest Name
+
{results.nameDepths.max} chars
+
{results.longestName.name}
+
+
+
Average Length
+
{results.nameDepths.average.toFixed(1)} chars
+
+
+
+ + +
+

+ + Largest Record +

+
+
{results.largestRecord.size} bytes
+
+
{results.largestRecord.record.owner}
+
+ {results.largestRecord.record.type} {results.largestRecord.record.rdata} +
+
+
+
+ + +
+

+ + Zone Health Checks +

+
+
+ + SOA Record Present +
+ +
+ + NS Records Present +
+ +
+ + + {results.sanityChecks.duplicates.length === 0 ? 'No Duplicate Records' : `${results.sanityChecks.duplicates.length} Duplicate Record${results.sanityChecks.duplicates.length !== 1 ? 's' : ''}`} + +
+ +
+ + + {results.sanityChecks.orphanedGlue.length === 0 ? 'No Orphaned Glue Records' : `${results.sanityChecks.orphanedGlue.length} Orphaned Glue Record${results.sanityChecks.orphanedGlue.length !== 1 ? 's' : ''}`} + +
+
+
+
+
+ {/if} + + +
+
+
+

Zone Statistics

+

+ Zone statistics help understand DNS structure, identify optimization opportunities, + and spot potential issues. Analyze record distribution, TTL patterns, and naming + conventions for better zone management. +

+
+ +
+

TTL Strategy

+

+ TTL distribution reveals caching patterns. Short TTLs enable quick changes but + increase DNS load. Long TTLs reduce queries but slow propagation. Balance based + on change frequency and traffic patterns. +

+
+ +
+

Record Analysis

+

+ Record type distribution shows zone complexity. Heavy A/AAAA records suggest + web services, many MX records indicate mail infrastructure, and diverse types + show comprehensive DNS usage. +

+
+ +
+

Health Monitoring

+

+ Regular zone analysis catches configuration drift, identifies duplicates, and + ensures essential records exist. Use statistics to track zone growth and + optimize DNS performance over time. +

+
+
+
+
+ + diff --git a/src/lib/constants/nav.ts b/src/lib/constants/nav.ts index e60bf53..8fa2424 100644 --- a/src/lib/constants/nav.ts +++ b/src/lib/constants/nav.ts @@ -495,6 +495,39 @@ export const SUB_NAV: Record = { keywords: ['dns', 'label', 'normalize', 'domain', 'homograph', 'attack', 'script', 'mixing', 'security', 'idn'] } ] + }, + { + title: 'Zone File Tools', + items: [ + { + href: '/dns/zone/linter', + label: 'Zone Linter', + description: 'Normalize and canonicalize BIND zone files with error checking and formatting', + icon: 'dns-zone-linter', + keywords: ['dns', 'zone', 'linter', 'normalize', 'canonicalize', 'bind', 'error', 'checking', 'format'] + }, + { + href: '/dns/zone/diff', + label: 'Zone Diff', + description: 'Compare two zone files and identify added, removed, and changed DNS records', + icon: 'dns-zone-diff', + keywords: ['dns', 'zone', 'diff', 'compare', 'changes', 'added', 'removed', 'modified', 'migration'] + }, + { + href: '/dns/zone/stats', + label: 'Zone Statistics', + description: 'Analyze zone file structure, record distribution, and configuration health', + icon: 'dns-zone-stats', + keywords: ['dns', 'zone', 'statistics', 'analysis', 'records', 'distribution', 'health', 'metrics'] + }, + { + href: '/dns/zone/name-length-checker', + label: 'Name Length Checker', + description: 'Validate DNS names against RFC length limits: 63 bytes per label, 255 bytes per FQDN', + icon: 'dns-name-length', + keywords: ['dns', 'name', 'length', 'validator', 'rfc', 'limits', 'label', 'fqdn', 'validation'] + } + ] } ], '/reference': [ diff --git a/src/lib/utils/zone-parser.ts b/src/lib/utils/zone-parser.ts new file mode 100644 index 0000000..48021ed --- /dev/null +++ b/src/lib/utils/zone-parser.ts @@ -0,0 +1,445 @@ +export interface ResourceRecord { + owner: string; + ttl?: number; + class: string; + type: string; + rdata: string; + line?: number; + raw?: string; +} + +export interface ParsedZone { + records: ResourceRecord[]; + errors: ParseError[]; + warnings: ParseWarning[]; + soa?: ResourceRecord; + defaultTTL?: number; + origin?: string; +} + +export interface ParseError { + line: number; + message: string; + severity: 'error' | 'warning'; +} + +export interface ParseWarning extends ParseError { + severity: 'warning'; +} + +export interface ZoneStats { + totalRecords: number; + recordsByType: Record; + ttlDistribution: Record; + nameDepths: { + min: number; + max: number; + average: number; + }; + largestRecord: { + record: ResourceRecord; + size: number; + }; + longestName: { + name: string; + length: number; + }; + sanityChecks: { + hasSoa: boolean; + hasNs: boolean; + duplicates: ResourceRecord[]; + orphanedGlue: ResourceRecord[]; + }; +} + +export interface ZoneDiff { + added: ResourceRecord[]; + removed: ResourceRecord[]; + changed: Array<{ + before: ResourceRecord; + after: ResourceRecord; + }>; + unchanged: ResourceRecord[]; +} + +export interface NameLengthViolation { + name: string; + type: 'label' | 'fqdn'; + length: number; + limit: number; + labels?: string[]; +} + +// Constants +const MAX_LABEL_LENGTH = 63; +const MAX_FQDN_LENGTH = 255; +const DEFAULT_CLASS = 'IN'; +const DEFAULT_TTL = 3600; + +export function parseZoneFile(content: string): ParsedZone { + const lines = content.split('\n'); + const records: ResourceRecord[] = []; + const errors: ParseError[] = []; + const warnings: ParseWarning[] = []; + + let currentOrigin = ''; + let defaultTTL = DEFAULT_TTL; + let lastOwner = ''; + let soa: ResourceRecord | undefined; + + for (let i = 0; i < lines.length; i++) { + const line = lines[i].trim(); + const lineNum = i + 1; + + // Skip empty lines and comments + if (!line || line.startsWith(';')) continue; + + try { + // Handle $ORIGIN directive + if (line.startsWith('$ORIGIN')) { + const match = line.match(/^\$ORIGIN\s+(\S+)/); + if (match) { + currentOrigin = match[1]; + if (!currentOrigin.endsWith('.')) { + currentOrigin += '.'; + } + } + continue; + } + + // Handle $TTL directive + if (line.startsWith('$TTL')) { + const match = line.match(/^\$TTL\s+(\d+)/); + if (match) { + defaultTTL = parseInt(match[1]); + } + continue; + } + + // Parse resource record + const record = parseResourceRecord(line, lastOwner, defaultTTL, currentOrigin, lineNum); + if (record) { + records.push(record); + lastOwner = record.owner; + + if (record.type === 'SOA' && !soa) { + soa = record; + } + } + } catch (error) { + errors.push({ + line: lineNum, + message: error instanceof Error ? error.message : 'Unknown parsing error', + severity: 'error' + }); + } + } + + // Add warnings for common issues + if (!soa) { + warnings.push({ + line: 0, + message: 'No SOA record found in zone', + severity: 'warning' + }); + } + + return { + records, + errors, + warnings, + soa, + defaultTTL, + origin: currentOrigin + }; +} + +function parseResourceRecord( + line: string, + lastOwner: string, + defaultTTL: number, + origin: string, + lineNum: number +): ResourceRecord | null { + // Remove comments + const commentIndex = line.indexOf(';'); + const cleanLine = commentIndex >= 0 ? line.substring(0, commentIndex).trim() : line; + + if (!cleanLine) return null; + + const parts = cleanLine.split(/\s+/); + if (parts.length < 3) return null; + + let owner = parts[0]; + let ttl: number | undefined; + let recordClass = DEFAULT_CLASS; + let type: string; + let rdata: string; + let partIndex = 1; + + // Handle implicit owner (blank or continuation) + if (owner === '' || owner === '@') { + owner = lastOwner || origin; + } else if (!owner.endsWith('.') && origin) { + owner = owner + '.' + origin; + } + + // Parse TTL (optional) + if (/^\d+$/.test(parts[partIndex])) { + ttl = parseInt(parts[partIndex]); + partIndex++; + } + + // Parse class (optional, usually IN) + if (parts[partIndex] && ['IN', 'CH', 'HS'].includes(parts[partIndex].toUpperCase())) { + recordClass = parts[partIndex].toUpperCase(); + partIndex++; + } + + // Parse type (required) + if (partIndex >= parts.length) return null; + type = parts[partIndex].toUpperCase(); + partIndex++; + + // Parse RDATA (rest of the line) + rdata = parts.slice(partIndex).join(' '); + + return { + owner, + ttl: ttl || defaultTTL, + class: recordClass, + type, + rdata, + line: lineNum, + raw: line + }; +} + +export function normalizeZone(zone: ParsedZone): ParsedZone { + const normalizedRecords = [...zone.records] + .sort((a, b) => { + // Sort by owner name first + if (a.owner !== b.owner) { + return a.owner.localeCompare(b.owner); + } + // Then by type + if (a.type !== b.type) { + return a.type.localeCompare(b.type); + } + // Then by RDATA + return a.rdata.localeCompare(b.rdata); + }) + // Remove duplicates + .filter((record, index, array) => { + if (index === 0) return true; + const prev = array[index - 1]; + return !( + record.owner === prev.owner && + record.type === prev.type && + record.rdata === prev.rdata + ); + }); + + return { + ...zone, + records: normalizedRecords + }; +} + +export function generateZoneStats(zone: ParsedZone): ZoneStats { + const recordsByType: Record = {}; + const ttlDistribution: Record = {}; + const nameLengths: number[] = []; + + let largestRecord = { record: zone.records[0], size: 0 }; + let longestName = { name: '', length: 0 }; + + for (const record of zone.records) { + // Count by type + recordsByType[record.type] = (recordsByType[record.type] || 0) + 1; + + // Count TTL distribution + const ttl = record.ttl || 0; + ttlDistribution[ttl] = (ttlDistribution[ttl] || 0) + 1; + + // Track name lengths and depths + const nameLength = record.owner.length; + nameLengths.push(nameLength); + + if (nameLength > longestName.length) { + longestName = { name: record.owner, length: nameLength }; + } + + // Track largest record + const recordSize = (record.raw || '').length; + if (recordSize > largestRecord.size) { + largestRecord = { record, size: recordSize }; + } + } + + // Calculate name depth statistics + const nameDepths = { + min: Math.min(...nameLengths), + max: Math.max(...nameLengths), + average: nameLengths.reduce((sum, len) => sum + len, 0) / nameLengths.length || 0 + }; + + // Find duplicates + const duplicates: ResourceRecord[] = []; + const seen = new Set(); + + for (const record of zone.records) { + const key = `${record.owner}:${record.type}:${record.rdata}`; + if (seen.has(key)) { + duplicates.push(record); + } else { + seen.add(key); + } + } + + // Basic sanity checks + const hasSoa = zone.records.some(r => r.type === 'SOA'); + const hasNs = zone.records.some(r => r.type === 'NS'); + + // Find orphaned glue records (A/AAAA records for NS that don't exist) + const nsTargets = new Set( + zone.records + .filter(r => r.type === 'NS') + .map(r => r.rdata.trim()) + ); + + const orphanedGlue = zone.records.filter(record => { + return (record.type === 'A' || record.type === 'AAAA') && + !nsTargets.has(record.owner); + }); + + return { + totalRecords: zone.records.length, + recordsByType, + ttlDistribution, + nameDepths, + largestRecord, + longestName, + sanityChecks: { + hasSoa, + hasNs, + duplicates, + orphanedGlue + } + }; +} + +export function compareZones(oldZone: ParsedZone, newZone: ParsedZone): ZoneDiff { + const oldRecords = new Map(); + const newRecords = new Map(); + + // Create maps for easy comparison + oldZone.records.forEach(record => { + const key = `${record.owner}:${record.type}`; + oldRecords.set(key, record); + }); + + newZone.records.forEach(record => { + const key = `${record.owner}:${record.type}`; + newRecords.set(key, record); + }); + + const added: ResourceRecord[] = []; + const removed: ResourceRecord[] = []; + const changed: Array<{ before: ResourceRecord; after: ResourceRecord }> = []; + const unchanged: ResourceRecord[] = []; + + // Find added and changed records + newRecords.forEach((newRecord, key) => { + const oldRecord = oldRecords.get(key); + if (!oldRecord) { + added.push(newRecord); + } else if (oldRecord.rdata !== newRecord.rdata || oldRecord.ttl !== newRecord.ttl) { + changed.push({ before: oldRecord, after: newRecord }); + } else { + unchanged.push(newRecord); + } + }); + + // Find removed records + oldRecords.forEach((oldRecord, key) => { + if (!newRecords.has(key)) { + removed.push(oldRecord); + } + }); + + return { + added, + removed, + changed, + unchanged + }; +} + +export function checkNameLengths(zone: ParsedZone): NameLengthViolation[] { + const violations: NameLengthViolation[] = []; + const checkedNames = new Set(); + + for (const record of zone.records) { + const name = record.owner; + + if (checkedNames.has(name)) continue; + checkedNames.add(name); + + // Check FQDN length + if (name.length > MAX_FQDN_LENGTH) { + violations.push({ + name, + type: 'fqdn', + length: name.length, + limit: MAX_FQDN_LENGTH + }); + } + + // Check individual label lengths + const labels = name.split('.'); + for (const label of labels) { + if (label.length > MAX_LABEL_LENGTH) { + violations.push({ + name, + type: 'label', + length: label.length, + limit: MAX_LABEL_LENGTH, + labels + }); + break; // Only report once per name + } + } + } + + return violations; +} + +export function formatZoneFile(zone: ParsedZone): string { + const lines: string[] = []; + + // Add directives + if (zone.origin) { + lines.push(`$ORIGIN ${zone.origin}`); + } + + if (zone.defaultTTL) { + lines.push(`$TTL ${zone.defaultTTL}`); + } + + if (lines.length > 0) { + lines.push(''); // Empty line after directives + } + + // Add records + let lastOwner = ''; + for (const record of zone.records) { + const owner = record.owner === lastOwner ? '' : record.owner; + const ttl = record.ttl === zone.defaultTTL ? '' : record.ttl?.toString() || ''; + const parts = [owner, ttl, record.class, record.type, record.rdata].filter(Boolean); + lines.push(parts.join('\t')); + lastOwner = record.owner; + } + + return lines.join('\n'); +} \ No newline at end of file diff --git a/src/routes/dns/zone/+page.svelte b/src/routes/dns/zone/+page.svelte new file mode 100644 index 0000000..d63e2e1 --- /dev/null +++ b/src/routes/dns/zone/+page.svelte @@ -0,0 +1,385 @@ + + + + DNS Zone File Tools - IP Calculator + + + +
+
+
+

DNS Zone File Tools

+

Professional tools for DNS zone file analysis, validation, and management. Built for network administrators, DNS engineers, and automation workflows.

+
+
+ +
+ {#each zoneTools as tool} + +
+ +
+
+

{tool.label}

+

{tool.description}

+
+
+ +
+
+ {/each} +
+ +
+
+
+
+ +
+
+

Zone Validation

+

Comprehensive RFC compliance checking with detailed error reporting and recommendations for fixing common issues.

+
+
+ +
+
+ +
+
+

Change Tracking

+

Compare zone file versions to track DNS changes, plan migrations, and audit modifications with unified diff support.

+
+
+ +
+
+ +
+
+

Analytics & Insights

+

Deep analysis of record distribution, TTL patterns, name lengths, and zone health metrics for optimization.

+
+
+ +
+
+ +
+
+

Standards Compliance

+

Ensure DNS names meet RFC length limits and zone files follow best practices for reliable DNS operation.

+
+
+
+
+ +
+

Common Use Cases

+
+
+

DNS Migration Planning

+

Compare existing and target zones to understand exactly what changes during migrations and ensure nothing is missed.

+
+ +
+

Zone File Cleanup

+

Normalize messy zone files with consistent formatting, proper ordering, duplicate removal, and error correction.

+
+ +
+

Compliance Auditing

+

Validate zone files against DNS standards to identify potential issues before they cause resolution failures.

+
+ +
+

Configuration Analysis

+

Understand zone structure, identify optimization opportunities, and track DNS infrastructure growth over time.

+
+
+
+ +
+

Zone File Best Practices

+
+
+ + Always include SOA and NS records for proper delegation +
+ +
+ + Use fully qualified domain names ending with dots +
+ +
+ + Maintain consistent TTL values based on change frequency +
+ +
+ + Keep domain names under 63 characters per label +
+ +
+ + Remove duplicate records to avoid confusion +
+ +
+ + Validate zones after changes before deployment +
+
+
+
+ + \ No newline at end of file diff --git a/src/routes/dns/zone/diff/+page.svelte b/src/routes/dns/zone/diff/+page.svelte new file mode 100644 index 0000000..efc2cb0 --- /dev/null +++ b/src/routes/dns/zone/diff/+page.svelte @@ -0,0 +1,10 @@ + + + + DNS Zone Diff - IP Calculator + + + + \ No newline at end of file diff --git a/src/routes/dns/zone/linter/+page.svelte b/src/routes/dns/zone/linter/+page.svelte new file mode 100644 index 0000000..c15926c --- /dev/null +++ b/src/routes/dns/zone/linter/+page.svelte @@ -0,0 +1,10 @@ + + + + DNS Zone Linter - IP Calculator + + + + \ No newline at end of file diff --git a/src/routes/dns/zone/name-length-checker/+page.svelte b/src/routes/dns/zone/name-length-checker/+page.svelte new file mode 100644 index 0000000..5ac51a2 --- /dev/null +++ b/src/routes/dns/zone/name-length-checker/+page.svelte @@ -0,0 +1,10 @@ + + + + DNS Name Length Checker - IP Calculator + + + + \ No newline at end of file diff --git a/src/routes/dns/zone/stats/+page.svelte b/src/routes/dns/zone/stats/+page.svelte new file mode 100644 index 0000000..bdfc25c --- /dev/null +++ b/src/routes/dns/zone/stats/+page.svelte @@ -0,0 +1,10 @@ + + + + DNS Zone Statistics - IP Calculator + + + + \ No newline at end of file