From dd61ec99f1c9e634d7881c5f96f82534dc636bf7 Mon Sep 17 00:00:00 2001 From: jacobyoby Date: Tue, 8 Sep 2026 13:32:24 -0700 Subject: [PATCH] fix(snmp): prefer the most specific credential map --- NetDiagram-PS/NetDiagram-PS.psm1 | 74 +++++++++++++++++++++++++++----- examples/credmap.json | 4 +- tests/NetDiagram.Tests.ps1 | 60 ++++++++++++++++++++++++++ 3 files changed, 127 insertions(+), 11 deletions(-) diff --git a/NetDiagram-PS/NetDiagram-PS.psm1 b/NetDiagram-PS/NetDiagram-PS.psm1 index e84ea15..ed5f697 100644 --- a/NetDiagram-PS/NetDiagram-PS.psm1 +++ b/NetDiagram-PS/NetDiagram-PS.psm1 @@ -337,6 +337,11 @@ function Get-SnmpNeighbors { Uses credential map to resolve community strings from SecretManagement. Adds discovered edges to the topology with L2-SNMP confidence. + CREDENTIAL MATCHING: The most specific matching IPv4 CIDR wins regardless of + JSON property order. Default is used only when no CIDR matches. If the selected + entry has no available community secret, the node is skipped unless -TryPublic + was explicitly supplied. + NODE ELIGIBILITY: By default every node is queried EXCEPT nodes that have been explicitly marked unreachable (Reachable -eq $false). Nodes with unknown reachability (Reachable -eq $null, e.g. straight after Import-Inventory) ARE @@ -453,16 +458,14 @@ All SNMP attempts will be logged to verbose output. $source = 'CredentialMap' if ($credMap.PSObject.Properties['snmp'] -and $credMap.snmp) { - foreach ($cidrEntry in $credMap.snmp.PSObject.Properties) { - $cidr = $cidrEntry.Name - $config = $cidrEntry.Value - - # Simple CIDR matching (for MVP, just match Default or exact match) - if ($cidr -eq 'Default' -or (Test-IPInSubnet -IP $node.IP -CIDR $cidr)) { - if ($config.PSObject.Properties['communitySecret']) { - $communitySecret = $config.communitySecret - break - } + $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)" } } } @@ -573,6 +576,57 @@ All SNMP attempts will be logged to verbose output. } } +function Resolve-SnmpCredentialConfig { + param( + [Parameter(Mandatory)][psobject]$SnmpMap, + [Parameter(Mandatory)][string]$IPAddress + ) + + $defaultConfig = $null + $cidrMatches = @() + + foreach ($entry in $SnmpMap.PSObject.Properties) { + if ($entry.Name -eq 'Default') { + $defaultConfig = $entry.Value + continue + } + + if ($entry.Name -notmatch '^(\d{1,3}(?:\.\d{1,3}){3})\/(\d{1,2})$') { + throw "Invalid SNMP credential-map CIDR '$($entry.Name)'. Expected an IPv4 CIDR or Default." + } + + $prefixLength = [int]$matches[2] + $networkAddress = $null + if ($prefixLength -gt 32 -or + -not [System.Net.IPAddress]::TryParse($matches[1], [ref]$networkAddress) -or + $networkAddress.AddressFamily -ne [System.Net.Sockets.AddressFamily]::InterNetwork) { + throw "Invalid SNMP credential-map CIDR '$($entry.Name)'. Expected an IPv4 CIDR or Default." + } + + if (Test-IPInSubnet -IP $IPAddress -CIDR $entry.Name) { + $cidrMatches += [pscustomobject]@{ + CIDR = $entry.Name + PrefixLength = $prefixLength + Config = $entry.Value + } + } + } + + $bestMatch = $cidrMatches | Sort-Object PrefixLength -Descending | Select-Object -First 1 + if ($bestMatch) { + return $bestMatch + } + if ($null -ne $defaultConfig) { + return [pscustomobject]@{ + CIDR = 'Default' + PrefixLength = -1 + Config = $defaultConfig + } + } + + return $null +} + function Test-IPInSubnet { <# .SYNOPSIS diff --git a/examples/credmap.json b/examples/credmap.json index 3a10538..62113e6 100644 --- a/examples/credmap.json +++ b/examples/credmap.json @@ -17,6 +17,8 @@ "_instructions": { "setup": "1. Install: Install-Module Microsoft.PowerShell.SecretManagement", "store_secret": "2. Store secrets: Set-Secret -Name 'YourSNMPSecretName' -Secret 'your-community-string'", - "usage": "3. Use: Get-SnmpNeighbors -CredentialMapPath .\\examples\\credmap.json" + "usage": "3. Use: Get-SnmpNeighbors -CredentialMapPath .\\examples\\credmap.json", + "matching": "The most specific matching IPv4 CIDR wins. Default is used only when no CIDR matches.", + "missing_secret": "A missing or unavailable selected secret skips that node unless -TryPublic is explicitly supplied." } } diff --git a/tests/NetDiagram.Tests.ps1 b/tests/NetDiagram.Tests.ps1 index e321402..ad0d511 100644 --- a/tests/NetDiagram.Tests.ps1 +++ b/tests/NetDiagram.Tests.ps1 @@ -462,6 +462,66 @@ Describe 'Test-IPInSubnet (private helper)' { } } +Describe 'SNMP credential-map precedence (#17 regression)' { + It 'Uses a matching subnet even when Default appears first' { + InModuleScope 'NetDiagram-PS' { + $map = '{"Default":{"communitySecret":"fallback"},"192.168.1.0/24":{"communitySecret":"office"}}' | ConvertFrom-Json + $match = Resolve-SnmpCredentialConfig -SnmpMap $map -IPAddress '192.168.1.40' + + $match.CIDR | Should -Be '192.168.1.0/24' + $match.Config.communitySecret | Should -Be 'office' + } + } + + It 'Uses a matching subnet when Default appears last' { + InModuleScope 'NetDiagram-PS' { + $map = '{"192.168.1.0/24":{"communitySecret":"office"},"Default":{"communitySecret":"fallback"}}' | ConvertFrom-Json + $match = Resolve-SnmpCredentialConfig -SnmpMap $map -IPAddress '192.168.1.40' + + $match.CIDR | Should -Be '192.168.1.0/24' + } + } + + It 'Chooses the longest matching prefix' { + InModuleScope 'NetDiagram-PS' { + $map = '{"10.0.0.0/16":{"communitySecret":"site"},"10.0.4.0/24":{"communitySecret":"floor"}}' | ConvertFrom-Json + $match = Resolve-SnmpCredentialConfig -SnmpMap $map -IPAddress '10.0.4.25' + + $match.CIDR | Should -Be '10.0.4.0/24' + $match.Config.communitySecret | Should -Be 'floor' + } + } + + It 'Falls back to Default when no subnet matches' { + InModuleScope 'NetDiagram-PS' { + $map = '{"10.0.0.0/8":{"communitySecret":"internal"},"Default":{"communitySecret":"fallback"}}' | ConvertFrom-Json + $match = Resolve-SnmpCredentialConfig -SnmpMap $map -IPAddress '192.168.1.40' + + $match.CIDR | Should -Be 'Default' + $match.Config.communitySecret | Should -Be 'fallback' + } + } + + It 'Rejects an invalid CIDR entry' { + InModuleScope 'NetDiagram-PS' { + $map = '{"192.168.999.0/24":{"communitySecret":"bad"}}' | ConvertFrom-Json + + { Resolve-SnmpCredentialConfig -SnmpMap $map -IPAddress '192.168.1.40' } | + Should -Throw '*Invalid SNMP credential-map CIDR*' + } + } + + It 'Returns the selected entry when its secret name is missing' { + InModuleScope 'NetDiagram-PS' { + $map = '{"192.168.1.0/24":{"version":"v2c"},"Default":{"communitySecret":"fallback"}}' | ConvertFrom-Json + $match = Resolve-SnmpCredentialConfig -SnmpMap $map -IPAddress '192.168.1.40' + + $match.CIDR | Should -Be '192.168.1.0/24' + $match.Config.PSObject.Properties['communitySecret'] | Should -BeNullOrEmpty + } + } +} + Describe 'Get-SnmpNeighbors node eligibility (#1 regression)' { BeforeEach { # Empty credential map is valid; -TryPublic supplies the community so no