diff --git a/.gitignore b/.gitignore index bfa9a1e..0c42f1f 100644 --- a/.gitignore +++ b/.gitignore @@ -9,8 +9,9 @@ scanmeta.json # Claude Code settings .claude/ -# Test files -test-*.ps1 +# Test files (only in tests/ or repo root — not module source) +/test-*.ps1 +tests/test-*.ps1 # OS files .DS_Store diff --git a/NetDiagram-PS/NetDiagram-PS.psd1 b/NetDiagram-PS/NetDiagram-PS.psd1 index 6c0c387..34bd8db 100644 --- a/NetDiagram-PS/NetDiagram-PS.psd1 +++ b/NetDiagram-PS/NetDiagram-PS.psd1 @@ -26,6 +26,7 @@ # Level 2 & 3: SNMP Discovery 'Invoke-SnmpWalk' 'Get-SnmpNeighbors' + 'Get-SnmpBridgeNeighbors' 'Get-CommonSNMPStrings' # Export and Analysis diff --git a/NetDiagram-PS/Private/ConvertFrom-ArpText.ps1 b/NetDiagram-PS/Private/ConvertFrom-ArpText.ps1 index 7488821..a1a8f8a 100644 --- a/NetDiagram-PS/Private/ConvertFrom-ArpText.ps1 +++ b/NetDiagram-PS/Private/ConvertFrom-ArpText.ps1 @@ -10,22 +10,44 @@ function ConvertFrom-ArpText { if ($Format -eq 'MacOS') { if ($line -notmatch '\s+at\s+') { continue } if ($line -match '\s+at\s+\(incomplete\)') { continue } - if ($line -notmatch '\((\d+\.\d+\.\d+\.\d+)\)\s+at\s+([0-9a-fA-F:]{17})\s+on\s+(\S+)') { - throw "Unable to parse macOS ARP entry: $line" + # Try IPv4 first, then IPv6 + if ($line -match '\((\d+\.\d+\.\d+\.\d+)\)\s+at\s+([0-9a-fA-F:]{17})\s+on\s+(\S+)') { + $entry = [pscustomobject]@{ + IPAddress = $matches[1]; MACAddress = $matches[2].ToUpperInvariant() + State = 'Reachable'; InterfaceAlias = $matches[3]; InterfaceIndex = $null + AddressFamily = 'IPv4' + } } - $entry = [pscustomobject]@{ - IPAddress = $matches[1]; MACAddress = $matches[2].ToUpperInvariant() - State = 'Reachable'; InterfaceAlias = $matches[3]; InterfaceIndex = $null + elseif ($line -match '\(([0-9a-fA-F:]+)\)\s+at\s+([0-9a-fA-F:]{17})\s+on\s+(\S+)') { + $entry = [pscustomobject]@{ + IPAddress = $matches[1]; MACAddress = $matches[2].ToUpperInvariant() + State = 'Reachable'; InterfaceAlias = $matches[3]; InterfaceIndex = $null + AddressFamily = 'IPv6' + } + } + else { + throw "Unable to parse macOS ARP entry: $line" } } elseif ($Format -eq 'LinuxIp') { if ($line -notmatch '\s+lladdr\s+') { continue } - if ($line -notmatch '^(\d+\.\d+\.\d+\.\d+)\s+dev\s+(\S+)\s+lladdr\s+([0-9a-fA-F:]{17})\s+(\S+)') { - throw "Unable to parse Linux ip-neigh entry: $line" + # Try IPv4 first, then IPv6 + if ($line -match '^(\d+\.\d+\.\d+\.\d+)\s+dev\s+(\S+)\s+lladdr\s+([0-9a-fA-F:]{17})\s+(\S+)') { + $entry = [pscustomobject]@{ + IPAddress = $matches[1]; MACAddress = $matches[3].ToUpperInvariant() + State = $matches[4]; InterfaceAlias = $matches[2]; InterfaceIndex = $null + AddressFamily = 'IPv4' + } } - $entry = [pscustomobject]@{ - IPAddress = $matches[1]; MACAddress = $matches[3].ToUpperInvariant() - State = $matches[4]; InterfaceAlias = $matches[2]; InterfaceIndex = $null + elseif ($line -match '^([0-9a-fA-F:]+)\s+dev\s+(\S+)\s+lladdr\s+([0-9a-fA-F:]{17})\s+(\S+)') { + $entry = [pscustomobject]@{ + IPAddress = $matches[1]; MACAddress = $matches[3].ToUpperInvariant() + State = $matches[4]; InterfaceAlias = $matches[2]; InterfaceIndex = $null + AddressFamily = 'IPv6' + } + } + else { + throw "Unable to parse Linux ip-neigh entry: $line" } } else { @@ -36,6 +58,7 @@ function ConvertFrom-ArpText { $entry = [pscustomobject]@{ IPAddress = $matches[1]; MACAddress = $matches[2].ToUpperInvariant() State = 'Reachable'; InterfaceAlias = $null; InterfaceIndex = $null + AddressFamily = 'IPv4' } } diff --git a/NetDiagram-PS/Private/Test-IPInSubnet.ps1 b/NetDiagram-PS/Private/Test-IPInSubnet.ps1 index 5fd52cb..b3f7961 100644 --- a/NetDiagram-PS/Private/Test-IPInSubnet.ps1 +++ b/NetDiagram-PS/Private/Test-IPInSubnet.ps1 @@ -1,7 +1,11 @@ function Test-IPInSubnet { <# .SYNOPSIS - Simple CIDR matching helper + CIDR matching helper for both IPv4 and IPv6 + .DESCRIPTION + Returns true when Address falls within the network defined by CIDR. + Mixed address families (v4 address against v6 CIDR or vice versa) + return false without throwing. #> param([string]$IP, [string]$CIDR) @@ -9,14 +13,16 @@ function Test-IPInSubnet { return $false } - if ($CIDR -notmatch '^(\d{1,3}(?:\.\d{1,3}){3})\/(\d{1,2})$') { + # Split CIDR into network address and prefix length. Accept both IPv4 and + # IPv6 CIDR notation (e.g. '10.0.0.0/8' or '2001:db8::/32'). + $cidrParts = $CIDR -split '/' + if ($cidrParts.Count -ne 2) { return $false } - $networkAddressString = $matches[1] - $prefixLength = [int]$matches[2] - - if ($prefixLength -lt 0 -or $prefixLength -gt 32) { + $networkAddressString = $cidrParts[0] + $prefixLength = 0 + if (-not [int]::TryParse($cidrParts[1], [ref]$prefixLength)) { return $false } @@ -28,31 +34,30 @@ function Test-IPInSubnet { return $false } - if ($ipAddress.AddressFamily -ne [System.Net.Sockets.AddressFamily]::InterNetwork -or - $networkAddress.AddressFamily -ne [System.Net.Sockets.AddressFamily]::InterNetwork) { + # Mixed families never match — return false, never throw. + if ($ipAddress.AddressFamily -ne $networkAddress.AddressFamily) { + return $false + } + + # Validate prefix length for the address family. + $maxPrefix = if ($ipAddress.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork) { 32 } else { 128 } + if ($prefixLength -lt 0 -or $prefixLength -gt $maxPrefix) { return $false } + # Compare bytes up to prefix length. $ipBytes = $ipAddress.GetAddressBytes() $networkBytes = $networkAddress.GetAddressBytes() - if ([System.BitConverter]::IsLittleEndian) { - [Array]::Reverse($ipBytes) - [Array]::Reverse($networkBytes) - } - - $ipValue = [System.BitConverter]::ToUInt32($ipBytes, 0) - $networkValue = [System.BitConverter]::ToUInt32($networkBytes, 0) + $fullBytes = [math]::Floor($prefixLength / 8) + $remainBits = $prefixLength % 8 - # Build the prefix mask. Compute in UInt64 to avoid the int overflow that - # '[uint32]0xFFFFFFFF -shl n' triggers (0xFFFFFFFF parses as int -1), then - # truncate back to 32 bits. - $mask = if ($prefixLength -eq 0) { - [uint32]0 + for ($i = 0; $i -lt $fullBytes; $i++) { + if ($ipBytes[$i] -ne $networkBytes[$i]) { return $false } } - else { - [uint32]((([uint64]4294967295) -shl (32 - $prefixLength)) -band [uint64]4294967295) + if ($remainBits -gt 0) { + $mask = 0xFF -shl (8 - $remainBits) + if (($ipBytes[$fullBytes] -band $mask) -ne ($networkBytes[$fullBytes] -band $mask)) { return $false } } - - return (($ipValue -band $mask) -eq ($networkValue -band $mask)) + return $true } diff --git a/NetDiagram-PS/Public/Get-LocalARPTable.ps1 b/NetDiagram-PS/Public/Get-LocalARPTable.ps1 index 31cbdb3..2255eeb 100644 --- a/NetDiagram-PS/Public/Get-LocalARPTable.ps1 +++ b/NetDiagram-PS/Public/Get-LocalARPTable.ps1 @@ -27,20 +27,22 @@ function Get-LocalARPTable { $arpEntries = @() if ($IsWindows) { - # Windows: Use Get-NetNeighbor - $neighbors = Get-NetNeighbor -AddressFamily IPv4 -ErrorAction Stop + # Windows: Use Get-NetNeighbor (both IPv4 and IPv6) + $neighbors = Get-NetNeighbor -ErrorAction Stop if ($InterfaceAlias) { $neighbors = $neighbors | Where-Object { $_.InterfaceAlias -eq $InterfaceAlias } } foreach ($entry in $neighbors) { + $family = if ($entry.AddressFamily -eq 'IPv4') { 'IPv4' } else { 'IPv6' } $arpEntries += [pscustomobject]@{ IPAddress = $entry.IPAddress MACAddress = $entry.LinkLayerAddress State = $entry.State InterfaceAlias = $entry.InterfaceAlias InterfaceIndex = $entry.InterfaceIndex + AddressFamily = $family } } } diff --git a/NetDiagram-PS/Public/Get-SnmpBridgeNeighbors.ps1 b/NetDiagram-PS/Public/Get-SnmpBridgeNeighbors.ps1 new file mode 100644 index 0000000..a8ed515 --- /dev/null +++ b/NetDiagram-PS/Public/Get-SnmpBridgeNeighbors.ps1 @@ -0,0 +1,274 @@ +function Get-SnmpBridgeNeighbors { + <# + .SYNOPSIS + Discovers layer-2 neighbors via BRIDGE-MIB forwarding tables + .DESCRIPTION + Walks the BRIDGE-MIB dot1dTpFdbTable on each eligible node to learn which MAC + addresses the switch has forwarded. For each learned MAC (status = 3), resolves + the MAC to an IP address via the local ARP table (Get-LocalARPTable) and emits + an edge when the IP matches a node already in the topology. + + This fills in layer-2 edges that CDP and LLDP do not report (e.g. unmanaged + switches, devices that do not speak CDP/LLDP). + + CONFIDENCE: Edges are emitted with Confidence = 'L2-FDB', which ranks between + L2-SNMP (CDP/LLDP) and L3-Inferred in Merge-Edges. + + NODE ELIGIBILITY: Same as Get-SnmpNeighbors — every node except those explicitly + marked unreachable (Reachable -eq $false) is queried by default. + + ARP RESOLUTION: The local ARP table is queried once at the start. MACs that + cannot be resolved to an IP produce a Verbose message, not a warning. + + SECURITY: Reuses Invoke-SnmpWalk for all SNMP queries (redaction + injection guards). + .PARAMETER Topology + Topology object with nodes + .PARAMETER CredentialMapPath + Path to credential map JSON file + .PARAMETER OnlyReachable + Only query nodes proven reachable (Reachable -eq $true). + .PARAMETER TryPublic + If no credentials found for a node, try the common "public" community string. + .EXAMPLE + $topo = $topo | Get-SnmpBridgeNeighbors -CredentialMapPath '.\credmap.json' -TryPublic + #> + [CmdletBinding()] + param( + [Parameter(Mandatory, ValueFromPipeline)] + [pscustomobject]$Topology, + + [Parameter(Mandatory)] + [string]$CredentialMapPath, + + [Parameter()] + [switch]$OnlyReachable, + + [Parameter()] + [switch]$TryPublic + ) + + process { + if ($null -eq $Topology -or $null -eq $Topology.Nodes) { + throw "Invalid topology object" + } + + if (-not (Test-Path -Path $CredentialMapPath -PathType Leaf)) { + throw "Credential map file not found: $CredentialMapPath" + } + + try { + $credMap = Get-Content -Path $CredentialMapPath -Raw | ConvertFrom-Json + } + catch { + throw "Failed to parse credential map JSON: $_" + } + + # Build a MAC-to-IP lookup from the local ARP table (queried once). + $arpLookup = @{} + try { + $arpEntries = @(Get-LocalARPTable) + foreach ($entry in $arpEntries) { + if (-not [string]::IsNullOrWhiteSpace($entry.MACAddress) -and + -not [string]::IsNullOrWhiteSpace($entry.IPAddress)) { + # Normalize MAC to colon-delimited uppercase for consistent matching + $normalizedMAC = ($entry.MACAddress -replace '[-.]', ':').ToUpperInvariant() + $arpLookup[$normalizedMAC] = $entry.IPAddress + } + } + Write-Verbose "ARP table loaded: $($arpLookup.Count) MAC-to-IP mappings" + } + catch { + Write-Warning "Failed to load local ARP table: $_. Bridge neighbor discovery will not resolve MACs to IPs." + } + + # Decide which nodes to query (same logic as Get-SnmpNeighbors). + if ($OnlyReachable) { + $nodesToQuery = @($Topology.Nodes | Where-Object { $_.Reachable -eq $true }) + $eligibilityDesc = 'reachable' + } + else { + $nodesToQuery = @($Topology.Nodes | Where-Object { $_.Reachable -ne $false }) + $eligibilityDesc = 'eligible (reachable or untested)' + } + + if ($nodesToQuery.Count -eq 0) { + Write-Warning "No $eligibilityDesc nodes to query via SNMP bridge walk" + return $Topology + } + + Write-Verbose "Querying BRIDGE-MIB for $($nodesToQuery.Count) $eligibilityDesc node(s)" + + $discoveredEdges = [System.Collections.ArrayList]::new() + + # BRIDGE-MIB OIDs + $oidFdbAddress = '1.3.6.1.2.1.17.4.3.1.1' # dot1dTpFdbAddress (MAC) + $oidFdbPort = '1.3.6.1.2.1.17.4.3.1.2' # dot1dTpFdbPort (port number) + $oidFdbStatus = '1.3.6.1.2.1.17.4.3.1.3' # dot1dTpFdbStatus (1=other,2=invalid,3=learned,4=self,5=mgmt) + + foreach ($node in $nodesToQuery) { + # Resolve SNMP community for this node + $community = $null + $communitySecret = $null + $source = 'CredentialMap' + + if ($credMap.PSObject.Properties['snmp'] -and $credMap.snmp) { + $credentialMatch = Resolve-SnmpCredentialConfig -SnmpMap $credMap.snmp -IPAddress $node.IP + if ($credentialMatch) { + $source = "CredentialMap:$($credentialMatch.CIDR)" + if ($credentialMatch.Config.PSObject.Properties['communitySecret']) { + $communitySecret = $credentialMatch.Config.communitySecret + } + else { + Write-Warning "SNMP credential entry '$($credentialMatch.CIDR)' has no communitySecret; skipping configured credential for $($node.IP)" + } + } + } + + # Try to get secret from SecretManagement + if ($communitySecret) { + try { + $secretModule = Get-Module -Name Microsoft.PowerShell.SecretManagement -ListAvailable -ErrorAction SilentlyContinue + if ($secretModule) { + Import-Module Microsoft.PowerShell.SecretManagement -ErrorAction SilentlyContinue + $communitySecretInfo = Get-Secret -Name $communitySecret -AsPlainText -ErrorAction SilentlyContinue + if ($communitySecretInfo) { + $community = $communitySecretInfo + } + } + } + catch { + Write-Warning "Failed to retrieve secret '$communitySecret' for $($node.IP): $_" + } + } + + # Try "public" if no credentials found and -TryPublic is enabled + if ([string]::IsNullOrWhiteSpace($community) -and $TryPublic) { + $community = 'public' + $source = 'DefaultPublic' + Write-Verbose "[TryPublic] Attempting default 'public' community for $($node.IP)" + } + + if ([string]::IsNullOrWhiteSpace($community)) { + Write-Warning "No SNMP community found for $($node.IP), skipping bridge walk" + continue + } + + Write-Verbose " Walking BRIDGE-MIB on $($node.IP) with community from $source" + + # Walk the three columns of dot1dTpFdbTable + $addressLines = @() + $portLines = @() + $statusLines = @() + try { + $addressLines = @(Invoke-SnmpWalk -TargetIP $node.IP -Community $community -OID $oidFdbAddress -ErrorAction Stop) + $portLines = @(Invoke-SnmpWalk -TargetIP $node.IP -Community $community -OID $oidFdbPort -ErrorAction Stop) + $statusLines = @(Invoke-SnmpWalk -TargetIP $node.IP -Community $community -OID $oidFdbStatus -ErrorAction Stop) + } + catch { + Write-Warning "BRIDGE-MIB walk failed for $($node.IP): $($_.Exception.Message)" + continue + } + + if (@($addressLines).Count -eq 0) { + Write-Verbose "No BRIDGE-MIB data returned from $($node.IP)" + continue + } + + # Parse status walk into a hashtable: MAC-index → status value + # Status lines look like: + # .1.3.6.1.2.1.17.4.3.1.3.0.26.183.12.34.56 = INTEGER: 3 + $statusMap = @{} + foreach ($line in $statusLines) { + if ($line -match '\.1\.3\.6\.1\.2\.1\.17\.4\.3\.1\.3\.(.+?)\s*=\s*INTEGER:\s*(\d+)') { + $macIndex = $matches[1] + $statusVal = [int]$matches[2] + $statusMap[$macIndex] = $statusVal + } + } + + # Parse port walk into a hashtable: MAC-index → port number + # Port lines look like: + # .1.3.6.1.2.1.17.4.3.1.2.0.26.183.12.34.56 = INTEGER: 3 + $portMap = @{} + foreach ($line in $portLines) { + if ($line -match '\.1\.3\.6\.1\.2\.1\.17\.4\.3\.1\.2\.(.+?)\s*=\s*INTEGER:\s*(\d+)') { + $macIndex = $matches[1] + $portVal = [int]$matches[2] + $portMap[$macIndex] = $portVal + } + } + + # Parse address walk: extract MAC from Hex-STRING value, keyed by MAC-index + # Address lines look like: + # .1.3.6.1.2.1.17.4.3.1.1.0.26.183.12.34.56 = Hex-STRING: 00 1A B7 0C 22 38 + $addressMap = @{} + foreach ($line in $addressLines) { + if ($line -match '\.1\.3\.6\.1\.2\.1\.17\.4\.3\.1\.1\.(.+?)\s*=\s*Hex-STRING:\s*(.+)') { + $macIndex = $matches[1] + $hexValue = $matches[2].Trim() + # Parse hex octets into colon-delimited uppercase MAC + $octets = $hexValue -split '[\s:]+' | Where-Object { $_ -ne '' } + if ($octets.Count -ge 6) { + $mac = ($octets[0..5] | ForEach-Object { $_.ToUpperInvariant().PadLeft(2, '0') }) -join ':' + $addressMap[$macIndex] = $mac + } + } + } + + Write-Verbose " $($node.IP): parsed $($addressMap.Count) FDB addresses, $($statusMap.Count) statuses, $($portMap.Count) ports" + + # For each learned MAC (status=3), resolve via ARP and emit edge + foreach ($macIndex in $addressMap.Keys) { + # Filter: only keep status=3 (learned) + $status = if ($statusMap.ContainsKey($macIndex)) { $statusMap[$macIndex] } else { $null } + if ($status -ne 3) { + continue + } + + $mac = $addressMap[$macIndex] + $port = if ($portMap.ContainsKey($macIndex)) { $portMap[$macIndex] } else { $null } + + # Look up MAC in local ARP table + $resolvedIP = if ($arpLookup.ContainsKey($mac)) { $arpLookup[$mac] } else { $null } + + if ([string]::IsNullOrWhiteSpace($resolvedIP)) { + Write-Verbose " MAC $mac (port $port) on $($node.IP): no ARP match, skipping" + continue + } + + # Skip self-loops + if ($resolvedIP -eq $node.IP) { continue } + + # Only accept addresses that map to a node already in the topology + $targetNode = $Topology.Nodes | Where-Object { $_.IP -eq $resolvedIP } + if (-not $targetNode) { continue } + + $label = if ($null -ne $port) { "port-$port" } else { 'FDB' } + + $edge = [pscustomobject]@{ + SourceIP = $node.IP + TargetIP = $resolvedIP + Label = $label + Source = 'SNMP-FDB' + Confidence = 'L2-FDB' + } + + $null = $discoveredEdges.Add($edge) + } + } + + Write-Verbose "Discovered $($discoveredEdges.Count) bridge-FDB edges" + + # Merge new edges with existing ones. Filter nulls so an empty pscustomobject + # Edges property (which PowerShell unwraps to $null) does not become @($null). + $existingEdges = @($Topology.Edges | Where-Object { $null -ne $_ }) + if ($existingEdges.Count -eq 0 -and $discoveredEdges.Count -eq 0) { + $Topology.Edges = @() + return $Topology + } + + $Topology.Edges = Merge-Edges -Edges ($existingEdges + @($discoveredEdges)) + + return $Topology + } +} diff --git a/NetDiagram-PS/Public/Merge-Edges.ps1 b/NetDiagram-PS/Public/Merge-Edges.ps1 index 5da31ce..9750454 100644 --- a/NetDiagram-PS/Public/Merge-Edges.ps1 +++ b/NetDiagram-PS/Public/Merge-Edges.ps1 @@ -4,8 +4,9 @@ function Merge-Edges { Merges and deduplicates edge candidates .DESCRIPTION Deduplicates edges using sorted endpoints as key. - Prioritizes verified L2-SNMP, then provisional L2-SNMP-Heuristic, then - L3-Inferred. An SNMP source alone never promotes an edge to verified. + Prioritizes verified L2-SNMP, then L2-FDB (bridge forwarding table), + then provisional L2-SNMP-Heuristic, then L3-Inferred. + An SNMP source alone never promotes an edge to verified. Keeps first non-empty label. .PARAMETER Edges Array of edge objects to merge @@ -53,7 +54,8 @@ function Merge-Edges { $confidenceRank = @{ 'L3-Inferred' = 1 'L2-SNMP-Heuristic' = 2 - 'L2-SNMP' = 3 + 'L2-FDB' = 3 + 'L2-SNMP' = 4 } if ($edgeMap.Contains($key)) { @@ -83,5 +85,9 @@ function Merge-Edges { } } + if ($edgeMap.Count -eq 0) { + return @() + } + return @($edgeMap.Values) } diff --git a/tests/NetDiagram.Tests.ps1 b/tests/NetDiagram.Tests.ps1 index 1197538..cdc61c5 100644 --- a/tests/NetDiagram.Tests.ps1 +++ b/tests/NetDiagram.Tests.ps1 @@ -62,6 +62,7 @@ Describe 'Module Import' { $commandNames | Should -Contain 'Export-NetBox' $commandNames | Should -Contain 'Import-NmapScan' $commandNames | Should -Contain 'Compare-NetworkScans' + $commandNames | Should -Contain 'Get-SnmpBridgeNeighbors' } } @@ -265,6 +266,42 @@ Describe 'Merge-Edges' { $merged | Should -HaveCount 1 $merged[0].Label | Should -Be 'Good' } + + It 'Three-way confidence ranking: L2-SNMP > L2-FDB > L3-Inferred (forward order)' { + $edges = @( + [pscustomobject]@{ SourceIP = '10.0.0.1'; TargetIP = '10.0.0.2'; Label = 'inferred'; Source = 'Manual'; Confidence = 'L3-Inferred' } + [pscustomobject]@{ SourceIP = '10.0.0.1'; TargetIP = '10.0.0.2'; Label = 'fdb'; Source = 'SNMP-FDB'; Confidence = 'L2-FDB' } + [pscustomobject]@{ SourceIP = '10.0.0.1'; TargetIP = '10.0.0.2'; Label = 'snmp'; Source = 'SNMP'; Confidence = 'L2-SNMP' } + ) + + $merged = Merge-Edges -Edges $edges + $merged | Should -HaveCount 1 + $merged[0].Confidence | Should -Be 'L2-SNMP' + } + + It 'Three-way confidence ranking: L2-SNMP > L2-FDB > L3-Inferred (reverse order)' { + $edges = @( + [pscustomobject]@{ SourceIP = '10.0.0.1'; TargetIP = '10.0.0.2'; Label = 'snmp'; Source = 'SNMP'; Confidence = 'L2-SNMP' } + [pscustomobject]@{ SourceIP = '10.0.0.2'; TargetIP = '10.0.0.1'; Label = 'fdb'; Source = 'SNMP-FDB'; Confidence = 'L2-FDB' } + [pscustomobject]@{ SourceIP = '10.0.0.1'; TargetIP = '10.0.0.2'; Label = 'inferred'; Source = 'Manual'; Confidence = 'L3-Inferred' } + ) + + $merged = Merge-Edges -Edges $edges + $merged | Should -HaveCount 1 + $merged[0].Confidence | Should -Be 'L2-SNMP' + } + + It 'L2-FDB outranks L3-Inferred and L2-SNMP-Heuristic' { + $edges = @( + [pscustomobject]@{ SourceIP = '10.0.0.1'; TargetIP = '10.0.0.2'; Label = 'hint'; Source = 'SNMP'; Confidence = 'L2-SNMP-Heuristic' } + [pscustomobject]@{ SourceIP = '10.0.0.1'; TargetIP = '10.0.0.2'; Label = 'inferred'; Source = 'Manual'; Confidence = 'L3-Inferred' } + [pscustomobject]@{ SourceIP = '10.0.0.2'; TargetIP = '10.0.0.1'; Label = 'fdb'; Source = 'SNMP-FDB'; Confidence = 'L2-FDB' } + ) + + $merged = Merge-Edges -Edges $edges + $merged | Should -HaveCount 1 + $merged[0].Confidence | Should -Be 'L2-FDB' + } } Describe 'Export-DrawIO' { @@ -578,6 +615,153 @@ Describe 'Export-NodeInventoryCsv (#41 regression)' { } } +Describe 'Get-SnmpBridgeNeighbors (#39 regression)' { + BeforeEach { + $script:CredMapPath = Join-Path $script:TestDataPath 'credmap-bridge.json' + '{}' | Out-File -FilePath $script:CredMapPath -Force + } + + It 'Produces edges from BRIDGE-MIB snmpwalk text for learned MACs with ARP matches' { + # Simulated snmpwalk output for three BRIDGE-MIB columns: + # dot1dTpFdbAddress (1.3.6.1.2.1.17.4.3.1.1) — MAC as Hex-STRING + # dot1dTpFdbPort (1.3.6.1.2.1.17.4.3.1.2) — INTEGER port number + # dot1dTpFdbStatus (1.3.6.1.2.1.17.4.3.1.3) — INTEGER status + # MAC AA:BB:CC:DD:EE:01 (index 170.187.204.221.238.1) = learned (status=3), port 5 + # MAC AA:BB:CC:DD:EE:02 (index 170.187.204.221.238.2) = learned (status=3), port 8 + # MAC AA:BB:CC:DD:EE:03 (index 170.187.204.221.238.3) = self (status=4), port 1 (should be filtered) + + $addressLines = @( + '.1.3.6.1.2.1.17.4.3.1.1.170.187.204.221.238.1 = Hex-STRING: AA BB CC DD EE 01' + '.1.3.6.1.2.1.17.4.3.1.1.170.187.204.221.238.2 = Hex-STRING: AA BB CC DD EE 02' + '.1.3.6.1.2.1.17.4.3.1.1.170.187.204.221.238.3 = Hex-STRING: AA BB CC DD EE 03' + ) + $portLines = @( + '.1.3.6.1.2.1.17.4.3.1.2.170.187.204.221.238.1 = INTEGER: 5' + '.1.3.6.1.2.1.17.4.3.1.2.170.187.204.221.238.2 = INTEGER: 8' + '.1.3.6.1.2.1.17.4.3.1.2.170.187.204.221.238.3 = INTEGER: 1' + ) + $statusLines = @( + '.1.3.6.1.2.1.17.4.3.1.3.170.187.204.221.238.1 = INTEGER: 3' + '.1.3.6.1.2.1.17.4.3.1.3.170.187.204.221.238.2 = INTEGER: 3' + '.1.3.6.1.2.1.17.4.3.1.3.170.187.204.221.238.3 = INTEGER: 4' + ) + + $topology = [pscustomobject]@{ + Nodes = @( + [pscustomobject]@{ IP = '10.0.0.1'; Hostname = 'switch1'; Role = 'switch'; Vendor = 'X'; OS = 'X'; Layer = 'Access'; Reachable = $true } + [pscustomobject]@{ IP = '10.0.0.10'; Hostname = 'host10'; Role = 'server'; Vendor = 'X'; OS = 'X'; Layer = 'Servers'; Reachable = $true } + [pscustomobject]@{ IP = '10.0.0.20'; Hostname = 'host20'; Role = 'server'; Vendor = 'X'; OS = 'X'; Layer = 'Servers'; Reachable = $true } + ) + Edges = @() + Subnets = @() + } + + Mock Invoke-SnmpWalk { + if ($TargetIP -ne '10.0.0.1') { return @() } + if ($OID -eq '1.3.6.1.2.1.17.4.3.1.1') { return $addressLines } + if ($OID -eq '1.3.6.1.2.1.17.4.3.1.2') { return $portLines } + if ($OID -eq '1.3.6.1.2.1.17.4.3.1.3') { return $statusLines } + return @() + } -ModuleName 'NetDiagram-PS' + + Mock Get-LocalARPTable { + @( + [pscustomobject]@{ IPAddress = '10.0.0.10'; MACAddress = 'AA:BB:CC:DD:EE:01' } + [pscustomobject]@{ IPAddress = '10.0.0.20'; MACAddress = 'AA:BB:CC:DD:EE:02' } + ) + } -ModuleName 'NetDiagram-PS' + + $result = $topology | Get-SnmpBridgeNeighbors -CredentialMapPath $script:CredMapPath -TryPublic -WarningAction SilentlyContinue + + # Two learned MACs with ARP matches → two edges (status=4 is filtered out) + $result.Edges | Should -HaveCount 2 + $result.Edges[0].Source | Should -Be 'SNMP-FDB' + $result.Edges[0].Confidence | Should -Be 'L2-FDB' + ($result.Edges | Where-Object TargetIP -eq '10.0.0.10').Label | Should -Be 'port-5' + ($result.Edges | Where-Object TargetIP -eq '10.0.0.20').Label | Should -Be 'port-8' + } + + It 'Filters out entries where status is not 3 (learned)' { + # All three entries have status != 3 + $addressLines = @( + '.1.3.6.1.2.1.17.4.3.1.1.1.2.3.4.5.6 = Hex-STRING: 01 02 03 04 05 06' + '.1.3.6.1.2.1.17.4.3.1.1.7.8.9.10.11.12 = Hex-STRING: 07 08 09 0A 0B 0C' + ) + $portLines = @( + '.1.3.6.1.2.1.17.4.3.1.2.1.2.3.4.5.6 = INTEGER: 1' + '.1.3.6.1.2.1.17.4.3.1.2.7.8.9.10.11.12 = INTEGER: 2' + ) + $statusLines = @( + '.1.3.6.1.2.1.17.4.3.1.3.1.2.3.4.5.6 = INTEGER: 4' + '.1.3.6.1.2.1.17.4.3.1.3.7.8.9.10.11.12 = INTEGER: 2' + ) + + $topology = [pscustomobject]@{ + Nodes = @( + [pscustomobject]@{ IP = '10.0.0.1'; Hostname = 'sw'; Role = 'switch'; Vendor = 'X'; OS = 'X'; Layer = 'Access'; Reachable = $true } + [pscustomobject]@{ IP = '10.0.0.50'; Hostname = 'host50'; Role = 'server'; Vendor = 'X'; OS = 'X'; Layer = 'Servers'; Reachable = $true } + ) + Edges = @() + Subnets = @() + } + + Mock Invoke-SnmpWalk { + if ($TargetIP -ne '10.0.0.1') { return @() } + if ($OID -eq '1.3.6.1.2.1.17.4.3.1.1') { return $addressLines } + if ($OID -eq '1.3.6.1.2.1.17.4.3.1.2') { return $portLines } + if ($OID -eq '1.3.6.1.2.1.17.4.3.1.3') { return $statusLines } + return @() + } -ModuleName 'NetDiagram-PS' + + Mock Get-LocalARPTable { + @( + [pscustomobject]@{ IPAddress = '10.0.0.50'; MACAddress = '01:02:03:04:05:06' } + ) + } -ModuleName 'NetDiagram-PS' + + $result = $topology | Get-SnmpBridgeNeighbors -CredentialMapPath $script:CredMapPath -TryPublic -WarningAction SilentlyContinue + $result.Edges | Should -HaveCount 0 + } + + It 'Unresolvable MAC yields no edge (verbose message, not warning)' { + $addressLines = @( + '.1.3.6.1.2.1.17.4.3.1.1.1.2.3.4.5.6 = Hex-STRING: 01 02 03 04 05 06' + ) + $portLines = @( + '.1.3.6.1.2.1.17.4.3.1.2.1.2.3.4.5.6 = INTEGER: 3' + ) + $statusLines = @( + '.1.3.6.1.2.1.17.4.3.1.3.1.2.3.4.5.6 = INTEGER: 3' + ) + + $topology = [pscustomobject]@{ + Nodes = @( + [pscustomobject]@{ IP = '10.0.0.1'; Hostname = 'sw'; Role = 'switch'; Vendor = 'X'; OS = 'X'; Layer = 'Access'; Reachable = $true } + ) + Edges = @() + Subnets = @() + } + + Mock Invoke-SnmpWalk { + if ($OID -eq '1.3.6.1.2.1.17.4.3.1.1') { return $addressLines } + if ($OID -eq '1.3.6.1.2.1.17.4.3.1.2') { return $portLines } + if ($OID -eq '1.3.6.1.2.1.17.4.3.1.3') { return $statusLines } + return @() + } -ModuleName 'NetDiagram-PS' + + # Empty ARP table — MAC cannot be resolved + Mock Get-LocalARPTable { @() } -ModuleName 'NetDiagram-PS' + + # Should NOT produce a warning (Write-Warning should not be called for unresolvable MACs) + $result = $topology | Get-SnmpBridgeNeighbors -CredentialMapPath $script:CredMapPath -TryPublic -WarningVariable warns -WarningAction SilentlyContinue + + $result.Edges | Should -HaveCount 0 + # Filter out the TryPublic security warning (if any); no bridge-related warnings + $bridgeWarns = @($warns | Where-Object { $_ -notmatch 'SECURITY WARNING' -and $_ -notmatch 'TryPublic' -and $_ -notmatch 'public' }) + $bridgeWarns | Should -HaveCount 0 + } +} + Describe 'Defensive Coding Tests' { It 'Should handle null topology gracefully in Export-DrawIO' { $nullTopo = [pscustomobject]@{ @@ -839,6 +1023,30 @@ Describe 'Test-IPInSubnet (private helper)' { Test-IPInSubnet -IP '192.168.1.50' -CIDR 'not-a-cidr' | Should -Be $false } } + + It 'Should match an IPv6 address inside its CIDR range' { + InModuleScope 'NetDiagram-PS' { + Test-IPInSubnet -IP '2001:db8::1' -CIDR '2001:db8::/32' | Should -Be $true + } + } + + It 'Should reject an IPv6 address outside the CIDR range' { + InModuleScope 'NetDiagram-PS' { + Test-IPInSubnet -IP '2001:db8:1::1' -CIDR '2001:db8::/48' | Should -Be $false + } + } + + It 'Should return false for mixed address families (v4 address, v6 CIDR)' { + InModuleScope 'NetDiagram-PS' { + Test-IPInSubnet -IP '192.168.1.1' -CIDR '2001:db8::/32' | Should -Be $false + } + } + + It 'Should return false for mixed address families (v6 address, v4 CIDR)' { + InModuleScope 'NetDiagram-PS' { + Test-IPInSubnet -IP '2001:db8::1' -CIDR '192.168.0.0/16' | Should -Be $false + } + } } Describe 'SNMP credential-map precedence (#17 regression)' { @@ -1159,6 +1367,45 @@ Describe 'Export-DrawIO subnet container parenting' { $n.parent | Should -Be $container.id } } + + It 'Parents IPv6 nodes into the matching IPv6 subnet container' { + $nodes = @( + [pscustomobject]@{ + IP = '2001:db8::10'; Hostname = 'v6-node'; Role = 'switch' + Vendor = 'Test'; OS = 'Test'; Layer = 'Access'; Reachable = $null + } + [pscustomobject]@{ + IP = '192.168.1.10'; Hostname = 'v4-node'; Role = 'switch' + Vendor = 'Test'; OS = 'Test'; Layer = 'Access'; Reachable = $null + } + ) + $topology = [pscustomobject]@{ + Nodes = $nodes + Edges = @() + Subnets = @( + [pscustomobject]@{ CIDR = '2001:db8::/32'; Label = 'v6-net'; VLAN = 100 } + [pscustomobject]@{ CIDR = '192.168.1.0/24'; Label = 'v4-net'; VLAN = 1 } + ) + } + $drawioPath = Join-Path $script:TestDataPath 'ipv6-containers.drawio' + $topology | Export-DrawIO -OutFile $drawioPath + + $xml = [xml](Get-Content -Path $drawioPath -Raw) + $containers = @($xml.SelectNodes("//mxCell[contains(@style,'swimlane')]")) + $containers.Count | Should -Be 2 + + # Find v6 container by its label + $v6Container = $containers | Where-Object { $_.value -match 'v6-net' } + $v4Container = $containers | Where-Object { $_.value -match 'v4-net' } + $v6Container | Should -Not -BeNullOrEmpty + $v4Container | Should -Not -BeNullOrEmpty + + # Verify v6 node is parented to v6 container and v4 node to v4 container + $v6Node = $xml.SelectSingleNode("//UserObject[@ip='2001:db8::10']") + $v4Node = $xml.SelectSingleNode("//UserObject[@ip='192.168.1.10']") + $v6Node.mxCell.parent | Should -Be $v6Container.id + $v4Node.mxCell.parent | Should -Be $v4Container.id + } } Describe 'Export-DrawIO dynamic container layout (#19 regression)' {