From d2f0b4c6f609fa48b4924c6e7f8a08962ea4d634 Mon Sep 17 00:00:00 2001 From: jacobyoby Date: Thu, 30 Jul 2026 08:55:14 -0700 Subject: [PATCH 1/5] Harden SNMP, port scan, DNS, and draw.io export (Codex review) - Get-SnmpNeighbors: query untested nodes (Reachable=$null) by default so the import-then-discover workflow works; add -OnlyReachable opt-in switch. - Invoke-SnmpWalk: redact community from verbose output (-c ****); validate Version/TargetIP/OID and reject values starting with '-'; restrict binary resolution to -CommandType Application; document process-list exposure. - Harden LLDP/CDP parsing (value-only, octet-validated, Hex-STRING aware, self-loop guard) and document it as best-effort. - Export-DrawIO: de-duplicate node IPs; parent nodes into their matching subnet container via Test-IPInSubnet, laying unmatched nodes out below the containers. - Invoke-PortScan: ValidateRange on ports (1-65535) and timeout (1-60000); drop TCP 161 from defaults (SNMP is UDP). - Resolve-IPHostname: honor -TimeoutSeconds via async DNS with a bounded wait. Co-Authored-By: wren --- NetDiagram-PS/NetDiagram-PS.psm1 | 276 ++++++++++++++++++++++++------- 1 file changed, 219 insertions(+), 57 deletions(-) diff --git a/NetDiagram-PS/NetDiagram-PS.psm1 b/NetDiagram-PS/NetDiagram-PS.psm1 index f1dda37..e84ea15 100644 --- a/NetDiagram-PS/NetDiagram-PS.psm1 +++ b/NetDiagram-PS/NetDiagram-PS.psm1 @@ -11,7 +11,7 @@ Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' # Module-level variables -$script:ModuleVersion = '1.2.0' +$script:ModuleVersion = '1.3.0' #region Helper Functions @@ -222,14 +222,23 @@ function Invoke-SnmpWalk { Calls snmpwalk directly (must be in PATH) with specified OID and credentials. Resolves 'snmpwalk' on macOS/Linux and 'snmpwalk.exe' on Windows. Returns raw output lines. + + SECURITY - PROCESS LIST EXPOSURE (known limitation): snmpwalk receives the + community string as a command-line argument ('-c '). While it runs, + the community is visible to any local user who can list processes (ps, Get-Process + with command-line access, /proc). This is inherent to shelling out to net-snmp and + cannot be avoided without a native SNMP client. Verbose logging in this function + redacts the community (prints '-c ****'), but the process arguments themselves are + not redacted. Treat SNMP v1/v2c community strings as low-secrecy and prefer SNMPv3 + with authentication for anything sensitive. .PARAMETER TargetIP - IP address to query + IP address or hostname (FQDN) to query. Must not begin with '-'. .PARAMETER Community - SNMP community string + SNMP community string. Must not begin with '-' (argument-injection guard). .PARAMETER OID - OID to walk (default: LLDP remote table) + OID to walk (default: LLDP remote table). Digits and dots only. .PARAMETER Version - SNMP version (default: v2c) + SNMP version: v1, v2c, or v3 (default: v2c) .PARAMETER TimeoutSeconds Timeout in seconds (default: 2) .EXAMPLE @@ -238,26 +247,41 @@ function Invoke-SnmpWalk { [CmdletBinding()] param( [Parameter(Mandatory)] + [ValidateScript({ + if ($_ -match '^-') { throw "TargetIP must not begin with '-'." } + if ($_ -notmatch '^(?:\d{1,3}(?:\.\d{1,3}){3}|[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])?)*)$') { + throw "TargetIP '$_' is not a valid IPv4 address or hostname." + } + $true + })] [string]$TargetIP, [Parameter(Mandatory)] + [ValidateScript({ + if ($_ -match '^-') { throw "Community must not begin with '-' (argument-injection guard)." } + $true + })] [string]$Community, [Parameter()] + [ValidatePattern('^\d+(\.\d+)*$')] [string]$OID = '1.0.8802.1.1.2.1.4', [Parameter()] + [ValidateSet('v1', 'v2c', 'v3')] [string]$Version = 'v2c', [Parameter()] + [ValidateRange(1, 300)] [int]$TimeoutSeconds = 2 ) # Locate the snmpwalk binary. It is 'snmpwalk.exe' on Windows and 'snmpwalk' # on macOS/Linux, so probe for both rather than assuming the Windows name. + # Restrict to Application so a same-named function/alias/script cannot be invoked. $snmpWalkCmd = $null foreach ($candidate in @('snmpwalk', 'snmpwalk.exe')) { - $found = Get-Command -Name $candidate -ErrorAction SilentlyContinue + $found = Get-Command -Name $candidate -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 if ($found) { $snmpWalkCmd = $found.Source break @@ -276,7 +300,17 @@ function Invoke-SnmpWalk { $OID ) - Write-Verbose "Running: $snmpWalkCmd $($arguments -join ' ')" + # Never emit the community string in verbose output. Redact '-c ' + # to '-c ****'. (The community is still visible in the process argument list + # while snmpwalk runs - see the SECURITY note in the function help.) + $redactedArgs = @( + '-' + $Version.ToLower() + '-c', '****' + '-t', $TimeoutSeconds.ToString() + $TargetIP + $OID + ) + Write-Verbose "Running: $snmpWalkCmd $($redactedArgs -join ' ')" $output = & $snmpWalkCmd @arguments 2>&1 @@ -297,17 +331,34 @@ function Invoke-SnmpWalk { function Get-SnmpNeighbors { <# .SYNOPSIS - Discovers neighbors via SNMP LLDP/CDP + Discovers neighbors via SNMP LLDP/CDP (best-effort MVP) .DESCRIPTION - Queries reachable nodes for LLDP neighbor information via SNMP. + Queries nodes for LLDP neighbor information via SNMP. Uses credential map to resolve community strings from SecretManagement. Adds discovered edges to the topology with L2-SNMP confidence. + + 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 + queried, so the documented "import inventory then discover via SNMP" workflow + works without first running Test-DeviceReachability. Pass -OnlyReachable to + restrict querying to nodes proven reachable (Reachable -eq $true). + + PARSING IS BEST-EFFORT (MVP): the neighbor parser scans snmpwalk output for the + first IPv4-looking token on each line and only creates an edge when that address + already exists as a node in the topology. It does NOT fully decode the LLDP/CDP + MIB rows (chassis-id / management-address / port-id sub-OIDs are not joined). It + can miss neighbors and, on unusual output, misattribute a link. Treat the SNMP + edges as hints to verify, not authoritative topology. .PARAMETER Topology Topology object with nodes .PARAMETER CredentialMapPath Path to credential map JSON file .PARAMETER OID SNMP OID to walk (default: LLDP remote table) + .PARAMETER OnlyReachable + Only query nodes proven reachable (Reachable -eq $true). Off by default so that + freshly imported inventory (Reachable = $null) is still queried. .PARAMETER TryPublic If no credentials found for a node, try the common "public" community string. WARNING: This may be logged by security systems. Only use on networks you own. @@ -317,6 +368,10 @@ function Get-SnmpNeighbors { $topo = $topo | Get-SnmpNeighbors -CredentialMapPath '.\credmap.json' -TryPublic Tries user credentials first, falls back to "public" if none found (with warning) + .EXAMPLE + $topo = $topo | Test-DeviceReachability | Get-SnmpNeighbors -CredentialMapPath '.\credmap.json' -OnlyReachable + + Ping-tests first, then queries only the nodes that answered. #> [CmdletBinding()] param( @@ -329,6 +384,9 @@ function Get-SnmpNeighbors { [Parameter()] [string]$OID = '1.0.8802.1.1.2.1.4', + [Parameter()] + [switch]$OnlyReachable, + [Parameter()] [switch]$TryPublic ) @@ -366,19 +424,29 @@ All SNMP attempts will be logged to verbose output. "@ } - # Only query reachable nodes - $reachableNodes = @($Topology.Nodes | Where-Object { $_.Reachable -eq $true }) - if ($reachableNodes.Count -eq 0) { - Write-Warning "No reachable nodes to query via SNMP" + # Decide which nodes to query. Default: everything that is not explicitly + # unreachable (so freshly imported inventory with Reachable = $null is eligible). + # -OnlyReachable narrows to nodes proven reachable (Reachable -eq $true). + 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" return $Topology } - Write-Verbose "Querying SNMP neighbors for $($reachableNodes.Count) reachable nodes" + Write-Verbose "Querying SNMP neighbors for $($nodesToQuery.Count) $eligibilityDesc node(s)" $discoveredEdges = [System.Collections.ArrayList]::new() $publicAttempts = 0 - foreach ($node in $reachableNodes) { + foreach ($node in $nodesToQuery) { # Resolve SNMP community for this node $community = $null $communitySecret = $null @@ -433,39 +501,61 @@ All SNMP attempts will be logged to verbose output. Write-Verbose " Querying $($node.IP) with community from $source" $output = Invoke-SnmpWalk -TargetIP $node.IP -Community $community -OID $OID -ErrorAction SilentlyContinue - if ($output.Count -eq 0) { + if ($null -eq $output -or @($output).Count -eq 0) { Write-Verbose "No SNMP data returned from $($node.IP)" continue } - # Parse LLDP output (simplified parser for MVP) - # Expected format: iso.0.8802.1.1.2.1.4.1.1.X.Y.Z = Type: Value + # Parse LLDP/CDP output. BEST-EFFORT MVP (see function help): we do not fully + # decode the LLDP MIB rows. For each output line we look only at the VALUE + # portion (right of '='), never the OID itself (the numeric OID contains + # dotted-decimal runs that would otherwise be mistaken for IPv4 addresses), + # extract an octet-validated IPv4 management address, and only create an edge + # when that address is already a known node. foreach ($line in $output) { - if ($line -match '(\d+\.\d+\.\d+\.\d+)') { + $value = if ($line -match '=\s*(.+)$') { $matches[1] } else { '' } + if ([string]::IsNullOrWhiteSpace($value)) { continue } + + $targetIP = $null + + # net-snmp renders an LLDP management address either as a dotted quad + # (sometimes prefixed 'IpAddress:') or as a 4-octet Hex-STRING. + if ($value -match '(?:IpAddress:\s*)?\b((?:25[0-5]|2[0-4]\d|1?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3})\b') { $targetIP = $matches[1] + } + elseif ($value -match 'Hex-STRING:\s*([0-9A-Fa-f]{2})[ :]+([0-9A-Fa-f]{2})[ :]+([0-9A-Fa-f]{2})[ :]+([0-9A-Fa-f]{2})') { + $targetIP = @( + [Convert]::ToInt32($matches[1], 16) + [Convert]::ToInt32($matches[2], 16) + [Convert]::ToInt32($matches[3], 16) + [Convert]::ToInt32($matches[4], 16) + ) -join '.' + } - # Check if target IP is in our topology - $targetNode = $Topology.Nodes | Where-Object { $_.IP -eq $targetIP } - if (-not $targetNode) { - continue - } + if ([string]::IsNullOrWhiteSpace($targetIP)) { continue } - # Extract interface label if possible - $label = 'LLDP' - if ($line -match 'ifName|Interface|Port\s*[:=]\s*(\S+)') { - $label = $matches[1] - } + # Skip self-loops. + if ($targetIP -eq $node.IP) { continue } - $edge = [pscustomobject]@{ - SourceIP = $node.IP - TargetIP = $targetIP - Label = $label - Source = 'SNMP' - Confidence = 'L2-SNMP' - } + # Only accept addresses that map to a node already in the topology. + $targetNode = $Topology.Nodes | Where-Object { $_.IP -eq $targetIP } + if (-not $targetNode) { continue } + + # Best-effort interface label extraction. + $label = 'LLDP' + if ($value -match '(?:ifName|Interface|Port(?:Id)?)\s*[:=]\s*"?([^"\s]+)"?') { + $label = $matches[1] + } - $null = $discoveredEdges.Add($edge) + $edge = [pscustomobject]@{ + SourceIP = $node.IP + TargetIP = $targetIP + Label = $label + Source = 'SNMP' + Confidence = 'L2-SNMP' } + + $null = $discoveredEdges.Add($edge) } } @@ -658,14 +748,29 @@ function Export-DrawIO { throw "Invalid topology object" } - # Build node ID map + # De-duplicate nodes by IP first. Duplicate IPs would otherwise share a single + # node-ID map entry yet each still be rendered, emitting multiple mxCells with + # the same id - which is invalid draw.io. Keep the first occurrence and warn. + $uniqueNodes = [System.Collections.Generic.List[object]]::new() + $seenIPs = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) + foreach ($node in $Topology.Nodes) { + if ([string]::IsNullOrWhiteSpace($node.IP)) { + Write-Warning "Skipping node with no IP address" + continue + } + if (-not $seenIPs.Add([string]$node.IP)) { + Write-Warning "Duplicate IP '$($node.IP)' - keeping first occurrence, skipping duplicate node" + continue + } + $uniqueNodes.Add($node) + } + + # Build node ID map (one entry per unique IP) $nodeIDMap = @{} $nextID = 2 # Start after mxCell id="0" and id="1" - foreach ($node in $Topology.Nodes) { - if (-not [string]::IsNullOrWhiteSpace($node.IP)) { - $nodeIDMap[$node.IP] = $nextID++ - } + foreach ($node in $uniqueNodes) { + $nodeIDMap[$node.IP] = $nextID++ } # Layer order for Y-axis positioning @@ -674,7 +779,7 @@ function Export-DrawIO { # Group nodes by layer $nodesByLayer = @{} foreach ($layer in $layerOrder) { - $nodesByLayer[$layer] = @($Topology.Nodes | Where-Object { $_.Layer -eq $layer }) + $nodesByLayer[$layer] = @($uniqueNodes | Where-Object { $_.Layer -eq $layer }) } # Start building XML @@ -711,16 +816,51 @@ function Export-DrawIO { $nextID = $containerID + # Map each node to the first subnet container whose CIDR contains it, so nodes + # are parented/positioned inside the right swimlane instead of always parent="1". + $nodeContainer = @{} + foreach ($node in $uniqueNodes) { + foreach ($subnet in $Topology.Subnets) { + if ($subnetContainers.ContainsKey($subnet.CIDR) -and (Test-IPInSubnet -IP $node.IP -CIDR $subnet.CIDR)) { + $nodeContainer[$node.IP] = $subnetContainers[$subnet.CIDR] + break + } + } + } + + # Layout bookkeeping: per-container child index, and a base Y for unmatched + # (canvas-level) nodes placed below the container grid so nothing overlaps. + $containerChildCount = @{} + $containerRows = [Math]::Ceiling($subnetContainers.Count / 2.0) + $unmatchedBaseY = 20 + ([int]$containerRows * 600) + 40 + # Add nodes with enhanced styles and metadata foreach ($layer in $layerOrder) { $nodesInLayer = $nodesByLayer[$layer] - $yPos = 60 + ($layerOrder.IndexOf($layer) * 130) + $layerIndex = $layerOrder.IndexOf($layer) for ($i = 0; $i -lt $nodesInLayer.Count; $i++) { $node = $nodesInLayer[$i] - $xPos = 60 + ($i * 190) $nodeID = $nodeIDMap[$node.IP] + # Decide parent container and geometry. Nodes matched to a subnet go + # inside that swimlane (geometry relative to the container); unmatched + # nodes are laid out on the open canvas by layer, below the containers. + if ($nodeContainer.ContainsKey($node.IP)) { + $parentID = $nodeContainer[$node.IP] + $childIndex = if ($containerChildCount.ContainsKey($parentID)) { $containerChildCount[$parentID] } else { 0 } + $containerChildCount[$parentID] = $childIndex + 1 + $col = $childIndex % 4 + $row = [Math]::Floor($childIndex / 4) + $xPos = 20 + ($col * 190) + $yPos = 40 + ($row * 110) + } + else { + $parentID = 1 + $xPos = 60 + ($i * 190) + $yPos = $unmatchedBaseY + ($layerIndex * 130) + } + # Get role-specific icon shape and colors $shapeConfig = switch ($node.Role) { 'core-router' { @{ shape='mxgraph.cisco.routers.router'; fillColor='#dae8fc'; strokeColor='#6c8ebf' } } @@ -765,7 +905,7 @@ function Export-DrawIO { ) $tooltip = [System.Security.SecurityElement]::Escape(($tooltipParts -join "`n")) - $null = $xml.AppendLine(" ") + $null = $xml.AppendLine(" ") $null = $xml.AppendLine(" ") $null = $xml.AppendLine(' ') @@ -1236,7 +1376,8 @@ function Resolve-IPHostname { .PARAMETER IPAddress IP address or array of IP addresses to resolve .PARAMETER TimeoutSeconds - DNS query timeout in seconds (default: 2) + DNS query timeout in seconds, 1-300 (default: 2). Enforced with an async lookup; + addresses that do not resolve within the window are returned with Success = $false. .EXAMPLE Resolve-IPHostname -IPAddress '8.8.8.8' @@ -1253,19 +1394,36 @@ function Resolve-IPHostname { [string[]]$IPAddress, [Parameter()] + [ValidateRange(1, 300)] [int]$TimeoutSeconds = 2 ) process { foreach ($ip in $IPAddress) { try { - $result = [System.Net.Dns]::GetHostEntry($ip) - - [pscustomobject]@{ - IPAddress = $ip - Hostname = $result.HostName - Aliases = $result.Aliases - Success = $true + # Honor TimeoutSeconds: resolve asynchronously and wait at most + # $TimeoutSeconds so a slow or unreachable resolver cannot hang the + # 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 + } } } catch { @@ -1392,9 +1550,11 @@ function Invoke-PortScan { .PARAMETER IPAddress Target IP address or array of IP addresses .PARAMETER Ports - Array of ports to scan (default: common ports 21,22,23,80,443,161,3389,8080) + Array of TCP ports to scan, 1-65535 (default: common TCP service ports). + Note: SNMP (161) is UDP and is deliberately NOT in the defaults - a TCP probe of + 161 does not detect SNMP. Use Invoke-SnmpWalk for SNMP. .PARAMETER TimeoutMs - Connection timeout in milliseconds (default: 1000) + Per-port connection timeout in milliseconds, 1-60000 (default: 1000) .PARAMETER GrabBanners Attempt to grab service banners from open ports .EXAMPLE @@ -1412,9 +1572,11 @@ function Invoke-PortScan { [string[]]$IPAddress, [Parameter()] - [int[]]$Ports = @(21, 22, 23, 25, 80, 443, 161, 445, 3389, 8080, 8443), + [ValidateRange(1, 65535)] + [int[]]$Ports = @(21, 22, 23, 25, 80, 443, 445, 3389, 8080, 8443), [Parameter()] + [ValidateRange(1, 60000)] [int]$TimeoutMs = 1000, [Parameter()] From af0d518ad7ea5cd1c029117d013329782337f2f4 Mon Sep 17 00:00:00 2001 From: jacobyoby Date: Thu, 30 Jul 2026 08:55:25 -0700 Subject: [PATCH 2/5] Bump module to 1.3.0 and reconcile docs - Manifest ModuleVersion 1.2.0 -> 1.3.0 with review-summary ReleaseNotes. - Add CHANGELOG 1.3.0 entry. - README: require 7.4+ (was 7.0+); document SNMP eligibility, -OnlyReachable, best-effort LLDP parsing, and community redaction/process-list caveat. - STRUCTURE: update to 1.3.0/2026-07-30, add .github CI to the layout, and describe the CI workflow. Co-Authored-By: wren --- CHANGELOG.md | 37 ++++++++++++++++++++++++++++++++ NetDiagram-PS/NetDiagram-PS.psd1 | 4 ++-- README.md | 15 +++++++++++-- STRUCTURE.md | 15 +++++++++++-- 4 files changed, 65 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 07b387a..6c723f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,43 @@ All notable changes to NetDiagram-PS will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [1.3.0] - 2026-07-30 + +### Fixed +- **SNMP discovery now works straight after `Import-Inventory`.** `Get-SnmpNeighbors` + only queried nodes with `Reachable -eq $true`, but freshly imported inventory has + `Reachable = $null`, so the documented import-then-discover workflow silently returned + nothing. Untested nodes are now eligible by default; only nodes proven unreachable are + skipped. New `-OnlyReachable` switch restores the strict behavior. +- **Community string no longer leaked to verbose output.** `Invoke-SnmpWalk` redacts + `-c ` to `-c ****` in verbose logging. Process-list exposure (inherent to + shelling out to net-snmp) is now documented as a known limitation. +- **`Export-DrawIO` duplicate-IP handling.** Duplicate device IPs overwrote the node-ID + map and emitted multiple `mxCell` elements with the same id (invalid draw.io). Nodes + are now de-duplicated by IP (first occurrence wins, with a warning). +- **Subnet containers now contain their nodes.** Nodes are parented into the matching + subnet swimlane via `Test-IPInSubnet` instead of always being parented to `1`; + unmatched nodes are laid out on the canvas below the containers. +- **Quick-start wizard subnet math.** The example script assumed a /24 (first three + octets, `.1`-`.254`). It now derives host addresses from the interface's real CIDR + prefix and caps scans of large subnets at a /22 (1022 hosts) with a warning. Also + fixed a Windows-separator `Join-Path` in the module path. +- `Resolve-IPHostname` now honors `-TimeoutSeconds` (previously ignored) using an async + DNS lookup with a bounded wait. + +### Changed +- **Hardened LLDP/CDP parsing.** The neighbor parser inspects only the value portion of + each line, validates IPv4 octets, decodes 4-octet `Hex-STRING` management addresses, + and skips self-loops. It remains best-effort (does not fully decode the LLDP MIB) and + is now clearly documented as such. +- **`Invoke-SnmpWalk` parameter validation.** SNMP `Version` restricted to v1/v2c/v3, + `TargetIP` validated as IPv4/FQDN, `OID` validated as dotted-decimal, and an + argument-injection guard rejects values beginning with `-`. Binary resolution is + restricted to `-CommandType Application`. +- **`Invoke-PortScan` validation.** `-Ports` constrained to 1-65535, `-TimeoutMs` to + 1-60000 (previously unbounded, allowing indefinite hangs). TCP 161 removed from the + defaults (SNMP is UDP; a TCP probe does not detect it). + ## [1.2.0] - 2025-11-02 ### Fixed diff --git a/NetDiagram-PS/NetDiagram-PS.psd1 b/NetDiagram-PS/NetDiagram-PS.psd1 index 8707496..ab2a863 100644 --- a/NetDiagram-PS/NetDiagram-PS.psd1 +++ b/NetDiagram-PS/NetDiagram-PS.psd1 @@ -1,6 +1,6 @@ @{ RootModule = 'NetDiagram-PS.psm1' - ModuleVersion = '1.2.0' + ModuleVersion = '1.3.0' GUID = 'a8f7e9c4-6d2b-4a1c-9e3f-7b8c9d0e1f2a' Author = 'Jacob Yoby' CompanyName = 'NetDiagram-PS' @@ -42,7 +42,7 @@ LicenseUri = 'https://github.com/jacobyoby/PSNetMap/blob/main/LICENSE' ProjectUri = 'https://github.com/jacobyoby/PSNetMap' IconUri = '' - ReleaseNotes = 'Version 1.2.0 - Fixed SNMP discovery on macOS/Linux (snmpwalk binary resolution), raised the minimum PowerShell version to 7.4 (Test-Connection -TimeoutSeconds), added CompatiblePSEditions, expanded the Pester suite, and documented the PowerShell Gallery publish path.' + ReleaseNotes = 'Version 1.3.0 - Code-review hardening. Get-SnmpNeighbors now queries untested nodes by default (Reachable = $null), fixing the import-then-discover workflow, with an -OnlyReachable opt-in switch. Invoke-SnmpWalk redacts the community string from verbose output, validates all parameters (SNMP version set, IP/FQDN, OID format, argument-injection guard), restricts binary resolution to Application, and documents process-list exposure. LLDP/CDP parsing hardened (value-only, octet-validated, Hex-STRING aware) and clearly documented as best-effort. Export-DrawIO de-duplicates node IPs and parents nodes into their matching subnet containers. Invoke-PortScan validates port/timeout ranges and drops TCP 161 (SNMP is UDP). Resolve-IPHostname now honors -TimeoutSeconds via async DNS. Example wizard uses real CIDR host enumeration (with a /22 scan cap) instead of assuming /24.' } } } diff --git a/README.md b/README.md index 9a193e1..208fa2f 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # NetDiagram-PS -NetDiagram-PS is a cross-platform PowerShell 7+ module that discovers your network topology and generates draw.io diagrams with Cisco network icons, subnet containers, and consistent styling. +NetDiagram-PS is a cross-platform PowerShell 7.4+ module that discovers your network topology and generates draw.io diagrams with Cisco network icons, subnet containers, and consistent styling. **✓ Windows | ✓ macOS | ✓ Linux** @@ -114,6 +114,17 @@ $topo = $topo | Get-SnmpNeighbors -CredentialMapPath '.\my-credmap.json' $topo | Export-DrawIO -OutFile '.\network.drawio' ``` +> **Note:** `Get-SnmpNeighbors` queries every imported node by default (nodes whose +> reachability has not been tested are still queried), so the workflow above runs end to +> end without a separate reachability pass. Add `-OnlyReachable` (after piping through +> `Test-DeviceReachability`) to query only nodes that answered a ping. +> +> **LLDP/CDP parsing is best-effort (MVP):** it extracts management IPs from `snmpwalk` +> output and links them to known nodes, but does not fully decode the LLDP MIB. Treat the +> resulting SNMP edges as hints to verify, not authoritative topology. The community +> string is redacted from verbose logging, but is briefly visible in the local process +> list while `snmpwalk` runs — prefer SNMPv3 for anything sensitive. + --- ## Inventory File Format @@ -320,7 +331,7 @@ Check the `examples/` directory: **Cause:** PowerShell version too old **Solutions:** -- Check version: `$PSVersionTable.PSVersion` (must be 7.0+) +- Check version: `$PSVersionTable.PSVersion` (must be 7.4+) - Upgrade: Download from https://aka.ms/powershell ### "SNMP returns nothing" diff --git a/STRUCTURE.md b/STRUCTURE.md index 728fdb8..9389169 100644 --- a/STRUCTURE.md +++ b/STRUCTURE.md @@ -6,8 +6,12 @@ This document describes the folder structure following PowerShell module best pr ``` PSNetMap/ +├── .github/ +│ └── workflows/ +│ └── ci.yml # CI: Pester (Win/macOS/Linux) + PSScriptAnalyzer ├── CHANGELOG.md # Release history ├── LICENSE # MIT License +├── PUBLISHING.md # PowerShell Gallery release process ├── README.md # Main documentation & quick start ├── STRUCTURE.md # This file ├── WHERE-TO-SAVE-FILES.txt # Guidance on storing personal data @@ -22,6 +26,13 @@ PSNetMap/ └── NetDiagram.Tests.ps1 # Tests for the module functions ``` +## Continuous Integration + +`.github/workflows/ci.yml` runs on every push/PR to `main`: +- **Pester** test suite on `ubuntu-latest`, `macos-latest`, and `windows-latest`. +- **PSScriptAnalyzer** (fails the build on any Error-severity finding). +- Manifest validation via `Test-ModuleManifest`. + ## Best Practices Implemented ### ✅ Standard PowerShell Module Layout @@ -73,5 +84,5 @@ For the easiest experience, run the wizard: --- -**Last Updated:** 2025-11-02 -**Module Version:** 1.1.0 +**Last Updated:** 2026-07-30 +**Module Version:** 1.3.0 From 72b46e6883748ad2a1083711782ee3e55cafb0c7 Mon Sep 17 00:00:00 2001 From: jacobyoby Date: Thu, 30 Jul 2026 08:55:25 -0700 Subject: [PATCH 3/5] Fix quick-start wizard subnet math and module path - Replace the /24 assumption with real IPv4 CIDR host enumeration derived from the interface prefix; cap Full scans of large subnets at a /22 (1022 hosts) with a warning; extract Get-SubnetScanTarget for testability. - Fix Windows-separator Join-Path for the module path. Co-Authored-By: wren --- examples/New-NetworkDiagram.ps1 | 125 ++++++++++++++++++++++++++++---- 1 file changed, 112 insertions(+), 13 deletions(-) diff --git a/examples/New-NetworkDiagram.ps1 b/examples/New-NetworkDiagram.ps1 index d617cf0..e20d7d2 100644 --- a/examples/New-NetworkDiagram.ps1 +++ b/examples/New-NetworkDiagram.ps1 @@ -8,7 +8,9 @@ This script automatically discovers your network configuration and creates a professional network diagram. No configuration files needed - just run it! .PARAMETER ScanDepth - How deep to scan: Quick (common IPs only), Medium (first 50 IPs), Full (all 254 IPs) + How deep to scan the detected subnet: Quick (up to 8 hosts sampled across the range), + Medium (first 50 hosts), Full (all usable hosts, capped at a /22 = 1022 hosts for + larger subnets). Host addresses are derived from the interface's real CIDR prefix. .PARAMETER OutputPath Where to save the diagram (default: .\my-network.drawio) .EXAMPLE @@ -29,8 +31,82 @@ param( [string]$OutputPath = '.\my-network.drawio' ) +# ── IPv4 CIDR helpers ──────────────────────────────────────────────────────── +# Real prefix-aware host enumeration (replaces the old /24-only "first 3 octets" +# assumption). Works for any prefix; the caller caps how many hosts get scanned. +function ConvertTo-UInt32Address { + param([Parameter(Mandatory)][string]$IPAddress) + $bytes = [System.Net.IPAddress]::Parse($IPAddress).GetAddressBytes() + if ([System.BitConverter]::IsLittleEndian) { [Array]::Reverse($bytes) } + return [System.BitConverter]::ToUInt32($bytes, 0) +} + +function ConvertFrom-UInt32Address { + param([Parameter(Mandatory)][uint32]$Value) + $bytes = [System.BitConverter]::GetBytes($Value) + if ([System.BitConverter]::IsLittleEndian) { [Array]::Reverse($bytes) } + return ([System.Net.IPAddress]::new($bytes)).ToString() +} + +function Get-PrefixMask { + param([Parameter(Mandatory)][int]$PrefixLength) + if ($PrefixLength -le 0) { return [uint32]0 } + if ($PrefixLength -ge 32) { return [uint32]4294967295 } + return [uint32]((([uint64]4294967295) -shl (32 - $PrefixLength)) -band [uint64]4294967295) +} + +function Get-SubnetScanTarget { + <# + .SYNOPSIS + Returns the list of host addresses (as UInt32 values) to scan within a subnet, + derived from the real network/broadcast bounds and bounded by scan depth. + .DESCRIPTION + Usable hosts are the addresses strictly between the network and broadcast + addresses. Quick samples up to 8 hosts spread across the range; Medium takes the + first 50; Full takes all usable hosts up to MaxScanHosts (a /22 by default). + #> + param( + [Parameter(Mandatory)][uint32]$NetworkValue, + [Parameter(Mandatory)][uint32]$BroadcastValue, + [ValidateSet('Quick', 'Medium', 'Full')][string]$ScanDepth = 'Quick', + [int]$MaxScanHosts = 1022 + ) + + [int64]$firstHost = [int64]$NetworkValue + 1 + [int64]$lastHost = [int64]$BroadcastValue - 1 + [int64]$usableCount = if ($lastHost -ge $firstHost) { $lastHost - $firstHost + 1 } else { 0 } + + $hostValues = [System.Collections.Generic.List[uint32]]::new() + if ($usableCount -le 0) { + # point-to-point (/31) or single host (/32): nothing to sweep + } + elseif ($ScanDepth -eq 'Quick') { + $sampleCount = [int][Math]::Min(8, $usableCount) + for ($s = 0; $s -lt $sampleCount; $s++) { + $offset = if ($sampleCount -eq 1) { 0 } else { [int64][Math]::Round(($s * ($usableCount - 1)) / ($sampleCount - 1)) } + $hostValues.Add([uint32]($firstHost + $offset)) + } + } + else { + $limit = if ($ScanDepth -eq 'Medium') { + [int64][Math]::Min(50, $usableCount) + } else { + [int64][Math]::Min($MaxScanHosts, $usableCount) + } + for ($h = 0; $h -lt $limit; $h++) { + $hostValues.Add([uint32]($firstHost + $h)) + } + } + + return $hostValues.ToArray() +} + +# Allow the Pester suite to dot-source this script for the CIDR helper functions above +# without launching the interactive wizard (which performs a live network scan). +if ($MyInvocation.InvocationName -eq '.') { return } + # Import the module -$modulePath = Join-Path $PSScriptRoot '..\NetDiagram-PS\NetDiagram-PS.psd1' +$modulePath = Join-Path $PSScriptRoot '..' 'NetDiagram-PS' 'NetDiagram-PS.psd1' if (-not (Test-Path $modulePath)) { Write-Host "✗ Module not found at: $modulePath" -ForegroundColor Red Write-Host " Please run this script from the examples/ folder or ensure NetDiagram-PS module is installed." -ForegroundColor Yellow @@ -182,10 +258,19 @@ $nodes = @() $edges = @() $subnets = @() -# Calculate subnet -$ipParts = $myIP.Split('.') -$subnet = "$($ipParts[0]).$($ipParts[1]).$($ipParts[2])" -$cidr = "$subnet.0/$prefix" +# Calculate subnet from the actual IP + prefix (real CIDR math, not a /24 assumption) +$prefixInt = [int]$prefix +if ($prefixInt -lt 0 -or $prefixInt -gt 32) { + Write-Host " Prefix /$prefixInt is invalid; defaulting to /24" -ForegroundColor Yellow + $prefixInt = 24 +} + +$ipValue = ConvertTo-UInt32Address $myIP +$mask = Get-PrefixMask -PrefixLength $prefixInt +$networkValue = $ipValue -band $mask +$broadcastValue = [uint32](($networkValue -bor ((-bnot $mask) -band [uint32]4294967295))) +$networkAddress = ConvertFrom-UInt32Address $networkValue +$cidr = "$networkAddress/$prefixInt" $subnets += [pscustomobject]@{ CIDR = $cidr @@ -293,19 +378,33 @@ Write-Host " Created base topology with $($nodes.Count) nodes" -ForegroundC # Step 3: Scan for additional devices Write-Host "`n[3/5] Scanning for other devices on your network..." -ForegroundColor Yellow -$scanRanges = switch ($ScanDepth) { - 'Quick' { @(1, 2, 10, 20, 50, 100, 200, 254) } - 'Medium' { 1..50 } - 'Full' { 1..254 } +# Enumerate real host addresses from the actual prefix. Usable hosts are between the +# network and broadcast addresses (for /31 and /32 there is no usable-host range). +$maxScanHosts = 1022 # a /22 worth of hosts - the scan cap for large subnets +[int64]$usableCount = [int64]$broadcastValue - [int64]$networkValue - 1 +if ($usableCount -lt 0) { $usableCount = 0 } + +if ($usableCount -le 0) { + Write-Host " Subnet $cidr has no scannable host range (point-to-point or /32)" -ForegroundColor Yellow +} +elseif ($ScanDepth -eq 'Full' -and $usableCount -gt $maxScanHosts) { + Write-Host " ⚠ Subnet /$prefixInt has $usableCount usable hosts; capping scan to the first $maxScanHosts (a /22)." -ForegroundColor Yellow + Write-Host " Use a smaller subnet or an inventory file for a full sweep." -ForegroundColor Yellow } -Write-Host " Scan depth: $ScanDepth ($($scanRanges.Count) addresses)" -ForegroundColor Cyan +$hostValues = Get-SubnetScanTarget -NetworkValue $networkValue -BroadcastValue $broadcastValue -ScanDepth $ScanDepth -MaxScanHosts $maxScanHosts + +# Materialize scan targets as IP strings before the parallel block (the CIDR helper +# functions are not available inside ForEach-Object -Parallel runspaces). +$scanTargets = @($hostValues | ForEach-Object { ConvertFrom-UInt32Address $_ }) + +Write-Host " Scan depth: $ScanDepth ($($scanTargets.Count) addresses in $cidr)" -ForegroundColor Cyan Write-Host " This may take 10-60 seconds..." -ForegroundColor Gray $discovered = [System.Collections.Concurrent.ConcurrentBag[object]]::new() -$scanRanges | ForEach-Object -Parallel { - $testIP = "$using:subnet.$_" +$scanTargets | ForEach-Object -Parallel { + $testIP = $_ # Skip IPs we already have if ($testIP -in @($using:myIP, $using:gateway) + $using:dnsServers) { From 0eb8ce962c9ab1504725df2c77569f0cc7ffabec Mon Sep 17 00:00:00 2001 From: jacobyoby Date: Thu, 30 Jul 2026 08:55:25 -0700 Subject: [PATCH 4/5] Add regression tests for the Codex review fixes Covers SNMP node eligibility (#1), Invoke-SnmpWalk parameter validation (#6), Invoke-PortScan validation (#7), Export-DrawIO duplicate-IP dedupe (#8) and subnet-container parenting (#9), and the wizard CIDR math (#4). Co-Authored-By: wren --- tests/NetDiagram.Tests.ps1 | 176 +++++++++++++++++++++++++++++++++++++ 1 file changed, 176 insertions(+) diff --git a/tests/NetDiagram.Tests.ps1 b/tests/NetDiagram.Tests.ps1 index 883e126..e321402 100644 --- a/tests/NetDiagram.Tests.ps1 +++ b/tests/NetDiagram.Tests.ps1 @@ -461,3 +461,179 @@ Describe 'Test-IPInSubnet (private helper)' { } } } + +Describe 'Get-SnmpNeighbors node eligibility (#1 regression)' { + BeforeEach { + # Empty credential map is valid; -TryPublic supplies the community so no + # SecretManagement dependency is needed for the test. + $script:CredMapPath = Join-Path $script:TestDataPath 'credmap-empty.json' + '{}' | Out-File -FilePath $script:CredMapPath -Force + } + + It 'Queries nodes with unknown reachability (Reachable = $null) by default' { + # Import-Inventory leaves Reachable = $null; these must still be queried. + $topology = Import-Inventory -Path $script:TestInventoryPath + Mock Invoke-SnmpWalk { @() } -ModuleName 'NetDiagram-PS' + + $null = $topology | Get-SnmpNeighbors -CredentialMapPath $script:CredMapPath -TryPublic -WarningAction SilentlyContinue + + Should -Invoke Invoke-SnmpWalk -ModuleName 'NetDiagram-PS' -Times 3 -Exactly + } + + It 'Skips untested nodes when -OnlyReachable is specified' { + $topology = Import-Inventory -Path $script:TestInventoryPath + Mock Invoke-SnmpWalk { @() } -ModuleName 'NetDiagram-PS' + + $null = $topology | Get-SnmpNeighbors -CredentialMapPath $script:CredMapPath -TryPublic -OnlyReachable -WarningAction SilentlyContinue + + Should -Invoke Invoke-SnmpWalk -ModuleName 'NetDiagram-PS' -Times 0 -Exactly + } + + It 'Does not query nodes explicitly marked unreachable' { + $topology = Import-Inventory -Path $script:TestInventoryPath + foreach ($n in $topology.Nodes) { $n.Reachable = $false } + $topology.Nodes[0].Reachable = $true + Mock Invoke-SnmpWalk { @() } -ModuleName 'NetDiagram-PS' + + $null = $topology | Get-SnmpNeighbors -CredentialMapPath $script:CredMapPath -TryPublic -WarningAction SilentlyContinue + + # Only the single reachable/unmarked node should be queried + Should -Invoke Invoke-SnmpWalk -ModuleName 'NetDiagram-PS' -Times 1 -Exactly + } +} + +Describe 'Invoke-SnmpWalk parameter validation (#6 regression)' { + It 'Rejects an invalid SNMP version' { + { Invoke-SnmpWalk -TargetIP '192.0.2.1' -Community 'public' -Version 'v9' } | Should -Throw + } + + It 'Rejects a TargetIP beginning with a dash (argument-injection guard)' { + { Invoke-SnmpWalk -TargetIP '-oOutputFile' -Community 'public' } | Should -Throw + } + + It 'Rejects a community beginning with a dash' { + { Invoke-SnmpWalk -TargetIP '192.0.2.1' -Community '-c' } | Should -Throw + } + + It 'Rejects a non-numeric OID' { + { Invoke-SnmpWalk -TargetIP '192.0.2.1' -Community 'public' -OID 'not.an.oid' } | Should -Throw + } + + It 'Accepts a valid FQDN target' { + # Valid params get past binding; with the binary mocked away it throws the + # "not found" error, which proves validation passed. + Mock Get-Command { $null } -ModuleName 'NetDiagram-PS' -ParameterFilter { $Name -like 'snmpwalk*' } + { Invoke-SnmpWalk -TargetIP 'switch01.example.com' -Community 'public' } | + Should -Throw -ExpectedMessage '*snmpwalk not found*' + } +} + +Describe 'Invoke-PortScan parameter validation (#7 regression)' { + It 'Rejects a port outside 1-65535' { + { Invoke-PortScan -IPAddress '192.0.2.1' -Ports 70000 } | Should -Throw + } + + It 'Rejects a timeout outside 1-60000 (guards against indefinite hang)' { + { Invoke-PortScan -IPAddress '192.0.2.1' -TimeoutMs 0 } | Should -Throw + } +} + +Describe 'Export-DrawIO duplicate-IP handling (#8 regression)' { + It 'Emits unique mxCell ids and de-duplicates nodes sharing an IP' { + $topology = [pscustomobject]@{ + Nodes = @( + [pscustomobject]@{ IP = '192.168.1.5'; Hostname = 'dup-a'; Role = 'switch'; Vendor = 'x'; OS = 'x'; Layer = 'Access'; Reachable = $true } + [pscustomobject]@{ IP = '192.168.1.5'; Hostname = 'dup-b'; Role = 'switch'; Vendor = 'x'; OS = 'x'; Layer = 'Access'; Reachable = $true } + [pscustomobject]@{ IP = '192.168.1.6'; Hostname = 'uniq'; Role = 'server'; Vendor = 'x'; OS = 'x'; Layer = 'Servers'; Reachable = $true } + ) + Edges = @() + Subnets = @() + } + + $drawioPath = Join-Path $script:TestDataPath 'dup-ip.drawio' + $topology | Export-DrawIO -OutFile $drawioPath -WarningAction SilentlyContinue + + $xml = [xml](Get-Content -Path $drawioPath -Raw) + $ids = @($xml.SelectNodes('//mxCell') | ForEach-Object { $_.id }) + + # All mxCell ids must be unique + ($ids | Sort-Object -Unique).Count | Should -Be $ids.Count + + # Duplicate IP collapsed to a single node vertex (2 unique IPs) + @($xml.SelectNodes("//mxCell[@vertex='1']")).Count | Should -Be 2 + } +} + +Describe 'Export-DrawIO subnet container parenting (#9 regression)' { + It 'Parents nodes into the matching subnet container instead of the root' { + # Test inventory nodes live in 192.168.1.0/24 and there is a matching subnet. + $topology = Import-Inventory -Path $script:TestInventoryPath + $drawioPath = Join-Path $script:TestDataPath 'containers.drawio' + $topology | Export-DrawIO -OutFile $drawioPath + + $xml = [xml](Get-Content -Path $drawioPath -Raw) + $container = @($xml.SelectNodes("//mxCell[contains(@style,'swimlane')]"))[0] + $container | Should -Not -BeNullOrEmpty + + $nodeCells = @($xml.SelectNodes("//mxCell[@vertex='1' and not(contains(@style,'swimlane'))]")) + $nodeCells.Count | Should -Be 3 + foreach ($n in $nodeCells) { + $n.parent | Should -Be $container.id + } + } +} + +Describe 'Quick-start wizard CIDR math (#4 regression)' { + BeforeAll { + # Dot-source the example; the dot-source guard returns before the wizard body + # runs, so only the pure CIDR helper functions get defined. + $exampleScript = Join-Path $PSScriptRoot '..' 'examples' 'New-NetworkDiagram.ps1' + . $exampleScript + } + + It 'Computes the correct network address for a non-/24 prefix' { + $ipValue = ConvertTo-UInt32Address '10.0.5.37' + $mask = Get-PrefixMask -PrefixLength 22 + $network = ConvertFrom-UInt32Address ([uint32]($ipValue -band $mask)) + $network | Should -Be '10.0.4.0' + } + + It 'Round-trips an address through UInt32 conversion' { + ConvertFrom-UInt32Address (ConvertTo-UInt32Address '192.168.1.200') | Should -Be '192.168.1.200' + } + + It 'Enumerates all usable hosts of a /24 on Full depth' { + $net = ConvertTo-UInt32Address '192.168.1.0' + $bc = ConvertTo-UInt32Address '192.168.1.255' + $targets = @(Get-SubnetScanTarget -NetworkValue $net -BroadcastValue $bc -ScanDepth 'Full') + $targets.Count | Should -Be 254 + (ConvertFrom-UInt32Address $targets[0]) | Should -Be '192.168.1.1' + (ConvertFrom-UInt32Address $targets[-1]) | Should -Be '192.168.1.254' + } + + It 'Caps a large subnet (/16) at a /22 worth of hosts on Full depth' { + $net = ConvertTo-UInt32Address '10.1.0.0' + $bc = ConvertTo-UInt32Address '10.1.255.255' + $targets = @(Get-SubnetScanTarget -NetworkValue $net -BroadcastValue $bc -ScanDepth 'Full' -MaxScanHosts 1022) + $targets.Count | Should -Be 1022 + } + + It 'Samples at most 8 in-range hosts on Quick depth' { + $net = ConvertTo-UInt32Address '192.168.1.0' + $bc = ConvertTo-UInt32Address '192.168.1.255' + $targets = @(Get-SubnetScanTarget -NetworkValue $net -BroadcastValue $bc -ScanDepth 'Quick') + $targets.Count | Should -BeLessOrEqual 8 + $targets.Count | Should -BeGreaterThan 0 + foreach ($t in $targets) { + (ConvertTo-UInt32Address (ConvertFrom-UInt32Address $t)) | Should -BeGreaterThan $net + (ConvertTo-UInt32Address (ConvertFrom-UInt32Address $t)) | Should -BeLessThan $bc + } + } + + It 'Returns no targets for a /31 point-to-point link' { + $net = ConvertTo-UInt32Address '10.0.0.0' + $bc = ConvertTo-UInt32Address '10.0.0.1' + $targets = @(Get-SubnetScanTarget -NetworkValue $net -BroadcastValue $bc -ScanDepth 'Full') + $targets.Count | Should -Be 0 + } +} From 23513507f97fc7143fdee58b29d84a356d7ff733 Mon Sep 17 00:00:00 2001 From: jacobyoby Date: Thu, 30 Jul 2026 08:55:25 -0700 Subject: [PATCH 5/5] Ignore code-review artifacts and logs Co-Authored-By: wren --- .gitignore | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.gitignore b/.gitignore index 9f24b27..bfa9a1e 100644 --- a/.gitignore +++ b/.gitignore @@ -38,3 +38,9 @@ dist/ # PowerShell module cache PSGetModuleInfo.xml + +# Code review artifacts / logs (never commit) +CODEX_REVIEW.txt +*-review.txt +*review*.log +review-*.md