From 72471379105e069ec325a8f563ce1b7b41c3b92b Mon Sep 17 00:00:00 2001 From: jacobyoby Date: Tue, 8 Sep 2026 01:24:19 -0700 Subject: [PATCH 1/2] fix(wizard): select the routed interface --- README.md | 4 +- examples/New-NetworkDiagram.ps1 | 187 ++++++++++++++++++++++---------- tests/NetDiagram.Tests.ps1 | 64 +++++++++++ 3 files changed, 197 insertions(+), 58 deletions(-) diff --git a/README.md b/README.md index 208fa2f..989979a 100644 --- a/README.md +++ b/README.md @@ -80,6 +80,9 @@ pwsh .\examples\New-NetworkDiagram.ps1 -ScanDepth Medium # Full scan (all 254 IPs, ~2 minutes) pwsh .\examples\New-NetworkDiagram.ps1 -ScanDepth Full -OutputPath .\office-network.drawio + +# Choose an interface explicitly (useful with VPNs or multiple adapters) +pwsh .\examples\New-NetworkDiagram.ps1 -InterfaceName en0 ``` ### Method 2: Manual Workflow (manual inventory) @@ -419,4 +422,3 @@ Import-Inventory my-network-inventory.json | Export-DrawIO -OutFile my-network.d 2. Check command help: `Get-Help -Examples` 3. Review example files in `examples/` 4. Report issues with detailed error messages - diff --git a/examples/New-NetworkDiagram.ps1 b/examples/New-NetworkDiagram.ps1 index a3fc7e3..266f865 100644 --- a/examples/New-NetworkDiagram.ps1 +++ b/examples/New-NetworkDiagram.ps1 @@ -13,6 +13,9 @@ larger subnets). Host addresses are derived from the interface's real CIDR prefix. .PARAMETER OutputPath Where to save the diagram (default: .\my-network.drawio) +.PARAMETER InterfaceName + Interface name or numeric interface index to scan. By default, the interface + used by the active IPv4 default route is selected. .EXAMPLE .\New-NetworkDiagram.ps1 @@ -28,7 +31,9 @@ param( [ValidateSet('Quick', 'Medium', 'Full')] [string]$ScanDepth = 'Quick', - [string]$OutputPath = '.\my-network.drawio' + [string]$OutputPath = '.\my-network.drawio', + + [string]$InterfaceName ) function Get-WizardInventoryPath { @@ -134,6 +139,94 @@ function Get-InventoryOutputPath { return $inventoryPath } +function Select-ScanInterface { + param( + [Parameter(Mandatory)][object[]]$Interfaces, + [string]$RequestedInterface, + [string]$DefaultInterfaceName, + [Nullable[int]]$DefaultInterfaceIndex + ) + + if ($Interfaces.Count -eq 0) { + throw 'No active IPv4 network interfaces were found.' + } + + if (-not [string]::IsNullOrWhiteSpace($RequestedInterface)) { + $matchingInterfaces = @($Interfaces | Where-Object { + $_.Name -eq $RequestedInterface -or + ($null -ne $_.Index -and "$($_.Index)" -eq $RequestedInterface) + }) + if ($matchingInterfaces.Count -eq 0) { + throw "Network interface '$RequestedInterface' was not found. Available interfaces: $($Interfaces.Name -join ', ')" + } + if ($matchingInterfaces.Count -gt 1) { + throw "Network interface '$RequestedInterface' is ambiguous. Use its numeric interface index." + } + return $matchingInterfaces[0] + } + + $routeMatches = @($Interfaces | Where-Object { + (-not [string]::IsNullOrWhiteSpace($DefaultInterfaceName) -and $_.Name -eq $DefaultInterfaceName) -or + ($null -ne $DefaultInterfaceIndex -and $_.Index -eq $DefaultInterfaceIndex) + }) + if ($routeMatches.Count -eq 1) { + return $routeMatches[0] + } + if ($routeMatches.Count -gt 1) { + throw 'The default route maps to multiple IPv4 addresses. Select one with -InterfaceName.' + } + if ($Interfaces.Count -eq 1) { + return $Interfaces[0] + } + + throw 'No IPv4 default-route interface could be selected. Use -InterfaceName with an available interface name or index.' +} + +function ConvertFrom-MacOSInterfaceText { + param([Parameter(Mandatory)][string[]]$Lines) + + $name = $null + foreach ($line in $Lines) { + if ($line -match '^([^\s:]+):\s') { + $name = $matches[1] + continue + } + if ($name -and $line -match '^\s+inet\s+(\d+\.\d+\.\d+\.\d+)(?:\s+-->\s+\d+\.\d+\.\d+\.\d+)?\s+netmask\s+0x([0-9a-fA-F]+)') { + if ($matches[1] -eq '127.0.0.1') { continue } + $binaryMask = [Convert]::ToString([Convert]::ToInt64($matches[2], 16), 2) + [pscustomobject]@{ + Name = $name + Index = $null + IPAddress = $matches[1] + PrefixLength = ($binaryMask.ToCharArray() | Where-Object { $_ -eq '1' }).Count + } + } + } +} + +function ConvertFrom-LinuxInterfaceText { + param([Parameter(Mandatory)][string[]]$Lines) + + $name = $null + $index = $null + foreach ($line in $Lines) { + if ($line -match '^(\d+):\s+([^:@]+)(?:@[^:]+)?:') { + $index = [int]$matches[1] + $name = $matches[2] + continue + } + if ($name -and $line -match '^\s+inet\s+(\d+\.\d+\.\d+\.\d+)/(\d+)') { + if ($matches[1] -eq '127.0.0.1') { continue } + [pscustomobject]@{ + Name = $name + Index = $index + IPAddress = $matches[1] + PrefixLength = [int]$matches[2] + } + } + } +} + # Allow the Pester suite to dot-source this script for the pure helper functions above # without launching the interactive wizard (which performs a live network scan). if ($MyInvocation.InvocationName -eq '.') { return } @@ -158,26 +251,29 @@ Write-Host "[1/5] Discovering your network configuration..." -ForegroundColor Ye # Cross-platform network discovery if ($IsWindows -or $PSVersionTable.PSVersion.Major -lt 6 -or $null -eq $IsWindows) { # Windows: Use native cmdlets - $interfaces = Get-NetIPAddress -AddressFamily IPv4 -ErrorAction SilentlyContinue | Where-Object { + $interfaces = @(Get-NetIPAddress -AddressFamily IPv4 -ErrorAction SilentlyContinue | Where-Object { $_.IPAddress -ne '127.0.0.1' -and $_.PrefixOrigin -ne 'WellKnown' - } - - if ($interfaces.Count -eq 0) { - Write-Host "✗ No active network interfaces found!" -ForegroundColor Red - exit 1 - } - - $primaryInterface = $interfaces | Select-Object -First 1 - $myIP = $primaryInterface.IPAddress - $prefix = $primaryInterface.PrefixLength + } | ForEach-Object { + [pscustomobject]@{ + Name = $_.InterfaceAlias + Index = $_.InterfaceIndex + IPAddress = $_.IPAddress + PrefixLength = $_.PrefixLength + } + }) # Get gateway $routes = Get-NetRoute -AddressFamily IPv4 -DestinationPrefix '0.0.0.0/0' -ErrorAction SilentlyContinue | Where-Object { $_.NextHop -ne '0.0.0.0' } - $gateway = $routes | Select-Object -First 1 -ExpandProperty NextHop + $defaultRoute = $routes | Sort-Object RouteMetric | Select-Object -First 1 + $primaryInterface = Select-ScanInterface -Interfaces $interfaces -RequestedInterface $InterfaceName ` + -DefaultInterfaceIndex $defaultRoute.InterfaceIndex + $selectedRoute = $routes | Where-Object { $_.InterfaceIndex -eq $primaryInterface.Index } | + Sort-Object RouteMetric | Select-Object -First 1 + $gateway = $selectedRoute.NextHop # Get DNS - $dnsServers = @(Get-DnsClientServerAddress -AddressFamily IPv4 -ErrorAction SilentlyContinue | + $dnsServers = @(Get-DnsClientServerAddress -AddressFamily IPv4 -InterfaceIndex $primaryInterface.Index -ErrorAction SilentlyContinue | Where-Object { $_.ServerAddresses.Count -gt 0 } | Select-Object -ExpandProperty ServerAddresses -Unique | Where-Object { $_ -notmatch '^(127\.|::1|fe80:)' } | @@ -187,35 +283,23 @@ if ($IsWindows -or $PSVersionTable.PSVersion.Major -lt 6 -or $null -eq $IsWindow if ($IsMacOS) { # Use ifconfig on macOS $ifconfigOutput = & ifconfig -a 2>&1 - $ifconfigText = $ifconfigOutput -join "`n" - - # Parse for active IPv4 addresses - $ipMatches = [regex]::Matches($ifconfigText, 'inet\s+(\d+\.\d+\.\d+\.\d+)\s+netmask\s+0x([0-9a-f]+)') - $interfaces = @() - - foreach ($match in $ipMatches) { - $ip = $match.Groups[1].Value - if ($ip -ne '127.0.0.1') { - # Convert hex netmask to prefix length - $hexMask = $match.Groups[2].Value - $binaryMask = [Convert]::ToString([Convert]::ToInt64($hexMask, 16), 2) - $prefix = ($binaryMask.ToCharArray() | Where-Object { $_ -eq '1' }).Count - - $interfaces += [PSCustomObject]@{ - IPAddress = $ip - PrefixLength = $prefix - } - } - } + $interfaces = @(ConvertFrom-MacOSInterfaceText -Lines $ifconfigOutput) # Get default gateway using route command $routeOutput = & route -n get default 2>&1 $gatewayMatch = [regex]::Match(($routeOutput -join "`n"), 'gateway:\s+(\d+\.\d+\.\d+\.\d+)') + $routeInterfaceMatch = [regex]::Match(($routeOutput -join "`n"), 'interface:\s+(\S+)') if ($gatewayMatch.Success) { $gateway = $gatewayMatch.Groups[1].Value } else { $gateway = $null } + $defaultInterfaceName = if ($routeInterfaceMatch.Success) { $routeInterfaceMatch.Groups[1].Value } else { $null } + $primaryInterface = Select-ScanInterface -Interfaces $interfaces -RequestedInterface $InterfaceName ` + -DefaultInterfaceName $defaultInterfaceName + if ($InterfaceName -and $primaryInterface.Name -ne $defaultInterfaceName) { + $gateway = $null + } # Get DNS servers from /etc/resolv.conf or scutil $dnsOutput = & scutil --dns 2>&1 @@ -234,30 +318,23 @@ if ($IsWindows -or $PSVersionTable.PSVersion.Major -lt 6 -or $null -eq $IsWindow } elseif ($IsLinux) { # Use ip command on Linux $ipOutput = & ip -4 addr show 2>&1 - $ipText = $ipOutput -join "`n" - - # Parse for active IPv4 addresses - $ipMatches = [regex]::Matches($ipText, 'inet\s+(\d+\.\d+\.\d+\.\d+)/(\d+)') - $interfaces = @() - - foreach ($match in $ipMatches) { - $ip = $match.Groups[1].Value - if ($ip -ne '127.0.0.1') { - $interfaces += [PSCustomObject]@{ - IPAddress = $ip - PrefixLength = [int]$match.Groups[2].Value - } - } - } + $interfaces = @(ConvertFrom-LinuxInterfaceText -Lines $ipOutput) # Get default gateway $routeOutput = & ip route show default 2>&1 $gatewayMatch = [regex]::Match(($routeOutput -join "`n"), 'default\s+via\s+(\d+\.\d+\.\d+\.\d+)') + $routeInterfaceMatch = [regex]::Match(($routeOutput -join "`n"), '\bdev\s+(\S+)') if ($gatewayMatch.Success) { $gateway = $gatewayMatch.Groups[1].Value } else { $gateway = $null } + $defaultInterfaceName = if ($routeInterfaceMatch.Success) { $routeInterfaceMatch.Groups[1].Value } else { $null } + $primaryInterface = Select-ScanInterface -Interfaces $interfaces -RequestedInterface $InterfaceName ` + -DefaultInterfaceName $defaultInterfaceName + if ($InterfaceName -and $primaryInterface.Name -ne $defaultInterfaceName) { + $gateway = $null + } # Get DNS servers from /etc/resolv.conf $dnsServers = @() @@ -268,18 +345,14 @@ if ($IsWindows -or $PSVersionTable.PSVersion.Major -lt 6 -or $null -eq $IsWindow } } - if ($interfaces.Count -eq 0) { - Write-Host "✗ No active network interfaces found!" -ForegroundColor Red - exit 1 - } - - $primaryInterface = $interfaces | Select-Object -First 1 - $myIP = $primaryInterface.IPAddress - $prefix = $primaryInterface.PrefixLength } +$myIP = $primaryInterface.IPAddress +$prefix = $primaryInterface.PrefixLength + Write-Host " Found $($interfaces.Count) active network interface(s)" -ForegroundColor Green +Write-Host " Interface: $($primaryInterface.Name)" -ForegroundColor Cyan Write-Host " Your IP: $myIP/$prefix" -ForegroundColor Cyan Write-Host " Gateway: $gateway" -ForegroundColor Cyan Write-Host " DNS: $($dnsServers -join ', ')" -ForegroundColor Cyan diff --git a/tests/NetDiagram.Tests.ps1 b/tests/NetDiagram.Tests.ps1 index c14204b..aa790d1 100644 --- a/tests/NetDiagram.Tests.ps1 +++ b/tests/NetDiagram.Tests.ps1 @@ -683,3 +683,67 @@ Describe 'Quick-start wizard output paths (#9 regression)' { Should -Not -Be ([System.IO.Path]::GetFullPath($diagramPath)) } } + +Describe 'Quick-start wizard interface selection (#15 regression)' { + BeforeAll { + $exampleScript = Join-Path $PSScriptRoot '..' 'examples' 'New-NetworkDiagram.ps1' + . $exampleScript + } + + It 'Selects the Windows address attached to the default route index' { + $interfaces = @( + [pscustomobject]@{ Name = 'VPN'; Index = 7; IPAddress = '10.8.0.2'; PrefixLength = 24 } + [pscustomobject]@{ Name = 'Ethernet'; Index = 12; IPAddress = '192.168.1.20'; PrefixLength = 24 } + ) + + $selected = Select-ScanInterface -Interfaces $interfaces -DefaultInterfaceIndex 12 + $selected.Name | Should -Be 'Ethernet' + $selected.IPAddress | Should -Be '192.168.1.20' + } + + It 'Retains macOS interface names and selects the default-route interface' { + $interfaces = @(ConvertFrom-MacOSInterfaceText -Lines @( + 'utun4: flags=8051 mtu 1380' + ' inet 10.8.0.2 --> 10.8.0.2 netmask 0xffffffff' + 'en0: flags=8863 mtu 1500' + ' inet 192.168.50.12 netmask 0xffffff00 broadcast 192.168.50.255' + )) + + $selected = Select-ScanInterface -Interfaces $interfaces -DefaultInterfaceName 'en0' + $selected.Name | Should -Be 'en0' + $selected.PrefixLength | Should -Be 24 + } + + It 'Retains Linux interface names and honors an explicit selector' { + $interfaces = @(ConvertFrom-LinuxInterfaceText -Lines @( + '2: eth0: mtu 1500' + ' inet 192.168.1.20/24 brd 192.168.1.255 scope global eth0' + '5: wg0: mtu 1420' + ' inet 10.8.0.2/24 scope global wg0' + )) + + $selected = Select-ScanInterface -Interfaces $interfaces -RequestedInterface 'wg0' ` + -DefaultInterfaceName 'eth0' + $selected.Name | Should -Be 'wg0' + $selected.IPAddress | Should -Be '10.8.0.2' + } + + It 'Fails clearly when multiple interfaces exist without a default route' { + $interfaces = @( + [pscustomobject]@{ Name = 'eth0'; Index = 2; IPAddress = '192.168.1.20'; PrefixLength = 24 } + [pscustomobject]@{ Name = 'wg0'; Index = 5; IPAddress = '10.8.0.2'; PrefixLength = 24 } + ) + + { Select-ScanInterface -Interfaces $interfaces } | + Should -Throw '*Use -InterfaceName*' + } + + It 'Fails clearly for an unavailable explicit selector' { + $interfaces = @( + [pscustomobject]@{ Name = 'eth0'; Index = 2; IPAddress = '192.168.1.20'; PrefixLength = 24 } + ) + + { Select-ScanInterface -Interfaces $interfaces -RequestedInterface 'missing0' } | + Should -Throw '*was not found*' + } +} From c7de3c545140c82558365b81174db1ad22f2b3cb Mon Sep 17 00:00:00 2001 From: jacobyoby Date: Tue, 8 Sep 2026 01:33:32 -0700 Subject: [PATCH 2/2] fix(wizard): bound reverse DNS discovery --- NetDiagram-PS/NetDiagram-PS.psm1 | 52 ++++++++++++++++++++------------ README.md | 3 ++ examples/New-NetworkDiagram.ps1 | 19 ++++++++++-- tests/NetDiagram.Tests.ps1 | 32 ++++++++++++++++++++ 4 files changed, 84 insertions(+), 22 deletions(-) diff --git a/NetDiagram-PS/NetDiagram-PS.psm1 b/NetDiagram-PS/NetDiagram-PS.psm1 index e84ea15..f8b8179 100644 --- a/NetDiagram-PS/NetDiagram-PS.psm1 +++ b/NetDiagram-PS/NetDiagram-PS.psm1 @@ -1366,6 +1366,38 @@ function Get-LocalARPTable { } } +function Wait-DnsLookupTask { + param( + [Parameter(Mandatory)][System.Threading.Tasks.Task]$LookupTask, + [Parameter(Mandatory)][string]$IPAddress, + [Parameter(Mandatory)][int]$TimeoutSeconds + ) + + try { + if ($LookupTask.Wait([TimeSpan]::FromSeconds($TimeoutSeconds))) { + $result = $LookupTask.Result + return [pscustomobject]@{ + IPAddress = $IPAddress + Hostname = $result.HostName + Aliases = $result.Aliases + Success = $true + } + } + + Write-Verbose "DNS lookup for $IPAddress timed out after $TimeoutSeconds second(s)" + } + catch { + Write-Verbose "DNS lookup for $IPAddress failed: $($_.Exception.Message)" + } + + return [pscustomobject]@{ + IPAddress = $IPAddress + Hostname = $null + Aliases = @() + Success = $false + } +} + function Resolve-IPHostname { <# .SYNOPSIS @@ -1406,25 +1438,7 @@ function Resolve-IPHostname { # pipeline. On timeout we return a failure object (the background task # is abandoned). $task = [System.Net.Dns]::GetHostEntryAsync($ip) - - if ($task.Wait([TimeSpan]::FromSeconds($TimeoutSeconds))) { - $result = $task.Result - [pscustomobject]@{ - IPAddress = $ip - Hostname = $result.HostName - Aliases = $result.Aliases - Success = $true - } - } - else { - Write-Verbose "DNS lookup for $ip timed out after $TimeoutSeconds second(s)" - [pscustomobject]@{ - IPAddress = $ip - Hostname = $null - Aliases = @() - Success = $false - } - } + Wait-DnsLookupTask -LookupTask $task -IPAddress $ip -TimeoutSeconds $TimeoutSeconds } catch { [pscustomobject]@{ diff --git a/README.md b/README.md index 989979a..c7402e1 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,9 @@ pwsh .\examples\New-NetworkDiagram.ps1 -ScanDepth Full -OutputPath .\office-netw # Choose an interface explicitly (useful with VPNs or multiple adapters) pwsh .\examples\New-NetworkDiagram.ps1 -InterfaceName en0 + +# Limit each reverse DNS lookup to one second +pwsh .\examples\New-NetworkDiagram.ps1 -DnsTimeoutSeconds 1 ``` ### Method 2: Manual Workflow (manual inventory) diff --git a/examples/New-NetworkDiagram.ps1 b/examples/New-NetworkDiagram.ps1 index 266f865..a04e725 100644 --- a/examples/New-NetworkDiagram.ps1 +++ b/examples/New-NetworkDiagram.ps1 @@ -16,6 +16,8 @@ .PARAMETER InterfaceName Interface name or numeric interface index to scan. By default, the interface used by the active IPv4 default route is selected. +.PARAMETER DnsTimeoutSeconds + Maximum time for each reverse DNS lookup during discovery (default: 2 seconds). .EXAMPLE .\New-NetworkDiagram.ps1 @@ -33,7 +35,10 @@ param( [string]$OutputPath = '.\my-network.drawio', - [string]$InterfaceName + [string]$InterfaceName, + + [ValidateRange(1, 30)] + [int]$DnsTimeoutSeconds = 2 ) function Get-WizardInventoryPath { @@ -521,8 +526,16 @@ $scanTargets | ForEach-Object -Parallel { if ($result) { $hostname = try { - $resolved = [System.Net.Dns]::GetHostEntry($testIP) - $resolved.HostName + if (-not (Get-Command Resolve-IPHostname -ErrorAction SilentlyContinue)) { + Import-Module $using:modulePath -Force + } + $resolved = Resolve-IPHostname -IPAddress $testIP -TimeoutSeconds $using:DnsTimeoutSeconds + if ($resolved.Success -and -not [string]::IsNullOrWhiteSpace($resolved.Hostname)) { + $resolved.Hostname + } + else { + "Device-$testIP" + } } catch { "Device-$testIP" } diff --git a/tests/NetDiagram.Tests.ps1 b/tests/NetDiagram.Tests.ps1 index aa790d1..9a07962 100644 --- a/tests/NetDiagram.Tests.ps1 +++ b/tests/NetDiagram.Tests.ps1 @@ -432,6 +432,38 @@ Describe 'Resolve-IPHostname' { $result.IPAddress | Should -Be '192.0.2.1' $result.Success | Should -Be $false } + + It 'Returns within the configured deadline for a stalled resolver task' { + InModuleScope 'NetDiagram-PS' { + $source = [System.Threading.Tasks.TaskCompletionSource[System.Net.IPHostEntry]]::new() + $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() + + $result = Wait-DnsLookupTask -LookupTask $source.Task ` + -IPAddress '192.0.2.10' -TimeoutSeconds 1 + $stopwatch.Stop() + + $result.IPAddress | Should -Be '192.0.2.10' + $result.Hostname | Should -BeNullOrEmpty + $result.Success | Should -Be $false + $stopwatch.Elapsed.TotalSeconds | Should -BeLessThan 2.5 + } + } + + It 'Returns a failure immediately for a faulted resolver task' { + InModuleScope 'NetDiagram-PS' { + $source = [System.Threading.Tasks.TaskCompletionSource[System.Net.IPHostEntry]]::new() + $source.SetException([InvalidOperationException]::new('fixture failure')) + $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() + + $result = Wait-DnsLookupTask -LookupTask $source.Task ` + -IPAddress '192.0.2.11' -TimeoutSeconds 5 + $stopwatch.Stop() + + $result.IPAddress | Should -Be '192.0.2.11' + $result.Success | Should -Be $false + $stopwatch.Elapsed.TotalSeconds | Should -BeLessThan 1 + } + } } Describe 'Invoke-SnmpWalk' {