diff --git a/src/lib/components/tools/DHCPFingerprinting.svelte b/src/lib/components/tools/DHCPFingerprinting.svelte new file mode 100644 index 0000000..2de1580 --- /dev/null +++ b/src/lib/components/tools/DHCPFingerprinting.svelte @@ -0,0 +1,862 @@ + + + + {#if activeTab === 'lookup'} + ex.label} + getDescription={(ex) => ex.description} + /> + +
+

Device Fingerprint Lookup

+ +
+ + + Enter as comma-separated, hex, or space-separated numbers +
+ +
+ + + Helps improve match accuracy +
+ + {#if error} +
+ Error: +

{error}

+
+ {/if} +
+ + {#if parsedParams.length > 0} +
+

Requested DHCP Options

+ +
+ Parameter List: + {formatParameterListDisplay(parsedParams)} + +
+ +
+ Hex Encoded: + {formatParameterListToHex(parsedParams)} + +
+ +
+ {#each parsedParams as param, i (i)} +
+ {param} + {DHCP_OPTION_NAMES[param] || 'Unknown'} +
+ {/each} +
+ + {#if analysis && analysis.warnings.length > 0} +
+

Security Warnings

+ {#each analysis.warnings as warning, i (i)} +
⚠️ {warning}
+ {/each} +
+ {/if} + + {#if analysis && (analysis.unusual.length > 0 || (analysis.missing.length > 0 && matches.length > 0))} +
+

Option Analysis

+ + {#if analysis.unusual.length > 0} +
+

Unusual Options Detected

+

These options may indicate vendor-specific configurations:

+ {analysis.unusual.map((o) => `${o} (${DHCP_OPTION_NAMES[o] || 'Unknown'})`).join(', ')} +
+ {/if} + + {#if analysis.missing.length > 0 && matches.length > 0} +
+

Missing Options (vs. Best Match)

+

Options present in the best match but not in your fingerprint:

+ {analysis.missing.map((o) => `${o} (${DHCP_OPTION_NAMES[o] || 'Unknown'})`).join(', ')} +
+ {/if} +
+ {/if} +
+ {/if} + + {#if matches.length > 0} +
+
+

Matching Devices ({matches.length})

+
+ + +
+
+ +
+ {#each matches as match, i (i)} +
+
+
+ + {match.fingerprint.category} + +

{match.fingerprint.device}

+ + {confidenceBadges[match.fingerprint.confidence] || ''} + {match.fingerprint.confidence} confidence + +
+
+ {match.matchScore.toFixed(0)}% + Match +
+
+ +
+
+ OS: + {match.fingerprint.os} +
+
+ Matched On: + {match.matchedOn.join(', ')} +
+ {#if match.fingerprint.description} +
+ Description: + {match.fingerprint.description} +
+ {/if} +
+ Known Parameters: + {formatParameterListDisplay(match.fingerprint.parameterRequestList)} +
+
+
+ {/each} +
+
+ {:else if parsedParams.length > 0 && !error} +
+

No Matches Found

+

The provided fingerprint doesn't match any known devices in the database. This could be:

+
    +
  • A custom DHCP client configuration
  • +
  • An uncommon device or operating system
  • +
  • A device with a modified DHCP request list
  • +
+

Try adding the Vendor Class Identifier if available.

+
+ {/if} + {:else} +
+

Search by Device or OS

+ +
+ + + Search the database by device name, OS, or vendor +
+
+ + {#if reverseResults.length > 0} +
+

Found {reverseResults.length} Device{reverseResults.length > 1 ? 's' : ''}

+ + {#each reverseResults as device, i (i)} +
+
+ + {device.category} + +

{device.device}

+ + {confidenceBadges[device.confidence] || ''} + {device.confidence} confidence + +
+ +
+
+ OS: + {device.os} +
+ {#if device.description} +
+ Description: + {device.description} +
+ {/if} +
+ Parameter Request List: + {formatParameterListDisplay(device.parameterRequestList)} + +
+ {#if device.vendorClassPattern} +
+ Vendor Class Pattern: + {device.vendorClassPattern} +
+ {/if} +
+
+ {/each} +
+ {:else if reverseQuery.trim()} +
+

No Devices Found

+

No devices matched "{reverseQuery}". Try a different search term.

+
+ {/if} + {/if} +
+ + diff --git a/src/lib/components/tools/DHCPv6FQDN.svelte b/src/lib/components/tools/DHCPv6FQDN.svelte new file mode 100644 index 0000000..b2e1ba2 --- /dev/null +++ b/src/lib/components/tools/DHCPv6FQDN.svelte @@ -0,0 +1,707 @@ + + + + ex.label} + getDescription={(ex) => ex.description} + selectedIndex={selectedExampleIndex} + /> + +
+
+

FQDN Configuration

+

Fully Qualified Domain Name for the DHCPv6 client

+
+
+
+ + +
+
+
+ +
+
+

DNS Update Flags

+

Control how DNS updates are performed

+
+
+
+ + +
+ +
+ + +
+ +
+ + +
+
+
+ + {#if validationErrors.length > 0} +
+

Validation Errors

+ {#each validationErrors as error, i (i)} +
+ + {error} +
+ {/each} +
+ {/if} + + {#if result && validationErrors.length === 0} +
+

Option 39: Client FQDN

+ +
+
FQDN: {result.fqdn}
+
Total Length: {result.totalLength} bytes
+
+ +
+

Flags Breakdown

+
+
+ +
+ S Flag + {result.flags.S ? 'Set' : 'Not Set'} +
+
+
+ +
+ O Flag + {result.flags.O ? 'Set' : 'Not Set'} +
+
+
+ +
+ N Flag + {result.flags.N ? 'Set' : 'Not Set'} +
+
+
+ +
+ {#each result.flags.description as desc, i (i)} +
+ + {desc} +
+ {/each} +
+ +
+
+

Flags Byte

+ +
+
{result.flags.flagsByte}
+
+
+ +
+
+

Hex-Encoded (Compact)

+ +
+
{result.hexEncoded}
+
+ +
+
+

Wire Format (Spaced)

+ +
+
{result.wireFormat}
+
+ +
+

Encoding Breakdown

+
+
+ Flags: + {result.breakdown.flags} +
+
+ FQDN: + {result.breakdown.fqdn} +
+
+
+
+ + {#if result.examples.keaDhcp6} +
+

Configuration Example

+ +
+
+

Kea DHCPv6 Configuration

+ +
+
{result.examples.keaDhcp6}
+
+
+ {/if} + +
+

About RFC 4704

+

+ RFC 4704 defines the Client FQDN Option for DHCPv6, enabling clients and servers to negotiate dynamic DNS + updates for IPv6 addresses. +

+
    +
  • + S Flag (Bit 0): Server should perform DNS updates +
  • +
  • + O Flag (Bit 1): Server can override client preferences +
  • +
  • + N Flag (Bit 2): Client requests server to perform updates (client will NOT update) +
  • +
+

+ The FQDN is encoded using DNS wire format with length-prefixed labels, enabling automated hostname registration + in DNS for IPv6 networks. +

+
+ {/if} +
+ + diff --git a/src/lib/components/tools/DNSOptions6And15.svelte b/src/lib/components/tools/DNSOptions6And15.svelte new file mode 100644 index 0000000..d12b068 --- /dev/null +++ b/src/lib/components/tools/DNSOptions6And15.svelte @@ -0,0 +1,642 @@ + + + + ex.label} + getDescription={(ex) => ex.description} + /> + + {#if activeTab === 'build'} +
+

DNS Configuration

+ +
+ DNS Servers (Option 6) + {#each dnsServers as _server, i (i)} +
+ + {#if dnsServers.length > 1} + + {/if} +
+ {/each} + +
+ +
+ + + Domain name for client hostname resolution +
+ + {#if buildErrors.length > 0} +
+ Validation Errors: +
    + {#each buildErrors as error, i (i)} +
  • {error}
  • + {/each} +
+
+ {/if} +
+ + {#if buildResult} +
+

DHCP DNS Options

+ + {#if buildResult.option6} +
+

Option 6 - DNS Servers

+
+
+ DNS Servers: +
+ {#each buildResult.option6.servers as srv, i (i)} + {srv} + {/each} +
+
+ +
+ Hex Encoded: + {buildResult.option6.hexEncoded} + +
+ +
+ Wire Format: + {buildResult.option6.wireFormat} + +
+ +
+ Total Length: + {buildResult.option6.totalLength} bytes +
+
+
+ {/if} + + {#if buildResult.option15} +
+

Option 15 - Domain Name

+
+
+ Domain: + {buildResult.option15.domain} +
+ +
+ Hex Encoded: + {buildResult.option15.hexEncoded} + +
+ +
+ Wire Format: + {buildResult.option15.wireFormat} + +
+ +
+ Total Length: + {buildResult.option15.totalLength} bytes +
+
+
+ {/if} + +
+

Configuration Examples

+ +
+
ISC DHCPd
+
{buildResult.configExamples.iscDhcpd}
+ +
+ +
+
Kea DHCPv4
+
{buildResult.configExamples.keaDhcp4}
+ +
+ +
+
dnsmasq
+
{buildResult.configExamples.dnsmasq}
+ +
+
+
+ {/if} + {:else} +
+

Decode DNS Options

+ +
+ Option to Decode +
+ + +
+
+ +
+ + + Enter hex bytes (spaces optional) +
+ + {#if decodeError} +
+ Decode Error: +

{decodeError}

+
+ {/if} +
+ + {#if decodeResult} +
+

Decoded {decodeOption === 'option6' ? 'Option 6' : 'Option 15'}

+ + {#if decodeOption === 'option6'} +
+
+ DNS Servers: +
+ {#each decodeResult.servers as srv, i (i)} + {srv} + {/each} +
+
+ +
+ Server Count: + {decodeResult.servers.length} +
+ +
+ Total Length: + {decodeResult.totalLength} bytes +
+
+ {:else} +
+
+ Domain Name: + {decodeResult.domain} +
+ +
+ Total Length: + {decodeResult.totalLength} bytes +
+
+ {/if} +
+ {/if} + {/if} +
+ + diff --git a/src/lib/components/tools/GatewayOption3.svelte b/src/lib/components/tools/GatewayOption3.svelte new file mode 100644 index 0000000..eba35da --- /dev/null +++ b/src/lib/components/tools/GatewayOption3.svelte @@ -0,0 +1,543 @@ + + + + ex.label} + getDescription={(ex) => ex.description} + /> + + {#if activeTab === 'build'} +
+

Gateway Configuration

+ +
+ + + If provided, gateways will be validated against this subnet +
+ +
+ + {#each gateways as _gateway, i (i)} +
+ 0 ? `Gateway ${i + 1}` : undefined} + /> + {#if gateways.length > 1} + + {/if} +
+ {/each} + +
+ + {#if buildErrors.length > 0} +
+ Validation Errors: +
    + {#each buildErrors as error, i (i)} +
  • {error}
  • + {/each} +
+
+ {/if} +
+ + {#if buildResult} +
+

Option 3 - Router

+ +
+
+ Gateways: +
+ {#each buildResult.gateways as gw, i (i)} + + {i + 1}. {gw} + + {/each} +
+
+ +
+ Hex Encoded: + {buildResult.hexEncoded} + +
+ +
+ Wire Format: + {buildResult.wireFormat} + +
+ +
+ Total Length: + {buildResult.totalLength} bytes +
+
+ +
+

Configuration Examples

+ +
+
ISC DHCPd
+
{buildResult.configExamples.iscDhcpd}
+ +
+ +
+
Kea DHCPv4
+
{buildResult.configExamples.keaDhcp4}
+ +
+ +
+
dnsmasq
+
{buildResult.configExamples.dnsmasq}
+ +
+
+
+ {/if} + {:else} +
+

Decode Option 3

+ +
+ + + Enter hex bytes (spaces optional) +
+ + {#if decodeError} +
+ Decode Error: +

{decodeError}

+
+ {/if} +
+ + {#if decodeResult} +
+

Decoded Option 3

+ +
+
+ Gateways: +
+ {#each decodeResult.gateways as gw, i (i)} + + {i + 1}. {gw} + + {/each} +
+
+ +
+ Total Length: + {decodeResult.totalLength} bytes +
+ +
+ Gateway Count: + {decodeResult.gateways.length} +
+
+ +
+

Configuration Examples

+ +
+
ISC DHCPd
+
{decodeResult.configExamples.iscDhcpd}
+ +
+ +
+
Kea DHCPv4
+
{decodeResult.configExamples.keaDhcp4}
+ +
+ +
+
dnsmasq
+
{decodeResult.configExamples.dnsmasq}
+ +
+
+
+ {/if} + {/if} +
+ + diff --git a/src/lib/components/tools/LeaseTimeCalculator.svelte b/src/lib/components/tools/LeaseTimeCalculator.svelte new file mode 100644 index 0000000..b6cdef8 --- /dev/null +++ b/src/lib/components/tools/LeaseTimeCalculator.svelte @@ -0,0 +1,559 @@ + + + + ex.label} + getDescription={(ex) => ex.description} + selectedIndex={selectedExampleIndex} + /> + +
+
+

Network Configuration

+

Enter your network characteristics to calculate optimal lease times

+
+
+
+
+ + + Total available IP addresses in your DHCP pool +
+ +
+ + + Average number of concurrent clients +
+
+ +
+ + + {#if networkType !== 'custom'} + {NETWORK_TYPE_DEFAULTS[networkType].description} + {/if} +
+ +
+ + + How long devices typically stay connected +
+ + {#if churnRate === 'custom'} +
+ + + Average hours a device stays connected +
+ {/if} +
+
+ + {#if validationErrors.length > 0} +
+

Validation Errors

+ {#each validationErrors as error, i (i)} +
+ + {error} +
+ {/each} +
+ {/if} + + {#if result && validationErrors.length === 0} +
+

Calculated Lease Times

+ +
+
Pool Utilization: {result.utilizationPercent}%
+
Recommended Lease: {result.recommendedLeaseFormatted}
+
+ + {#if result.exhaustionTime} +
+ + Address Exhaustion: {result.exhaustionTime} +
+ {/if} + +
+ {#each [{ label: 'Default Lease Time', value: result.recommendedLeaseFormatted, seconds: result.recommendedLeaseSeconds, key: 'lease' }, { label: 'T1 (Renewal)', value: result.t1RenewalFormatted, seconds: result.t1RenewalSeconds, key: 't1' }, { label: 'T2 (Rebinding)', value: result.t2RebindingFormatted, seconds: result.t2RebindingSeconds, key: 't2' }] as time (time.key)} +
+
+ {time.label} + +
+
{time.value}
+
{time.seconds} seconds
+
+ {/each} +
+ + {#if result.recommendations.length > 0} +
+

Recommendations

+ {#each result.recommendations as recommendation, i (i)} +
+ {recommendation} +
+ {/each} +
+ {/if} +
+ + {#each [{ title: 'ISC DHCPd Configuration', content: result.configExamples.iscDhcpd, key: 'isc' }, { title: 'Kea DHCPv4 Configuration', content: result.configExamples.keaDhcp4, key: 'kea' }] as config (config.key)} +
+
+

{config.title}

+ +
+
{config.content}
+
+ {/each} + {/if} +
+ + diff --git a/src/lib/components/tools/LeaseTimeOption51.svelte b/src/lib/components/tools/LeaseTimeOption51.svelte new file mode 100644 index 0000000..ab65b54 --- /dev/null +++ b/src/lib/components/tools/LeaseTimeOption51.svelte @@ -0,0 +1,556 @@ + + + + ex.label} getDescription={(ex) => ex.description} /> + + {#if activeTab === 'build'} +
+

Lease Time Configuration

+ +
+ + Permanent IP address assignment (may not be supported by all servers) +
+ + {#if !infinite} +
+ + + {#if leaseSeconds > 0} + = {formatTime(leaseSeconds)} + {/if} +
+ +
+ Quick Values: + + + + + +
+ {/if} + + {#if buildErrors.length > 0} +
e.startsWith('Warning:'))}> + {buildErrors.some((e) => e.startsWith('Warning:')) ? 'Warnings:' : 'Validation Errors:'} +
    + {#each buildErrors as error, i (i)} +
  • {error}
  • + {/each} +
+
+ {/if} +
+ + {#if buildResult} +
+

Option 51 - Lease Time

+ +
+
+ Lease Time: + {buildResult.humanReadable} +
+ +
+ Hex Encoded: + {buildResult.hexEncoded} + +
+ +
+ Wire Format: + {buildResult.wireFormat} + +
+ +
+ Total Length: + {buildResult.totalLength} bytes +
+ + {#if !buildResult.isInfinite} +
+ T1 Renewal: + {buildResult.t1RenewalFormatted} (50% of lease) +
+ +
+ T2 Rebinding: + {buildResult.t2RebindingFormatted} (87.5% of lease) +
+ {/if} +
+ +
+

Configuration Examples

+ +
+
ISC DHCPd
+
{buildResult.configExamples.iscDhcpd}
+ +
+ +
+
Kea DHCPv4
+
{buildResult.configExamples.keaDhcp4}
+ +
+ +
+
dnsmasq
+
{buildResult.configExamples.dnsmasq}
+ +
+
+
+ {/if} + {:else} +
+

Decode Option 51

+ +
+ + + Enter 8 hex characters (4 bytes, spaces optional) +
+ + {#if decodeError} +
+ Decode Error: +

{decodeError}

+
+ {/if} +
+ + {#if decodeResult} +
+

Decoded Option 51

+ +
+
+ Lease Time: + {decodeResult.humanReadable} +
+ +
+ Seconds: + {decodeResult.leaseSeconds.toLocaleString()} +
+ + {#if decodeResult.isInfinite} +
+ Infinite Lease +
+ {/if} + + {#if !decodeResult.isInfinite} +
+ T1 Renewal: + {decodeResult.t1RenewalFormatted} (50% of lease) +
+ +
+ T2 Rebinding: + {decodeResult.t2RebindingFormatted} (87.5% of lease) +
+ {/if} +
+ +
+

Configuration Examples

+ +
+
ISC DHCPd
+
{decodeResult.configExamples.iscDhcpd}
+ +
+ +
+
Kea DHCPv4
+
{decodeResult.configExamples.keaDhcp4}
+ +
+ +
+
dnsmasq
+
{decodeResult.configExamples.dnsmasq}
+ +
+
+
+ {/if} + {/if} +
+ + diff --git a/src/lib/components/tools/PrefixDelegation.svelte b/src/lib/components/tools/PrefixDelegation.svelte new file mode 100644 index 0000000..751c438 --- /dev/null +++ b/src/lib/components/tools/PrefixDelegation.svelte @@ -0,0 +1,554 @@ + + + + loadExample(ex)} + getLabel={(ex) => ex.label} + getDescription={(ex) => ex.description} + /> + +
+

Prefix Delegation Configuration

+ +
+
+ + + Unique identifier for this IA_PD (0-4294967295) +
+ +
+ + + {#if t1} + = {formatTime(t1)} + {/if} +
+ +
+ + + {#if t2} + = {formatTime(t2)} + {/if} +
+
+ +
+ + {#each prefixes as prefix, i (i)} +
+
+ 0 ? `Prefix ${i + 1}` : undefined} + /> + + +
+ {#if prefixes.length > 1} + + {/if} +
+ {/each} + +
+ + {#if errors.length > 0} +
+ Validation Errors: +
    + {#each errors as error, i (i)} +
  • {error}
  • + {/each} +
+
+ {/if} +
+ + {#if result} +
+

Option 25 - IA_PD

+ +
+
+ IAID: + {result.iaid} (0x{result.iaidHex}) +
+ +
+ T1 Renewal: + {result.t1Formatted} ({result.t1}s) +
+ +
+ T2 Rebinding: + {result.t2Formatted} ({result.t2}s) +
+ +
+ Full Hex: + {result.fullHex} + +
+ +
+ Wire Format: + {result.fullWireFormat} + +
+ +
+ Total Length: + {result.totalLength} bytes +
+
+ +
+

Delegated Prefixes (Option 26)

+ {#each result.prefixes as prefix, i (i)} +
+
+ {i + 1} + {prefix.prefix} +
+
+
+ Preferred Lifetime: + {prefix.preferredLifetimeFormatted} ({prefix.preferredLifetime}s) +
+
+ Valid Lifetime: + {prefix.validLifetimeFormatted} ({prefix.validLifetime}s) +
+
+ Wire Format: + {prefix.wireFormat} + +
+
+
+ {/each} +
+ +
+

Configuration Example

+ +
+
Kea DHCPv6
+
{result.examples.keaDhcp6}
+ +
+
+
+ {/if} +
+ + diff --git a/src/lib/constants/nav.ts b/src/lib/constants/nav.ts index 9fe80aa..59cc538 100644 --- a/src/lib/constants/nav.ts +++ b/src/lib/constants/nav.ts @@ -805,6 +805,87 @@ export const SUB_NAV: Record = { title: 'DHCPv4 Options', description: 'DHCPv4 option generators and builders', items: [ + { + href: makePath('/dhcp/v4/options/option3-default-gateway'), + label: 'Option 3 - Router/Default Gateway', + description: + 'Build and decode DHCP default gateway configuration with support for multiple gateways and subnet validation', + icon: 'router', + keywords: [ + 'dhcp', + 'dhcpv4', + 'option', + 'option 3', + 'router', + 'default', + 'gateway', + 'routing', + 'gateways', + 'redundancy', + 'failover', + 'load balancing', + 'multiple', + 'subnet', + 'validation', + 'network', + 'isc', + 'kea', + 'dnsmasq', + ], + }, + { + href: makePath('/dhcp/v4/options/options6-15-dns'), + label: 'Options 6 & 15 - DNS & Domain', + description: 'Build and decode DNS server and domain name options for complete DNS configuration', + icon: 'dns', + keywords: [ + 'dhcp', + 'dhcpv4', + 'option', + 'option 6', + 'option 15', + 'dns', + 'domain', + 'name', + 'servers', + 'nameservers', + 'resolution', + 'hostname', + 'google', + 'cloudflare', + 'quad9', + 'public dns', + 'isc', + 'kea', + 'dnsmasq', + ], + }, + { + href: makePath('/dhcp/v4/options/option51-lease-time'), + label: 'Option 51 - IP Address Lease Time', + description: 'Build and decode lease time option with automatic T1/T2 renewal timer calculations', + icon: 'clock', + keywords: [ + 'dhcp', + 'dhcpv4', + 'option', + '51', + 'lease', + 'time', + 'duration', + 't1', + 't2', + 'renewal', + 'rebinding', + 'infinite', + 'permanent', + 'timer', + 'seconds', + 'isc', + 'kea', + 'dnsmasq', + ], + }, { href: makePath('/dhcp/v4/options/option43-vendor-specific'), label: 'Option 43 - Vendor Specific', @@ -1143,6 +1224,77 @@ export const SUB_NAV: Record = { 'suffix', ], }, + { + href: makePath('/dhcp/v6/options/option25-prefix-delegation'), + label: 'Options 25/26 - Prefix Delegation', + description: + 'Build DHCPv6 IA_PD options for delegating IPv6 prefixes to requesting routers with IA Prefix options per RFC 8415', + icon: 'share', + keywords: [ + 'dhcpv6', + 'dhcp', + 'v6', + 'ipv6', + 'option', + '25', + '26', + 'ia_pd', + 'prefix', + 'delegation', + 'pd', + 'router', + 'isp', + 'subnet', + 'allocation', + 'rfc', + '8415', + 'wire', + 'format', + 'kea', + 'isc', + 'configuration', + 'iaid', + 't1', + 't2', + 'lifetime', + ], + }, + { + href: makePath('/dhcp/v6/options/option39-fqdn'), + label: 'Option 39 - Client FQDN', + description: + 'Configure Client FQDN Option for DHCPv6 dynamic DNS updates with S, O, and N flags per RFC 4704', + icon: 'globe', + keywords: [ + 'dhcpv6', + 'dhcp', + 'v6', + 'ipv6', + 'option', + '39', + 'fqdn', + 'client', + 'fully', + 'qualified', + 'domain', + 'name', + 'hostname', + 'dns', + 'ddns', + 'dynamic', + 'updates', + 'rfc', + '4704', + 'flags', + 'server', + 'override', + 'wire', + 'format', + 'kea', + 'isc', + 'configuration', + ], + }, ], }, { @@ -1214,6 +1366,64 @@ export const SUB_NAV: Record = { }, ], }, + { + title: 'Calculators & Planning', + description: 'Network planning and optimization tools', + items: [ + { + href: makePath('/dhcp/calculators/lease-time'), + label: 'Lease Time Calculator', + description: + 'Calculate optimal DHCP lease times based on pool size, client count, and turnover rate with T1/T2 renewal timers', + icon: 'clock', + keywords: [ + 'dhcp', + 'lease', + 'time', + 'calculator', + 'renewal', + 't1', + 't2', + 'rebinding', + 'optimization', + 'planning', + 'pool', + 'utilization', + 'exhaustion', + 'churn', + 'turnover', + ], + }, + { + href: makePath('/dhcp/tools/fingerprinting'), + label: 'DHCP Fingerprinting Database', + description: + 'Identify devices by their DHCP fingerprints using Parameter Request List (Option 55) and Vendor Class patterns', + icon: 'fingerprint', + keywords: [ + 'dhcp', + 'fingerprint', + 'fingerprinting', + 'device', + 'identification', + 'option', + '55', + 'parameter', + 'request', + 'list', + 'vendor', + 'class', + 'windows', + 'macos', + 'ios', + 'android', + 'linux', + 'detection', + 'analysis', + ], + }, + ], + }, { title: 'Configuration Generators', description: 'Server configuration generators and snippets', diff --git a/src/lib/utils/dhcp-fingerprinting.ts b/src/lib/utils/dhcp-fingerprinting.ts new file mode 100644 index 0000000..75ac1b4 --- /dev/null +++ b/src/lib/utils/dhcp-fingerprinting.ts @@ -0,0 +1,858 @@ +/** + * DHCP Fingerprinting Database + * + * Identifies devices based on DHCP fingerprints, primarily using: + * - Option 55 (Parameter Request List) + * - Option 60 (Vendor Class Identifier) + * - Option 61 (Client Identifier format) + * + * References: + * - fingerbank.org + * - dhcpcd project + * - ISC DHCP fingerprints + */ + +export interface DHCPFingerprint { + id: string; + device: string; + os: string; + category: 'desktop' | 'mobile' | 'iot' | 'server' | 'network' | 'gaming' | 'other'; + parameterRequestList: number[]; // Option 55 + vendorClassPattern?: string; // Option 60 pattern + description?: string; + confidence: 'high' | 'medium' | 'low'; +} + +export interface FingerprintMatch { + fingerprint: DHCPFingerprint; + matchScore: number; + matchedOn: string[]; +} + +export interface OptionAnalysis { + unusual: number[]; + security: number[]; + missing: number[]; + warnings: string[]; +} + +// Security-relevant DHCP options +const SECURITY_OPTIONS = [252, 249, 82, 43, 125]; + +// Rare/unusual options that might indicate specific vendors +const UNUSUAL_OPTIONS = [ + 77, 93, 94, 97, 120, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, + 150, 208, 209, 210, 211, 212, 213, 220, +]; + +/** + * Database of known DHCP fingerprints + */ +export const FINGERPRINT_DATABASE: DHCPFingerprint[] = [ + // Windows + { + id: 'win10', + device: 'Windows 10/11', + os: 'Windows', + category: 'desktop', + parameterRequestList: [1, 3, 6, 15, 31, 33, 43, 44, 46, 47, 119, 121, 249, 252], + confidence: 'high', + description: 'Windows 10/11 desktop or laptop', + }, + { + id: 'win7', + device: 'Windows 7', + os: 'Windows', + category: 'desktop', + parameterRequestList: [1, 3, 6, 15, 31, 33, 43, 44, 46, 47, 121, 249, 252], + confidence: 'high', + description: 'Windows 7 desktop or laptop', + }, + { + id: 'winserver', + device: 'Windows Server', + os: 'Windows Server', + category: 'server', + parameterRequestList: [1, 3, 6, 15, 31, 33, 43, 44, 46, 47, 119, 121, 249, 252], + vendorClassPattern: 'MSFT', + confidence: 'medium', + description: 'Windows Server 2016/2019/2022', + }, + + // macOS / iOS + { + id: 'macos', + device: 'macOS', + os: 'macOS', + category: 'desktop', + parameterRequestList: [1, 3, 6, 15, 119, 252], + confidence: 'high', + description: 'Apple macOS device', + }, + { + id: 'ios', + device: 'iPhone/iPad', + os: 'iOS', + category: 'mobile', + parameterRequestList: [1, 3, 6, 15, 119, 252], + confidence: 'medium', + description: 'Apple iOS device (iPhone/iPad)', + }, + + // Android + { + id: 'android', + device: 'Android Device', + os: 'Android', + category: 'mobile', + parameterRequestList: [1, 3, 6, 15, 26, 28, 51, 58, 59, 43], + vendorClassPattern: 'dhcpcd', + confidence: 'high', + description: 'Android smartphone or tablet', + }, + { + id: 'android-alt', + device: 'Android Device', + os: 'Android', + category: 'mobile', + parameterRequestList: [1, 3, 6, 15, 26, 28], + confidence: 'medium', + description: 'Android device (alternative fingerprint)', + }, + + // Linux + { + id: 'linux-dhclient', + device: 'Linux (dhclient)', + os: 'Linux', + category: 'desktop', + parameterRequestList: [1, 3, 6, 15, 26, 28, 42], + confidence: 'high', + description: 'Linux system using ISC dhclient', + }, + { + id: 'linux-dhcpcd', + device: 'Linux (dhcpcd)', + os: 'Linux', + category: 'desktop', + parameterRequestList: [1, 3, 6, 15, 26, 28, 51, 58, 59], + vendorClassPattern: 'dhcpcd', + confidence: 'high', + description: 'Linux system using dhcpcd', + }, + { + id: 'ubuntu', + device: 'Ubuntu Linux', + os: 'Linux', + category: 'desktop', + parameterRequestList: [1, 28, 2, 3, 15, 6, 119, 12, 44, 47, 26, 121, 42], + confidence: 'medium', + description: 'Ubuntu desktop or server', + }, + + // IoT Devices + { + id: 'raspberry-pi', + device: 'Raspberry Pi', + os: 'Linux', + category: 'iot', + parameterRequestList: [1, 3, 6, 15, 26, 28, 51, 58, 59, 43], + vendorClassPattern: 'dhcpcd', + confidence: 'medium', + description: 'Raspberry Pi (Raspbian/Raspberry Pi OS)', + }, + { + id: 'esp32', + device: 'ESP32', + os: 'ESP-IDF/Arduino', + category: 'iot', + parameterRequestList: [1, 3, 6, 15], + confidence: 'low', + description: 'ESP32 microcontroller', + }, + { + id: 'arduino', + device: 'Arduino', + os: 'Arduino', + category: 'iot', + parameterRequestList: [1, 3, 6, 15, 28, 51, 58, 59], + confidence: 'low', + description: 'Arduino with Ethernet shield', + }, + + // Network Equipment + { + id: 'cisco-phone', + device: 'Cisco IP Phone', + os: 'Cisco', + category: 'network', + parameterRequestList: [1, 3, 6, 12, 15, 28, 42, 66, 67, 120, 150], + vendorClassPattern: 'Cisco', + confidence: 'high', + description: 'Cisco IP Phone', + }, + { + id: 'hp-printer', + device: 'HP Printer', + os: 'Printer OS', + category: 'network', + parameterRequestList: [1, 3, 6, 12, 15, 28, 40, 41, 42], + vendorClassPattern: 'HP', + confidence: 'high', + description: 'HP Network Printer', + }, + + // Gaming Consoles + { + id: 'ps5', + device: 'PlayStation 5', + os: 'PlayStation OS', + category: 'gaming', + parameterRequestList: [1, 3, 6, 15, 12], + confidence: 'medium', + description: 'Sony PlayStation 5', + }, + { + id: 'ps4', + device: 'PlayStation 4', + os: 'PlayStation OS', + category: 'gaming', + parameterRequestList: [1, 3, 6, 15, 12, 28], + confidence: 'medium', + description: 'Sony PlayStation 4', + }, + { + id: 'xbox', + device: 'Xbox Series X/S', + os: 'Xbox OS', + category: 'gaming', + parameterRequestList: [1, 3, 6, 15, 44, 46, 47], + vendorClassPattern: 'MSFT', + confidence: 'medium', + description: 'Microsoft Xbox Series X/S', + }, + { + id: 'nintendo-switch', + device: 'Nintendo Switch', + os: 'Nintendo OS', + category: 'gaming', + parameterRequestList: [1, 3, 6, 15, 26, 28, 51, 58, 59], + confidence: 'low', + description: 'Nintendo Switch', + }, + + // Chrome OS + { + id: 'chromeos', + device: 'Chrome OS / Chromebook', + os: 'Chrome OS', + category: 'desktop', + parameterRequestList: [1, 3, 6, 15, 26, 28, 42], + confidence: 'medium', + description: 'Google Chrome OS device', + }, + + // Smart TVs + { + id: 'samsung-tv', + device: 'Samsung Smart TV', + os: 'Tizen', + category: 'iot', + parameterRequestList: [1, 3, 6, 12, 15, 28, 40, 41, 42, 119], + vendorClassPattern: 'SAMSUNG', + confidence: 'high', + description: 'Samsung Smart TV', + }, + { + id: 'lg-tv', + device: 'LG Smart TV', + os: 'webOS', + category: 'iot', + parameterRequestList: [1, 3, 6, 12, 15, 28, 42], + vendorClassPattern: 'LGE', + confidence: 'high', + description: 'LG Smart TV', + }, + { + id: 'roku', + device: 'Roku Device', + os: 'Roku OS', + category: 'iot', + parameterRequestList: [1, 3, 6, 15, 28, 42], + vendorClassPattern: 'Roku', + confidence: 'high', + description: 'Roku streaming device', + }, + { + id: 'firetv', + device: 'Amazon Fire TV', + os: 'Fire OS', + category: 'iot', + parameterRequestList: [1, 3, 6, 15, 26, 28, 51, 58, 59], + confidence: 'medium', + description: 'Amazon Fire TV Stick/Cube', + }, + { + id: 'appletv', + device: 'Apple TV', + os: 'tvOS', + category: 'iot', + parameterRequestList: [1, 3, 6, 15, 119, 252], + confidence: 'medium', + description: 'Apple TV streaming device', + }, + + // More Printers + { + id: 'canon-printer', + device: 'Canon Printer', + os: 'Printer OS', + category: 'network', + parameterRequestList: [1, 3, 6, 12, 15, 28, 42], + vendorClassPattern: 'Canon', + confidence: 'high', + description: 'Canon Network Printer', + }, + { + id: 'epson-printer', + device: 'Epson Printer', + os: 'Printer OS', + category: 'network', + parameterRequestList: [1, 3, 6, 12, 15, 28, 42, 54], + vendorClassPattern: 'EPSON', + confidence: 'high', + description: 'Epson Network Printer', + }, + { + id: 'brother-printer', + device: 'Brother Printer', + os: 'Printer OS', + category: 'network', + parameterRequestList: [1, 3, 6, 12, 15, 28, 42], + vendorClassPattern: 'Brother', + confidence: 'high', + description: 'Brother Network Printer', + }, + + // More Network Equipment + { + id: 'ubiquiti-ap', + device: 'Ubiquiti Access Point', + os: 'UniFi', + category: 'network', + parameterRequestList: [1, 3, 6, 12, 15, 28, 42, 43, 66, 67], + vendorClassPattern: 'ubnt', + confidence: 'high', + description: 'Ubiquiti UniFi Access Point', + }, + { + id: 'aruba-ap', + device: 'Aruba Access Point', + os: 'ArubaOS', + category: 'network', + parameterRequestList: [1, 3, 6, 12, 15, 28, 42, 43, 60], + vendorClassPattern: 'ArubaAP', + confidence: 'high', + description: 'Aruba Wireless Access Point', + }, + { + id: 'mikrotik', + device: 'MikroTik Router', + os: 'RouterOS', + category: 'network', + parameterRequestList: [1, 3, 6, 12, 15, 28, 42], + vendorClassPattern: 'MikroTik', + confidence: 'high', + description: 'MikroTik Router/Switch', + }, + + // More VoIP Phones + { + id: 'yealink-phone', + device: 'Yealink IP Phone', + os: 'VoIP', + category: 'network', + parameterRequestList: [1, 3, 6, 12, 15, 28, 42, 43, 66, 120], + vendorClassPattern: 'yealink', + confidence: 'high', + description: 'Yealink VoIP Phone', + }, + { + id: 'polycom-phone', + device: 'Polycom IP Phone', + os: 'VoIP', + category: 'network', + parameterRequestList: [1, 3, 6, 12, 15, 28, 42, 43, 66, 67, 120, 160], + vendorClassPattern: 'PolycomSoundPointIP', + confidence: 'high', + description: 'Polycom VoIP Phone', + }, + { + id: 'grandstream-phone', + device: 'Grandstream IP Phone', + os: 'VoIP', + category: 'network', + parameterRequestList: [1, 3, 6, 12, 15, 28, 42, 66, 120], + vendorClassPattern: 'Grandstream', + confidence: 'high', + description: 'Grandstream VoIP Phone', + }, + + // More IoT Devices + { + id: 'nest-thermostat', + device: 'Google Nest Thermostat', + os: 'Nest OS', + category: 'iot', + parameterRequestList: [1, 3, 6, 15, 28, 42], + vendorClassPattern: 'Nest', + confidence: 'medium', + description: 'Google Nest Smart Thermostat', + }, + { + id: 'ring-doorbell', + device: 'Ring Doorbell', + os: 'Ring OS', + category: 'iot', + parameterRequestList: [1, 3, 6, 15, 28, 42], + confidence: 'low', + description: 'Ring Video Doorbell', + }, + { + id: 'philips-hue', + device: 'Philips Hue Bridge', + os: 'IoT', + category: 'iot', + parameterRequestList: [1, 3, 6, 12, 15, 28], + vendorClassPattern: 'Philips', + confidence: 'medium', + description: 'Philips Hue Smart Light Bridge', + }, + { + id: 'alexa-echo', + device: 'Amazon Echo', + os: 'Fire OS', + category: 'iot', + parameterRequestList: [1, 3, 6, 15, 26, 28, 51, 58, 59], + confidence: 'low', + description: 'Amazon Alexa Echo Device', + }, + { + id: 'google-home', + device: 'Google Home', + os: 'Cast OS', + category: 'iot', + parameterRequestList: [1, 3, 6, 15, 28, 42], + confidence: 'low', + description: 'Google Home/Nest Speaker', + }, + { + id: 'sonos', + device: 'Sonos Speaker', + os: 'Sonos OS', + category: 'iot', + parameterRequestList: [1, 3, 6, 12, 15, 28, 42], + vendorClassPattern: 'Sonos', + confidence: 'medium', + description: 'Sonos Wireless Speaker', + }, + { + id: 'hikvision-camera', + device: 'Hikvision IP Camera', + os: 'Camera OS', + category: 'iot', + parameterRequestList: [1, 3, 6, 12, 15, 28, 42], + vendorClassPattern: 'HIKVISION', + confidence: 'high', + description: 'Hikvision Security Camera', + }, + { + id: 'axis-camera', + device: 'Axis IP Camera', + os: 'AXIS OS', + category: 'iot', + parameterRequestList: [1, 3, 6, 12, 15, 28, 42, 43], + vendorClassPattern: 'AXIS', + confidence: 'high', + description: 'Axis Communications Camera', + }, + { + id: 'tesla', + device: 'Tesla Vehicle', + os: 'Tesla OS', + category: 'iot', + parameterRequestList: [1, 3, 6, 15, 28, 42], + confidence: 'low', + description: 'Tesla Electric Vehicle', + }, +]; + +/** + * Parse parameter request list from various formats + */ +export function parseParameterList(input: string): number[] { + // Handle comma-separated (e.g., "1,3,6,15") + if (input.includes(',')) { + return input.split(',').map((s) => parseInt(s.trim(), 10)); + } + + // Handle space-separated + if (input.includes(' ')) { + const tokens = input.split(/\s+/); + + // Check if all tokens are exactly 2 hex chars (hex with spaces like "01 03 06 0f") + const allHexTokens = tokens.every((t) => /^[0-9a-fA-F]{2}$/.test(t)); + + if (allHexTokens) { + // Parse as hex + return tokens.map((t) => parseInt(t, 16)); + } + + // Otherwise parse as decimal space-separated (e.g., "1 3 6 15") + return tokens.map((s) => parseInt(s.trim(), 10)); + } + + // Handle hex format without spaces (e.g., "0103060f") + if (/^[0-9a-fA-F]+$/.test(input) && input.length % 2 === 0) { + const params: number[] = []; + for (let i = 0; i < input.length; i += 2) { + params.push(parseInt(input.substring(i, i + 2), 16)); + } + return params; + } + + // Single number + return [parseInt(input, 10)]; +} + +/** + * Calculate match score between two parameter lists with order weighting + */ +function calculateMatchScore(requested: number[], fingerprint: number[]): number { + if (fingerprint.length === 0) return 0; + + let score = 0; + const matches = requested.filter((param) => fingerprint.includes(param)).length; + const baseScore = (matches / fingerprint.length) * 100; + + // Bonus for matching order of first 5 critical options + let orderBonus = 0; + const criticalCount = Math.min(5, Math.min(requested.length, fingerprint.length)); + for (let i = 0; i < criticalCount; i++) { + if (requested[i] === fingerprint[i]) orderBonus += 2; + } + + score = Math.min(100, baseScore + orderBonus); + return score; +} + +/** + * Check if arrays match exactly + */ +function exactMatch(a: number[], b: number[]): boolean { + if (a.length !== b.length) return false; + return a.every((val, idx) => val === b[idx]); +} + +/** + * Analyze DHCP options for unusual patterns and security concerns + */ +export function analyzeOptions(parameterList: number[], matches: FingerprintMatch[]): OptionAnalysis { + const unusual = parameterList.filter((opt) => UNUSUAL_OPTIONS.includes(opt)); + const security = parameterList.filter((opt) => SECURITY_OPTIONS.includes(opt)); + const warnings: string[] = []; + + // Security warnings + if (security.includes(252)) { + warnings.push('Option 252 (WPAD) detected - potential security risk if misconfigured'); + } + if (security.includes(82)) { + warnings.push('Option 82 (Relay Agent) - typically inserted by network equipment'); + } + + // Find missing options from best match + let missing: number[] = []; + if (matches.length > 0) { + const bestMatch = matches[0].fingerprint; + missing = bestMatch.parameterRequestList.filter((opt) => !parameterList.includes(opt)); + } + + return { unusual, security, missing, warnings }; +} + +/** + * Search for matching fingerprints with improved algorithm + */ +export function searchFingerprints(parameterList: number[], vendorClass?: string): FingerprintMatch[] { + const matches: FingerprintMatch[] = []; + + for (const fingerprint of FINGERPRINT_DATABASE) { + const matchedOn: string[] = []; + let matchScore = 0; + let vendorBonus = 0; + + // Check parameter list + const paramScore = calculateMatchScore(parameterList, fingerprint.parameterRequestList); + + if (paramScore > 0) { + matchScore = paramScore; + if (exactMatch(parameterList, fingerprint.parameterRequestList)) { + matchedOn.push('Parameter List (Exact)'); + matchScore = 100; + } else { + matchedOn.push(`Parameter List (${paramScore.toFixed(0)}%)`); + } + } + + // Check vendor class if provided + if (vendorClass && fingerprint.vendorClassPattern) { + const vendorLower = vendorClass.toLowerCase(); + const patternLower = fingerprint.vendorClassPattern.toLowerCase(); + + if (vendorLower.includes(patternLower) || patternLower.includes(vendorLower)) { + matchedOn.push('Vendor Class'); + vendorBonus = 30; // Vendor match gives significant boost + matchScore = Math.max(matchScore, 60); // Minimum score with vendor match + } + } + + // Apply vendor bonus + matchScore = Math.min(100, matchScore + vendorBonus); + + // Only include matches with score > 45% or vendor class match + if (matchScore >= 45 || matchedOn.some((m) => m.includes('Vendor'))) { + matches.push({ + fingerprint, + matchScore, + matchedOn, + }); + } + } + + // Sort by match score (descending), then by confidence + return matches.sort((a, b) => { + if (b.matchScore !== a.matchScore) return b.matchScore - a.matchScore; + const confWeight = { high: 3, medium: 2, low: 1 }; + return confWeight[b.fingerprint.confidence] - confWeight[a.fingerprint.confidence]; + }); +} + +/** + * Reverse lookup: find fingerprints by device/OS name + */ +export function searchByDevice(query: string): DHCPFingerprint[] { + const lowerQuery = query.toLowerCase(); + return FINGERPRINT_DATABASE.filter( + (fp) => + fp.device.toLowerCase().includes(lowerQuery) || + fp.os.toLowerCase().includes(lowerQuery) || + fp.description?.toLowerCase().includes(lowerQuery), + ); +} + +/** + * Get DHCP option names (comprehensive list) + */ +export const DHCP_OPTION_NAMES: Record = { + 1: 'Subnet Mask', + 2: 'Time Offset', + 3: 'Router', + 4: 'Time Server', + 5: 'Name Server', + 6: 'Domain Name Server', + 7: 'Log Server', + 8: 'Cookie Server', + 9: 'LPR Server', + 10: 'Impress Server', + 11: 'Resource Location Server', + 12: 'Host Name', + 13: 'Boot File Size', + 14: 'Merit Dump File', + 15: 'Domain Name', + 16: 'Swap Server', + 17: 'Root Path', + 18: 'Extensions Path', + 19: 'IP Forwarding', + 20: 'Non-Local Source Routing', + 21: 'Policy Filter', + 22: 'Maximum Datagram Reassembly Size', + 23: 'Default IP TTL', + 24: 'Path MTU Aging Timeout', + 25: 'Path MTU Plateau Table', + 26: 'Interface MTU', + 27: 'All Subnets Local', + 28: 'Broadcast Address', + 29: 'Perform Mask Discovery', + 30: 'Mask Supplier', + 31: 'Router Discovery', + 32: 'Router Solicitation Address', + 33: 'Static Route', + 34: 'Trailer Encapsulation', + 35: 'ARP Cache Timeout', + 36: 'Ethernet Encapsulation', + 37: 'TCP Default TTL', + 38: 'TCP Keepalive Interval', + 39: 'TCP Keepalive Garbage', + 40: 'NIS Domain', + 41: 'NIS Servers', + 42: 'NTP Servers', + 43: 'Vendor Specific', + 44: 'NetBIOS Name Server', + 45: 'NetBIOS Datagram Distribution Server', + 46: 'NetBIOS Node Type', + 47: 'NetBIOS Scope', + 48: 'X Window Font Server', + 49: 'X Window Display Manager', + 50: 'Requested IP Address', + 51: 'IP Address Lease Time', + 52: 'Option Overload', + 53: 'DHCP Message Type', + 54: 'Server Identifier', + 55: 'Parameter Request List', + 56: 'Message', + 57: 'Maximum DHCP Message Size', + 58: 'Renewal Time (T1)', + 59: 'Rebinding Time (T2)', + 60: 'Vendor Class Identifier', + 61: 'Client Identifier', + 64: 'NIS+ Domain Name', + 65: 'NIS+ Servers', + 66: 'TFTP Server Name', + 67: 'Bootfile Name', + 68: 'Mobile IP Home Agent', + 69: 'SMTP Server', + 70: 'POP3 Server', + 71: 'NNTP Server', + 72: 'WWW Server', + 73: 'Finger Server', + 74: 'IRC Server', + 75: 'StreetTalk Server', + 76: 'STDA Server', + 77: 'User Class', + 78: 'Directory Agent', + 79: 'Service Scope', + 80: 'Rapid Commit', + 81: 'Client FQDN', + 82: 'Relay Agent Information', + 83: 'iSNS', + 85: 'NDS Servers', + 86: 'NDS Tree Name', + 87: 'NDS Context', + 93: 'Client System Architecture', + 94: 'Client Network Interface', + 97: 'Client Machine Identifier', + 100: 'IEEE 1003.1 TZ String', + 101: 'Reference to TZ Database', + 108: 'IPv6-Only Preferred', + 114: 'Captive Portal', + 116: 'Auto-Config', + 117: 'Name Service Search', + 118: 'Subnet Selection', + 119: 'Domain Search', + 120: 'SIP Servers', + 121: 'Classless Static Route', + 122: 'CableLabs Client Configuration', + 123: 'GeoConf', + 124: 'Vendor Class', + 125: 'Vendor-Specific Information', + 128: 'TFTP Server IP', + 129: 'Call Server IP', + 130: 'Discrimination String', + 131: 'Remote Statistics Server', + 132: 'VLAN ID', + 133: 'Layer 2 Priority', + 134: 'Diffserv Code Point', + 135: 'HTTP Proxy for Phone', + 136: 'PANA Authentication Agent', + 137: 'LoST Server', + 138: 'CAPWAP Access Controller', + 139: 'IPv4 Address-MoS', + 140: 'IPv4 FQDN-MoS', + 141: 'SIP UA Configuration Service', + 142: 'IPv4 Address ANDSF', + 143: 'IPv6 Address ANDSF', + 144: 'GeoLoc', + 145: 'FORCERENEW_NONCE_CAPABLE', + 146: 'RDNSS Selection', + 150: 'TFTP Server Address', + 151: 'Status Code', + 152: 'Base Time', + 153: 'Start Time of State', + 154: 'Query Start Time', + 155: 'Query End Time', + 156: 'DHCP State', + 157: 'Data Source', + 158: 'PCP Server', + 159: 'Port Params', + 160: 'Captive Portal (DHCP)', + 161: 'MUD URL', + 208: 'PXELINUX Magic', + 209: 'Configuration File', + 210: 'Path Prefix', + 211: 'Reboot Time', + 212: '6RD', + 213: 'V4 Access Domain', + 220: 'Subnet Allocation', + 249: 'Private/Classless Static Route (MS)', + 252: 'Private/WPAD', +}; + +/** + * Format parameter list to hex + */ +export function formatParameterListToHex(params: number[]): string { + return params.map((p) => p.toString(16).padStart(2, '0')).join(''); +} + +/** + * Format parameter list for display + */ +export function formatParameterListDisplay(params: number[]): string { + return params.join(', '); +} + +/** + * Export fingerprint results as JSON + */ +export function exportAsJSON( + parameterList: number[], + matches: FingerprintMatch[], + analysis: OptionAnalysis, + vendorClass?: string, +): string { + const exportData = { + timestamp: new Date().toISOString(), + input: { + parameterList, + vendorClass: vendorClass || null, + hexEncoded: formatParameterListToHex(parameterList), + }, + analysis, + matches: matches.map((m) => ({ + device: m.fingerprint.device, + os: m.fingerprint.os, + category: m.fingerprint.category, + confidence: m.fingerprint.confidence, + matchScore: m.matchScore, + matchedOn: m.matchedOn, + })), + }; + return JSON.stringify(exportData, null, 2); +} + +/** + * Export fingerprint results as CSV + */ +export function exportAsCSV(matches: FingerprintMatch[]): string { + const headers = ['Device', 'OS', 'Category', 'Confidence', 'Match Score', 'Matched On']; + const rows = matches.map((m) => [ + m.fingerprint.device, + m.fingerprint.os, + m.fingerprint.category, + m.fingerprint.confidence, + m.matchScore.toFixed(1), + m.matchedOn.join('; '), + ]); + + return [headers.join(','), ...rows.map((row) => row.map((cell) => `"${cell}"`).join(','))].join('\n'); +} diff --git a/src/lib/utils/dhcp-lease-calculator.ts b/src/lib/utils/dhcp-lease-calculator.ts new file mode 100644 index 0000000..4950038 --- /dev/null +++ b/src/lib/utils/dhcp-lease-calculator.ts @@ -0,0 +1,337 @@ +/** + * DHCP Lease Time Calculator + * + * Calculates optimal lease times based on network characteristics: + * - Pool size and expected client count + * - Client turnover/churn rate + * - Network type (guest, corporate, IoT, etc.) + * + * Also provides T1 (renewal) and T2 (rebinding) times + */ + +export interface LeaseTimeConfig { + poolSize: number; + expectedClients: number; + churnRate: 'low' | 'medium' | 'high' | 'custom'; + customChurnHours?: number; + networkType?: 'corporate' | 'guest' | 'iot' | 'residential' | 'custom'; +} + +export interface LeaseTimeResult { + recommendedLeaseSeconds: number; + recommendedLeaseFormatted: string; + t1RenewalSeconds: number; + t1RenewalFormatted: string; + t2RebindingSeconds: number; + t2RebindingFormatted: string; + utilizationPercent: number; + exhaustionTime: string | null; + recommendations: string[]; + configExamples: { + iscDhcpd: string; + keaDhcp4: string; + }; +} + +interface NetworkTypeDefaults { + name: string; + leaseSeconds: number; + description: string; +} + +export const NETWORK_TYPE_DEFAULTS: Record = { + corporate: { + name: 'Corporate LAN', + leaseSeconds: 86400, // 24 hours + description: 'Stable network with known devices, daily renewal', + }, + guest: { + name: 'Guest WiFi', + leaseSeconds: 3600, // 1 hour + description: 'High turnover, short stays, frequent address recycling', + }, + iot: { + name: 'IoT Devices', + leaseSeconds: 604800, // 7 days + description: 'Stable devices, infrequent reboots, long leases preferred', + }, + residential: { + name: 'Residential/Home', + leaseSeconds: 86400, // 24 hours + description: 'Mix of stable and mobile devices, moderate turnover', + }, +}; + +export const CHURN_RATE_HOURS: Record = { + low: 168, // 7 days - devices stay connected for weeks + medium: 24, // 1 day - typical office environment + high: 4, // 4 hours - guest networks, conferences +}; + +/** + * Format seconds into human-readable time + */ +export function formatTime(seconds: number): string { + if (seconds < 60) { + return `${seconds} second${seconds !== 1 ? 's' : ''}`; + } + + if (seconds < 3600) { + const minutes = Math.floor(seconds / 60); + return `${minutes} minute${minutes !== 1 ? 's' : ''}`; + } + + if (seconds < 86400) { + const hours = Math.floor(seconds / 3600); + const minutes = Math.floor((seconds % 3600) / 60); + if (minutes === 0) { + return `${hours} hour${hours !== 1 ? 's' : ''}`; + } + return `${hours} hour${hours !== 1 ? 's' : ''}, ${minutes} minute${minutes !== 1 ? 's' : ''}`; + } + + const days = Math.floor(seconds / 86400); + const hours = Math.floor((seconds % 86400) / 3600); + if (hours === 0) { + return `${days} day${days !== 1 ? 's' : ''}`; + } + return `${days} day${days !== 1 ? 's' : ''}, ${hours} hour${hours !== 1 ? 's' : ''}`; +} + +/** + * Validate lease time configuration + */ +export function validateLeaseTimeConfig(config: LeaseTimeConfig): string[] { + const errors: string[] = []; + + if (config.poolSize <= 0) { + errors.push('Pool size must be greater than 0'); + } + + if (config.expectedClients < 0) { + errors.push('Expected clients cannot be negative'); + } + + if (config.expectedClients > config.poolSize) { + errors.push('Expected clients exceeds pool size - addresses will be exhausted'); + } + + if (config.churnRate === 'custom') { + if (config.customChurnHours === undefined || config.customChurnHours <= 0) { + errors.push('Custom churn rate must be greater than 0 hours'); + } + } + + return errors; +} + +/** + * Calculate optimal lease time + */ +export function calculateLeaseTime(config: LeaseTimeConfig): LeaseTimeResult { + const errors = validateLeaseTimeConfig(config); + if (errors.length > 0) { + throw new Error(errors.join('; ')); + } + + // Determine churn hours + const churnHours = config.churnRate === 'custom' ? config.customChurnHours! : CHURN_RATE_HOURS[config.churnRate]; + + // Calculate base lease time + let leaseSeconds: number; + + if (config.networkType && config.networkType !== 'custom') { + // Use network type default as baseline + leaseSeconds = NETWORK_TYPE_DEFAULTS[config.networkType].leaseSeconds; + } else { + // Calculate based on churn and utilization + const utilizationRatio = config.expectedClients / config.poolSize; + + if (utilizationRatio < 0.5) { + // Low utilization - can use longer leases + leaseSeconds = Math.min(churnHours * 3600 * 2, 604800); // Up to 7 days + } else if (utilizationRatio < 0.8) { + // Moderate utilization + leaseSeconds = churnHours * 3600; + } else { + // High utilization - shorter leases for faster recycling + leaseSeconds = Math.max(Math.floor(churnHours * 3600 * 0.5), 600); // At least 10 minutes + } + } + + // Calculate T1 (renewal time) - typically 50% of lease + const t1Seconds = Math.floor(leaseSeconds * 0.5); + + // Calculate T2 (rebinding time) - typically 87.5% of lease + const t2Seconds = Math.floor(leaseSeconds * 0.875); + + // Calculate utilization + const utilizationPercent = Math.round((config.expectedClients / config.poolSize) * 100); + + // Estimate time to exhaustion + let exhaustionTime: string | null = null; + if (config.expectedClients > config.poolSize) { + exhaustionTime = 'Immediate - not enough addresses'; + } else if (utilizationPercent > 90) { + const timeToExhaustion = ((config.poolSize - config.expectedClients) / config.expectedClients) * leaseSeconds; + exhaustionTime = `~${formatTime(Math.floor(timeToExhaustion))} under current load`; + } + + // Generate recommendations + const recommendations: string[] = []; + + if (utilizationPercent > 90) { + recommendations.push('⚠️ High utilization - consider expanding pool or shortening lease times'); + } + + if (utilizationPercent < 30) { + recommendations.push('✓ Low utilization - safe to use longer lease times for stability'); + } + + if (leaseSeconds < 3600) { + recommendations.push('Short lease times increase DHCP server load - ensure server can handle traffic'); + } + + if (leaseSeconds > 604800) { + recommendations.push('Very long leases may delay address reclamation - ensure adequate pool size'); + } + + if (config.networkType === 'guest') { + recommendations.push('Guest networks benefit from short leases (1-4 hours) for rapid address recycling'); + } + + if (config.networkType === 'iot') { + recommendations.push('IoT devices prefer long leases (7-30 days) to minimize network chatter'); + } + + // Generate config examples + const configExamples = generateConfigExamples(leaseSeconds, t1Seconds, t2Seconds); + + return { + recommendedLeaseSeconds: leaseSeconds, + recommendedLeaseFormatted: formatTime(leaseSeconds), + t1RenewalSeconds: t1Seconds, + t1RenewalFormatted: formatTime(t1Seconds), + t2RebindingSeconds: t2Seconds, + t2RebindingFormatted: formatTime(t2Seconds), + utilizationPercent, + exhaustionTime, + recommendations, + configExamples, + }; +} + +/** + * Generate configuration examples + */ +function generateConfigExamples( + leaseSeconds: number, + t1Seconds: number, + t2Seconds: number, +): { + iscDhcpd: string; + keaDhcp4: string; +} { + const maxLeaseSeconds = leaseSeconds * 2; // Typical max is 2x default + + const iscDhcpd = `# ISC DHCPd Lease Configuration +default-lease-time ${leaseSeconds}; +max-lease-time ${maxLeaseSeconds}; + +# Subnet configuration example +subnet 192.168.1.0 netmask 255.255.255.0 { + range 192.168.1.100 192.168.1.200; + option routers 192.168.1.1; + option domain-name-servers 192.168.1.1; + default-lease-time ${leaseSeconds}; + max-lease-time ${maxLeaseSeconds}; +}`; + + const keaDhcp4 = `{ + "Dhcp4": { + "valid-lifetime": ${leaseSeconds}, + "renew-timer": ${t1Seconds}, + "rebind-timer": ${t2Seconds}, + "subnet4": [ + { + "subnet": "192.168.1.0/24", + "pools": [ + { + "pool": "192.168.1.100 - 192.168.1.200" + } + ], + "option-data": [ + { + "name": "routers", + "data": "192.168.1.1" + }, + { + "name": "domain-name-servers", + "data": "192.168.1.1" + } + ], + "valid-lifetime": ${leaseSeconds} + } + ] + } +}`; + + return { + iscDhcpd, + keaDhcp4, + }; +} + +/** + * Example scenarios + */ +export const LEASE_TIME_EXAMPLES: Array = [ + { + name: 'Small Office', + description: '50 devices, stable network', + poolSize: 100, + expectedClients: 50, + churnRate: 'low', + networkType: 'corporate', + }, + { + name: 'Guest WiFi', + description: 'High turnover, 200 capacity', + poolSize: 200, + expectedClients: 150, + churnRate: 'high', + networkType: 'guest', + }, + { + name: 'IoT Network', + description: '500 sensors, very stable', + poolSize: 600, + expectedClients: 500, + churnRate: 'low', + networkType: 'iot', + }, + { + name: 'Home Network', + description: '10-20 devices, mixed types', + poolSize: 50, + expectedClients: 15, + churnRate: 'medium', + networkType: 'residential', + }, + { + name: 'Near Capacity', + description: 'Running close to limit', + poolSize: 100, + expectedClients: 95, + churnRate: 'medium', + networkType: 'corporate', + }, + { + name: 'Conference WiFi', + description: 'Very high churn, 500 attendees', + poolSize: 600, + expectedClients: 450, + churnRate: 'high', + networkType: 'guest', + }, +]; diff --git a/src/lib/utils/dhcp-option3-gateway.ts b/src/lib/utils/dhcp-option3-gateway.ts new file mode 100644 index 0000000..0a3c755 --- /dev/null +++ b/src/lib/utils/dhcp-option3-gateway.ts @@ -0,0 +1,277 @@ +/** + * DHCP Option 3 - Router/Default Gateway (RFC 2132) + * + * Specifies a list of IP addresses for routers on the client's subnet. + * Routers are listed in order of preference. + * + * Multiple gateways are used for: + * - Redundancy (failover) + * - Load balancing (some clients) + * - Metric-based routing (Windows) + */ + +export interface GatewayConfig { + gateways: string[]; + subnet?: string; // Optional for validation +} + +export interface GatewayResult { + gateways: string[]; + hexEncoded: string; + wireFormat: string; + totalLength: number; + configExamples: { + iscDhcpd: string; + keaDhcp4: string; + dnsmasq: string; + }; +} + +/** + * Validates an IPv4 address + */ +function validateIPv4(ip: string): boolean { + const parts = ip.split('.'); + if (parts.length !== 4) return false; + + for (const part of parts) { + const num = parseInt(part, 10); + if (isNaN(num) || num < 0 || num > 255 || part !== num.toString()) { + return false; + } + } + return true; +} + +/** + * Checks if IP is within subnet + */ +function isInSubnet(ip: string, subnet: string): boolean { + const [network, prefixStr] = subnet.split('/'); + const prefix = parseInt(prefixStr, 10); + + if (!validateIPv4(network) || isNaN(prefix) || prefix < 0 || prefix > 32) { + return false; + } + + const ipNum = ipToNumber(ip); + const networkNum = ipToNumber(network); + const mask = (0xffffffff << (32 - prefix)) >>> 0; + + return (ipNum & mask) === (networkNum & mask); +} + +/** + * Converts IP address to number + */ +function ipToNumber(ip: string): number { + const parts = ip.split('.').map((p) => parseInt(p, 10)); + return ((parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]) >>> 0; +} + +/** + * Converts IPv4 address to hex bytes + */ +function ipv4ToHex(ip: string): string { + const parts = ip.split('.').map((p) => parseInt(p, 10)); + return parts.map((p) => p.toString(16).padStart(2, '0')).join(''); +} + +/** + * Converts hex bytes to IPv4 address + */ +function hexToIpv4(hex: string): string { + const bytes = hex.match(/.{1,2}/g) || []; + return bytes.map((b) => parseInt(b, 16).toString()).join('.'); +} + +/** + * Formats hex string as wire format (with spaces) + */ +function formatWireFormat(hex: string): string { + return hex.match(/.{1,2}/g)?.join(' ') || ''; +} + +/** + * Validates gateway configuration + */ +export function validateGatewayConfig(config: GatewayConfig): string[] { + const errors: string[] = []; + + if (!config.gateways || config.gateways.length === 0) { + errors.push('At least one gateway must be specified'); + return errors; + } + + // Filter out empty entries + const validGateways = config.gateways.filter((g) => g.trim()); + + if (validGateways.length === 0) { + errors.push('At least one gateway must be specified'); + return errors; + } + + // Validate each gateway + for (let i = 0; i < config.gateways.length; i++) { + const gateway = config.gateways[i]; + if (!gateway.trim()) continue; + + if (!validateIPv4(gateway)) { + errors.push(`Gateway ${i + 1}: Invalid IPv4 address`); + continue; + } + + // Check if gateway is in subnet (if subnet provided) + if (config.subnet && config.subnet.trim()) { + if (!isInSubnet(gateway, config.subnet)) { + errors.push(`Gateway ${i + 1}: Not within subnet ${config.subnet}`); + } + } + } + + // Check for duplicates + const seen = new Set(); + for (const gateway of validGateways) { + if (seen.has(gateway)) { + errors.push(`Duplicate gateway: ${gateway}`); + } + seen.add(gateway); + } + + return errors; +} + +/** + * Builds DHCP Option 3 (Router) + */ +export function buildGatewayOption(config: GatewayConfig): GatewayResult { + const errors = validateGatewayConfig(config); + if (errors.length > 0) { + throw new Error(errors.join('; ')); + } + + const validGateways = config.gateways.filter((g) => g.trim()); + let hexEncoded = ''; + + for (const gateway of validGateways) { + hexEncoded += ipv4ToHex(gateway); + } + + return { + gateways: validGateways, + hexEncoded, + wireFormat: formatWireFormat(hexEncoded), + totalLength: hexEncoded.length / 2, + configExamples: generateConfigExamples(validGateways), + }; +} + +/** + * Decodes DHCP Option 3 from hex + */ +export function decodeGatewayOption(hex: string): GatewayResult { + // Remove spaces and validate hex + const cleanHex = hex.replace(/\s+/g, ''); + + if (!/^[0-9a-fA-F]*$/.test(cleanHex)) { + throw new Error('Invalid hex string'); + } + + if (cleanHex.length === 0) { + throw new Error('Hex string cannot be empty'); + } + + if (cleanHex.length % 8 !== 0) { + throw new Error('Hex string must be multiple of 8 characters (4 bytes per IP)'); + } + + const gateways: string[] = []; + for (let i = 0; i < cleanHex.length; i += 8) { + const ipHex = cleanHex.substring(i, i + 8); + gateways.push(hexToIpv4(ipHex)); + } + + return { + gateways, + hexEncoded: cleanHex, + wireFormat: formatWireFormat(cleanHex), + totalLength: cleanHex.length / 2, + configExamples: generateConfigExamples(gateways), + }; +} + +/** + * Generates configuration examples for various DHCP servers + */ +function generateConfigExamples(gateways: string[]): { + iscDhcpd: string; + keaDhcp4: string; + dnsmasq: string; +} { + const gatewayList = gateways.join(', '); + + const iscDhcpd = `subnet 192.168.1.0 netmask 255.255.255.0 { + range 192.168.1.100 192.168.1.200; + option routers ${gatewayList}; +}`; + + const keaDhcp4 = `{ + "Dhcp4": { + "subnet4": [ + { + "subnet": "192.168.1.0/24", + "pools": [ + { + "pool": "192.168.1.100 - 192.168.1.200" + } + ], + "option-data": [ + { + "name": "routers", + "code": 3, + "data": "${gatewayList}" + } + ] + } + ] + } +}`; + + const dnsmasq = + gateways.length === 1 + ? `dhcp-option=3,${gateways[0]}` + : `# Multiple gateways (order matters)\n${gateways.map((g) => `dhcp-option=3,${g}`).join('\n')}`; + + return { + iscDhcpd, + keaDhcp4, + dnsmasq, + }; +} + +/** + * Example gateway configurations + */ +export const GATEWAY_EXAMPLES = [ + { + label: 'Single Gateway', + description: 'Most common setup with one default gateway', + gateways: ['192.168.1.1'], + }, + { + label: 'Dual Gateway (Redundancy)', + description: 'Primary and backup gateway for failover', + gateways: ['192.168.1.1', '192.168.1.2'], + }, + { + label: 'Multiple Gateways', + description: 'Multiple gateways for load balancing or complex routing', + gateways: ['10.0.1.1', '10.0.1.2', '10.0.1.3'], + }, + { + label: 'Enterprise Network', + description: 'Corporate network with redundant gateways', + gateways: ['172.16.0.1', '172.16.0.2'], + subnet: '172.16.0.0/16', + }, +]; diff --git a/src/lib/utils/dhcp-option51-lease-time.ts b/src/lib/utils/dhcp-option51-lease-time.ts new file mode 100644 index 0000000..13108cf --- /dev/null +++ b/src/lib/utils/dhcp-option51-lease-time.ts @@ -0,0 +1,271 @@ +/** + * DHCP Option 51 - IP Address Lease Time (RFC 2132) + * + * Specifies the lease time in seconds for the IP address. + * The value is a 32-bit unsigned integer. + * + * Special values: + * - 0xFFFFFFFF: Infinite lease (permanent assignment) + * - Common values: 3600 (1h), 86400 (24h), 604800 (7d) + */ + +export interface LeaseTimeConfig { + leaseSeconds: number; + infinite?: boolean; +} + +export interface LeaseTimeResult { + leaseSeconds: number; + hexEncoded: string; + wireFormat: string; + totalLength: number; + humanReadable: string; + isInfinite: boolean; + t1RenewalSeconds?: number; + t1RenewalFormatted?: string; + t2RebindingSeconds?: number; + t2RebindingFormatted?: string; + configExamples: { + iscDhcpd: string; + keaDhcp4: string; + dnsmasq: string; + }; +} + +/** + * Formats time in human-readable format + */ +export function formatTime(seconds: number): string { + if (seconds === 0xffffffff) return 'Infinite'; + + const days = Math.floor(seconds / 86400); + const hours = Math.floor((seconds % 86400) / 3600); + const minutes = Math.floor((seconds % 3600) / 60); + const secs = seconds % 60; + + const parts: string[] = []; + if (days > 0) parts.push(`${days} day${days !== 1 ? 's' : ''}`); + if (hours > 0) parts.push(`${hours} hour${hours !== 1 ? 's' : ''}`); + if (minutes > 0) parts.push(`${minutes} minute${minutes !== 1 ? 's' : ''}`); + if (secs > 0 || parts.length === 0) parts.push(`${secs} second${secs !== 1 ? 's' : ''}`); + + return parts.join(', '); +} + +/** + * Validates lease time configuration + */ +export function validateLeaseTimeConfig(config: LeaseTimeConfig): string[] { + const errors: string[] = []; + + if (config.infinite) { + return errors; // Infinite lease is always valid + } + + if (config.leaseSeconds < 0) { + errors.push('Lease time cannot be negative'); + } + + if (config.leaseSeconds > 0xfffffffe) { + errors.push('Lease time exceeds maximum value (use infinite lease instead)'); + } + + if (config.leaseSeconds > 0 && config.leaseSeconds < 60) { + errors.push('Warning: Lease time less than 60 seconds is unusually short'); + } + + if (config.leaseSeconds > 31536000) { + // 1 year + errors.push('Warning: Lease time greater than 1 year is unusually long'); + } + + return errors; +} + +/** + * Converts seconds to 32-bit hex (big-endian) + */ +function secondsToHex(seconds: number): string { + const value = seconds >>> 0; // Ensure unsigned 32-bit + return value.toString(16).padStart(8, '0'); +} + +/** + * Converts hex to seconds (32-bit big-endian) + */ +function hexToSeconds(hex: string): number { + return parseInt(hex, 16) >>> 0; // Ensure unsigned 32-bit +} + +/** + * Formats hex string as wire format (with spaces) + */ +function formatWireFormat(hex: string): string { + return hex.match(/.{1,2}/g)?.join(' ') || ''; +} + +/** + * Builds DHCP Option 51 (Lease Time) + */ +export function buildLeaseTimeOption(config: LeaseTimeConfig): LeaseTimeResult { + const errors = validateLeaseTimeConfig(config); + // Only throw on actual errors, not warnings + const actualErrors = errors.filter((e) => !e.startsWith('Warning:')); + if (actualErrors.length > 0) { + throw new Error(actualErrors.join('; ')); + } + + const leaseSeconds = config.infinite ? 0xffffffff : config.leaseSeconds; + const hexEncoded = secondsToHex(leaseSeconds); + const isInfinite = leaseSeconds === 0xffffffff; + + const result: LeaseTimeResult = { + leaseSeconds, + hexEncoded, + wireFormat: formatWireFormat(hexEncoded), + totalLength: 4, + humanReadable: formatTime(leaseSeconds), + isInfinite, + configExamples: generateConfigExamples(leaseSeconds, isInfinite), + }; + + // Calculate T1 and T2 if not infinite + if (!isInfinite) { + result.t1RenewalSeconds = Math.floor(leaseSeconds * 0.5); + result.t1RenewalFormatted = formatTime(result.t1RenewalSeconds); + result.t2RebindingSeconds = Math.floor(leaseSeconds * 0.875); + result.t2RebindingFormatted = formatTime(result.t2RebindingSeconds); + } + + return result; +} + +/** + * Decodes DHCP Option 51 from hex + */ +export function decodeLeaseTimeOption(hex: string): LeaseTimeResult { + // Remove spaces and validate hex + const cleanHex = hex.replace(/\s+/g, ''); + + if (!/^[0-9a-fA-F]*$/.test(cleanHex)) { + throw new Error('Invalid hex string'); + } + + if (cleanHex.length === 0) { + throw new Error('Hex string cannot be empty'); + } + + if (cleanHex.length !== 8) { + throw new Error('Hex string must be exactly 8 characters (4 bytes)'); + } + + const leaseSeconds = hexToSeconds(cleanHex); + const isInfinite = leaseSeconds === 0xffffffff; + + const result: LeaseTimeResult = { + leaseSeconds, + hexEncoded: cleanHex.toLowerCase(), + wireFormat: formatWireFormat(cleanHex.toLowerCase()), + totalLength: 4, + humanReadable: formatTime(leaseSeconds), + isInfinite, + configExamples: generateConfigExamples(leaseSeconds, isInfinite), + }; + + // Calculate T1 and T2 if not infinite + if (!isInfinite) { + result.t1RenewalSeconds = Math.floor(leaseSeconds * 0.5); + result.t1RenewalFormatted = formatTime(result.t1RenewalSeconds); + result.t2RebindingSeconds = Math.floor(leaseSeconds * 0.875); + result.t2RebindingFormatted = formatTime(result.t2RebindingSeconds); + } + + return result; +} + +/** + * Generates configuration examples + */ +function generateConfigExamples( + leaseSeconds: number, + isInfinite: boolean, +): { + iscDhcpd: string; + keaDhcp4: string; + dnsmasq: string; +} { + const iscDhcpd = isInfinite + ? `subnet 192.168.1.0 netmask 255.255.255.0 { + range 192.168.1.100 192.168.1.200; + default-lease-time ${leaseSeconds}; + max-lease-time ${leaseSeconds}; + # Note: Some DHCP servers may not support infinite leases +}` + : `subnet 192.168.1.0 netmask 255.255.255.0 { + range 192.168.1.100 192.168.1.200; + default-lease-time ${leaseSeconds}; + max-lease-time ${Math.floor(leaseSeconds * 1.5)}; +}`; + + const keaDhcp4 = isInfinite + ? `{ + "Dhcp4": { + "subnet4": [ + { + "subnet": "192.168.1.0/24", + "pools": [ + { + "pool": "192.168.1.100 - 192.168.1.200" + } + ], + "valid-lifetime": ${leaseSeconds}, + "comment": "Infinite lease - may not be supported" + } + ] + } +}` + : `{ + "Dhcp4": { + "subnet4": [ + { + "subnet": "192.168.1.0/24", + "pools": [ + { + "pool": "192.168.1.100 - 192.168.1.200" + } + ], + "valid-lifetime": ${leaseSeconds}, + "renew-timer": ${Math.floor(leaseSeconds * 0.5)}, + "rebind-timer": ${Math.floor(leaseSeconds * 0.875)} + } + ] + } +}`; + + const dnsmasq = isInfinite + ? `# Infinite lease +dhcp-range=192.168.1.100,192.168.1.200,infinite` + : `# Lease time in seconds or with suffix (m/h/d) +dhcp-range=192.168.1.100,192.168.1.200,${leaseSeconds}s`; + + return { + iscDhcpd, + keaDhcp4, + dnsmasq, + }; +} + +/** + * Common lease time presets + */ +export const LEASE_TIME_PRESETS = [ + { label: '1 Hour', seconds: 3600, description: 'Guest networks, high churn' }, + { label: '4 Hours', seconds: 14400, description: 'Coffee shops, public WiFi' }, + { label: '8 Hours', seconds: 28800, description: 'Office workday' }, + { label: '12 Hours', seconds: 43200, description: 'Half day' }, + { label: '24 Hours', seconds: 86400, description: 'Corporate networks (default)' }, + { label: '3 Days', seconds: 259200, description: 'Small offices' }, + { label: '7 Days', seconds: 604800, description: 'IoT devices, stable networks' }, + { label: '30 Days', seconds: 2592000, description: 'Very stable environments' }, + { label: 'Infinite', seconds: 0xffffffff, description: 'Permanent assignment', infinite: true }, +]; diff --git a/src/lib/utils/dhcp-options6-15-dns.ts b/src/lib/utils/dhcp-options6-15-dns.ts new file mode 100644 index 0000000..2b365e4 --- /dev/null +++ b/src/lib/utils/dhcp-options6-15-dns.ts @@ -0,0 +1,389 @@ +/** + * DHCP Options 6 & 15 - DNS Servers and Domain Name (RFC 2132) + * + * Option 6: Domain Name Server - List of DNS servers available to client + * Option 15: Domain Name - Domain name for client resolution + * + * These options work together to provide complete DNS configuration. + */ + +export interface DNSConfig { + dnsServers: string[]; + domainName?: string; +} + +export interface DNSResult { + option6?: { + servers: string[]; + hexEncoded: string; + wireFormat: string; + totalLength: number; + }; + option15?: { + domain: string; + hexEncoded: string; + wireFormat: string; + totalLength: number; + }; + configExamples: { + iscDhcpd: string; + keaDhcp4: string; + dnsmasq: string; + }; +} + +/** + * Validates an IPv4 address + */ +function validateIPv4(ip: string): boolean { + const parts = ip.split('.'); + if (parts.length !== 4) return false; + + for (const part of parts) { + const num = parseInt(part, 10); + if (isNaN(num) || num < 0 || num > 255 || part !== num.toString()) { + return false; + } + } + return true; +} + +/** + * Validates a domain name (FQDN or hostname) + */ +function validateDomainName(domain: string): boolean { + // Basic domain validation - RFC 1035 + if (domain.length === 0 || domain.length > 253) return false; + + // Allow FQDN with or without trailing dot + const normalized = domain.endsWith('.') ? domain.slice(0, -1) : domain; + + // Check each label + const labels = normalized.split('.'); + if (labels.length === 0) return false; + + for (const label of labels) { + // Label must be 1-63 characters + if (label.length === 0 || label.length > 63) return false; + + // Must start and end with alphanumeric + if (!/^[a-zA-Z0-9]/.test(label) || !/[a-zA-Z0-9]$/.test(label)) return false; + + // Can contain alphanumeric and hyphens + if (!/^[a-zA-Z0-9-]+$/.test(label)) return false; + } + + return true; +} + +/** + * Converts IPv4 address to hex bytes + */ +function ipv4ToHex(ip: string): string { + const parts = ip.split('.').map((p) => parseInt(p, 10)); + return parts.map((p) => p.toString(16).padStart(2, '0')).join(''); +} + +/** + * Converts hex bytes to IPv4 address + */ +function hexToIpv4(hex: string): string { + const bytes = hex.match(/.{1,2}/g) || []; + return bytes.map((b) => parseInt(b, 16).toString()).join('.'); +} + +/** + * Converts domain name to ASCII hex bytes + */ +function domainToHex(domain: string): string { + // Remove trailing dot if present + const normalized = domain.endsWith('.') ? domain.slice(0, -1) : domain; + + // Convert to ASCII hex + return normalized + .split('') + .map((c) => c.charCodeAt(0).toString(16).padStart(2, '0')) + .join(''); +} + +/** + * Converts hex bytes to domain name + */ +function hexToDomain(hex: string): string { + const bytes = hex.match(/.{1,2}/g) || []; + return bytes.map((b) => String.fromCharCode(parseInt(b, 16))).join(''); +} + +/** + * Formats hex string as wire format (with spaces) + */ +function formatWireFormat(hex: string): string { + return hex.match(/.{1,2}/g)?.join(' ') || ''; +} + +/** + * Validates DNS configuration + */ +export function validateDNSConfig(config: DNSConfig): string[] { + const errors: string[] = []; + + // Check that at least one option is configured + const hasDNSServers = config.dnsServers && config.dnsServers.some((s) => s.trim()); + const hasDomainName = config.domainName && config.domainName.trim(); + + if (!hasDNSServers && !hasDomainName) { + errors.push('At least one DNS server or domain name must be configured'); + } + + // Validate DNS servers (Option 6) + if (config.dnsServers) { + for (let i = 0; i < config.dnsServers.length; i++) { + const server = config.dnsServers[i]; + if (!server.trim()) continue; + + if (!validateIPv4(server)) { + errors.push(`DNS Server ${i + 1}: Invalid IPv4 address`); + } + } + + // Check for duplicates + const validServers = config.dnsServers.filter((s) => s.trim()); + const seen = new Set(); + for (const server of validServers) { + if (seen.has(server)) { + errors.push(`Duplicate DNS server: ${server}`); + } + seen.add(server); + } + } + + // Validate domain name (Option 15) + if (config.domainName && config.domainName.trim()) { + if (!validateDomainName(config.domainName.trim())) { + errors.push('Domain Name: Invalid domain name format'); + } + } + + return errors; +} + +/** + * Builds DHCP Options 6 and/or 15 + */ +export function buildDNSOptions(config: DNSConfig): DNSResult { + const errors = validateDNSConfig(config); + if (errors.length > 0) { + throw new Error(errors.join('; ')); + } + + const result: Partial = {}; + + // Build Option 6: DNS Servers + if (config.dnsServers && config.dnsServers.length > 0) { + const validServers = config.dnsServers.filter((s) => s.trim()); + + if (validServers.length > 0) { + let serversHex = ''; + for (const server of validServers) { + serversHex += ipv4ToHex(server); + } + + result.option6 = { + servers: validServers, + hexEncoded: serversHex, + wireFormat: formatWireFormat(serversHex), + totalLength: serversHex.length / 2, + }; + } + } + + // Build Option 15: Domain Name + if (config.domainName && config.domainName.trim()) { + const domainInput = config.domainName.trim(); + // Remove trailing dot for consistency + const domain = domainInput.endsWith('.') ? domainInput.slice(0, -1) : domainInput; + const domainHex = domainToHex(domain); + + result.option15 = { + domain, + hexEncoded: domainHex, + wireFormat: formatWireFormat(domainHex), + totalLength: domainHex.length / 2, + }; + } + + result.configExamples = generateConfigExamples(result.option6?.servers || [], result.option15?.domain); + + return result as DNSResult; +} + +/** + * Decodes DHCP Option 6 (DNS Servers) from hex + */ +export function decodeDNSServersOption(hex: string): DNSResult['option6'] { + // Remove spaces and validate hex + const cleanHex = hex.replace(/\s+/g, ''); + + if (!/^[0-9a-fA-F]*$/.test(cleanHex)) { + throw new Error('Invalid hex string'); + } + + if (cleanHex.length === 0) { + throw new Error('Hex string cannot be empty'); + } + + if (cleanHex.length % 8 !== 0) { + throw new Error('Hex string must be multiple of 8 characters (4 bytes per IP)'); + } + + const servers: string[] = []; + for (let i = 0; i < cleanHex.length; i += 8) { + const ipHex = cleanHex.substring(i, i + 8); + servers.push(hexToIpv4(ipHex)); + } + + return { + servers, + hexEncoded: cleanHex, + wireFormat: formatWireFormat(cleanHex), + totalLength: cleanHex.length / 2, + }; +} + +/** + * Decodes DHCP Option 15 (Domain Name) from hex + */ +export function decodeDomainNameOption(hex: string): DNSResult['option15'] { + // Remove spaces and validate hex + const cleanHex = hex.replace(/\s+/g, ''); + + if (!/^[0-9a-fA-F]*$/.test(cleanHex)) { + throw new Error('Invalid hex string'); + } + + if (cleanHex.length === 0) { + throw new Error('Hex string cannot be empty'); + } + + const domain = hexToDomain(cleanHex); + + // Validate decoded domain + if (!validateDomainName(domain)) { + throw new Error('Decoded domain name is invalid'); + } + + return { + domain, + hexEncoded: cleanHex, + wireFormat: formatWireFormat(cleanHex), + totalLength: cleanHex.length / 2, + }; +} + +/** + * Generates configuration examples + */ +function generateConfigExamples( + servers: string[], + domain?: string, +): { + iscDhcpd: string; + keaDhcp4: string; + dnsmasq: string; +} { + const hasServers = servers.length > 0; + const hasDomain = domain && domain.trim(); + + let iscDhcpd = 'subnet 192.168.1.0 netmask 255.255.255.0 {\n range 192.168.1.100 192.168.1.200;\n'; + if (hasServers) { + iscDhcpd += ` option domain-name-servers ${servers.join(', ')};\n`; + } + if (hasDomain) { + iscDhcpd += ` option domain-name "${domain}";\n`; + } + iscDhcpd += '}'; + + const optionData: string[] = []; + if (hasServers) { + optionData.push(` { + "name": "domain-name-servers", + "code": 6, + "data": "${servers.join(', ')}" + }`); + } + if (hasDomain) { + optionData.push(` { + "name": "domain-name", + "code": 15, + "data": "${domain}" + }`); + } + + const keaDhcp4 = `{ + "Dhcp4": { + "subnet4": [ + { + "subnet": "192.168.1.0/24", + "pools": [ + { + "pool": "192.168.1.100 - 192.168.1.200" + } + ], + "option-data": [ +${optionData.join(',\n')} + ] + } + ] + } +}`; + + let dnsmasq = ''; + if (hasServers) { + dnsmasq += `dhcp-option=6,${servers.join(',')}\n`; + } + if (hasDomain) { + dnsmasq += `dhcp-option=15,${domain}`; + } + + return { + iscDhcpd, + keaDhcp4, + dnsmasq: dnsmasq.trim(), + }; +} + +/** + * Example DNS configurations + */ +export const DNS_EXAMPLES = [ + { + label: 'Google DNS', + description: 'Public DNS servers from Google', + dnsServers: ['8.8.8.8', '8.8.4.4'], + domainName: 'example.com', + }, + { + label: 'Cloudflare DNS', + description: 'Fast public DNS from Cloudflare', + dnsServers: ['1.1.1.1', '1.0.0.1'], + domainName: 'example.org', + }, + { + label: 'Quad9 DNS', + description: 'Security-focused public DNS', + dnsServers: ['9.9.9.9', '149.112.112.112'], + domainName: 'example.net', + }, + { + label: 'Corporate Network', + description: 'Internal DNS servers with company domain', + dnsServers: ['10.0.1.10', '10.0.1.11'], + domainName: 'corp.example.com', + }, + { + label: 'Single DNS Server', + description: 'Simple configuration with one DNS server', + dnsServers: ['192.168.1.1'], + domainName: 'home.local', + }, +]; diff --git a/src/lib/utils/dhcpv6-fqdn-rfc4704.ts b/src/lib/utils/dhcpv6-fqdn-rfc4704.ts new file mode 100644 index 0000000..94afa4a --- /dev/null +++ b/src/lib/utils/dhcpv6-fqdn-rfc4704.ts @@ -0,0 +1,276 @@ +/** + * DHCPv6 Client FQDN Option (RFC 4704) + * + * Option 39: Client FQDN + * + * Allows DHCPv6 clients to exchange FQDN information with servers, + * enabling dynamic DNS updates. + */ + +export interface FQDNConfig { + fqdn: string; + serverShouldUpdate: boolean; + serverOverride: boolean; + clientShouldUpdate: boolean; +} + +export interface FQDNResult { + flags: { + S: boolean; // Server should update DNS + O: boolean; // Server override + N: boolean; // Client should not update + flagsByte: string; + description: string[]; + }; + fqdn: string; + hexEncoded: string; + wireFormat: string; + totalLength: number; + breakdown: { + flags: string; + fqdn: string; + }; + examples: { + keaDhcp6?: string; + }; +} + +/** + * Validates FQDN format + */ +function validateFQDN(fqdn: string): boolean { + // Basic FQDN validation - must be valid domain name + // Allow labels with alphanumeric chars and hyphens (not at start/end) + const labelRegex = /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/; + const fqdnRegex = /^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)*[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/; + + // Check overall format and length + if (!fqdnRegex.test(fqdn) || fqdn.length > 253) { + return false; + } + + // Check each label individually + const labels = fqdn.split('.'); + for (const label of labels) { + if (!labelRegex.test(label) || label.length > 63) { + return false; + } + } + + return true; +} + +/** + * Validates FQDN configuration + */ +export function validateFQDNConfig(config: FQDNConfig): string[] { + const errors: string[] = []; + + // Validate FQDN + if (!config.fqdn || !config.fqdn.trim()) { + errors.push('FQDN is required'); + } else if (!validateFQDN(config.fqdn)) { + errors.push('Invalid FQDN format'); + } + + // Validate flags logic + if (config.clientShouldUpdate && config.serverShouldUpdate) { + errors.push('Both client and server cannot be set to update DNS simultaneously'); + } + + return errors; +} + +/** + * Converts a string to hex bytes (UTF-8 encoding) + */ +function stringToHex(str: string): string { + const encoder = new TextEncoder(); + const bytes = encoder.encode(str); + return Array.from(bytes) + .map((b) => b.toString(16).padStart(2, '0')) + .join(''); +} + +/** + * Converts FQDN to DNS wire format (length-prefixed labels) + */ +function fqdnToHex(fqdn: string): string { + const labels = fqdn.split('.'); + let hex = ''; + + for (const label of labels) { + const labelLength = label.length; + hex += labelLength.toString(16).padStart(2, '0'); + hex += stringToHex(label); + } + + // Add null terminator + hex += '00'; + + return hex; +} + +/** + * Formats hex string as wire format (with spaces) + */ +function formatWireFormat(hex: string): string { + return hex.match(/.{1,2}/g)?.join(' ') || ''; +} + +/** + * Builds DHCPv6 FQDN option + */ +export function buildFQDNOption(config: FQDNConfig): FQDNResult { + const errors = validateFQDNConfig(config); + if (errors.length > 0) { + throw new Error(errors.join('; ')); + } + + // Build flags byte + // Bit 0: S (Server should update) + // Bit 1: O (Server override) + // Bit 2: N (Client should NOT update) + let flagsByte = 0; + + if (config.serverShouldUpdate) { + flagsByte |= 0b00000001; // Set S bit + } + + if (config.serverOverride) { + flagsByte |= 0b00000010; // Set O bit + } + + if (!config.clientShouldUpdate) { + flagsByte |= 0b00000100; // Set N bit + } + + const flagsHex = flagsByte.toString(16).padStart(2, '0'); + + // Build FQDN in wire format + const fqdnHex = fqdnToHex(config.fqdn); + + // Combine flags + FQDN + const fullHex = flagsHex + fqdnHex; + + const flagDescriptions: string[] = []; + if (config.serverShouldUpdate) { + flagDescriptions.push('S=1: Server should perform DNS updates'); + } else { + flagDescriptions.push('S=0: Server should not perform DNS updates'); + } + + if (config.serverOverride) { + flagDescriptions.push('O=1: Server can override client preferences'); + } else { + flagDescriptions.push('O=0: Server should honor client preferences'); + } + + if (!config.clientShouldUpdate) { + flagDescriptions.push('N=1: Client requests server to perform updates'); + } else { + flagDescriptions.push('N=0: Client will perform its own updates'); + } + + const result: FQDNResult = { + flags: { + S: config.serverShouldUpdate, + O: config.serverOverride, + N: !config.clientShouldUpdate, + flagsByte: flagsHex, + description: flagDescriptions, + }, + fqdn: config.fqdn, + hexEncoded: fullHex, + wireFormat: formatWireFormat(fullHex), + totalLength: fullHex.length / 2, + breakdown: { + flags: formatWireFormat(flagsHex), + fqdn: formatWireFormat(fqdnHex), + }, + examples: generateConfigExamples(config), + }; + + return result; +} + +/** + * Generates Kea DHCPv6 configuration examples + */ +function generateConfigExamples(config: FQDNConfig): { + keaDhcp6?: string; +} { + const keaDhcp6 = `{ + "Dhcp6": { + "ddns-send-updates": ${config.serverShouldUpdate}, + "ddns-override-no-update": ${config.serverOverride}, + "ddns-override-client-update": ${config.serverOverride}, + "ddns-replace-client-name": "${config.serverShouldUpdate ? 'always' : 'never'}", + "ddns-qualifying-suffix": "${config.fqdn.split('.').slice(1).join('.')}", + "subnet6": [ + { + "subnet": "2001:db8::/64", + "pools": [ + { + "pool": "2001:db8::100 - 2001:db8::200" + } + ] + } + ] + } +}`; + + return { + keaDhcp6, + }; +} + +/** + * Returns a default FQDN configuration + */ +export function getDefaultFQDNConfig(): FQDNConfig { + return { + fqdn: '', + serverShouldUpdate: true, + serverOverride: false, + clientShouldUpdate: false, + }; +} + +/** + * Example FQDN configurations + */ +export const FQDN_EXAMPLES: Array = [ + { + label: 'Server Updates DNS', + description: 'Server performs all DNS updates', + fqdn: 'client.example.com', + serverShouldUpdate: true, + serverOverride: true, + clientShouldUpdate: false, + }, + { + label: 'Client Updates DNS', + description: 'Client performs its own DNS updates', + fqdn: 'workstation.corp.example.com', + serverShouldUpdate: false, + serverOverride: false, + clientShouldUpdate: true, + }, + { + label: 'Server with Override', + description: 'Server updates and can override client', + fqdn: 'managed-device.internal.example.com', + serverShouldUpdate: true, + serverOverride: true, + clientShouldUpdate: false, + }, + { + label: 'No Updates', + description: 'Neither client nor server updates DNS', + fqdn: 'static.example.org', + serverShouldUpdate: false, + serverOverride: false, + clientShouldUpdate: false, + }, +]; diff --git a/src/lib/utils/dhcpv6-prefix-delegation.ts b/src/lib/utils/dhcpv6-prefix-delegation.ts new file mode 100644 index 0000000..77b3dda --- /dev/null +++ b/src/lib/utils/dhcpv6-prefix-delegation.ts @@ -0,0 +1,416 @@ +/** + * DHCPv6 Prefix Delegation (RFC 8415) + * + * Option 25: Identity Association for Prefix Delegation (IA_PD) + * Option 26: IA Prefix Option + * + * Used for delegating IPv6 prefixes to requesting routers/clients. + */ + +export interface PrefixDelegationConfig { + iaid: number; // IA_PD IAID (4 bytes) + t1?: number; // T1 renewal time (seconds) + t2?: number; // T2 rebinding time (seconds) + prefixes: PrefixConfig[]; +} + +export interface PrefixConfig { + prefix: string; // IPv6 prefix (e.g., "2001:db8::/48") + preferredLifetime?: number; // Preferred lifetime (seconds, 0xFFFFFFFF = infinite) + validLifetime?: number; // Valid lifetime (seconds, 0xFFFFFFFF = infinite) +} + +export interface PrefixDelegationResult { + iaid: number; + iaidHex: string; + t1: number; + t1Hex: string; + t1Formatted: string; + t2: number; + t2Hex: string; + t2Formatted: string; + prefixes: Array<{ + prefix: string; + prefixLength: number; + preferredLifetime: number; + preferredLifetimeHex: string; + preferredLifetimeFormatted: string; + validLifetime: number; + validLifetimeHex: string; + validLifetimeFormatted: string; + prefixHex: string; + wireFormat: string; + optionLength: number; + }>; + fullHex: string; + fullWireFormat: string; + totalLength: number; + examples: { + keaDhcp6?: string; + }; +} + +/** + * Validates an IPv6 prefix + */ +function validateIPv6Prefix(prefix: string): boolean { + const parts = prefix.split('/'); + if (parts.length !== 2) return false; + + const [addr, len] = parts; + const prefixLen = parseInt(len, 10); + + if (isNaN(prefixLen) || prefixLen < 0 || prefixLen > 128) return false; + + // Basic IPv6 address validation + const ipv6Regex = /^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$/; + const ipv6CompressedRegex = /^::([0-9a-fA-F]{0,4}:){0,6}[0-9a-fA-F]{0,4}$/; + const ipv6FullCompressedRegex = /^::$/; + + return ipv6Regex.test(addr) || ipv6CompressedRegex.test(addr) || ipv6FullCompressedRegex.test(addr); +} + +/** + * Expands IPv6 address to full form + */ +function expandIPv6(ip: string): string { + let expanded = ip; + + // Handle :: compression + if (ip.includes('::')) { + const parts = ip.split('::'); + const leftParts = parts[0] ? parts[0].split(':') : []; + const rightParts = parts[1] ? parts[1].split(':') : []; + const missingParts = 8 - leftParts.length - rightParts.length; + const middleParts = Array(missingParts).fill('0000'); + expanded = [...leftParts, ...middleParts, ...rightParts].join(':'); + } + + // Pad each segment to 4 hex digits + const segments = expanded.split(':').map((seg) => seg.padStart(4, '0')); + + return segments.join(':'); +} + +/** + * Converts IPv6 address to hex bytes (16 bytes) + */ +function ipv6ToHex(ip: string): string { + const expanded = expandIPv6(ip); + return expanded.split(':').join(''); +} + +/** + * Converts 32-bit number to hex (4 bytes) + */ +function uint32ToHex(value: number): string { + return value.toString(16).padStart(8, '0'); +} + +/** + * Formats time value to human-readable string + */ +export function formatTime(seconds: number): string { + if (seconds === 0xffffffff) return 'Infinite'; + if (seconds === 0) return '0 seconds'; + + const days = Math.floor(seconds / 86400); + const hours = Math.floor((seconds % 86400) / 3600); + const mins = Math.floor((seconds % 3600) / 60); + const secs = seconds % 60; + + const parts: string[] = []; + if (days > 0) parts.push(`${days}d`); + if (hours > 0) parts.push(`${hours}h`); + if (mins > 0) parts.push(`${mins}m`); + if (secs > 0) parts.push(`${secs}s`); + + return parts.join(' ') || '0s'; +} + +/** + * Formats hex string with spaces every 2 characters + */ +function formatWireFormat(hex: string): string { + return hex.match(/.{1,2}/g)?.join(' ') || ''; +} + +/** + * Validates prefix delegation configuration + */ +export function validatePrefixDelegationConfig(config: PrefixDelegationConfig): string[] { + const errors: string[] = []; + + // Validate IAID + if (config.iaid < 0 || config.iaid > 0xffffffff) { + errors.push('IAID must be between 0 and 4294967295'); + } + + // Validate T1/T2 + if (config.t1 !== undefined && (config.t1 < 0 || config.t1 > 0xffffffff)) { + errors.push('T1 must be between 0 and 4294967295'); + } + + if (config.t2 !== undefined && (config.t2 < 0 || config.t2 > 0xffffffff)) { + errors.push('T2 must be between 0 and 4294967295'); + } + + if ( + config.t1 !== undefined && + config.t2 !== undefined && + config.t1 !== 0 && + config.t2 !== 0 && + config.t1 > config.t2 + ) { + errors.push('T1 must be less than or equal to T2'); + } + + // Validate prefixes + if (!config.prefixes || config.prefixes.length === 0) { + errors.push('At least one prefix must be configured'); + } else { + config.prefixes.forEach((prefix, i) => { + if (!validateIPv6Prefix(prefix.prefix)) { + errors.push(`Prefix ${i + 1}: Invalid IPv6 prefix format`); + } + + if ( + prefix.preferredLifetime !== undefined && + (prefix.preferredLifetime < 0 || prefix.preferredLifetime > 0xffffffff) + ) { + errors.push(`Prefix ${i + 1}: Preferred lifetime must be between 0 and 4294967295`); + } + + if (prefix.validLifetime !== undefined && (prefix.validLifetime < 0 || prefix.validLifetime > 0xffffffff)) { + errors.push(`Prefix ${i + 1}: Valid lifetime must be between 0 and 4294967295`); + } + + if ( + prefix.preferredLifetime !== undefined && + prefix.validLifetime !== undefined && + prefix.preferredLifetime !== 0xffffffff && + prefix.validLifetime !== 0xffffffff && + prefix.preferredLifetime > prefix.validLifetime + ) { + errors.push(`Prefix ${i + 1}: Preferred lifetime must be <= valid lifetime`); + } + }); + } + + return errors; +} + +/** + * Builds DHCPv6 IA_PD option + */ +export function buildPrefixDelegation(config: PrefixDelegationConfig): PrefixDelegationResult { + const errors = validatePrefixDelegationConfig(config); + if (errors.length > 0) { + throw new Error(errors.join('; ')); + } + + const t1 = config.t1 ?? 0; + const t2 = config.t2 ?? 0; + + const iaidHex = uint32ToHex(config.iaid); + const t1Hex = uint32ToHex(t1); + const t2Hex = uint32ToHex(t2); + + const prefixes: PrefixDelegationResult['prefixes'] = []; + let prefixesHex = ''; + + for (const prefix of config.prefixes) { + const [addr, len] = prefix.prefix.split('/'); + const prefixLength = parseInt(len, 10); + const preferredLifetime = prefix.preferredLifetime ?? 604800; // 7 days default + const validLifetime = prefix.validLifetime ?? 2592000; // 30 days default + + const preferredLifetimeHex = uint32ToHex(preferredLifetime); + const validLifetimeHex = uint32ToHex(validLifetime); + const prefixHex = ipv6ToHex(addr); + + // Option 26 format: option-code (2) + option-len (2) + preferred-lifetime (4) + valid-lifetime (4) + prefix-length (1) + prefix (16) + const optionData = preferredLifetimeHex + validLifetimeHex + prefixLength.toString(16).padStart(2, '0') + prefixHex; + const optionLen = (optionData.length / 2).toString(16).padStart(4, '0'); + const optionCode = '001a'; // 0x001a = 26 + const fullOptionHex = optionCode + optionLen + optionData; + + prefixesHex += fullOptionHex; + + prefixes.push({ + prefix: prefix.prefix, + prefixLength, + preferredLifetime, + preferredLifetimeHex, + preferredLifetimeFormatted: formatTime(preferredLifetime), + validLifetime, + validLifetimeHex, + validLifetimeFormatted: formatTime(validLifetime), + prefixHex, + wireFormat: formatWireFormat(fullOptionHex), + optionLength: fullOptionHex.length / 2, + }); + } + + // Full IA_PD option: option-code (2) + option-len (2) + IAID (4) + T1 (4) + T2 (4) + IA_PD-options + const iaPdData = iaidHex + t1Hex + t2Hex + prefixesHex; + const iaPdLen = (iaPdData.length / 2).toString(16).padStart(4, '0'); + const iaPdCode = '0019'; // 0x0019 = 25 + const fullHex = iaPdCode + iaPdLen + iaPdData; + + return { + iaid: config.iaid, + iaidHex, + t1, + t1Hex, + t1Formatted: formatTime(t1), + t2, + t2Hex, + t2Formatted: formatTime(t2), + prefixes, + fullHex, + fullWireFormat: formatWireFormat(fullHex), + totalLength: fullHex.length / 2, + examples: generateConfigExamples(config, prefixes), + }; +} + +/** + * Generates Kea DHCPv6 configuration examples + */ +function generateConfigExamples( + config: PrefixDelegationConfig, + prefixes: PrefixDelegationResult['prefixes'], +): { keaDhcp6?: string } { + const _prefixConfigs = prefixes + .map( + (p) => ` { + "prefix": "${p.prefix.split('/')[0]}", + "prefix-len": ${p.prefixLength}, + "delegated-len": ${p.prefixLength}, + "preferred-lifetime": ${p.preferredLifetime === 0xffffffff ? 4294967295 : p.preferredLifetime}, + "valid-lifetime": ${p.validLifetime === 0xffffffff ? 4294967295 : p.validLifetime} + }`, + ) + .join(',\n'); + + const keaDhcp6 = `{ + "Dhcp6": { + "subnet6": [ + { + "subnet": "2001:db8::/32", + "pd-pools": [ + { + "prefix": "${prefixes[0].prefix.split('/')[0]}", + "prefix-len": ${prefixes[0].prefixLength}, + "delegated-len": ${prefixes[0].prefixLength} + } + ]${ + config.t1 !== undefined || config.t2 !== undefined + ? `, + "renew-timer": ${config.t1 ?? 0}, + "rebind-timer": ${config.t2 ?? 0}` + : '' + } + } + ] + } +}`; + + return { keaDhcp6 }; +} + +/** + * Example configurations + */ +export const PREFIX_DELEGATION_EXAMPLES: Array<{ + label: string; + description: string; + config: PrefixDelegationConfig; +}> = [ + { + label: 'Home Router /56', + description: 'Typical home router prefix delegation', + config: { + iaid: 1, + t1: 302400, // 3.5 days + t2: 483840, // 5.6 days + prefixes: [ + { + prefix: '2001:db8:1000::/56', + preferredLifetime: 604800, // 7 days + validLifetime: 2592000, // 30 days + }, + ], + }, + }, + { + label: 'Small Business /48', + description: 'Small business with larger prefix', + config: { + iaid: 100, + t1: 1209600, // 14 days + t2: 1814400, // 21 days + prefixes: [ + { + prefix: '2001:db8::/48', + preferredLifetime: 2592000, // 30 days + validLifetime: 7776000, // 90 days + }, + ], + }, + }, + { + label: 'ISP Customer /60', + description: 'ISP delegating /60 to customer', + config: { + iaid: 42, + t1: 86400, // 1 day + t2: 138240, // 1.6 days + prefixes: [ + { + prefix: '2001:db8:abcd::/60', + preferredLifetime: 172800, // 2 days + validLifetime: 604800, // 7 days + }, + ], + }, + }, + { + label: 'Multiple Prefixes', + description: 'Router with multiple delegated prefixes', + config: { + iaid: 1, + prefixes: [ + { + prefix: '2001:db8:1::/56', + preferredLifetime: 604800, + validLifetime: 2592000, + }, + { + prefix: '2001:db8:2::/56', + preferredLifetime: 604800, + validLifetime: 2592000, + }, + ], + }, + }, +]; + +/** + * Returns default configuration + */ +export function getDefaultPrefixDelegationConfig(): PrefixDelegationConfig { + return { + iaid: 1, + t1: 302400, // 3.5 days + t2: 483840, // 5.6 days + prefixes: [ + { + prefix: '2001:db8::/56', + preferredLifetime: 604800, // 7 days + validLifetime: 2592000, // 30 days + }, + ], + }; +} diff --git a/src/routes/dhcp/calculators/lease-time/+page.svelte b/src/routes/dhcp/calculators/lease-time/+page.svelte new file mode 100644 index 0000000..ecf1525 --- /dev/null +++ b/src/routes/dhcp/calculators/lease-time/+page.svelte @@ -0,0 +1,5 @@ + + + diff --git a/src/routes/dhcp/tools/fingerprinting/+page.svelte b/src/routes/dhcp/tools/fingerprinting/+page.svelte new file mode 100644 index 0000000..f52fdc9 --- /dev/null +++ b/src/routes/dhcp/tools/fingerprinting/+page.svelte @@ -0,0 +1,17 @@ + + + + DHCP Fingerprinting Database | IP Calc + + + + + diff --git a/src/routes/dhcp/v4/options/option3-default-gateway/+page.svelte b/src/routes/dhcp/v4/options/option3-default-gateway/+page.svelte new file mode 100644 index 0000000..ecd9e7c --- /dev/null +++ b/src/routes/dhcp/v4/options/option3-default-gateway/+page.svelte @@ -0,0 +1,5 @@ + + + diff --git a/src/routes/dhcp/v4/options/option51-lease-time/+page.svelte b/src/routes/dhcp/v4/options/option51-lease-time/+page.svelte new file mode 100644 index 0000000..e0c8872 --- /dev/null +++ b/src/routes/dhcp/v4/options/option51-lease-time/+page.svelte @@ -0,0 +1,5 @@ + + + diff --git a/src/routes/dhcp/v4/options/options6-15-dns/+page.svelte b/src/routes/dhcp/v4/options/options6-15-dns/+page.svelte new file mode 100644 index 0000000..0bc0070 --- /dev/null +++ b/src/routes/dhcp/v4/options/options6-15-dns/+page.svelte @@ -0,0 +1,5 @@ + + + diff --git a/src/routes/dhcp/v6/options/option25-prefix-delegation/+page.svelte b/src/routes/dhcp/v6/options/option25-prefix-delegation/+page.svelte new file mode 100644 index 0000000..883c743 --- /dev/null +++ b/src/routes/dhcp/v6/options/option25-prefix-delegation/+page.svelte @@ -0,0 +1,17 @@ + + + + DHCPv6 Prefix Delegation (IA_PD) - Options 25/26 | IP Calc + + + + + diff --git a/src/routes/dhcp/v6/options/option39-fqdn/+page.svelte b/src/routes/dhcp/v6/options/option39-fqdn/+page.svelte new file mode 100644 index 0000000..ea75964 --- /dev/null +++ b/src/routes/dhcp/v6/options/option39-fqdn/+page.svelte @@ -0,0 +1,17 @@ + + + + DHCPv6 Client FQDN Option (Option 39) - RFC 4704 | IP Calc + + + + + diff --git a/tests/unit/utils/dhcp-fingerprinting.test.ts b/tests/unit/utils/dhcp-fingerprinting.test.ts new file mode 100644 index 0000000..4001904 --- /dev/null +++ b/tests/unit/utils/dhcp-fingerprinting.test.ts @@ -0,0 +1,171 @@ +import { describe, it, expect } from 'vitest'; +import { + parseParameterList, + searchFingerprints, + formatParameterListToHex, + formatParameterListDisplay, +} from '$lib/utils/dhcp-fingerprinting'; + +describe('dhcp-fingerprinting', () => { + describe('parseParameterList', () => { + it('should parse hex format', () => { + const result = parseParameterList('0103060f'); + expect(result).toEqual([1, 3, 6, 15]); + }); + + it('should parse hex with spaces', () => { + const result = parseParameterList('01 03 06 0f'); + expect(result).toEqual([1, 3, 6, 15]); + }); + + it('should parse comma-separated', () => { + const result = parseParameterList('1,3,6,15'); + expect(result).toEqual([1, 3, 6, 15]); + }); + + it('should parse space-separated', () => { + const result = parseParameterList('1 3 6 15'); + expect(result).toEqual([1, 3, 6, 15]); + }); + + it('should parse single number', () => { + const result = parseParameterList('1'); + expect(result).toEqual([1]); + }); + + it('should handle leading zeros in hex', () => { + const result = parseParameterList('010306'); + expect(result).toEqual([1, 3, 6]); + }); + }); + + describe('formatParameterListToHex', () => { + it('should format to hex', () => { + const result = formatParameterListToHex([1, 3, 6, 15]); + expect(result).toBe('0103060f'); + }); + + it('should pad single digit hex', () => { + const result = formatParameterListToHex([1, 255]); + expect(result).toBe('01ff'); + }); + + it('should handle empty array', () => { + const result = formatParameterListToHex([]); + expect(result).toBe(''); + }); + }); + + describe('formatParameterListDisplay', () => { + it('should format with commas', () => { + const result = formatParameterListDisplay([1, 3, 6, 15]); + expect(result).toBe('1, 3, 6, 15'); + }); + + it('should handle single value', () => { + const result = formatParameterListDisplay([1]); + expect(result).toBe('1'); + }); + + it('should handle empty array', () => { + const result = formatParameterListDisplay([]); + expect(result).toBe(''); + }); + }); + + describe('searchFingerprints', () => { + it('should find Windows 10/11 exact match', () => { + const params = [1, 3, 6, 15, 31, 33, 43, 44, 46, 47, 119, 121, 249, 252]; + const matches = searchFingerprints(params); + + expect(matches.length).toBeGreaterThan(0); + const win10Match = matches.find((m) => m.fingerprint.id === 'win10'); + expect(win10Match).toBeDefined(); + expect(win10Match!.matchScore).toBe(100); + }); + + it('should find macOS match', () => { + const params = [1, 3, 6, 15, 119, 252]; + const matches = searchFingerprints(params); + + expect(matches.length).toBeGreaterThan(0); + const macMatch = matches.find((m) => m.fingerprint.id === 'macos'); + expect(macMatch).toBeDefined(); + expect(macMatch!.matchScore).toBe(100); + }); + + it('should find Android match with vendor class', () => { + const params = [1, 3, 6, 15, 26, 28, 51, 58, 59, 43]; + const matches = searchFingerprints(params, 'dhcpcd'); + + expect(matches.length).toBeGreaterThan(0); + const androidMatch = matches.find((m) => m.fingerprint.id === 'android'); + expect(androidMatch).toBeDefined(); + expect(androidMatch!.matchedOn).toContain('Vendor Class'); + }); + + it('should find partial match', () => { + const params = [1, 3, 6, 15]; // Subset of many fingerprints + const matches = searchFingerprints(params); + + expect(matches.length).toBeGreaterThan(0); + // Should have at least some matches + expect(matches.some((m) => m.matchScore >= 50)).toBe(true); + }); + + it('should sort by match score', () => { + const params = [1, 3, 6, 15, 31, 33, 43, 44, 46, 47, 119, 121, 249, 252]; + const matches = searchFingerprints(params); + + // Verify descending order + for (let i = 1; i < matches.length; i++) { + expect(matches[i - 1].matchScore).toBeGreaterThanOrEqual(matches[i].matchScore); + } + }); + + it('should not match with very low score', () => { + const params = [99, 98, 97]; // Random options unlikely to match + const matches = searchFingerprints(params); + + // Should have very few or no matches + expect(matches.length).toBeLessThan(3); + }); + + it('should identify Linux dhclient', () => { + const params = [1, 3, 6, 15, 26, 28, 42]; + const matches = searchFingerprints(params); + + const linuxMatch = matches.find((m) => m.fingerprint.id === 'linux-dhclient'); + expect(linuxMatch).toBeDefined(); + expect(linuxMatch!.matchScore).toBe(100); + }); + + it('should handle empty parameter list', () => { + const matches = searchFingerprints([]); + expect(matches).toEqual([]); + }); + + it('should boost score for vendor class match', () => { + const params = [1, 3, 6]; // Partial match + const matchesWithoutVendor = searchFingerprints(params); + const matchesWithVendor = searchFingerprints(params, 'Cisco'); + + // Cisco matches should have higher scores when vendor is provided + const ciscoWithVendor = matchesWithVendor.find((m) => m.fingerprint.id === 'cisco-phone'); + const ciscoWithoutVendor = matchesWithoutVendor.find((m) => m.fingerprint.id === 'cisco-phone'); + + if (ciscoWithVendor && ciscoWithoutVendor) { + expect(ciscoWithVendor.matchScore).toBeGreaterThan(ciscoWithoutVendor.matchScore); + } + }); + + it('should indicate exact match in matchedOn', () => { + const params = [1, 3, 6, 15, 119, 252]; + const matches = searchFingerprints(params); + + const macMatch = matches.find((m) => m.fingerprint.id === 'macos'); + expect(macMatch).toBeDefined(); + expect(macMatch!.matchedOn.some((m) => m.includes('Exact'))).toBe(true); + }); + }); +}); diff --git a/tests/unit/utils/dhcp-lease-calculator.test.ts b/tests/unit/utils/dhcp-lease-calculator.test.ts new file mode 100644 index 0000000..671f6c5 --- /dev/null +++ b/tests/unit/utils/dhcp-lease-calculator.test.ts @@ -0,0 +1,223 @@ +import { describe, it, expect } from 'vitest'; +import { + validateLeaseTimeConfig, + calculateLeaseTime, + formatTime, + type LeaseTimeConfig, +} from '$lib/utils/dhcp-lease-calculator'; + +describe('dhcp-lease-calculator', () => { + describe('formatTime', () => { + it('should format seconds correctly', () => { + expect(formatTime(30)).toBe('30 seconds'); + expect(formatTime(1)).toBe('1 second'); + }); + + it('should format minutes correctly', () => { + expect(formatTime(60)).toBe('1 minute'); + expect(formatTime(120)).toBe('2 minutes'); + expect(formatTime(90)).toBe('1 minute'); + }); + + it('should format hours correctly', () => { + expect(formatTime(3600)).toBe('1 hour'); + expect(formatTime(7200)).toBe('2 hours'); + expect(formatTime(3660)).toBe('1 hour, 1 minute'); + }); + + it('should format days correctly', () => { + expect(formatTime(86400)).toBe('1 day'); + expect(formatTime(172800)).toBe('2 days'); + expect(formatTime(90000)).toBe('1 day, 1 hour'); + }); + }); + + describe('validateLeaseTimeConfig', () => { + it('should accept valid configuration', () => { + const config: LeaseTimeConfig = { + poolSize: 100, + expectedClients: 50, + churnRate: 'medium', + networkType: 'corporate', + }; + expect(validateLeaseTimeConfig(config)).toEqual([]); + }); + + it('should reject pool size <= 0', () => { + const config: LeaseTimeConfig = { + poolSize: 0, + expectedClients: 50, + churnRate: 'medium', + }; + const errors = validateLeaseTimeConfig(config); + expect(errors.length).toBeGreaterThan(0); + expect(errors[0]).toContain('Pool size must be greater than 0'); + }); + + it('should reject negative expected clients', () => { + const config: LeaseTimeConfig = { + poolSize: 100, + expectedClients: -10, + churnRate: 'medium', + }; + const errors = validateLeaseTimeConfig(config); + expect(errors.length).toBeGreaterThan(0); + expect(errors[0]).toContain('Expected clients cannot be negative'); + }); + + it('should warn when expected clients exceeds pool size', () => { + const config: LeaseTimeConfig = { + poolSize: 50, + expectedClients: 100, + churnRate: 'medium', + }; + const errors = validateLeaseTimeConfig(config); + expect(errors.length).toBeGreaterThan(0); + expect(errors[0]).toContain('exceeds pool size'); + }); + + it('should require custom churn hours when churn rate is custom', () => { + const config: LeaseTimeConfig = { + poolSize: 100, + expectedClients: 50, + churnRate: 'custom', + }; + const errors = validateLeaseTimeConfig(config); + expect(errors.length).toBeGreaterThan(0); + expect(errors[0]).toContain('Custom churn rate'); + }); + + it('should accept custom churn hours', () => { + const config: LeaseTimeConfig = { + poolSize: 100, + expectedClients: 50, + churnRate: 'custom', + customChurnHours: 12, + }; + expect(validateLeaseTimeConfig(config)).toEqual([]); + }); + }); + + describe('calculateLeaseTime', () => { + it('should calculate lease time for corporate network', () => { + const config: LeaseTimeConfig = { + poolSize: 100, + expectedClients: 50, + churnRate: 'medium', + networkType: 'corporate', + }; + const result = calculateLeaseTime(config); + + expect(result.recommendedLeaseSeconds).toBe(86400); // 24 hours + expect(result.utilizationPercent).toBe(50); + expect(result.t1RenewalSeconds).toBe(43200); // 50% of lease + expect(result.t2RebindingSeconds).toBe(75600); // 87.5% of lease + }); + + it('should calculate lease time for guest network', () => { + const config: LeaseTimeConfig = { + poolSize: 200, + expectedClients: 150, + churnRate: 'high', + networkType: 'guest', + }; + const result = calculateLeaseTime(config); + + expect(result.recommendedLeaseSeconds).toBe(3600); // 1 hour + expect(result.utilizationPercent).toBe(75); + expect(result.t1RenewalSeconds).toBe(1800); // 50% of lease + expect(result.t2RebindingSeconds).toBe(3150); // 87.5% of lease + }); + + it('should calculate lease time for IoT network', () => { + const config: LeaseTimeConfig = { + poolSize: 600, + expectedClients: 500, + churnRate: 'low', + networkType: 'iot', + }; + const result = calculateLeaseTime(config); + + expect(result.recommendedLeaseSeconds).toBe(604800); // 7 days + expect(result.utilizationPercent).toBe(83); + }); + + it('should use custom churn rate when specified', () => { + const config: LeaseTimeConfig = { + poolSize: 100, + expectedClients: 50, + churnRate: 'custom', + customChurnHours: 6, + networkType: 'custom', + }; + const result = calculateLeaseTime(config); + + // Low utilization (50%), should be 2x churn time but capped + expect(result.recommendedLeaseSeconds).toBeGreaterThan(0); + expect(result.utilizationPercent).toBe(50); + }); + + it('should provide exhaustion warning for high utilization', () => { + const config: LeaseTimeConfig = { + poolSize: 100, + expectedClients: 95, + churnRate: 'medium', + networkType: 'corporate', + }; + const result = calculateLeaseTime(config); + + expect(result.utilizationPercent).toBe(95); + expect(result.exhaustionTime).not.toBeNull(); + expect(result.exhaustionTime).toContain('under current load'); + }); + + it('should provide recommendations for high utilization', () => { + const config: LeaseTimeConfig = { + poolSize: 100, + expectedClients: 92, + churnRate: 'medium', + networkType: 'corporate', + }; + const result = calculateLeaseTime(config); + + expect(result.recommendations.length).toBeGreaterThan(0); + expect(result.recommendations.some((r) => r.includes('High utilization'))).toBe(true); + }); + + it('should provide recommendations for low utilization', () => { + const config: LeaseTimeConfig = { + poolSize: 100, + expectedClients: 20, + churnRate: 'medium', + networkType: 'corporate', + }; + const result = calculateLeaseTime(config); + + expect(result.recommendations.length).toBeGreaterThan(0); + expect(result.recommendations.some((r) => r.includes('Low utilization'))).toBe(true); + }); + + it('should include config examples', () => { + const config: LeaseTimeConfig = { + poolSize: 100, + expectedClients: 50, + churnRate: 'medium', + networkType: 'corporate', + }; + const result = calculateLeaseTime(config); + + expect(result.configExamples).toBeDefined(); + expect(result.configExamples.iscDhcpd).toContain('default-lease-time'); + expect(result.configExamples.keaDhcp4).toContain('valid-lifetime'); + }); + + it('should throw error for invalid configuration', () => { + const config: LeaseTimeConfig = { + poolSize: 0, + expectedClients: 50, + churnRate: 'medium', + }; + expect(() => calculateLeaseTime(config)).toThrow(); + }); + }); +}); diff --git a/tests/unit/utils/dhcp-option3-gateway.test.ts b/tests/unit/utils/dhcp-option3-gateway.test.ts new file mode 100644 index 0000000..ab65f29 --- /dev/null +++ b/tests/unit/utils/dhcp-option3-gateway.test.ts @@ -0,0 +1,197 @@ +import { describe, it, expect } from 'vitest'; +import { + validateGatewayConfig, + buildGatewayOption, + decodeGatewayOption, + type GatewayConfig, +} from '$lib/utils/dhcp-option3-gateway'; + +describe('dhcp-option3-gateway', () => { + describe('validateGatewayConfig', () => { + it('should require at least one gateway', () => { + const config: GatewayConfig = { + gateways: [], + }; + const errors = validateGatewayConfig(config); + expect(errors.length).toBeGreaterThan(0); + expect(errors[0]).toContain('At least one gateway'); + }); + + it('should reject empty gateway entries', () => { + const config: GatewayConfig = { + gateways: ['', ' '], + }; + const errors = validateGatewayConfig(config); + expect(errors.length).toBeGreaterThan(0); + expect(errors[0]).toContain('At least one gateway'); + }); + + it('should validate IPv4 addresses', () => { + const config: GatewayConfig = { + gateways: ['not-an-ip'], + }; + const errors = validateGatewayConfig(config); + expect(errors.length).toBeGreaterThan(0); + expect(errors[0]).toContain('Invalid IPv4 address'); + }); + + it('should accept valid IPv4 addresses', () => { + const config: GatewayConfig = { + gateways: ['192.168.1.1'], + }; + const errors = validateGatewayConfig(config); + expect(errors).toEqual([]); + }); + + it('should validate gateway is within subnet', () => { + const config: GatewayConfig = { + gateways: ['192.168.2.1'], + subnet: '192.168.1.0/24', + }; + const errors = validateGatewayConfig(config); + expect(errors.length).toBeGreaterThan(0); + expect(errors[0]).toContain('Not within subnet'); + }); + + it('should accept gateway within subnet', () => { + const config: GatewayConfig = { + gateways: ['192.168.1.1'], + subnet: '192.168.1.0/24', + }; + const errors = validateGatewayConfig(config); + expect(errors).toEqual([]); + }); + + it('should detect duplicate gateways', () => { + const config: GatewayConfig = { + gateways: ['192.168.1.1', '192.168.1.1'], + }; + const errors = validateGatewayConfig(config); + expect(errors.length).toBeGreaterThan(0); + expect(errors[0]).toContain('Duplicate gateway'); + }); + + it('should skip empty entries during validation', () => { + const config: GatewayConfig = { + gateways: ['192.168.1.1', '', '192.168.1.2'], + }; + const errors = validateGatewayConfig(config); + expect(errors).toEqual([]); + }); + + it('should validate multiple gateways', () => { + const config: GatewayConfig = { + gateways: ['192.168.1.1', '192.168.1.2', '192.168.1.3'], + }; + const errors = validateGatewayConfig(config); + expect(errors).toEqual([]); + }); + }); + + describe('buildGatewayOption', () => { + it('should build option for single gateway', () => { + const config: GatewayConfig = { + gateways: ['192.168.1.1'], + }; + const result = buildGatewayOption(config); + expect(result.gateways).toEqual(['192.168.1.1']); + expect(result.hexEncoded).toBe('c0a80101'); + expect(result.totalLength).toBe(4); + }); + + it('should build option for multiple gateways', () => { + const config: GatewayConfig = { + gateways: ['192.168.1.1', '192.168.1.2'], + }; + const result = buildGatewayOption(config); + expect(result.gateways).toEqual(['192.168.1.1', '192.168.1.2']); + expect(result.hexEncoded).toBe('c0a80101c0a80102'); + expect(result.totalLength).toBe(8); + }); + + it('should encode IP addresses correctly', () => { + const config: GatewayConfig = { + gateways: ['10.0.0.1'], + }; + const result = buildGatewayOption(config); + expect(result.hexEncoded).toBe('0a000001'); + }); + + it('should format wire format with spaces', () => { + const config: GatewayConfig = { + gateways: ['192.168.1.1'], + }; + const result = buildGatewayOption(config); + expect(result.wireFormat).toBe('c0 a8 01 01'); + }); + + it('should skip empty gateway entries', () => { + const config: GatewayConfig = { + gateways: ['192.168.1.1', '', '192.168.1.2'], + }; + const result = buildGatewayOption(config); + expect(result.gateways).toEqual(['192.168.1.1', '192.168.1.2']); + expect(result.totalLength).toBe(8); + }); + + it('should generate config examples', () => { + const config: GatewayConfig = { + gateways: ['192.168.1.1'], + }; + const result = buildGatewayOption(config); + expect(result.configExamples.iscDhcpd).toContain('option routers 192.168.1.1'); + expect(result.configExamples.keaDhcp4).toContain('"name": "routers"'); + expect(result.configExamples.dnsmasq).toContain('dhcp-option=3,192.168.1.1'); + }); + + it('should throw error for invalid configuration', () => { + const config: GatewayConfig = { + gateways: ['invalid-ip'], + }; + expect(() => buildGatewayOption(config)).toThrow(); + }); + }); + + describe('decodeGatewayOption', () => { + it('should decode single gateway', () => { + const result = decodeGatewayOption('c0a80101'); + expect(result.gateways).toEqual(['192.168.1.1']); + expect(result.totalLength).toBe(4); + }); + + it('should decode multiple gateways', () => { + const result = decodeGatewayOption('c0a80101c0a80102'); + expect(result.gateways).toEqual(['192.168.1.1', '192.168.1.2']); + expect(result.totalLength).toBe(8); + }); + + it('should handle hex with spaces', () => { + const result = decodeGatewayOption('c0 a8 01 01'); + expect(result.gateways).toEqual(['192.168.1.1']); + }); + + it('should handle uppercase hex', () => { + const result = decodeGatewayOption('C0A80101'); + expect(result.gateways).toEqual(['192.168.1.1']); + }); + + it('should throw error for empty hex', () => { + expect(() => decodeGatewayOption('')).toThrow('empty'); + }); + + it('should throw error for invalid hex characters', () => { + expect(() => decodeGatewayOption('zzzzz')).toThrow('Invalid hex'); + }); + + it('should throw error for incorrect length', () => { + expect(() => decodeGatewayOption('c0a801')).toThrow('multiple of 8'); + }); + + it('should decode and provide config examples', () => { + const result = decodeGatewayOption('c0a80101'); + expect(result.configExamples.iscDhcpd).toBeDefined(); + expect(result.configExamples.keaDhcp4).toBeDefined(); + expect(result.configExamples.dnsmasq).toBeDefined(); + }); + }); +}); diff --git a/tests/unit/utils/dhcp-option51-lease-time.test.ts b/tests/unit/utils/dhcp-option51-lease-time.test.ts new file mode 100644 index 0000000..bec2279 --- /dev/null +++ b/tests/unit/utils/dhcp-option51-lease-time.test.ts @@ -0,0 +1,239 @@ +import { describe, it, expect } from 'vitest'; +import { + validateLeaseTimeConfig, + buildLeaseTimeOption, + decodeLeaseTimeOption, + formatTime, + type LeaseTimeConfig, +} from '$lib/utils/dhcp-option51-lease-time'; + +describe('dhcp-option51-lease-time', () => { + describe('formatTime', () => { + it('should format infinite lease', () => { + expect(formatTime(0xffffffff)).toBe('Infinite'); + }); + + it('should format seconds', () => { + expect(formatTime(30)).toBe('30 seconds'); + expect(formatTime(1)).toBe('1 second'); + }); + + it('should format minutes', () => { + expect(formatTime(60)).toBe('1 minute'); + expect(formatTime(120)).toBe('2 minutes'); + }); + + it('should format hours', () => { + expect(formatTime(3600)).toBe('1 hour'); + expect(formatTime(7200)).toBe('2 hours'); + }); + + it('should format days', () => { + expect(formatTime(86400)).toBe('1 day'); + expect(formatTime(172800)).toBe('2 days'); + }); + + it('should format combined time', () => { + expect(formatTime(90061)).toBe('1 day, 1 hour, 1 minute, 1 second'); + }); + }); + + describe('validateLeaseTimeConfig', () => { + it('should accept infinite lease', () => { + const config: LeaseTimeConfig = { + leaseSeconds: 0, + infinite: true, + }; + const errors = validateLeaseTimeConfig(config); + expect(errors).toEqual([]); + }); + + it('should accept valid lease time', () => { + const config: LeaseTimeConfig = { + leaseSeconds: 86400, + }; + const errors = validateLeaseTimeConfig(config); + expect(errors).toEqual([]); + }); + + it('should reject negative lease time', () => { + const config: LeaseTimeConfig = { + leaseSeconds: -100, + }; + const errors = validateLeaseTimeConfig(config); + expect(errors.length).toBeGreaterThan(0); + expect(errors[0]).toContain('cannot be negative'); + }); + + it('should reject lease time exceeding max', () => { + const config: LeaseTimeConfig = { + leaseSeconds: 0xffffffff, + }; + const errors = validateLeaseTimeConfig(config); + expect(errors.length).toBeGreaterThan(0); + expect(errors[0]).toContain('exceeds maximum'); + }); + + it('should warn about very short lease', () => { + const config: LeaseTimeConfig = { + leaseSeconds: 30, + }; + const errors = validateLeaseTimeConfig(config); + expect(errors.length).toBeGreaterThan(0); + expect(errors[0]).toContain('Warning:'); + }); + + it('should warn about very long lease', () => { + const config: LeaseTimeConfig = { + leaseSeconds: 40000000, + }; + const errors = validateLeaseTimeConfig(config); + expect(errors.length).toBeGreaterThan(0); + expect(errors[0]).toContain('Warning:'); + }); + }); + + describe('buildLeaseTimeOption', () => { + it('should build infinite lease', () => { + const config: LeaseTimeConfig = { + leaseSeconds: 0, + infinite: true, + }; + const result = buildLeaseTimeOption(config); + expect(result.leaseSeconds).toBe(0xffffffff); + expect(result.hexEncoded).toBe('ffffffff'); + expect(result.isInfinite).toBe(true); + expect(result.humanReadable).toBe('Infinite'); + }); + + it('should build 24 hour lease', () => { + const config: LeaseTimeConfig = { + leaseSeconds: 86400, + }; + const result = buildLeaseTimeOption(config); + expect(result.leaseSeconds).toBe(86400); + expect(result.hexEncoded).toBe('00015180'); + expect(result.isInfinite).toBe(false); + expect(result.totalLength).toBe(4); + }); + + it('should calculate T1 renewal time', () => { + const config: LeaseTimeConfig = { + leaseSeconds: 86400, + }; + const result = buildLeaseTimeOption(config); + expect(result.t1RenewalSeconds).toBe(43200); // 50% + }); + + it('should calculate T2 rebinding time', () => { + const config: LeaseTimeConfig = { + leaseSeconds: 86400, + }; + const result = buildLeaseTimeOption(config); + expect(result.t2RebindingSeconds).toBe(75600); // 87.5% + }); + + it('should not calculate T1/T2 for infinite lease', () => { + const config: LeaseTimeConfig = { + leaseSeconds: 0, + infinite: true, + }; + const result = buildLeaseTimeOption(config); + expect(result.t1RenewalSeconds).toBeUndefined(); + expect(result.t2RebindingSeconds).toBeUndefined(); + }); + + it('should format wire format with spaces', () => { + const config: LeaseTimeConfig = { + leaseSeconds: 3600, + }; + const result = buildLeaseTimeOption(config); + expect(result.wireFormat).toBe('00 00 0e 10'); + }); + + it('should generate config examples', () => { + const config: LeaseTimeConfig = { + leaseSeconds: 86400, + }; + const result = buildLeaseTimeOption(config); + expect(result.configExamples.iscDhcpd).toContain('default-lease-time'); + expect(result.configExamples.keaDhcp4).toContain('valid-lifetime'); + expect(result.configExamples.dnsmasq).toContain('dhcp-range'); + }); + + it('should build with warnings but not throw', () => { + const config: LeaseTimeConfig = { + leaseSeconds: 30, + }; + expect(() => buildLeaseTimeOption(config)).not.toThrow(); + }); + + it('should throw for invalid config', () => { + const config: LeaseTimeConfig = { + leaseSeconds: -100, + }; + expect(() => buildLeaseTimeOption(config)).toThrow(); + }); + }); + + describe('decodeLeaseTimeOption', () => { + it('should decode infinite lease', () => { + const result = decodeLeaseTimeOption('ffffffff'); + expect(result.leaseSeconds).toBe(0xffffffff); + expect(result.isInfinite).toBe(true); + expect(result.humanReadable).toBe('Infinite'); + }); + + it('should decode 24 hour lease', () => { + const result = decodeLeaseTimeOption('00015180'); + expect(result.leaseSeconds).toBe(86400); + expect(result.isInfinite).toBe(false); + }); + + it('should decode 1 hour lease', () => { + const result = decodeLeaseTimeOption('00000e10'); + expect(result.leaseSeconds).toBe(3600); + }); + + it('should handle hex with spaces', () => { + const result = decodeLeaseTimeOption('00 01 51 80'); + expect(result.leaseSeconds).toBe(86400); + }); + + it('should handle uppercase hex', () => { + const result = decodeLeaseTimeOption('00015180'); + expect(result.leaseSeconds).toBe(86400); + }); + + it('should calculate T1 and T2 for decoded lease', () => { + const result = decodeLeaseTimeOption('00015180'); + expect(result.t1RenewalSeconds).toBe(43200); + expect(result.t2RebindingSeconds).toBe(75600); + }); + + it('should not calculate T1/T2 for infinite lease', () => { + const result = decodeLeaseTimeOption('ffffffff'); + expect(result.t1RenewalSeconds).toBeUndefined(); + expect(result.t2RebindingSeconds).toBeUndefined(); + }); + + it('should throw error for empty hex', () => { + expect(() => decodeLeaseTimeOption('')).toThrow('empty'); + }); + + it('should throw error for invalid hex', () => { + expect(() => decodeLeaseTimeOption('zzzz')).toThrow('Invalid hex'); + }); + + it('should throw error for incorrect length', () => { + expect(() => decodeLeaseTimeOption('0001')).toThrow('exactly 8 characters'); + }); + + it('should generate config examples for decoded value', () => { + const result = decodeLeaseTimeOption('00015180'); + expect(result.configExamples.iscDhcpd).toBeDefined(); + expect(result.configExamples.keaDhcp4).toBeDefined(); + expect(result.configExamples.dnsmasq).toBeDefined(); + }); + }); +}); diff --git a/tests/unit/utils/dhcp-options6-15-dns.test.ts b/tests/unit/utils/dhcp-options6-15-dns.test.ts new file mode 100644 index 0000000..9ac2b03 --- /dev/null +++ b/tests/unit/utils/dhcp-options6-15-dns.test.ts @@ -0,0 +1,240 @@ +import { describe, it, expect } from 'vitest'; +import { + validateDNSConfig, + buildDNSOptions, + decodeDNSServersOption, + decodeDomainNameOption, + type DNSConfig, +} from '$lib/utils/dhcp-options6-15-dns'; + +describe('dhcp-options6-15-dns', () => { + describe('validateDNSConfig', () => { + it('should require at least one DNS server or domain', () => { + const config: DNSConfig = { + dnsServers: [], + }; + const errors = validateDNSConfig(config); + expect(errors.length).toBeGreaterThan(0); + expect(errors[0]).toContain('At least one DNS server or domain name'); + }); + + it('should validate IPv4 DNS servers', () => { + const config: DNSConfig = { + dnsServers: ['invalid-ip'], + }; + const errors = validateDNSConfig(config); + expect(errors.length).toBeGreaterThan(0); + expect(errors[0]).toContain('Invalid IPv4 address'); + }); + + it('should accept valid DNS servers', () => { + const config: DNSConfig = { + dnsServers: ['8.8.8.8', '8.8.4.4'], + }; + const errors = validateDNSConfig(config); + expect(errors).toEqual([]); + }); + + it('should validate domain name format', () => { + const config: DNSConfig = { + dnsServers: [], + domainName: '-invalid-.com', + }; + const errors = validateDNSConfig(config); + expect(errors.length).toBeGreaterThan(0); + expect(errors[0]).toContain('Invalid domain name'); + }); + + it('should accept valid domain names', () => { + const config: DNSConfig = { + dnsServers: [], + domainName: 'example.com', + }; + const errors = validateDNSConfig(config); + expect(errors).toEqual([]); + }); + + it('should accept domain with trailing dot', () => { + const config: DNSConfig = { + dnsServers: [], + domainName: 'example.com.', + }; + const errors = validateDNSConfig(config); + expect(errors).toEqual([]); + }); + + it('should detect duplicate DNS servers', () => { + const config: DNSConfig = { + dnsServers: ['8.8.8.8', '8.8.8.8'], + }; + const errors = validateDNSConfig(config); + expect(errors.length).toBeGreaterThan(0); + expect(errors[0]).toContain('Duplicate'); + }); + + it('should skip empty entries', () => { + const config: DNSConfig = { + dnsServers: ['8.8.8.8', ''], + domainName: 'example.com', + }; + const errors = validateDNSConfig(config); + expect(errors).toEqual([]); + }); + }); + + describe('buildDNSOptions', () => { + it('should build Option 6 for DNS servers', () => { + const config: DNSConfig = { + dnsServers: ['8.8.8.8'], + }; + const result = buildDNSOptions(config); + expect(result.option6).toBeDefined(); + expect(result.option6!.servers).toEqual(['8.8.8.8']); + expect(result.option6!.hexEncoded).toBe('08080808'); + expect(result.option6!.totalLength).toBe(4); + }); + + it('should build Option 6 for multiple DNS servers', () => { + const config: DNSConfig = { + dnsServers: ['8.8.8.8', '8.8.4.4'], + }; + const result = buildDNSOptions(config); + expect(result.option6!.servers).toEqual(['8.8.8.8', '8.8.4.4']); + expect(result.option6!.hexEncoded).toBe('0808080808080404'); + expect(result.option6!.totalLength).toBe(8); + }); + + it('should build Option 15 for domain name', () => { + const config: DNSConfig = { + dnsServers: [], + domainName: 'example.com', + }; + const result = buildDNSOptions(config); + expect(result.option15).toBeDefined(); + expect(result.option15!.domain).toBe('example.com'); + expect(result.option15!.hexEncoded).toBe('6578616d706c652e636f6d'); + }); + + it('should build both options when provided', () => { + const config: DNSConfig = { + dnsServers: ['8.8.8.8'], + domainName: 'example.com', + }; + const result = buildDNSOptions(config); + expect(result.option6).toBeDefined(); + expect(result.option15).toBeDefined(); + }); + + it('should format wire format with spaces', () => { + const config: DNSConfig = { + dnsServers: ['8.8.8.8'], + }; + const result = buildDNSOptions(config); + expect(result.option6!.wireFormat).toBe('08 08 08 08'); + }); + + it('should skip empty DNS servers', () => { + const config: DNSConfig = { + dnsServers: ['8.8.8.8', '', '8.8.4.4'], + }; + const result = buildDNSOptions(config); + expect(result.option6!.servers).toEqual(['8.8.8.8', '8.8.4.4']); + }); + + it('should handle domain with trailing dot', () => { + const config: DNSConfig = { + dnsServers: [], + domainName: 'example.com.', + }; + const result = buildDNSOptions(config); + expect(result.option15!.domain).toBe('example.com'); + }); + + it('should generate config examples', () => { + const config: DNSConfig = { + dnsServers: ['8.8.8.8'], + domainName: 'example.com', + }; + const result = buildDNSOptions(config); + expect(result.configExamples.iscDhcpd).toContain('domain-name-servers'); + expect(result.configExamples.iscDhcpd).toContain('domain-name'); + expect(result.configExamples.keaDhcp4).toContain('"code": 6'); + expect(result.configExamples.keaDhcp4).toContain('"code": 15'); + expect(result.configExamples.dnsmasq).toContain('dhcp-option=6'); + expect(result.configExamples.dnsmasq).toContain('dhcp-option=15'); + }); + + it('should throw error for invalid config', () => { + const config: DNSConfig = { + dnsServers: ['invalid-ip'], + }; + expect(() => buildDNSOptions(config)).toThrow(); + }); + }); + + describe('decodeDNSServersOption', () => { + it('should decode single DNS server', () => { + const result = decodeDNSServersOption('08080808'); + expect(result!.servers).toEqual(['8.8.8.8']); + expect(result!.totalLength).toBe(4); + }); + + it('should decode multiple DNS servers', () => { + const result = decodeDNSServersOption('0808080808080404'); + expect(result!.servers).toEqual(['8.8.8.8', '8.8.4.4']); + expect(result!.totalLength).toBe(8); + }); + + it('should handle hex with spaces', () => { + const result = decodeDNSServersOption('08 08 08 08'); + expect(result!.servers).toEqual(['8.8.8.8']); + }); + + it('should handle uppercase hex', () => { + const result = decodeDNSServersOption('08080808'); + expect(result!.servers).toEqual(['8.8.8.8']); + }); + + it('should throw error for empty hex', () => { + expect(() => decodeDNSServersOption('')).toThrow('empty'); + }); + + it('should throw error for invalid hex', () => { + expect(() => decodeDNSServersOption('zzzz')).toThrow('Invalid hex'); + }); + + it('should throw error for incorrect length', () => { + expect(() => decodeDNSServersOption('080808')).toThrow('multiple of 8'); + }); + }); + + describe('decodeDomainNameOption', () => { + it('should decode domain name', () => { + const result = decodeDomainNameOption('6578616d706c652e636f6d'); + expect(result!.domain).toBe('example.com'); + }); + + it('should handle hex with spaces', () => { + const result = decodeDomainNameOption('65 78 61 6d 70 6c 65 2e 63 6f 6d'); + expect(result!.domain).toBe('example.com'); + }); + + it('should handle uppercase hex', () => { + const result = decodeDomainNameOption('6578616D706C652E636F6D'); + expect(result!.domain).toBe('example.com'); + }); + + it('should throw error for empty hex', () => { + expect(() => decodeDomainNameOption('')).toThrow('empty'); + }); + + it('should throw error for invalid hex', () => { + expect(() => decodeDomainNameOption('zzzz')).toThrow('Invalid hex'); + }); + + it('should throw error for invalid domain', () => { + // Invalid domain characters + expect(() => decodeDomainNameOption('2d2d2d')).toThrow('invalid'); + }); + }); +}); diff --git a/tests/unit/utils/dhcpv6-fqdn-rfc4704.test.ts b/tests/unit/utils/dhcpv6-fqdn-rfc4704.test.ts new file mode 100644 index 0000000..4a7eeb8 --- /dev/null +++ b/tests/unit/utils/dhcpv6-fqdn-rfc4704.test.ts @@ -0,0 +1,265 @@ +import { describe, it, expect } from 'vitest'; +import { + validateFQDNConfig, + buildFQDNOption, + getDefaultFQDNConfig, + type FQDNConfig, +} from '$lib/utils/dhcpv6-fqdn-rfc4704'; + +describe('dhcpv6-fqdn-rfc4704', () => { + describe('validateFQDNConfig', () => { + it('should require FQDN', () => { + const emptyConfig: FQDNConfig = { + fqdn: '', + serverShouldUpdate: false, + serverOverride: false, + clientShouldUpdate: false, + }; + const errors = validateFQDNConfig(emptyConfig); + expect(errors.length).toBeGreaterThan(0); + expect(errors[0]).toContain('FQDN is required'); + }); + + it('should validate FQDN format', () => { + const invalidConfig: FQDNConfig = { + fqdn: '-invalid-.com', + serverShouldUpdate: false, + serverOverride: false, + clientShouldUpdate: false, + }; + const errors = validateFQDNConfig(invalidConfig); + expect(errors.length).toBeGreaterThan(0); + expect(errors[0]).toContain('Invalid FQDN format'); + }); + + it('should accept valid FQDNs', () => { + const validConfig: FQDNConfig = { + fqdn: 'client.example.com', + serverShouldUpdate: true, + serverOverride: false, + clientShouldUpdate: false, + }; + const errors = validateFQDNConfig(validConfig); + expect(errors).toEqual([]); + }); + + it('should reject when both client and server should update', () => { + const invalidConfig: FQDNConfig = { + fqdn: 'client.example.com', + serverShouldUpdate: true, + serverOverride: false, + clientShouldUpdate: true, + }; + const errors = validateFQDNConfig(invalidConfig); + expect(errors.length).toBeGreaterThan(0); + expect(errors[0]).toContain('Both client and server cannot be set to update'); + }); + + it('should accept single-label domains', () => { + const validConfig: FQDNConfig = { + fqdn: 'localhost', + serverShouldUpdate: true, + serverOverride: false, + clientShouldUpdate: false, + }; + const errors = validateFQDNConfig(validConfig); + expect(errors).toEqual([]); + }); + + it('should accept multi-level subdomains', () => { + const validConfig: FQDNConfig = { + fqdn: 'workstation.corp.internal.example.com', + serverShouldUpdate: true, + serverOverride: false, + clientShouldUpdate: false, + }; + const errors = validateFQDNConfig(validConfig); + expect(errors).toEqual([]); + }); + }); + + describe('buildFQDNOption', () => { + it('should build FQDN option with server update flag', () => { + const config: FQDNConfig = { + fqdn: 'client.example.com', + serverShouldUpdate: true, + serverOverride: false, + clientShouldUpdate: false, + }; + const result = buildFQDNOption(config); + expect(result.fqdn).toBe('client.example.com'); + expect(result.flags.S).toBe(true); + expect(result.flags.O).toBe(false); + expect(result.flags.N).toBe(true); // N=1 means client should NOT update + }); + + it('should encode FQDN in DNS wire format', () => { + const config: FQDNConfig = { + fqdn: 'example.com', + serverShouldUpdate: false, + serverOverride: false, + clientShouldUpdate: false, + }; + const result = buildFQDNOption(config); + // Should be: flags(1 byte) + 07(example length) + example + 03(com length) + com + 00(null) + expect(result.hexEncoded).toContain('076578616d706c6503636f6d00'); + }); + + it('should set S flag correctly', () => { + const config: FQDNConfig = { + fqdn: 'test.com', + serverShouldUpdate: true, + serverOverride: false, + clientShouldUpdate: false, + }; + const result = buildFQDNOption(config); + expect(result.flags.S).toBe(true); + expect(result.flags.flagsByte).toBe('05'); // S=1, N=1 (0b00000101) + }); + + it('should set O flag correctly', () => { + const config: FQDNConfig = { + fqdn: 'test.com', + serverShouldUpdate: true, + serverOverride: true, + clientShouldUpdate: false, + }; + const result = buildFQDNOption(config); + expect(result.flags.O).toBe(true); + expect(result.flags.flagsByte).toBe('07'); // S=1, O=1, N=1 (0b00000111) + }); + + it('should set N flag correctly when client should update', () => { + const config: FQDNConfig = { + fqdn: 'test.com', + serverShouldUpdate: false, + serverOverride: false, + clientShouldUpdate: true, + }; + const result = buildFQDNOption(config); + expect(result.flags.N).toBe(false); // N=0 means client WILL update + expect(result.flags.flagsByte).toBe('00'); // All flags = 0 + }); + + it('should generate wire format with spaces', () => { + const config: FQDNConfig = { + fqdn: 'test.com', + serverShouldUpdate: false, + serverOverride: false, + clientShouldUpdate: false, + }; + const result = buildFQDNOption(config); + expect(result.wireFormat).toContain(' '); + expect(result.wireFormat.split(' ').length).toBeGreaterThan(1); + }); + + it('should calculate total length correctly', () => { + const config: FQDNConfig = { + fqdn: 'example.com', + serverShouldUpdate: false, + serverOverride: false, + clientShouldUpdate: false, + }; + const result = buildFQDNOption(config); + // 1 byte (flags) + 1 byte (len) + 7 bytes (example) + 1 byte (len) + 3 bytes (com) + 1 byte (null) = 14 + expect(result.totalLength).toBe(14); + }); + + it('should generate Kea configuration example', () => { + const config: FQDNConfig = { + fqdn: 'client.example.com', + serverShouldUpdate: true, + serverOverride: false, + clientShouldUpdate: false, + }; + const result = buildFQDNOption(config); + expect(result.examples.keaDhcp6).toBeDefined(); + expect(result.examples.keaDhcp6).toContain('ddns-send-updates'); + expect(result.examples.keaDhcp6).toContain('true'); + }); + + it('should generate Kea config with client updates', () => { + const config: FQDNConfig = { + fqdn: 'client.example.com', + serverShouldUpdate: false, + serverOverride: false, + clientShouldUpdate: true, + }; + const result = buildFQDNOption(config); + expect(result.examples.keaDhcp6).toBeDefined(); + expect(result.examples.keaDhcp6).toContain('ddns-send-updates'); + expect(result.examples.keaDhcp6).toContain('false'); + }); + + it('should provide flag descriptions', () => { + const config: FQDNConfig = { + fqdn: 'test.com', + serverShouldUpdate: true, + serverOverride: true, + clientShouldUpdate: false, + }; + const result = buildFQDNOption(config); + expect(result.flags.description.length).toBe(3); + expect(result.flags.description[0]).toContain('S=1'); + expect(result.flags.description[1]).toContain('O=1'); + expect(result.flags.description[2]).toContain('N=1'); + }); + + it('should provide encoding breakdown', () => { + const config: FQDNConfig = { + fqdn: 'test.com', + serverShouldUpdate: false, + serverOverride: false, + clientShouldUpdate: false, + }; + const result = buildFQDNOption(config); + expect(result.breakdown.flags).toBeDefined(); + expect(result.breakdown.fqdn).toBeDefined(); + }); + + it('should throw error for invalid configuration', () => { + const invalidConfig: FQDNConfig = { + fqdn: '', + serverShouldUpdate: false, + serverOverride: false, + clientShouldUpdate: false, + }; + expect(() => buildFQDNOption(invalidConfig)).toThrow(); + }); + + it('should handle subdomain FQDN correctly', () => { + const config: FQDNConfig = { + fqdn: 'workstation.corp.example.com', + serverShouldUpdate: true, + serverOverride: false, + clientShouldUpdate: false, + }; + const result = buildFQDNOption(config); + expect(result.fqdn).toBe('workstation.corp.example.com'); + expect(result.totalLength).toBeGreaterThan(0); + }); + + it('should handle single-label domain', () => { + const config: FQDNConfig = { + fqdn: 'localhost', + serverShouldUpdate: false, + serverOverride: false, + clientShouldUpdate: false, + }; + const result = buildFQDNOption(config); + expect(result.fqdn).toBe('localhost'); + // 1 byte (flags) + 1 byte (len) + 9 bytes (localhost) + 1 byte (null) = 12 + expect(result.totalLength).toBe(12); + }); + }); + + describe('getDefaultFQDNConfig', () => { + it('should return default configuration', () => { + const defaultConfig = getDefaultFQDNConfig(); + expect(defaultConfig.fqdn).toBe(''); + expect(defaultConfig.serverShouldUpdate).toBe(true); + expect(defaultConfig.serverOverride).toBe(false); + expect(defaultConfig.clientShouldUpdate).toBe(false); + }); + }); +}); diff --git a/tests/unit/utils/dhcpv6-prefix-delegation.test.ts b/tests/unit/utils/dhcpv6-prefix-delegation.test.ts new file mode 100644 index 0000000..34d5353 --- /dev/null +++ b/tests/unit/utils/dhcpv6-prefix-delegation.test.ts @@ -0,0 +1,214 @@ +import { describe, it, expect } from 'vitest'; +import { + validatePrefixDelegationConfig, + buildPrefixDelegation, + formatTime, + type PrefixDelegationConfig, +} from '$lib/utils/dhcpv6-prefix-delegation'; + +describe('dhcpv6-prefix-delegation', () => { + describe('validatePrefixDelegationConfig', () => { + it('should validate IAID range', () => { + const config: PrefixDelegationConfig = { + iaid: -1, + prefixes: [{ prefix: '2001:db8::/56' }], + }; + const errors = validatePrefixDelegationConfig(config); + expect(errors.length).toBeGreaterThan(0); + expect(errors[0]).toContain('IAID must be between'); + }); + + it('should validate T1/T2 relationship', () => { + const config: PrefixDelegationConfig = { + iaid: 1, + t1: 1000, + t2: 500, + prefixes: [{ prefix: '2001:db8::/56' }], + }; + const errors = validatePrefixDelegationConfig(config); + expect(errors.some((e) => e.includes('T1 must be less than'))).toBe(true); + }); + + it('should require at least one prefix', () => { + const config: PrefixDelegationConfig = { + iaid: 1, + prefixes: [], + }; + const errors = validatePrefixDelegationConfig(config); + expect(errors.some((e) => e.includes('At least one prefix'))).toBe(true); + }); + + it('should validate IPv6 prefix format', () => { + const config: PrefixDelegationConfig = { + iaid: 1, + prefixes: [{ prefix: 'invalid' }], + }; + const errors = validatePrefixDelegationConfig(config); + expect(errors.some((e) => e.includes('Invalid IPv6 prefix'))).toBe(true); + }); + + it('should validate lifetime relationship', () => { + const config: PrefixDelegationConfig = { + iaid: 1, + prefixes: [ + { + prefix: '2001:db8::/56', + preferredLifetime: 1000, + validLifetime: 500, + }, + ], + }; + const errors = validatePrefixDelegationConfig(config); + expect(errors.some((e) => e.includes('Preferred lifetime must be'))).toBe(true); + }); + + it('should accept valid configuration', () => { + const config: PrefixDelegationConfig = { + iaid: 1, + t1: 300, + t2: 500, + prefixes: [ + { + prefix: '2001:db8::/56', + preferredLifetime: 600, + validLifetime: 1000, + }, + ], + }; + const errors = validatePrefixDelegationConfig(config); + expect(errors).toEqual([]); + }); + }); + + describe('buildPrefixDelegation', () => { + it('should build basic IA_PD option', () => { + const config: PrefixDelegationConfig = { + iaid: 1, + prefixes: [{ prefix: '2001:db8::/56' }], + }; + const result = buildPrefixDelegation(config); + expect(result).toBeDefined(); + expect(result.iaid).toBe(1); + expect(result.iaidHex).toBe('00000001'); + }); + + it('should handle multiple prefixes', () => { + const config: PrefixDelegationConfig = { + iaid: 1, + prefixes: [{ prefix: '2001:db8:1::/56' }, { prefix: '2001:db8:2::/56' }], + }; + const result = buildPrefixDelegation(config); + expect(result.prefixes.length).toBe(2); + }); + + it('should encode prefix correctly', () => { + const config: PrefixDelegationConfig = { + iaid: 1, + prefixes: [ + { + prefix: '2001:db8::/56', + preferredLifetime: 604800, + validLifetime: 2592000, + }, + ], + }; + const result = buildPrefixDelegation(config); + expect(result.prefixes[0].prefixLength).toBe(56); + expect(result.prefixes[0].preferredLifetimeHex).toBe('00093a80'); + expect(result.prefixes[0].validLifetimeHex).toBe('00278d00'); + }); + + it('should format T1/T2 correctly', () => { + const config: PrefixDelegationConfig = { + iaid: 1, + t1: 86400, + t2: 138240, + prefixes: [{ prefix: '2001:db8::/56' }], + }; + const result = buildPrefixDelegation(config); + expect(result.t1).toBe(86400); + expect(result.t2).toBe(138240); + expect(result.t1Hex).toBe('00015180'); + expect(result.t2Hex).toBe('00021c00'); + }); + + it('should generate wire format', () => { + const config: PrefixDelegationConfig = { + iaid: 1, + prefixes: [{ prefix: '2001:db8::/56' }], + }; + const result = buildPrefixDelegation(config); + expect(result.fullWireFormat).toContain(' '); + expect(result.totalLength).toBeGreaterThan(0); + }); + + it('should generate Kea config example', () => { + const config: PrefixDelegationConfig = { + iaid: 1, + prefixes: [{ prefix: '2001:db8::/56' }], + }; + const result = buildPrefixDelegation(config); + expect(result.examples.keaDhcp6).toBeDefined(); + expect(result.examples.keaDhcp6).toContain('pd-pools'); + }); + + it('should handle compressed IPv6 addresses', () => { + const config: PrefixDelegationConfig = { + iaid: 1, + prefixes: [{ prefix: '2001:db8::1/64' }], + }; + const result = buildPrefixDelegation(config); + expect(result.prefixes[0].prefixLength).toBe(64); + }); + + it('should handle zero T1/T2', () => { + const config: PrefixDelegationConfig = { + iaid: 1, + t1: 0, + t2: 0, + prefixes: [{ prefix: '2001:db8::/56' }], + }; + const result = buildPrefixDelegation(config); + expect(result.t1).toBe(0); + expect(result.t2).toBe(0); + }); + + it('should throw on invalid config', () => { + const config: PrefixDelegationConfig = { + iaid: -1, + prefixes: [{ prefix: 'invalid' }], + }; + expect(() => buildPrefixDelegation(config)).toThrow(); + }); + }); + + describe('formatTime', () => { + it('should format infinite time', () => { + expect(formatTime(0xffffffff)).toBe('Infinite'); + }); + + it('should format zero', () => { + expect(formatTime(0)).toBe('0 seconds'); + }); + + it('should format days', () => { + expect(formatTime(86400)).toBe('1d'); + }); + + it('should format complex durations', () => { + const result = formatTime(90061); // 1d 1h 1m 1s + expect(result).toContain('1d'); + expect(result).toContain('1h'); + expect(result).toContain('1m'); + expect(result).toContain('1s'); + }); + + it('should format hours and minutes', () => { + expect(formatTime(3661)).toBe('1h 1m 1s'); + }); + + it('should format only seconds', () => { + expect(formatTime(42)).toBe('42s'); + }); + }); +});