chcp 65001 > $null $ErrorActionPreference = 'SilentlyContinue' $PSDefaultParameterValues['Format-Table:AutoSize'] = $true function Section([string]$t) { Write-Host '' Write-Host ('=' * 30) -ForegroundColor DarkCyan Write-Host (" $t") -ForegroundColor Cyan Write-Host ('=' * 30) -ForegroundColor DarkCyan } function Status([bool]$ok) { if ($ok) { Write-Host 'OK' -ForegroundColor Green } else { Write-Host 'FAIL' -ForegroundColor Red } } function Dim([string]$s) { Write-Host $s -ForegroundColor DarkGray } Section '1. Physical links & tunnels' Get-NetAdapter | Select-Object @{ n = 'State'; e = { if ($_.Status -eq 'Up') { '[x]' } else { '[ ]' } } }, Name, InterfaceDescription, MediaType, LinkSpeed, MacAddress | Format-Table Dim ' [x] = Up [ ] = Down' Section '2. IP config (IPv4 / public IPv6 / Gateway)' Get-NetIPConfiguration | Where-Object { $_.IPv4Address -or $_.IPv6Address } | ForEach-Object { Write-Host (' {0} (ifIndex {1})' -f $_.InterfaceAlias, $_.InterfaceIndex) -ForegroundColor Yellow $ip4 = ($_.IPv4Address | ForEach-Object IPAddress) -join ', ' if ($ip4) { Write-Host (' IPv4 : {0}' -f $ip4) } $ip6 = ($_.IPv6Address | Where-Object { $_.IPAddress -notmatch '^(::1|fe80|fc|fd)' } | ForEach-Object IPAddress) -join ', ' if ($ip6) { Write-Host (' IPv6(glob): {0}' -f $ip6) } $gw = ($_.IPv4DefaultGateway | ForEach-Object NextHop) -join ', ' if ($gw) { Write-Host (' Gateway : {0}' -f $gw) } } Section '3. DNS servers' Get-NetIPInterface -AddressFamily IPv4 | Where-Object ConnectionState -eq 'Connected' | ForEach-Object { [PSCustomObject]@{ Interface = $_.InterfaceAlias DHCP = $_.Dhcp DNS = ((Get-DnsClientServerAddress -InterfaceIndex $_.InterfaceIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue).ServerAddresses -join ', ') } } | Format-Table Section '4. Windows proxy (WinINET)' $p = Get-ItemProperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings' Write-Host ' ProxyEnable : ' -NoNewline if ($p.ProxyEnable) { Write-Host $p.ProxyEnable -ForegroundColor Yellow } else { Write-Host $p.ProxyEnable -ForegroundColor DarkGray } Write-Host (' ProxyServer : {0}' -f $p.ProxyServer) Write-Host (' ProxyOverride : {0}' -f $p.ProxyOverride) Write-Host (' AutoConfigURL : {0}' -f $p.AutoConfigURL) Write-Host (' AutoDetect : {0}' -f $p.AutoDetect) Section '5. WinHTTP proxy' netsh winhttp show proxy Section '6. Default routes' Dim ' IPv4:' Get-NetRoute -DestinationPrefix '0.0.0.0/0' | Select-Object ifIndex, InterfaceAlias, NextHop, RouteMetric | Format-Table Dim ' IPv6:' Get-NetRoute -DestinationPrefix '::/0' | Select-Object ifIndex, InterfaceAlias, NextHop, RouteMetric | Format-Table Section '6b. Default egress (effective metric, lower wins)' $eg4 = Find-NetRoute -RemoteIPAddress '223.5.5.5' | Select-Object -First 1 $eg6 = Find-NetRoute -RemoteIPAddress '2400:3200::1' | Select-Object -First 1 Get-NetRoute -DestinationPrefix '0.0.0.0/0' | ForEach-Object { $m = (Get-NetIPInterface -InterfaceIndex $_.ifIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue).InterfaceMetric [PSCustomObject]@{ Sel = if ($eg4 -and $_.ifIndex -eq $eg4.InterfaceIndex -and ((-not $eg4.PSObject.Properties['NextHop']) -or (-not $eg4.NextHop) -or [string]$_.NextHop -eq [string]$eg4.NextHop)) { '>>' } else { '' } Effective = ($_.RouteMetric + $m) Interface = $_.InterfaceAlias NextHop = $_.NextHop IfIndex = $_.ifIndex } } | Sort-Object Effective, IfIndex | Format-Table # Resolve the exact selected default route per address family. Do not keep every # NextHop from the selected interface in $nh4/$nh6: one interface may legitimately # have multiple default gateways, and treating that array as one path makes active / # alternate route classification ambiguous. $selRoute4 = $null; $selRoute6 = $null if ($eg4) { if ($eg4.PSObject.Properties['NextHop'] -and $eg4.NextHop) { $eg4Nh = [string]$eg4.NextHop $selRoute4 = Get-NetRoute -DestinationPrefix '0.0.0.0/0' -InterfaceIndex $eg4.InterfaceIndex -ErrorAction SilentlyContinue | Where-Object { [string]$_.NextHop -eq $eg4Nh } | Sort-Object RouteMetric | Select-Object -First 1 } if (-not $selRoute4) { $selRoute4 = Get-NetRoute -DestinationPrefix '0.0.0.0/0' -InterfaceIndex $eg4.InterfaceIndex -ErrorAction SilentlyContinue | Sort-Object RouteMetric | Select-Object -First 1 } } if ($eg6) { if ($eg6.PSObject.Properties['NextHop'] -and $eg6.NextHop) { $eg6Nh = [string]$eg6.NextHop $selRoute6 = Get-NetRoute -DestinationPrefix '::/0' -InterfaceIndex $eg6.InterfaceIndex -ErrorAction SilentlyContinue | Where-Object { [string]$_.NextHop -eq $eg6Nh } | Sort-Object RouteMetric | Select-Object -First 1 } if (-not $selRoute6) { $selRoute6 = Get-NetRoute -DestinationPrefix '::/0' -InterfaceIndex $eg6.InterfaceIndex -ErrorAction SilentlyContinue | Sort-Object RouteMetric | Select-Object -First 1 } } $nh4 = if ($selRoute4 -and $selRoute4.NextHop -and [string]$selRoute4.NextHop -ne '0.0.0.0') { [string]$selRoute4.NextHop } else { '' } $nh6 = if ($selRoute6 -and $selRoute6.NextHop -and [string]$selRoute6.NextHop -ne '::') { [string]$selRoute6.NextHop } else { '' } if ($eg4) { Write-Host ' IPv4 egress -> ' -NoNewline -ForegroundColor Green Write-Host ('{0} (ifIndex {1}) src {2} via {3}' -f $eg4.InterfaceAlias, $eg4.InterfaceIndex, $eg4.IPAddress, $nh4) -ForegroundColor White } else { Write-Host ' IPv4 egress -> none' -ForegroundColor Yellow } if ($eg6) { Write-Host ' IPv6 egress -> ' -NoNewline -ForegroundColor Green Write-Host ('{0} (ifIndex {1}) src {2} via {3}' -f $eg6.InterfaceAlias, $eg6.InterfaceIndex, $eg6.IPAddress, $nh6) -ForegroundColor White } else { Write-Host ' IPv6 egress -> none' -ForegroundColor DarkGray } Section '7. Proxy / Tunnel / VPN processes' $names = 'clash|mihomo|verge|v2ray|xray|sing-box|singbox|shadowsocks|ssr|trojan|naive|hysteria|tun2socks|openvpn|wireguard|tailscale|zerotier|frpc|frps|natfrp|gost|proxifier|netch|qv2ray|hiddify|surge|nordvpn|expressvpn|windscribe' $procs = Get-Process | Where-Object { $_.Name -match $names } if ($procs) { $procs | Select-Object Name, Id, Path | Format-Table } else { Write-Host ' none found' } Section '8. Local listening ports (all owners; proxy scoring later)' $allListenEarly = @(Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue | Sort-Object LocalAddress, LocalPort, OwningProcess -Unique) $lp = @() if ($procs) { $lp = @($allListenEarly | Where-Object { $procs.Id -contains $_.OwningProcess }) } if ($allListenEarly) { $allListenEarly | Select-Object @{ n = 'Addr'; e = { $_.LocalAddress } }, LocalPort, @{ n = 'PID'; e = { $_.OwningProcess } }, @{ n = 'Process'; e = { $pp0 = Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue; if ($pp0) { $pp0.Name } else { '?' } } } | Format-Table } else { Write-Host ' none found' } Section '9. Gateway reachability' $gatewayProbeRowsConsole = New-Object System.Collections.ArrayList foreach ($grt in @((Get-NetRoute -DestinationPrefix '0.0.0.0/0' -ErrorAction SilentlyContinue), (Get-NetRoute -DestinationPrefix '::/0' -ErrorAction SilentlyContinue)) | Where-Object { $_ }) { $gw = [string]$grt.NextHop if (-not $gw -or $gw -in @('0.0.0.0','::')) { continue } $fam = if ($gw -match ':') { 'IPv6' } else { 'IPv4' } $target = if ($fam -eq 'IPv6' -and $gw -match '^fe80:' -and $gw -notmatch '%') { $gw + '%' + [string]$grt.ifIndex } else { $gw } $probeKey = [string]$grt.ifIndex + '|' + $fam + '|' + $gw if (@($gatewayProbeRowsConsole | Where-Object Key -eq $probeKey).Count -gt 0) { continue } $ok = Test-Connection -ComputerName $target -Count 1 -Quiet [void]$gatewayProbeRowsConsole.Add([PSCustomObject]@{ Key = $probeKey; Gateway = $gw; Family = $fam; IfIndex = [int]$grt.ifIndex; Ping = $(if ($ok) { 'OK' } else { 'FAIL' }) }) Write-Host (' {0,-39} {1} ifIndex {2} ' -f $gw, $fam, $grt.ifIndex) -NoNewline Status $ok } Section '10. Internet reachability (IPv4 / IPv6)' $r4 = Test-NetConnection -ComputerName '223.5.5.5' -InformationLevel Detailed -WarningAction SilentlyContinue Write-Host ' 223.5.5.5 IPv4 : ' -NoNewline; Status $r4.PingSucceeded Write-Host (' egress -> {0} src {1}' -f $r4.InterfaceAlias, $r4.SourceAddress.IPAddress) $r6 = Test-NetConnection -ComputerName '2400:3200::1' -InformationLevel Detailed -WarningAction SilentlyContinue Write-Host ' 2400:3200::1 IPv6 : ' -NoNewline; Status $r6.PingSucceeded Write-Host (' egress -> {0} src {1}' -f $r6.InterfaceAlias, $r6.SourceAddress.IPAddress) Section '11. BIT campus infra (BitConnected targets)' $targets = '10.0.0.55', '10.0.0.54', '10.0.32.32', '10.0.32.33' $bitPing = @{} foreach ($ip in $targets) { $ping = Test-Connection -ComputerName $ip -Count 1 -Quiet $bitPing[$ip] = $ping $rt = Find-NetRoute -RemoteIPAddress $ip -ErrorAction SilentlyContinue | Select-Object -First 1 Write-Host (' {0,-16}' -f $ip) -NoNewline Status $ping if ($rt) { Dim (' via ' + $rt.InterfaceAlias) } else { Dim ' via none' } } $portalHttp = $false; $portalTitle = ''; $portalHttpMs = -1 $portalSw = [System.Diagnostics.Stopwatch]::StartNew() try { $r = Invoke-WebRequest -Uri 'http://10.0.0.55/' -TimeoutSec 8 -UseBasicParsing $portalHttp = ($r.StatusCode -eq 200) $portalTitle = [regex]::Match($r.Content, '(.*?)').Groups[1].Value $portalSw.Stop(); $portalHttpMs = [math]::Round($portalSw.Elapsed.TotalMilliseconds) Write-Host ' Portal 10.0.0.55 HTTP : ' -NoNewline Status $portalHttp Write-Host (' title = {0}' -f $portalTitle) } catch { if ($portalSw.IsRunning) { $portalSw.Stop() } Write-Host ' Portal 10.0.0.55 HTTP : ' -NoNewline Status $false } $loginInfo = [PSCustomObject]@{ Ok = $false; Id = ''; Ip = ''; SumBytes = ''; SumTime = ''; Raw = '' } try { $lu = Invoke-WebRequest -Uri 'http://10.0.0.55/cgi-bin/rad_user_info' -TimeoutSec 6 -UseBasicParsing $c = $lu.Content.Trim() Write-Host ' Login 10.0.0.55 rad_user_info : ' -NoNewline $fields = @() if ($c -match '^\{') { $j = $c | ConvertFrom-Json $fields = @($j.user_name, $j.online_ip, $j.sum_bytes, $j.sum_seconds) if ($fields[0]) { $loginInfo = [PSCustomObject]@{ Ok = $true; Id = $fields[0]; Ip = $fields[1]; SumBytes = $fields[2]; SumTime = $fields[3]; Raw = $c } } } elseif ($c -match '^\w+\(') { $j = [regex]::Match($c, '\(([\s\S]*)\)').Groups[1].Value | ConvertFrom-Json $loginInfo = [PSCustomObject]@{ Ok = $true; Id = $j.user_name; Ip = $j.online_ip; SumBytes = $j.sum_bytes; SumTime = $j.sum_seconds; Raw = $c } } elseif ($c -match ',') { $fields = $c -split ',' if ($fields.Count -ge 9) { $loginInfo = [PSCustomObject]@{ Ok = $true; Id = $fields[0]; Ip = $fields[8]; SumBytes = $fields[3]; SumTime = $fields[4]; Raw = $c } } } Status $loginInfo.Ok if ($loginInfo.Ok) { Write-Host (' id = {0} ip = {1} sum_bytes = {2} sum_seconds = {3}' -f $loginInfo.Id, $loginInfo.Ip, $loginInfo.SumBytes, $loginInfo.SumTime) } else { Write-Host ' (unrecognized response shape)' } } catch { Write-Host ' Login 10.0.0.55 rad_user_info : ' -NoNewline Status $false } $bitDns = @{} foreach ($dns in '10.0.32.32', '10.0.32.33') { try { $a = (Resolve-DnsName -Name www.baidu.com -Server $dns -Type A -ErrorAction Stop | Where-Object IPAddress | Select-Object -First 1).IPAddress $av = Find-NetRoute -RemoteIPAddress $a -ErrorAction SilentlyContinue | Select-Object -First 1 $aa = if ($av) { Get-NetAdapter -InterfaceIndex $av.InterfaceIndex -ErrorAction SilentlyContinue } else { $null } $intercepted = [bool]($aa -and $aa.MediaType -eq 'IP') $tag = if ($intercepted) { ' [proxy-intercepted]' } else { '' } $bitDns[$dns] = [PSCustomObject]@{ Ok = $true; Answer = $a; Flag = $(if ($intercepted) { 'proxy' } else { 'direct' }) } Write-Host (' DNS {0,-16}' -f $dns) -NoNewline Status $true Write-Host (' -> {0}{1}' -f $a, $tag) } catch { $bitDns[$dns] = [PSCustomObject]@{ Ok = $false; Answer = ''; Flag = '' } Write-Host (' DNS {0,-16}' -f $dns) -NoNewline Status $false } } $bitApi = [PSCustomObject]@{ Ok = $false; Http = -1; Title = '' }; $bitApiMs = -1 $bitApiSw = [System.Diagnostics.Stopwatch]::StartNew() try { $ra = Invoke-WebRequest -Uri 'http://10.0.0.54:8800/' -TimeoutSec 6 -UseBasicParsing $bitApi = [PSCustomObject]@{ Ok = $true; Http = $ra.StatusCode; Title = [regex]::Match($ra.Content, '(.*?)').Groups[1].Value } $bitApiSw.Stop(); $bitApiMs = [math]::Round($bitApiSw.Elapsed.TotalMilliseconds) Write-Host ' API 10.0.0.54:8800 HTTP : ' -NoNewline Status $true Write-Host (' status = {0}' -f $ra.StatusCode) } catch { if ($bitApiSw.IsRunning) { $bitApiSw.Stop() } $pt = Test-NetConnection -ComputerName '10.0.0.54' -Port 8800 -WarningAction SilentlyContinue -InformationLevel Quiet $bitApi = [PSCustomObject]@{ Ok = $pt; Http = 0; Title = '' } Write-Host ' API 10.0.0.54:8800 HTTP : ' -NoNewline Status $pt Write-Host ' (fallback: tcp probe)' } # ================= HTML report (two views: detail chain + node graph) ================= function Enc([string]$s) { [System.Net.WebUtility]::HtmlEncode($s) } function Table-Html($rows) { if (-not $rows) { return '
no data
' } $props = @($rows[0].PSObject.Properties.Name) $tb = New-Object System.Text.StringBuilder [void]$tb.Append('') foreach ($pr in $props) { [void]$tb.Append('') } [void]$tb.Append('') foreach ($r in $rows) { [void]$tb.Append('') foreach ($pr in $props) { [void]$tb.Append('') } [void]$tb.Append('') } [void]$tb.Append('
' + (Enc $pr) + '
' + (Enc $r.$pr) + '
') return $tb.ToString() } function Block-Html($b) { $cls = 'block'; if ($b.sel) { $cls = 'block selected' } $st = switch ($b.status) { 'OK' { 'OK' } 'FAIL' { 'FAIL' } default { '' } } $rows = '' foreach ($r in $b.rows) { $rows += '
' + $r + '
' } $hh = $b.hash.Substring(0, 14) $ph = $b.prev.Substring(0, 14) @"
#$($b.i)$st
$(Enc $b.title)
$(Enc $b.sub)
$rows
hash$hh…
prev$ph…
"@ } $ts = Get-Date -Format 'yyyy-MM-dd HH:mm:ss' $hostname = [System.Net.Dns]::GetHostName() $os = (Get-CimInstance Win32_OperatingSystem -ErrorAction SilentlyContinue).Caption $selAlias = if ($eg4) { $eg4.InterfaceAlias } else { '' } $selIdx = if ($eg4) { $eg4.InterfaceIndex } else { 0 } $v4txt = if ($r4.PingSucceeded) { 'OK' } else { 'FAIL' } $v6txt = if ($r6.PingSucceeded) { 'OK' } else { 'FAIL' } $r4src = if ($r4.SourceAddress) { $r4.SourceAddress.IPAddress } else { '' } # V5.2 general-fit adapter assessment. Route existence is evidence that an interface # can carry traffic; it is NOT proof that the interface is a physical NIC. A scored # assessment combines MediaType, PnP/driver identity, Windows PhysicalAdapter/Virtual # flags, address/DNS patterns and route shape. This catches renamed TAP/TUN adapters # without forcing every Hyper-V/VMware/PPP/RNDIS carrier into the tunnel bucket. $adapterAssessmentCache = @{} $cimAdapterByIf = @{} foreach ($ca in @(Get-CimInstance Win32_NetworkAdapter -ErrorAction SilentlyContinue | Where-Object { $null -ne $_.InterfaceIndex })) { $cimAdapterByIf[[string]$ca.InterfaceIndex] = $ca } $signedNetDriverByDevice = @{} foreach ($sd in @(Get-CimInstance Win32_PnPSignedDriver -ErrorAction SilentlyContinue | Where-Object { [string]$_.DeviceClass -eq 'NET' -and $_.DeviceID })) { $signedNetDriverByDevice[[string]$sd.DeviceID.ToUpperInvariant()] = $sd } $tunnelIdentityRegex = '(?i)\b(TUN|TAP|Wintun|WireGuard|Tailscale|ZeroTier|OpenVPN|VPN|Mihomo|Clash|sing[- ]?box|v2ray|xray|tun2socks|WinDivert|redirect|packet[ -]?filter)\b|tap0901' $knownVirtualCarrierRegex = '(?i)VMware|VirtualBox|Hyper-V|vEthernet|Docker|WSL|Npcap|Loopback|Bluetooth.*PAN' $pointCarrierRegex = '(?i)\b(PPP|RAS|RNDIS|WWAN|LTE|5G|cellular|mobile broadband)\b|USB.*tether' function Test-FakeIpStyleAddress([string]$addr) { if (-not $addr) { return $false } $v = $addr.Trim().Trim('[', ']') $pct = $v.IndexOf('%'); if ($pct -gt 0) { $v = $v.Substring(0, $pct) } $ipObj = $null if (-not [System.Net.IPAddress]::TryParse($v, [ref]$ipObj)) { return $false } if ($ipObj.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork) { $bb = $ipObj.GetAddressBytes() return [bool]($bb[0] -eq 198 -and ($bb[1] -eq 18 -or $bb[1] -eq 19)) } return [bool]($ipObj.ToString() -match '(?i)^fdfe:') } function Get-AdapterAssessment($ad) { if (-not $ad) { return $null } $key = [string]$ad.InterfaceIndex if ($adapterAssessmentCache.ContainsKey($key)) { return $adapterAssessmentCache[$key] } $cim = if ($cimAdapterByIf.ContainsKey($key)) { $cimAdapterByIf[$key] } else { $null } $pnpId = if ($cim) { [string]$cim.PNPDeviceID } else { '' } $signed = if ($pnpId -and $signedNetDriverByDevice.ContainsKey($pnpId.ToUpperInvariant())) { $signedNetDriverByDevice[$pnpId.ToUpperInvariant()] } else { $null } $service = if ($cim) { [string]$cim.ServiceName } else { '' } $provider = if ($signed) { [string]$signed.DriverProviderName } else { '' } $infName = if ($signed) { [string]$signed.InfName } else { '' } $driverVersion = if ($signed) { [string]$signed.DriverVersion } else { '' } $identity = ([string]$ad.Name + ' ' + [string]$ad.InterfaceDescription + ' ' + $service + ' ' + $provider + ' ' + $infName) $mt = [string]$ad.MediaType $default4 = @(Get-NetRoute -DestinationPrefix '0.0.0.0/0' -InterfaceIndex $ad.InterfaceIndex -ErrorAction SilentlyContinue) $default6 = @(Get-NetRoute -DestinationPrefix '::/0' -InterfaceIndex $ad.InterfaceIndex -ErrorAction SilentlyContinue) $hasDefault4 = $default4.Count -gt 0; $hasDefault6 = $default6.Count -gt 0; $hasDefault = $hasDefault4 -or $hasDefault6 $hasGateway = [bool](@($default4 | Where-Object { $_.NextHop -and [string]$_.NextHop -ne '0.0.0.0' }).Count -gt 0 -or @($default6 | Where-Object { $_.NextHop -and [string]$_.NextHop -ne '::' }).Count -gt 0) $vp = $ad.PSObject.Properties | Where-Object { $_.Name -eq 'Virtual' } | Select-Object -First 1 $virtualFlag = [bool]($vp -and [bool]$vp.Value) $cimPhysicalKnown = [bool]($cim -and $null -ne $cim.PhysicalAdapter) $cimPhysical = [bool]($cimPhysicalKnown -and [bool]$cim.PhysicalAdapter) $cimVirtual = [bool]($cimPhysicalKnown -and -not [bool]$cim.PhysicalAdapter) $rootEnumerated = [bool]($pnpId -match '(?i)^(ROOT|SWD|HTREE)\\') $knownVirtualCarrier = [bool]($identity -match $knownVirtualCarrierRegex) $pointCarrier = [bool]($identity -match $pointCarrierRegex) $isVirtual = $virtualFlag -or $cimVirtual -or $rootEnumerated $ipTexts = @(Get-NetIPAddress -InterfaceIndex $ad.InterfaceIndex -ErrorAction SilentlyContinue | ForEach-Object { [string]$_.IPAddress } | Where-Object { $_ }) $dnsTexts = @( (Get-DnsClientServerAddress -InterfaceIndex $ad.InterfaceIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue).ServerAddresses (Get-DnsClientServerAddress -InterfaceIndex $ad.InterfaceIndex -AddressFamily IPv6 -ErrorAction SilentlyContinue).ServerAddresses ) | Where-Object { $_ } | Select-Object -Unique $fakeIp = @($ipTexts | Where-Object { Test-FakeIpStyleAddress ([string]$_) }) $fakeDns = @($dnsTexts | Where-Object { Test-FakeIpStyleAddress ([string]$_) }) $loopDns = @($dnsTexts | Where-Object { [string]$_ -match '^(127\.|::1$)' }) $tun = 0.0; $carrier = 0.0; $signals = New-Object System.Collections.ArrayList if ($mt -eq 'IP') { $tun += 6.0; [void]$signals.Add('MediaType=IP') } if ($identity -match $tunnelIdentityRegex) { $tun += 8.0; [void]$signals.Add('tunnel/VPN identity in adapter, service or driver') } if ($fakeIp.Count -gt 0) { $tun += 6.0; [void]$signals.Add('198.18/15 or fdfe:: style interface address') } if ($fakeDns.Count -gt 0) { $tun += 5.0; [void]$signals.Add('198.18/15 or fdfe:: style DNS') } if ($loopDns.Count -gt 0) { $tun += 0.75; [void]$signals.Add('loopback DNS (weak signal)') } if ($isVirtual -and $hasDefault -and -not $knownVirtualCarrier -and -not $pointCarrier) { $tun += 4.0; [void]$signals.Add('virtual/non-physical adapter owns default route') } if ($isVirtual -and $hasDefault -and -not $hasGateway -and -not $pointCarrier) { $tun += 1.5; [void]$signals.Add('default route without conventional gateway') } if ($cimPhysical) { $carrier += 7.0; [void]$signals.Add('Win32_NetworkAdapter.PhysicalAdapter=true') } if ($mt -in @('802.3','Native 802.11')) { $carrier += 2.0 } if ($pnpId -match '(?i)^(PCI|USB)\\' -and -not $cimVirtual) { $carrier += 2.5; [void]$signals.Add('hardware-enumerated PCI/USB network device') } if ($pointCarrier) { $carrier += 5.0; [void]$signals.Add('PPP/RNDIS/WWAN carrier identity') } if ($knownVirtualCarrier -and $hasDefault) { $carrier += 4.0; [void]$signals.Add('known virtual/bridged carrier identity') } if ($hasDefault) { $carrier += 1.0 } $role = 'Other'; $confidence = 0.35 if ($tun -ge 7.0 -and $tun -gt ($carrier + 1.5)) { $role = 'Tunnel'; $confidence = [math]::Min(0.98, 0.74 + $tun * 0.02) } elseif ($tun -ge 4.0 -and $hasDefault -and $tun -ge $carrier) { $role = 'SuspectedTunnel'; $confidence = [math]::Min(0.79, 0.50 + $tun * 0.035) } elseif ($carrier -ge 5.0 -and $carrier -gt $tun) { $role = 'Carrier'; $confidence = [math]::Min(0.98, 0.68 + $carrier * 0.025) } elseif ($hasDefault -and -not $isVirtual -and $mt -in @('802.3','Native 802.11')) { $role = 'Carrier'; $confidence = 0.68 } elseif ($hasDefault) { $role = 'AmbiguousRoute'; $confidence = 0.45 } $result = [PSCustomObject]@{ IfIndex = [int]$ad.InterfaceIndex; Name = [string]$ad.Name; Role = $role; Confidence = [math]::Round($confidence, 2) TunnelScore = [math]::Round($tun, 2); CarrierScore = [math]::Round($carrier, 2); HasDefault4 = $hasDefault4; HasDefault6 = $hasDefault6 HasGateway = $hasGateway; IsVirtual = $isVirtual; PhysicalAdapter = $(if ($cimPhysicalKnown) { [string][bool]$cim.PhysicalAdapter } else { '?' }) ServiceName = $service; DriverProvider = $provider; InfName = $infName; DriverVersion = $driverVersion; PnpId = $pnpId FakeIP = ($fakeIp -join ', '); FakeDNS = ($fakeDns -join ', '); LoopbackDNS = ($loopDns -join ', '); Signals = @($signals) } $adapterAssessmentCache[$key] = $result return $result } function Test-IsTunnelAdapter($ad) { $aa = Get-AdapterAssessment $ad return [bool]($aa -and $aa.Role -in @('Tunnel','SuspectedTunnel')) } function Test-IsPhysicalAdapter($ad) { $aa = Get-AdapterAssessment $ad return [bool]($aa -and $aa.Role -eq 'Carrier') } $egAd = if ($eg4) { Get-NetAdapter -InterfaceIndex $eg4.InterfaceIndex -ErrorAction SilentlyContinue } else { $null } $egIsTun = [bool]($egAd -and (Test-IsTunnelAdapter $egAd)) $eg4Cidr = '' if ($eg4) { $eg4IpObj = Get-NetIPAddress -InterfaceIndex $eg4.InterfaceIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue | Where-Object { [string]$_.IPAddress -eq [string]$eg4.IPAddress } | Select-Object -First 1 if ($eg4IpObj) { $eg4Cidr = [string]$eg4IpObj.IPAddress + '/' + [string]$eg4IpObj.PrefixLength } elseif ($eg4.IPAddress) { $eg4Cidr = [string]$eg4.IPAddress } } $hops = New-Object System.Collections.ArrayList $h0 = @('trafficall local TCP/UDP') [void]$hops.Add([PSCustomObject]@{ name = ''; title = 'Applications'; sub = 'local user apps & system traffic'; rows = $h0; status = '' }) $h1 = @() $tunDns = '' if ($egIsTun -and $eg4) { if ($eg4Cidr) { $h1 += 'IPv4' + (Enc $eg4Cidr) + '' } if ($eg6 -and $eg6.InterfaceIndex -eq $eg4.InterfaceIndex) { $h1 += 'IPv6' + (Enc $eg6.IPAddress) + '' } $h1 += 'ifIndex' + $eg4.InterfaceIndex + '' if ($nh4) { $h1 += 'via' + (Enc $nh4) + '' } $tunDns = ((Get-DnsClientServerAddress -InterfaceIndex $eg4.InterfaceIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue).ServerAddresses | Select-Object -Unique) -join ' ' if ($tunDns) { $h1 += 'DNS' + (Enc $tunDns) + '' } [void]$hops.Add([PSCustomObject]@{ name = $eg4.InterfaceAlias; title = ($eg4.InterfaceAlias + ' TUN'); sub = 'selected default route (tunnel)'; rows = $h1; status = 'OK' }) } $mh = $procs | Where-Object { $_.Name -match '(mihomo|xray|v2ray|clash|sing-box|singbox|gost|trojan|hysteria)' } | Sort-Object { $_.Name -notmatch '(mihomo|xray|v2ray|sing-box|singbox|gost|trojan|hysteria)' } | Select-Object -First 1 $mhcore = if ($mh) { $mh.Name } else { 'proxy core' } $mhcoreSub = if ($mh) { 'proxy core process' } else { 'unidentified proxy core' } $h2 = @() if ($mh) { $h2 += 'PID' + $mh.Id + '' if ($mh.Path) { $h2 += 'path' + (Enc $mh.Path) + '' } } $mlp = if ($mh) { $lp | Where-Object { $_.OwningProcess -eq $mh.Id } | Select-Object -ExpandProperty LocalPort } else { @() } if ($mlp) { $h2 += 'listen' + (($mlp | ForEach-Object { ':' + $_ }) -join ' ') + '' } if ($egIsTun -and $mh) { [void]$hops.Add([PSCustomObject]@{ name = ''; title = $mhcore; sub = $mhcoreSub; rows = $h2; status = '' }) } # Build every UP physical default-route candidate. Each interface keeps its own # next hop; later graph projection therefore supports Wi-Fi + LAN connected to # different routers instead of pretending that all adapters belong to one Gateway. $physCandidatesRaw = New-Object System.Collections.ArrayList foreach ($rt in @(Get-NetRoute -DestinationPrefix '0.0.0.0/0' -ErrorAction SilentlyContinue)) { $ad = Get-NetAdapter -InterfaceIndex $rt.ifIndex -ErrorAction SilentlyContinue if (-not $ad -or $ad.Status -ne 'Up' -or -not (Test-IsPhysicalAdapter $ad)) { continue } $ipif = Get-NetIPInterface -InterfaceIndex $rt.ifIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue $cfgx = Get-NetIPConfiguration -InterfaceIndex $rt.ifIndex -ErrorAction SilentlyContinue $ipv4x = if ($cfgx) { (($cfgx.IPv4Address | ForEach-Object IPAddress) -join ', ') } else { '' } $gwx = if ($rt.NextHop -and $rt.NextHop -ne '0.0.0.0') { [string]$rt.NextHop } elseif ($cfgx) { (($cfgx.IPv4DefaultGateway | ForEach-Object NextHop) -join ', ') } else { '' } $ifMetric = if ($ipif) { [int]$ipif.InterfaceMetric } else { 0 } $routeMetric = [int]$rt.RouteMetric [void]$physCandidatesRaw.Add([PSCustomObject]@{ Route = $rt; IfIndex = [int]$rt.ifIndex; Name = [string]$ad.Name; Desc = [string]$ad.InterfaceDescription AddressFamily = 'IPv4'; MediaType = [string]$ad.MediaType; LinkSpeed = [string]$ad.LinkSpeed; IPv4 = $ipv4x; Gateway = $gwx InterfaceMetric = $ifMetric; RouteMetric = $routeMetric; EffectiveMetric = ($ifMetric + $routeMetric) }) } $physCandidates = @($physCandidatesRaw | Sort-Object EffectiveMetric, IfIndex | Group-Object { [string]$_.IfIndex + '|' + [string]$_.Gateway } | ForEach-Object { $_.Group | Select-Object -First 1 }) # Keep IPv6 default-route candidates separately. The same physical NIC may have an # independent IPv6 next hop, and multiple physical NICs may be simultaneously usable. $physCandidatesV6Raw = New-Object System.Collections.ArrayList foreach ($rt6 in @(Get-NetRoute -DestinationPrefix '::/0' -ErrorAction SilentlyContinue)) { $ad6 = Get-NetAdapter -InterfaceIndex $rt6.ifIndex -ErrorAction SilentlyContinue if (-not $ad6 -or $ad6.Status -ne 'Up' -or -not (Test-IsPhysicalAdapter $ad6)) { continue } $ipif6 = Get-NetIPInterface -InterfaceIndex $rt6.ifIndex -AddressFamily IPv6 -ErrorAction SilentlyContinue $ifMetric6 = if ($ipif6) { [int]$ipif6.InterfaceMetric } else { 0 } $routeMetric6 = [int]$rt6.RouteMetric $gw6 = if ($rt6.NextHop -and [string]$rt6.NextHop -ne '::') { [string]$rt6.NextHop } else { '' } [void]$physCandidatesV6Raw.Add([PSCustomObject]@{ Route = $rt6; IfIndex = [int]$rt6.ifIndex; Name = [string]$ad6.Name; Desc = [string]$ad6.InterfaceDescription AddressFamily = 'IPv6'; MediaType = [string]$ad6.MediaType; LinkSpeed = [string]$ad6.LinkSpeed; IPv4 = ''; Gateway = $gw6 InterfaceMetric = $ifMetric6; RouteMetric = $routeMetric6; EffectiveMetric = ($ifMetric6 + $routeMetric6) }) } $physCandidatesV6 = @($physCandidatesV6Raw | Sort-Object EffectiveMetric, IfIndex | Group-Object { [string]$_.IfIndex + '|' + [string]$_.Gateway } | ForEach-Object { $_.Group | Select-Object -First 1 }) $allPhysicalRouteCandidates = @($physCandidates) + @($physCandidatesV6) $physPrimary = $null if ($egIsTun) { $physPrimary = $physCandidates | Where-Object { $_.IfIndex -ne $selIdx } | Sort-Object EffectiveMetric, IfIndex | Select-Object -First 1 } elseif ($eg4) { $physPrimary = $physCandidates | Where-Object { $_.IfIndex -eq $selIdx -and ((-not $nh4) -or $_.Gateway -eq [string]$nh4) } | Sort-Object EffectiveMetric, IfIndex | Select-Object -First 1 if (-not $physPrimary) { $physPrimary = $physCandidates | Where-Object { $_.IfIndex -eq $selIdx } | Sort-Object EffectiveMetric, IfIndex | Select-Object -First 1 } } if (-not $physPrimary) { $physPrimary = $physCandidates | Sort-Object EffectiveMetric, IfIndex | Select-Object -First 1 } $physRoute = if ($physPrimary) { $physPrimary.Route } else { $null } if (-not $physRoute -and $eg4) { $physRoute = Get-NetRoute -DestinationPrefix '0.0.0.0/0' -InterfaceIndex $selIdx -ErrorAction SilentlyContinue | Select-Object -First 1 } $physIp = ''; $physGw = ''; $linkTxt = '' if ($physRoute) { $cfg = Get-NetIPConfiguration -InterfaceIndex $physRoute.ifIndex -ErrorAction SilentlyContinue $physIp = ($cfg.IPv4Address | ForEach-Object IPAddress) -join ', ' $physGw = if ($physRoute.NextHop -and $physRoute.NextHop -ne '0.0.0.0') { [string]$physRoute.NextHop } else { ($cfg.IPv4DefaultGateway | ForEach-Object NextHop) -join ', ' } $egAd2 = Get-NetAdapter -InterfaceIndex $physRoute.ifIndex -ErrorAction SilentlyContinue if ($egAd2) { if ($egAd2.MediaType -eq 'Native 802.11') { $wl = (netsh wlan show interfaces) -join "`n" $dm = [regex]::Match($wl, '(?m):\s*(-\d{1,3})\s*$') $pm = [regex]::Match($wl, '(?m):\s*(\d{1,3})%\s*$') $sig = if ($pm.Success) { $pm.Groups[1].Value + '%' } else { '' } $dbm = if ($dm.Success) { ' (' + $dm.Groups[1].Value + ' dBm)' } else { '' } $linkTxt = if ($sig) { $sig + $dbm } else { [string]$egAd2.LinkSpeed } } else { $linkTxt = [string]$egAd2.LinkSpeed } } } $h3 = @() if ($physRoute) { $h3 += 'adapter' + (Enc $physRoute.InterfaceAlias) + '' $h3 += 'ifIndex' + $physRoute.ifIndex + '' } if ($physIp) { $h3 += 'IPv4' + (Enc $physIp) + '' } if ($physGw) { $h3 += 'gateway' + (Enc $physGw) + '' } [void]$hops.Add([PSCustomObject]@{ name = ''; title = 'Physical NIC'; sub = 'upstream carrier'; rows = $h3; status = $(if ($physRoute) { 'OK' } else { 'FAIL' }) }) $gwOk = if ($physGw) { Test-Connection -ComputerName $physGw -Count 1 -Quiet } else { $false } $h4 = @() if ($physGw) { $h4 += 'address' + (Enc $physGw) + '' } $h4 += 'ping' + $(if ($gwOk) { 'reachable' } else { 'timeout' }) + '' [void]$hops.Add([PSCustomObject]@{ name = ''; title = 'LAN Gateway'; sub = 'first hop to ISP'; rows = $h4; status = $(if ($gwOk) { 'OK' } else { 'FAIL' }) }) $h5 = @('probe223.5.5.5') if ($r4.InterfaceAlias) { $h5 += 'egress' + (Enc $r4.InterfaceAlias) + '' } if ($r4src) { $h5 += 'src' + (Enc $r4src) + '' } [void]$hops.Add([PSCustomObject]@{ name = ''; title = 'Internet / ISP'; sub = 'IPv4 reachability'; rows = $h5; status = $(if ($r4.PingSucceeded) { 'OK' } else { 'FAIL' }) }) $sha = [System.Security.Cryptography.SHA256]::Create() function Get-ChainHash([string]$s) { $b = [System.Text.Encoding]::UTF8.GetBytes($s) (($sha.ComputeHash($b) | ForEach-Object { $_.ToString('x2') }) -join '') } $blocks = New-Object System.Collections.ArrayList $prev = '0' * 64 for ($i = 0; $i -lt $hops.Count; $i++) { $hop = $hops[$i] $txt = ($hop.rows | ForEach-Object { ($_ -replace '<[^>]+>', ' ') -replace '\s+', ' ' }) -join '; ' $content = "height=$i|title=$($hop.title)|sub=$($hop.sub)|rows=$txt|prev=$prev" $h = Get-ChainHash $content [void]$blocks.Add([PSCustomObject]@{ i = $i; sel = ($hop.name -and $hop.name -eq $selAlias); title = $hop.title; sub = $hop.sub; rows = $hop.rows; status = $hop.status; hash = $h; prev = $prev }) $prev = $h } $connSvg = '' $sb = New-Object System.Text.StringBuilder [void]$sb.Append('

Default egress chain

') [void]$sb.Append('
') for ($i = 0; $i -lt $blocks.Count; $i++) { if ($i -gt 0) { [void]$sb.Append($connSvg) } [void]$sb.Append((Block-Html $blocks[$i])) } [void]$sb.Append('
') $adRows = Get-NetAdapter | Sort-Object InterfaceIndex | ForEach-Object { [PSCustomObject]@{ State = $(if ($_.Status -eq 'Up') { 'UP' } else { 'DOWN' }); Name = $_.Name; Desc = $_.InterfaceDescription; Speed = $_.LinkSpeed; MAC = $_.MacAddress } } $ipRows = Get-NetIPConfiguration | Where-Object { $_.IPv4Address -or $_.IPv6Address } | ForEach-Object { [PSCustomObject]@{ Interface = $_.InterfaceAlias ifIndex = $_.InterfaceIndex IPv4 = (($_.IPv4Address | ForEach-Object IPAddress) -join ', ') IPv6 = (($_.IPv6Address | Where-Object { $_.IPAddress -notmatch '^(::1|fe80|fc|fd)' } | ForEach-Object IPAddress) -join ', ') Gateway = (($_.IPv4DefaultGateway | ForEach-Object NextHop) -join ', ') } } $dnsRows = Get-NetIPInterface -AddressFamily IPv4 | Where-Object ConnectionState -eq 'Connected' | ForEach-Object { [PSCustomObject]@{ Interface = $_.InterfaceAlias DHCP = $_.Dhcp DNS = ((Get-DnsClientServerAddress -InterfaceIndex $_.InterfaceIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue).ServerAddresses -join ', ') } } $route4 = @(Get-NetRoute -DestinationPrefix '0.0.0.0/0' | Select-Object ifIndex, InterfaceAlias, NextHop, RouteMetric) $route6 = @(Get-NetRoute -DestinationPrefix '::/0' | Select-Object ifIndex, InterfaceAlias, NextHop, RouteMetric) $egRows = @(Get-NetRoute -DestinationPrefix '0.0.0.0/0' | ForEach-Object { $m = (Get-NetIPInterface -InterfaceIndex $_.ifIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue).InterfaceMetric [PSCustomObject]@{ Selected = $(if ($_.InterfaceAlias -eq $selAlias -and $_.ifIndex -eq $selIdx) { '>>' } else { '' }) Effective = ($_.RouteMetric + $m) Interface = $_.InterfaceAlias NextHop = $_.NextHop ifIndex = $_.ifIndex } } | Sort-Object Effective, ifIndex) $procRows = @(if ($procs) { $procs | Select-Object Name, Id, Path } else { @() }) $portRows = @(if ($lp) { $lp | Select-Object @{ n = 'Addr'; e = { $_.LocalAddress } }, LocalPort, @{ n = 'Process'; e = { (Get-Process -Id $_.OwningProcess).Name } } } else { @() }) $gwRows = @($gatewayProbeRowsConsole | Select-Object Gateway, Family, IfIndex, Ping) $r6src = if ($r6.SourceAddress) { $r6.SourceAddress.IPAddress } else { '' } $reachRows = @( [PSCustomObject]@{ Dest = '223.5.5.5 (IPv4)'; Result = $v4txt; Egress = $(if ($r4.InterfaceAlias) { $r4.InterfaceAlias } else { '' }); Src = $r4src }, [PSCustomObject]@{ Dest = '2400:3200::1 (IPv6)'; Result = $v6txt; Egress = $(if ($r6.InterfaceAlias) { $r6.InterfaceAlias } else { '' }); Src = $r6src } ) $winhttp = (netsh winhttp show proxy) -join '
' $proxyHtml = '
' $proxyHtml += '
ProxyEnable' + $p.ProxyEnable + '
' $proxyHtml += '
ProxyServer' + (Enc $p.ProxyServer) + '
' $proxyHtml += '
Override' + (Enc $p.ProxyOverride) + '
' $proxyHtml += '
AutoConfigURL' + (Enc $p.AutoConfigURL) + '
' $proxyHtml += '
' $sections = @( [PSCustomObject]@{ t = 'Adapters'; b = (Table-Html $adRows) }, [PSCustomObject]@{ t = 'IP configuration'; b = (Table-Html $ipRows) }, [PSCustomObject]@{ t = 'DNS servers'; b = (Table-Html $dnsRows) }, [PSCustomObject]@{ t = 'Default routes IPv4'; b = (Table-Html $route4) }, [PSCustomObject]@{ t = 'Default routes IPv6'; b = (Table-Html $route6) }, [PSCustomObject]@{ t = 'Egress selection (effective metric)'; b = (Table-Html $egRows) }, [PSCustomObject]@{ t = 'Proxy / tunnel / VPN processes'; b = (Table-Html $procRows) }, [PSCustomObject]@{ t = 'Proxy listening ports'; b = (Table-Html $portRows) }, [PSCustomObject]@{ t = 'Gateway reachability'; b = (Table-Html $gwRows) }, [PSCustomObject]@{ t = 'Internet reachability'; b = (Table-Html $reachRows) }, [PSCustomObject]@{ t = 'Windows proxy (WinINET)'; b = $proxyHtml }, [PSCustomObject]@{ t = 'WinHTTP proxy'; b = ('
' + $winhttp + '
') } ) foreach ($s in $sections) { [void]$sb.Append('
' + (Enc $s.t) + '
' + $s.b + '
') } $viewChain = $sb.ToString() $ip4str = $eg4Cidr $ip6str = if ($eg6) { [string]$eg6.IPAddress } else { '' } $mhpid = if ($mh) { [string]$mh.Id } else { '' } $mhlisten = if ($mlp) { (($mlp | ForEach-Object { ':' + $_ }) -join ' ') } else { '' } $mhEndpoint = '' if ($mh -and $lp) { $mhConn = $lp | Where-Object { $_.OwningProcess -eq $mh.Id } | Sort-Object LocalPort | Select-Object -First 1 if ($mhConn) { $la = [string]$mhConn.LocalAddress if ($la -match ':') { $mhEndpoint = '[' + $la + ']:' + [string]$mhConn.LocalPort } else { $mhEndpoint = $la + ':' + [string]$mhConn.LocalPort } } } $physName = if ($physRoute) { $physRoute.InterfaceAlias } else { '' } $physIdx = if ($physRoute) { [string]$physRoute.ifIndex } else { '' } $mhstat = $(if ($physRoute) { 'OK' } else { 'FAIL' }) $gwstat = $(if ($gwOk) { 'OK' } else { 'FAIL' }) $ipstat = $(if ($r4.PingSucceeded) { 'OK' } else { 'FAIL' }) $gwping = $(if ($gwOk) { 'reachable' } else { 'timeout' }) $egalias4 = if ($r4.InterfaceAlias) { $r4.InterfaceAlias } else { '' } # Graph probes deliberately return a status plus a compact measurement so that # a parent item can summarize the child before following the edge to the node. function Test-Dns([string]$server) { $sw = [System.Diagnostics.Stopwatch]::StartNew() $ok = $false $answer = '' try { $rr = Resolve-DnsName -Name 'www.baidu.com' -Server $server -Type A -DnsOnly -ErrorAction Stop $answer = [string](($rr | Where-Object IPAddress | Select-Object -First 1).IPAddress) $ok = [bool]$rr } catch { } $sw.Stop() [PSCustomObject]@{ Ok = $ok; Ms = [math]::Round($sw.Elapsed.TotalMilliseconds); Answer = $answer } } function Test-PingProbe([string]$target, [int]$timeoutMs = 1400) { if (-not $target) { return [PSCustomObject]@{ Ok = $false; Ms = -1 } } $pg = New-Object System.Net.NetworkInformation.Ping try { $reply = $pg.Send($target, $timeoutMs) $ok = ($reply.Status -eq [System.Net.NetworkInformation.IPStatus]::Success) $ms = if ($ok) { [int]$reply.RoundtripTime } else { -1 } [PSCustomObject]@{ Ok = $ok; Ms = $ms } } catch { [PSCustomObject]@{ Ok = $false; Ms = -1 } } finally { $pg.Dispose() } } function Test-TcpProbe([string]$target, [int]$port, [int]$timeoutMs = 1400) { if (-not $target -or $port -le 0) { return [PSCustomObject]@{ Ok = $false; Ms = -1 } } $tcp = New-Object System.Net.Sockets.TcpClient $sw = [System.Diagnostics.Stopwatch]::StartNew() $ok = $false try { $task = $tcp.ConnectAsync($target, $port) if ($task.Wait($timeoutMs) -and $tcp.Connected) { $ok = $true } } catch { } $sw.Stop() $tcp.Dispose() [PSCustomObject]@{ Ok = $ok; Ms = $(if ($ok) { [math]::Round($sw.Elapsed.TotalMilliseconds) } else { -1 }) } } function GItem { param( [string]$id, [string]$k, [string]$v, [string]$status = '', [string]$meta = '', [string]$role = 'prop', [bool]$probe = $false, $detail = $null ) [ordered]@{ id = $id; k = $k; v = $v; status = $status; meta = $meta role = $role; probe = $probe; detail = $detail } } function GDetail { param( [string]$label, [string]$sub, [string]$kind, [string]$status, $items ) [ordered]@{ label = $label; sub = $sub; kind = $kind; status = $status; items = @($items) } } function GStatus([bool]$ok) { if ($ok) { 'OK' } else { 'FAIL' } } function GProbeMeta([bool]$ok, $probe) { if (-not $ok) { return 'T/O' } if ($probe -and $probe.Ms -ge 0) { return ([string]$probe.Ms + ' ms') } return 'T/O' } $dhcpSrv = '' try { $dhcpSrv = (Get-CimInstance Win32_NetworkAdapterConfiguration | Where-Object { $_.DHCPEnabled -and $_.IPEnabled } | Select-Object -First 1).DHCPServer } catch { } if (-not $dhcpSrv) { $dhcpSrv = $physGw } # Keep the original WinINET -> listening process resolution. The graph uses the # result as a real process node when a system proxy is enabled. $sysProxyOn = $false if ($p.ProxyEnable -and $p.ProxyServer) { $sysProxyOn = $true } $proxyProcName = ''; $proxyProcPid = ''; $proxyDead = $false $proxyEndpoints = @() $proxyCands = New-Object System.Collections.ArrayList if ($sysProxyOn) { foreach ($seg in (@($p.ProxyServer -split ';') | Where-Object { $_ -match ':\d{2,5}' })) { $pm = [regex]::Match($seg, '((?:https?|socks)\s*=\s*)?[\d\.a-z\*\[\]]*:(\d{2,5})') if ($pm.Success) { $pport = [int]$pm.Groups[2].Value $ppc = Get-NetTCPConnection -State Listen -LocalPort $pport -ErrorAction SilentlyContinue | Select-Object -First 1 $procNow = '' if ($ppc) { $procp = Get-Process -Id $ppc.OwningProcess -ErrorAction SilentlyContinue if ($procp) { $procNow = $procp.Name; if (-not $proxyProcName) { $proxyProcName = $procNow; $proxyProcPid = [string]$procp.Id } } } $proxyEndpoints += [PSCustomObject]@{ Endpoint = $seg.Trim(); Port = $pport; Up = [bool]$ppc } } } $proxyDead = (-not $proxyProcName) -and ($proxyEndpoints.Count -gt 0) if ($proxyDead) { $kw = '(clash|mihomo|verge|v2ray|xray|sing.?box|shadowsocks|ssr|trojan|hysteria|gost|naive|proxy|tunnel)' $inst = @() foreach ($root in @('HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*', 'HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*', 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*')) { $inst += Get-ItemProperty $root -ErrorAction SilentlyContinue } foreach ($u in $inst) { if ($u.DisplayName -match $kw) { [void]$proxyCands.Add([PSCustomObject]@{ Via = 'uninstall'; Name = $u.DisplayName; Path = $(if ($u.InstallLocation) { $u.InstallLocation } else { '' }) }) } } foreach ($rk in @('HKCU:\Software\Microsoft\Windows\CurrentVersion\Run', 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Run', 'HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Run')) { $rp = Get-ItemProperty $rk -ErrorAction SilentlyContinue if ($rp) { $rp.PSObject.Properties | Where-Object { $_.Name -notmatch '^PS' -and [string]$_.Value -match $kw } | ForEach-Object { [void]$proxyCands.Add([PSCustomObject]@{ Via = 'autostart'; Name = $_.Name; Path = [string]$_.Value }) } } } foreach ($sm in @("$env:ProgramData\Microsoft\Windows\Start Menu\Programs", "$env:APPDATA\Microsoft\Windows\Start Menu\Programs")) { Get-ChildItem $sm -Recurse -Filter *.lnk -ErrorAction SilentlyContinue | Where-Object { $_.Name -match $kw } | ForEach-Object { [void]$proxyCands.Add([PSCustomObject]@{ Via = 'startmenu'; Name = $_.BaseName; Path = $_.FullName }) } } foreach ($proot in @($env:ProgramFiles, "${env:ProgramFiles(x86)}")) { Get-ChildItem $proot -Directory -ErrorAction SilentlyContinue | Where-Object { $_.Name -match $kw } | ForEach-Object { [void]$proxyCands.Add([PSCustomObject]@{ Via = 'installdir'; Name = $_.Name; Path = $_.FullName }) } } foreach ($croot in @($env:APPDATA, $env:LOCALAPPDATA, "$env:USERPROFILE\.config")) { foreach ($cwd in (Get-ChildItem $croot -Directory -ErrorAction SilentlyContinue | Where-Object { $_.Name -match $kw })) { foreach ($pport2 in ($proxyEndpoints | ForEach-Object Port | Sort-Object -Unique)) { $hit = $false Get-ChildItem $cwd.FullName -File -Recurse -Depth 2 -Include '*.yaml', '*.yml', '*.json', '*.toml', '*.conf', '*.ini', '*.txt' -ErrorAction SilentlyContinue | Select-String -Pattern '(127\.0\.0\.1|localhost):' + $pport2 + '\b' -List | ForEach-Object { $hit = $true; [void]$proxyCands.Add([PSCustomObject]@{ Via = ('config:' + $pport2); Name = $cwd.Name; Path = $_.Path }) } if ($hit) { break } } } } } if ($proxyDead) { Write-Host ' System proxy -> software NOT running:' -ForegroundColor Yellow Write-Host (' proxy = {0}' -f $p.ProxyServer) foreach ($ep in $proxyEndpoints) { Write-Host (' {0} : {1}' -f $ep.Endpoint, $(if ($ep.Up) { 'UP' } else { 'DOWN' })) } $uniq = @($proxyCands | Select-Object -Unique) if ($uniq.Count -gt 0) { $uniq | Select-Object -First 8 | ForEach-Object { Write-Host (' candidate [{0}] {1} {2}' -f $_.Via, $_.Name, $_.Path) } } else { Write-Host ' no matching installed software found' } } elseif ($proxyProcName) { Write-Host (' System proxy -> running: {0} (PID {1})' -f $proxyProcName, $proxyProcPid) } } # ---------- V5.2 general-fit discovery: inventory -> evidence -> entity-compact flow-first graph projection ---------- # V5 keeps topology-driven discovery and adds identity-independent interception evidence; do not hard-code a single # mihomo -> one local relay -> one TUN re-entry pattern. Runtime sockets/routes are # authoritative; product-specific configuration/API data only enriches or raises the # confidence of relationships. Idle-path fallbacks are explicitly POSSIBLE, never # promoted to confirmed connectivity. function Get-CommandArgValue([string]$cmd, [string]$flag) { if (-not $cmd -or -not $flag) { return '' } $pat = '(?:^|\s)--?' + [regex]::Escape($flag) + '(?:=|\s+)(?:"([^"]*)"|([^\s]+))' $m = [regex]::Match($cmd, $pat) if (-not $m.Success) { return '' } if ($m.Groups[1].Success) { return $m.Groups[1].Value } return $m.Groups[2].Value } function Convert-YamlScalar([string]$v) { if ($null -eq $v) { return '' } $v = $v.Trim() if ($v.Length -ge 2) { $a = [int][char]$v[0]; $b = [int][char]$v[$v.Length - 1] if (($a -eq 34 -and $b -eq 34) -or ($a -eq 39 -and $b -eq 39)) { return $v.Substring(1, $v.Length - 2) } } return $v } function Read-TopYamlValue($lines, [string]$key) { if (-not $lines) { return '' } $pat = '^' + [regex]::Escape($key) + '\s*:\s*(.*?)\s*$' foreach ($ln in $lines) { $m = [regex]::Match([string]$ln, $pat) if ($m.Success) { return (Convert-YamlScalar $m.Groups[1].Value) } } return '' } function Read-TunStack($lines) { if (-not $lines) { return '' } $inside = $false foreach ($ln0 in $lines) { $ln = [string]$ln0 if ($ln -match '^tun\s*:\s*$') { $inside = $true; continue } if ($inside -and $ln -match '^[^\s#][^:]*\s*:') { break } if ($inside) { $m = [regex]::Match($ln, '^\s+stack\s*:\s*(.*?)\s*$') if ($m.Success) { return (Convert-YamlScalar $m.Groups[1].Value) } } } return '' } function Get-LocalProxyDefs($lines) { # This is intentionally only a simple *hint* reader. Complex YAML/provider/dialer # semantics are not inferred here; live sockets and the runtime API take priority. $out = New-Object System.Collections.ArrayList if (-not $lines) { return @($out) } $inside = $false; $cur = $null foreach ($ln0 in $lines) { $ln = [string]$ln0 if ($ln -match '^proxies\s*:\s*$') { $inside = $true; continue } if ($inside -and $ln -match '^[^\s#][^:]*\s*:') { if ($cur -and $cur.Name -and $cur.Server -and $cur.Port) { [void]$out.Add([PSCustomObject]$cur) } break } if (-not $inside) { continue } $mn = [regex]::Match($ln, '^\s*-\s+name\s*:\s*(.*?)\s*$') if ($mn.Success) { if ($cur -and $cur.Name -and $cur.Server -and $cur.Port) { [void]$out.Add([PSCustomObject]$cur) } $cur = [ordered]@{ Name = (Convert-YamlScalar $mn.Groups[1].Value); Type = ''; Server = ''; Port = 0 } continue } if (-not $cur) { continue } $mf = [regex]::Match($ln, '^\s+(type|server|port)\s*:\s*(.*?)\s*$') if ($mf.Success) { $k = $mf.Groups[1].Value.ToLowerInvariant(); $v = Convert-YamlScalar $mf.Groups[2].Value if ($k -eq 'type') { $cur.Type = $v } elseif ($k -eq 'server') { $cur.Server = $v } elseif ($k -eq 'port') { $pn = 0; if ([int]::TryParse($v, [ref]$pn)) { $cur.Port = $pn } } } } if ($inside -and $cur -and $cur.Name -and $cur.Server -and $cur.Port) { [void]$out.Add([PSCustomObject]$cur) } return @($out) } function Normalize-IPText([string]$addr) { if (-not $addr) { return '' } $v = $addr.Trim() if ($v.StartsWith('[') -and $v.EndsWith(']')) { $v = $v.Substring(1, $v.Length - 2) } # Zone IDs are routing metadata, not part of address identity for local endpoint # matching. Keep the original text for display/probing elsewhere. $pct = $v.IndexOf('%'); if ($pct -gt 0) { $v = $v.Substring(0, $pct) } $ipObj = $null if ([System.Net.IPAddress]::TryParse($v, [ref]$ipObj)) { if ($ipObj.IsIPv4MappedToIPv6) { $ipObj = $ipObj.MapToIPv4() } return $ipObj.ToString().ToLowerInvariant() } return $v.ToLowerInvariant() } function Test-IPTextEqual([string]$a, [string]$b) { if (-not $a -or -not $b) { return $false } return (Normalize-IPText $a) -eq (Normalize-IPText $b) } function Test-LoopbackAddr([string]$addr) { if (-not $addr) { return $false } if ($addr -eq 'localhost') { return $true } $n = Normalize-IPText $addr $ipObj = $null if ([System.Net.IPAddress]::TryParse($n, [ref]$ipObj)) { return [System.Net.IPAddress]::IsLoopback($ipObj) } return $false } function Test-UnspecifiedAddr([string]$addr) { $n = Normalize-IPText $addr return [bool]($n -eq '0.0.0.0' -or $n -eq '::') } $localHostAddressSet = @{} foreach ($lip in @(Get-NetIPAddress -ErrorAction SilentlyContinue | Where-Object { $_.IPAddress })) { $ln = Normalize-IPText ([string]$lip.IPAddress); if ($ln) { $localHostAddressSet[$ln] = $true } } $localHostNameSet = @{} foreach ($hn in @('localhost', [System.Net.Dns]::GetHostName(), $env:COMPUTERNAME)) { if ($hn) { $localHostNameSet[[string]$hn.ToLowerInvariant()] = $true } } try { $he = [System.Net.Dns]::GetHostEntry([System.Net.Dns]::GetHostName()) if ($he -and $he.HostName) { $localHostNameSet[[string]$he.HostName.ToLowerInvariant()] = $true } } catch { } function Test-IsLocalHostAddress([string]$addr) { if (-not $addr) { return $false } if (Test-LoopbackAddr $addr) { return $true } if (Test-UnspecifiedAddr $addr) { return $false } $nl = $addr.ToLowerInvariant() if ($localHostNameSet.ContainsKey($nl)) { return $true } $n = Normalize-IPText $addr return $localHostAddressSet.ContainsKey($n) } function Get-MetaField($meta, [string[]]$names) { if (-not $meta) { return '' } foreach ($nm in $names) { $pp = $meta.PSObject.Properties | Where-Object { $_.Name -eq $nm } | Select-Object -First 1 if ($pp -and $null -ne $pp.Value -and [string]$pp.Value) { return [string]$pp.Value } } return '' } function Format-MihomoRule($conn) { if (-not $conn) { return '' } $rule = [string]$conn.rule; $payload = [string]$conn.rulePayload $head = if ($rule -and $payload) { $rule + ':' + $payload } elseif ($rule) { $rule } else { '' } $chains = @($conn.chains | Where-Object { $_ }) if ($chains.Count -gt 0) { $tail = ($chains -join ' / ') if ($head) { return $head + ' -> ' + $tail } return $tail } return $head } function Safe-GraphId([string]$s) { if (-not $s) { return 'x' } return (($s -replace '[^A-Za-z0-9_-]', '_') -replace '_+', '_').Trim('_') } function Format-Endpoint([string]$addr, [int]$port) { if (-not $addr) { return '' } if ($addr -match ':') { return '[' + $addr + ']:' + [string]$port } return $addr + ':' + [string]$port } function Get-ConfiguredProxyEndpoints([string]$text, [string]$policy) { $out = New-Object System.Collections.ArrayList if (-not $text) { return @($out) } # Accept WinINET style `http=host:port;https=host:port`, URI forms and plain # host:port. This parser is intentionally syntactic only; it does not assert that # the configured endpoint is actually used by every application. # URI proxy variables may contain user-info. Strip only the user-info prefix # for discovery; credentials are never copied into the graph/report. $scan = [regex]::Replace($text, '(?i)((?:https?|ftp|socks(?:4a?|5)?)://)[^\s/@]+@', '$1') $pat = '(?i)(?:(?https?|ftp|socks(?:4a?|5)?|all)\s*=\s*|(?https?|ftp|socks(?:4a?|5)?)://)?(?localhost|127(?:\.\d{1,3}){3}|\[[0-9a-f:%.-]+\]|[A-Za-z0-9_.-]+):(?\d{1,5})' foreach ($m in [regex]::Matches($scan, $pat)) { # Do not use `$host`: PowerShell variable names are case-insensitive and `$Host` # is an automatic variable. Using it here silently corrupts endpoint ownership # on hosts where non-terminating assignment errors are suppressed. $proxyHost = [string]$m.Groups['host'].Value if ($proxyHost.StartsWith('[') -and $proxyHost.EndsWith(']')) { $proxyHost = $proxyHost.Substring(1, $proxyHost.Length - 2) } $pn = 0; if (-not [int]::TryParse([string]$m.Groups['port'].Value, [ref]$pn) -or $pn -lt 1 -or $pn -gt 65535) { continue } $scheme = if ($m.Groups['scheme'].Success) { [string]$m.Groups['scheme'].Value } elseif ($m.Groups['uri'].Success) { [string]$m.Groups['uri'].Value } else { '' } [void]$out.Add([PSCustomObject]@{ Policy = $policy; Scheme = $scheme; Host = $proxyHost; Port = $pn; Endpoint = (Format-Endpoint $proxyHost $pn) }) } return @($out | Group-Object Policy, Scheme, Host, Port | ForEach-Object { $_.Group | Select-Object -First 1 }) } function Resolve-ProxyEndpointOwner($ep) { if (-not $ep) { return $null } if (-not (Test-IsLocalHostAddress ([string]$ep.Host)) -and -not (Test-UnspecifiedAddr ([string]$ep.Host))) { return $null } return Find-LocalListener ([string]$ep.Host) ([int]$ep.Port) } function Get-IPv4Text([int]$ifIndex) { $aa = @(Get-NetIPAddress -InterfaceIndex $ifIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue | Where-Object { $_.IPAddress -and $_.IPAddress -ne '0.0.0.0' }) return (($aa | ForEach-Object { [string]$_.IPAddress + '/' + [string]$_.PrefixLength }) -join ', ') } function Get-IPv6Text([int]$ifIndex) { $aa = @(Get-NetIPAddress -InterfaceIndex $ifIndex -AddressFamily IPv6 -ErrorAction SilentlyContinue | Where-Object { $_.IPAddress -and $_.IPAddress -notmatch '^(::1|fe80:)' }) return (($aa | ForEach-Object { [string]$_.IPAddress + '/' + [string]$_.PrefixLength }) -join ', ') } function Get-LinkText($ad) { if (-not $ad) { return '' } if ([string]$ad.MediaType -eq 'Native 802.11') { $wl = (netsh wlan show interfaces) -join "`n" $dm = [regex]::Match($wl, '(?m):\s*(-\d{1,3})\s*$') $pm = [regex]::Match($wl, '(?m):\s*(\d{1,3})%\s*$') if ($pm.Success) { $dbm = if ($dm.Success) { ' (' + $dm.Groups[1].Value + ' dBm)' } else { '' } return $pm.Groups[1].Value + '%' + $dbm } } return [string]$ad.LinkSpeed } # A single Get-NetTCPConnection snapshot misses short-lived local proxy hand-offs # surprisingly often. Sample a few times and merge tuples; this remains passive and # adds only a small fixed delay while making the graph substantially less timing-sensitive. $tcpSnapshotCount = 3 $tcpSnapshotDelayMs = 180 $tcpByTuple = @{} for ($tsi = 0; $tsi -lt $tcpSnapshotCount; $tsi++) { foreach ($cc in @(Get-NetTCPConnection -ErrorAction SilentlyContinue)) { $tk = ([string]$cc.OwningProcess) + '|' + ([string]$cc.State) + '|' + ([string]$cc.LocalAddress) + '|' + ([string]$cc.LocalPort) + '|' + ([string]$cc.RemoteAddress) + '|' + ([string]$cc.RemotePort) if (-not $tcpByTuple.ContainsKey($tk)) { $tcpByTuple[$tk] = $cc } } if ($tsi -lt ($tcpSnapshotCount - 1)) { Start-Sleep -Milliseconds $tcpSnapshotDelayMs } } $tcpAll = @($tcpByTuple.Values) $udpAll = @(Get-NetUDPEndpoint -ErrorAction SilentlyContinue) $tcpListeners = @($tcpAll | Where-Object State -eq 'Listen') $procFactCache = @{} $routeFactCache = @{} $dnsProbeCache = @{} $pingProbeCache = @{} # V5 unknown-client discovery. Enumerate every loopback/wildcard listener and probe # for *protocol* behavior instead of requiring a product name. SOCKS5 negotiation does # not request a remote connection. HTTP CONNECT is only considered positive for proxy- # specific responses (407, Proxy-Agent, or a CONNECT-established response). function Test-Socks5Listener([string]$address, [int]$port, [int]$timeoutMs = 140) { $hostProbe = if (Test-LoopbackAddr $address) { $address } elseif ($address -match ':') { '::1' } else { '127.0.0.1' } $tcp = New-Object System.Net.Sockets.TcpClient try { $task = $tcp.ConnectAsync($hostProbe, $port) if (-not $task.Wait($timeoutMs) -or -not $tcp.Connected) { return $false } $ns = $tcp.GetStream(); $ns.ReadTimeout = $timeoutMs; $ns.WriteTimeout = $timeoutMs [byte[]]$hello = @(0x05,0x01,0x00); $ns.Write($hello,0,$hello.Length) [byte[]]$buf = New-Object byte[] 2; $n = $ns.Read($buf,0,2) return [bool]($n -eq 2 -and $buf[0] -eq 0x05) } catch { return $false } finally { $tcp.Dispose() } } function Test-HttpConnectProxyListener([string]$address, [int]$port, [int]$timeoutMs = 180) { $hostProbe = if (Test-LoopbackAddr $address) { $address } elseif ($address -match ':') { '::1' } else { '127.0.0.1' } $tcp = New-Object System.Net.Sockets.TcpClient try { $task = $tcp.ConnectAsync($hostProbe, $port) if (-not $task.Wait($timeoutMs) -or -not $tcp.Connected) { return '' } $ns = $tcp.GetStream(); $ns.ReadTimeout = $timeoutMs; $ns.WriteTimeout = $timeoutMs $req = [System.Text.Encoding]::ASCII.GetBytes("CONNECT 127.0.0.1:9 HTTP/1.1`r`nHost: 127.0.0.1:9`r`nProxy-Connection: close`r`n`r`n") $ns.Write($req,0,$req.Length) [byte[]]$buf = New-Object byte[] 768; $n = $ns.Read($buf,0,$buf.Length) if ($n -le 0) { return '' } $txt = [System.Text.Encoding]::ASCII.GetString($buf,0,$n) if ($txt -match '(?im)^HTTP/\d(?:\.\d)?\s+407\b') { return 'HTTP CONNECT / 407' } if ($txt -match '(?im)^Proxy-Agent\s*:') { return 'HTTP CONNECT / Proxy-Agent' } if ($txt -match '(?im)^HTTP/\d(?:\.\d)?\s+200\b' -and $txt -match '(?i)connection\s+established|connect') { return 'HTTP CONNECT / established' } return '' } catch { return '' } finally { $tcp.Dispose() } } $proxyStrongIdentityRegex = '(?i)(mihomo|clash|verge|v2ray|xray|sing[- ]?box|shadowsocks|ssr|trojan|naive|hysteria|tun2socks|openvpn|wireguard|tailscale|zerotier|gost|proxifier|hiddify|surge)' $proxyWeakIdentityRegex = '(?i)(vpn|proxy|tunnel|socks|redirect)' # Common interactive applications are a negative prior only. They are still inventoried # and can be promoted again by strong protocol/config/runtime evidence. This is deliberately # not a hard blacklist: a browser/game/IM process can still host a real proxy endpoint. $commonNonProxyIdentityRegex = '(?i)(^|[\\/\s])(chrome|msedge|firefox|steam|steamwebhelper|epicgameslauncher|battle\.net|discord|qq|weixin|wechat|teams|spotify|onedrive|outlook|winword|excel|powerpnt|code|devenv)(?:\.exe)?(?:$|[\\/\s])' $commonProxyPorts = @(1080,1081,3128,7890,7891,7892,8080,8118,8888,9050,10808,10809,10080) $proxyLikeListeners = New-Object System.Collections.ArrayList $listenerEvidenceRows = New-Object System.Collections.ArrayList # Resolve explicit proxy-policy references before active listener probing. A configured # local endpoint is strong evidence even when the owning binary is renamed/closed-source. # Keep this discovery copy separate from the later graph-policy projection. $discoveryPolicyEndpoints = New-Object System.Collections.ArrayList if ($sysProxyOn -and $p.ProxyServer) { foreach ($ep0 in @(Get-ConfiguredProxyEndpoints ([string]$p.ProxyServer) 'WinINET')) { [void]$discoveryPolicyEndpoints.Add($ep0) } } $winhttpRawDiscovery = (netsh winhttp show proxy 2>$null) -join "`n" foreach ($ep0 in @(Get-ConfiguredProxyEndpoints $winhttpRawDiscovery 'WinHTTP')) { [void]$discoveryPolicyEndpoints.Add($ep0) } foreach ($envName0 in @('HTTP_PROXY','HTTPS_PROXY','ALL_PROXY','FTP_PROXY','SOCKS_PROXY')) { $ev0 = [Environment]::GetEnvironmentVariable($envName0, 'Process') if (-not $ev0) { $ev0 = [Environment]::GetEnvironmentVariable($envName0, 'User') } if (-not $ev0) { continue } foreach ($ep0 in @(Get-ConfiguredProxyEndpoints $ev0 ('ENV:' + $envName0))) { [void]$discoveryPolicyEndpoints.Add($ep0) } } $policyReferencedListener = @{} foreach ($ep0 in @($discoveryPolicyEndpoints)) { if (-not (Test-IsLocalHostAddress ([string]$ep0.Host)) -and -not (Test-UnspecifiedAddr ([string]$ep0.Host))) { continue } $cand0 = @($tcpListeners | Where-Object { [int]$_.LocalPort -eq [int]$ep0.Port }) $owner0 = $cand0 | Where-Object { Test-IPTextEqual ([string]$_.LocalAddress) ([string]$ep0.Host) } | Select-Object -First 1 if (-not $owner0 -and ((Test-LoopbackAddr ([string]$ep0.Host)) -or [string]$ep0.Host -eq 'localhost')) { $owner0 = $cand0 | Where-Object { (Test-LoopbackAddr ([string]$_.LocalAddress)) -or (Test-UnspecifiedAddr ([string]$_.LocalAddress)) } | Select-Object -First 1 } if (-not $owner0 -and (Test-UnspecifiedAddr ([string]$ep0.Host))) { $owner0 = $cand0 | Select-Object -First 1 } if ($owner0 -and [int]$owner0.OwningProcess -gt 0) { $pk0 = [string]$owner0.OwningProcess + '|' + [string]$owner0.LocalPort if (-not $policyReferencedListener.ContainsKey($pk0)) { $policyReferencedListener[$pk0] = New-Object System.Collections.ArrayList } if (-not $policyReferencedListener[$pk0].Contains([string]$ep0.Policy)) { [void]$policyReferencedListener[$pk0].Add([string]$ep0.Policy) } } } # Remote sockets help rank what to probe, but are not proxy evidence by themselves: # browsers, Steam, IM clients and many desktop apps naturally listen locally and connect # remotely at the same time. $remoteEstablishedByPid = @{} foreach ($cc0 in @($tcpAll | Where-Object { $_.State -eq 'Established' -and $_.OwningProcess -gt 0 -and $_.RemoteAddress -and -not (Test-IsLocalHostAddress ([string]$_.RemoteAddress)) -and -not (Test-UnspecifiedAddr ([string]$_.RemoteAddress)) })) { $pk0 = [string]$cc0.OwningProcess if (-not $remoteEstablishedByPid.ContainsKey($pk0)) { $remoteEstablishedByPid[$pk0] = 0 } $remoteEstablishedByPid[$pk0] = [int]$remoteEstablishedByPid[$pk0] + 1 } $listenerSeeds = New-Object System.Collections.ArrayList foreach ($ll in @($tcpListeners | Where-Object { (Test-LoopbackAddr ([string]$_.LocalAddress)) -or (Test-UnspecifiedAddr ([string]$_.LocalAddress)) })) { $pid0 = [int]$ll.OwningProcess; if ($pid0 -le 0) { continue } $pp0 = Get-Process -Id $pid0 -ErrorAction SilentlyContinue $ci0 = Get-CimInstance Win32_Process -Filter ('ProcessId=' + [string]$pid0) -ErrorAction SilentlyContinue $identity = $(if ($pp0) { [string]$pp0.Name + ' ' + [string]$pp0.Path } else { '' }) + ' ' + $(if ($ci0) { [string]$ci0.CommandLine } else { '' }) $strongIdentityHit = [bool]($identity -match $proxyStrongIdentityRegex) $weakIdentityHit = [bool]((-not $strongIdentityHit) -and ($identity -match $proxyWeakIdentityRegex)) $knownNonProxy = [bool]((-not $strongIdentityHit) -and ($identity -match $commonNonProxyIdentityRegex)) $knownPort = [bool]($commonProxyPorts -contains [int]$ll.LocalPort) $remoteOut = if ($remoteEstablishedByPid.ContainsKey([string]$pid0)) { [int]$remoteEstablishedByPid[[string]$pid0] } else { 0 } $policyKey0 = [string]$pid0 + '|' + [string]$ll.LocalPort $configuredRef = [bool]$policyReferencedListener.ContainsKey($policyKey0) $policyRefs = if ($configuredRef) { @($policyReferencedListener[$policyKey0]) } else { @() } # A live server-side local connection proves another local process is using this # listener, but IPC alone is still not enough to call it a proxy. $localClients = @($tcpAll | Where-Object { $_.State -eq 'Established' -and [int]$_.OwningProcess -eq $pid0 -and [int]$_.LocalPort -eq [int]$ll.LocalPort -and (Test-IsLocalHostAddress ([string]$_.RemoteAddress)) }).Count $priority = $(if ($configuredRef) { 2600 } else { 0 }) + $(if ($strongIdentityHit) { 1800 } elseif ($weakIdentityHit) { 180 } else { 0 }) + $(if ($knownPort) { 250 } else { 0 }) + [math]::Min(720, $localClients * 180) + [math]::Min(420, $remoteOut * 10) - $(if ($knownNonProxy) { 1200 } else { 0 }) [void]$listenerSeeds.Add([PSCustomObject]@{ Listener = $ll; PID = $pid0; Process = $(if ($pp0) { [string]$pp0.Name } else { '?' }) StrongIdentityHit = $strongIdentityHit; WeakIdentityHit = $weakIdentityHit; KnownNonProxy = $knownNonProxy KnownPort = $knownPort; RemoteEstablished = $remoteOut; LocalClients = $localClients ConfiguredReference = $configuredRef; PolicyRefs = @($policyRefs); Priority = $priority }) } $listenerProbeResult = @{} $socksProbeBudget = 72; $httpProbeBudget = 36; $socksProbeUsed = 0; $httpProbeUsed = 0 $rankedListenerSeeds = @($listenerSeeds | Sort-Object @{Expression='Priority';Descending=$true}, @{Expression='LocalClients';Descending=$true}, @{Expression='RemoteEstablished';Descending=$true}, PID, @{Expression={ [int]$_.Listener.LocalPort }}) foreach ($seed in $rankedListenerSeeds) { if ($socksProbeUsed -ge $socksProbeBudget -and $httpProbeUsed -ge $httpProbeBudget) { break } $ll = $seed.Listener $rk = [string]$seed.PID + '|' + [string]$ll.LocalAddress + '|' + [string]$ll.LocalPort $socks = $false; $httpSig = ''; $socksTried = $false; $httpTried = $false # Common browsers/games/IM clients are not worth spending active-probe budget on # unless some independent signal (policy reference, local client, proxy port, etc.) # makes the endpoint relevant. They remain in passive inventory either way. $probeEligible = [bool]((-not $seed.KnownNonProxy) -or $seed.ConfiguredReference -or $seed.StrongIdentityHit -or $seed.KnownPort -or $seed.LocalClients -gt 0) if ($probeEligible -and $socksProbeUsed -lt $socksProbeBudget) { $socksTried = $true; $socks = Test-Socks5Listener ([string]$ll.LocalAddress) ([int]$ll.LocalPort); $socksProbeUsed++ } if ($probeEligible -and -not $socks -and $httpProbeUsed -lt $httpProbeBudget -and ($seed.ConfiguredReference -or $seed.StrongIdentityHit -or $seed.WeakIdentityHit -or $seed.KnownPort -or $seed.LocalClients -gt 0)) { $httpTried = $true; $httpSig = Test-HttpConnectProxyListener ([string]$ll.LocalAddress) ([int]$ll.LocalPort); $httpProbeUsed++ } $listenerProbeResult[$rk] = [PSCustomObject]@{ Socks = $socks; Http = $httpSig; SocksTried = $socksTried; HttpTried = $httpTried; ProbeEligible = $probeEligible } } foreach ($seed in @($listenerSeeds | Sort-Object PID, @{Expression={ [int]$_.Listener.LocalPort }})) { $ll = $seed.Listener $rk = [string]$seed.PID + '|' + [string]$ll.LocalAddress + '|' + [string]$ll.LocalPort $pr = if ($listenerProbeResult.ContainsKey($rk)) { $listenerProbeResult[$rk] } else { $null } $socks = [bool]($pr -and $pr.Socks); $httpSig = if ($pr) { [string]$pr.Http } else { '' } $score = 0.0; $sig = New-Object System.Collections.ArrayList if ($socks) { $score += 8.0; [void]$sig.Add('SOCKS5 negotiation') } if ($httpSig) { $score += 7.0; [void]$sig.Add($httpSig) } if ($seed.ConfiguredReference) { $score += 5.0; [void]$sig.Add('explicit proxy policy references listener (' + ((@($seed.PolicyRefs)) -join ', ') + ')') } if ($seed.StrongIdentityHit) { $score += 4.0; [void]$sig.Add('known proxy/tunnel process identity') } elseif ($seed.WeakIdentityHit) { $score += 1.0; [void]$sig.Add('generic proxy/vpn-like process identity (weak)') } if ($seed.LocalClients -gt 0) { $score += 3.0; [void]$sig.Add(([string]$seed.LocalClients + ' live local client connection(s)')) } if ($seed.KnownPort) { $score += 0.5; [void]$sig.Add('common proxy port (weak)') } if ($seed.RemoteEstablished -gt 0) { [void]$sig.Add(([string]$seed.RemoteEstablished + ' remote established socket(s), ranking only')) } if ($seed.KnownNonProxy) { $score -= 2.5; [void]$sig.Add('common interactive application negative prior') } if ($pr -and ($pr.SocksTried -or $pr.HttpTried) -and -not $socks -and -not $httpSig -and -not $seed.ConfiguredReference -and -not $seed.StrongIdentityHit) { $score -= 0.75; [void]$sig.Add('active proxy protocol probe negative') } if ($pr -and -not $pr.ProbeEligible) { [void]$sig.Add('active probe skipped by common-app negative prior') } elseif (-not $pr -or (-not $pr.SocksTried -and -not $pr.HttpTried)) { [void]$sig.Add('protocol probe budget not reached') } $tier = if ($score -ge 4.0) { 'candidate' } elseif ($score -ge 2.0) { 'investigate' } else { 'inventory' } $candidate = $tier -eq 'candidate' $row = [PSCustomObject]@{ Local = (Format-Endpoint ([string]$ll.LocalAddress) ([int]$ll.LocalPort)); PID = [int]$seed.PID; Process = [string]$seed.Process LocalClients = [int]$seed.LocalClients; RemoteEstablished = [int]$seed.RemoteEstablished; ProxyScore = [math]::Round($score,2) Tier = $tier; KnownAppPrior = [bool]$seed.KnownNonProxy; Signature = (@($sig) -join ' + '); Candidate = $candidate } [void]$listenerEvidenceRows.Add($row) if ($candidate) { [void]$proxyLikeListeners.Add($row) } } # Candidate summary is process-level. Fifty SOCKS ports owned by one connector are one # proxy candidate process, not fifty independent graph entities. $proxyCandidateProcessRows = @() foreach ($gg0 in @($listenerEvidenceRows | Group-Object PID)) { $rows0 = @($gg0.Group); if ($rows0.Count -eq 0) { continue } $cand0 = @($rows0 | Where-Object Candidate) $inv0 = @($rows0 | Where-Object { $_.Tier -eq 'investigate' }) $proto0 = @($rows0 | Where-Object { $_.Signature -match 'SOCKS5|HTTP CONNECT' }) $best0 = $rows0 | Sort-Object ProxyScore -Descending | Select-Object -First 1 $tier0 = if ($cand0.Count -gt 0) { 'candidate' } elseif ($inv0.Count -gt 0) { 'investigate' } else { 'inventory' } $ev0 = @($rows0 | Where-Object { $_.Signature } | Sort-Object ProxyScore -Descending | ForEach-Object Signature | Select-Object -Unique | Select-Object -First 3) $proxyCandidateProcessRows += [PSCustomObject]@{ PID = [int]$best0.PID; Process = [string]$best0.Process; Tier = $tier0; MaxScore = [double]$best0.ProxyScore Listeners = $rows0.Count; CandidateEndpoints = $cand0.Count; ProtocolEndpoints = $proto0.Count LocalClients = [int](($rows0 | Measure-Object LocalClients -Maximum).Maximum); RemoteEstablished = [int](($rows0 | Measure-Object RemoteEstablished -Maximum).Maximum) KnownAppPrior = [bool](@($rows0 | Where-Object KnownAppPrior).Count -gt 0); Evidence = ($ev0 -join ' | ') } } $proxyCandidateProcesses = @($proxyCandidateProcessRows | Where-Object { $_.Tier -eq 'candidate' }) # Driver/service evidence is intentionally identity-based and advisory. Unknown WFP # providers cannot always be attributed from user-mode PowerShell, so this inventory # is used as corroboration rather than as proof of an active data path. $interceptIdentityRegex = '(?i)(wintun|windivert|tap0901|tap-windows|wireguard|openvpn|openconnect|tun2socks|tailscale|zerotier|mihomo|clash|sing.?box|v2ray|xray|hysteria|shadowsocks|trojan|naive|gost|proxifier|hiddify|warp-svc)' $interceptDrivers = @(Get-CimInstance Win32_SystemDriver -ErrorAction SilentlyContinue | Where-Object { $_.State -eq 'Running' -and (([string]$_.Name + ' ' + [string]$_.DisplayName + ' ' + [string]$_.PathName) -match $interceptIdentityRegex) } | Select-Object Name, DisplayName, State, PathName) $interceptServices = @(Get-CimInstance Win32_Service -ErrorAction SilentlyContinue | Where-Object { $_.State -eq 'Running' -and (([string]$_.Name + ' ' + [string]$_.DisplayName + ' ' + [string]$_.PathName) -match $interceptIdentityRegex) } | Select-Object Name, DisplayName, State, PathName) function Test-RouteSourceConsistency([string]$target = '1.1.1.1', [int]$port = 443, [int]$timeoutMs = 900) { $rt = Find-NetRoute -RemoteIPAddress $target -ErrorAction SilentlyContinue | Select-Object -First 1 $tcp = New-Object System.Net.Sockets.TcpClient $ok = $false; $src = ''; $srcIf = 0 try { $task = $tcp.ConnectAsync($target, $port) if ($task.Wait($timeoutMs) -and $tcp.Connected) { $ok = $true; $src = [string]$tcp.Client.LocalEndPoint.Address $sip = Get-NetIPAddress -IPAddress $src -ErrorAction SilentlyContinue | Select-Object -First 1 if ($sip) { $srcIf = [int]$sip.InterfaceIndex } } } catch { } finally { $tcp.Dispose() } $routeIf = if ($rt) { [int]$rt.InterfaceIndex } else { 0 } $mismatch = [bool]($ok -and $routeIf -gt 0 -and $srcIf -gt 0 -and $routeIf -ne $srcIf) [PSCustomObject]@{ Target = ($target + ':' + [string]$port); Connected = $ok; RouteIf = $routeIf; SocketIf = $srcIf; Source = $src; Mismatch = $mismatch } } $routeSourceProbe = Test-RouteSourceConsistency $allAdapterAssessments = @(Get-NetAdapter -ErrorAction SilentlyContinue | Sort-Object InterfaceIndex | ForEach-Object { Get-AdapterAssessment $_ }) $egAssessment = if ($egAd) { Get-AdapterAssessment $egAd } else { $null } $interceptScore = 0.0; $interceptSignals = New-Object System.Collections.ArrayList if ($egAssessment -and $egAssessment.Role -eq 'SuspectedTunnel') { $interceptScore += 4.0; [void]$interceptSignals.Add('selected default-route adapter is tunnel-like but not conclusively identified') } if ($egAssessment -and $egAssessment.Role -eq 'Tunnel') { [void]$interceptSignals.Add('selected default-route adapter is an identified tunnel') } $protocolProxyListeners = @($proxyLikeListeners | Where-Object { $_.Signature -match 'SOCKS5|HTTP CONNECT' }) $protocolProxyPids = @($protocolProxyListeners | ForEach-Object PID | Sort-Object -Unique) $proxyCandidatePids = @($proxyLikeListeners | ForEach-Object PID | Sort-Object -Unique) if ($protocolProxyPids.Count -gt 0) { $interceptScore += [math]::Min(6.0, 4.0 + ($protocolProxyPids.Count - 1)); [void]$interceptSignals.Add('proxy protocol detected on local listener owner process(es), endpoint multiplicity collapsed') } elseif ($proxyCandidatePids.Count -gt 0) { $interceptScore += 2.0; [void]$interceptSignals.Add('proxy/tunnel-like local listener owner process(es)') } if ($interceptDrivers.Count -gt 0 -or $interceptServices.Count -gt 0) { $interceptScore += 3.0; [void]$interceptSignals.Add('running VPN/TUN/redirect/filter driver or service identity') } if ($routeSourceProbe.Mismatch) { $interceptScore += 5.0; [void]$interceptSignals.Add('active TCP socket source interface disagrees with Find-NetRoute') } if ($egAssessment -and ($egAssessment.FakeIP -or $egAssessment.FakeDNS)) { $interceptScore += 3.0; [void]$interceptSignals.Add('selected adapter exposes fake-IP style address/DNS') } $interceptLevel = if ($egAssessment -and $egAssessment.Role -eq 'Tunnel') { 'VISIBLE-TUNNEL' } elseif ($interceptScore -ge 8.0) { 'LIKELY' } elseif ($interceptScore -ge 4.0) { 'POSSIBLE' } else { 'NONE' } $interceptConfidence = if ($interceptLevel -eq 'VISIBLE-TUNNEL') { 1.0 } elseif ($interceptLevel -eq 'LIKELY') { 0.86 } elseif ($interceptLevel -eq 'POSSIBLE') { 0.58 } else { 0.20 } function Get-ProcessFact([int]$processId) { $key = [string]$processId if ($procFactCache.ContainsKey($key)) { return $procFactCache[$key] } $pp = Get-Process -Id $processId -ErrorAction SilentlyContinue if (-not $pp) { return $null } $ci = Get-CimInstance Win32_Process -Filter ('ProcessId=' + [string]$processId) -ErrorAction SilentlyContinue $path = if ($pp.Path) { [string]$pp.Path } elseif ($ci) { [string]$ci.ExecutablePath } else { '' } $cmd = if ($ci) { [string]$ci.CommandLine } else { '' } $tls = @($tcpListeners | Where-Object OwningProcess -eq $processId | Sort-Object LocalAddress, LocalPort) $uls = @($udpAll | Where-Object OwningProcess -eq $processId | Sort-Object LocalAddress, LocalPort) $fact = [PSCustomObject]@{ PID = $processId; Name = [string]$pp.Name; Path = $path; CommandLine = $cmd TcpListeners = $tls; UdpEndpoints = $uls } $procFactCache[$key] = $fact return $fact } function Find-LocalListener([string]$address, [int]$port) { $cand = @($tcpListeners | Where-Object { $_.LocalPort -eq $port }) if (-not $cand) { return $null } $exact = $cand | Where-Object { Test-IPTextEqual ([string]$_.LocalAddress) $address } | Select-Object -First 1 if ($exact) { return $exact } if (Test-LoopbackAddr $address -or $address -eq 'localhost') { $loop = $cand | Where-Object { Test-LoopbackAddr ([string]$_.LocalAddress) } | Select-Object -First 1 if ($loop) { return $loop } } $wild = $cand | Where-Object { Test-UnspecifiedAddr ([string]$_.LocalAddress) } | Select-Object -First 1 if ($wild) { return $wild } # Only fall back to another loopback bind for explicitly local names/addresses; # never map a connection to a different listener merely because the port matches. if (Test-IsLocalHostAddress $address) { return $cand | Where-Object { Test-LoopbackAddr ([string]$_.LocalAddress) } | Select-Object -First 1 } return $null } function Find-LocalPeerConnection($conn) { if (-not $conn -or [string]$conn.State -ne 'Established') { return $null } $la = [string]$conn.LocalAddress; $ra = [string]$conn.RemoteAddress $lp0 = [int]$conn.LocalPort; $rp0 = [int]$conn.RemotePort if (-not (Test-IsLocalHostAddress $ra)) { return $null } # An established TCP connection is represented once from each endpoint on the # local host. Reverse-tuple matching identifies the actual server process even # when several processes share/reuse a listening port. $peers = @($tcpAll | Where-Object { $_.State -eq 'Established' -and [int]$_.OwningProcess -ne [int]$conn.OwningProcess -and [int]$_.LocalPort -eq $rp0 -and [int]$_.RemotePort -eq $lp0 -and (Test-IPTextEqual ([string]$_.LocalAddress) $ra) -and (Test-IPTextEqual ([string]$_.RemoteAddress) $la) }) if ($peers.Count -eq 1) { return $peers[0] } if ($peers.Count -gt 1) { # Multiple snapshots may preserve duplicate reverse tuples. If they all point # to the same owner, the ownership is still unambiguous. $owners = @($peers | ForEach-Object OwningProcess | Sort-Object -Unique) if ($owners.Count -eq 1) { return $peers[0] } } return $null } function Get-CachedPing([string]$target) { if (-not $target) { return [PSCustomObject]@{ Ok = $false; Ms = -1 } } if ($pingProbeCache.ContainsKey($target)) { return $pingProbeCache[$target] } $pr = Test-PingProbe $target $pingProbeCache[$target] = $pr return $pr } function Get-CachedDns([string]$server) { if (-not $server) { return [PSCustomObject]@{ Ok = $false; Ms = -1; Answer = '' } } if ($dnsProbeCache.ContainsKey($server)) { return $dnsProbeCache[$server] } $pr = Test-Dns $server $dnsProbeCache[$server] = $pr return $pr } # Add V5 evidence inventories to the already-built detail view. They are collapsed by # default so a large listener/service inventory does not crowd the graph. $adapterAssessmentRows = @($allAdapterAssessments | ForEach-Object { [PSCustomObject]@{ Role = $_.Role; Confidence = $_.Confidence; ifIndex = $_.IfIndex; Name = $_.Name; Physical = $_.PhysicalAdapter; Virtual = $_.IsVirtual; Service = $_.ServiceName; Driver = (($_.DriverProvider + ' ' + $_.InfName).Trim()); FakeIP = $_.FakeIP; FakeDNS = $_.FakeDNS; Signals = (@($_.Signals) -join ' | ') } }) $candidateProcessRowsV52 = @($proxyCandidateProcessRows | Where-Object { $_.Tier -ne 'inventory' } | Sort-Object @{Expression={ if ($_.Tier -eq 'candidate') { 0 } else { 1 } }}, @{Expression='MaxScore';Descending=$true}, PID) $listenerRowsV52 = @($listenerEvidenceRows | Sort-Object @{Expression={ if ($_.Tier -eq 'candidate') { 0 } elseif ($_.Tier -eq 'investigate') { 1 } else { 2 } }}, @{Expression='ProxyScore';Descending=$true}, PID, Local) $interceptRowsV5 = @() foreach ($dr0 in $interceptDrivers) { $interceptRowsV5 += [PSCustomObject]@{ Type = 'driver'; Name = $dr0.Name; Display = $dr0.DisplayName; State = $dr0.State; Path = $dr0.PathName } } foreach ($sv0 in $interceptServices) { $interceptRowsV5 += [PSCustomObject]@{ Type = 'service'; Name = $sv0.Name; Display = $sv0.DisplayName; State = $sv0.State; Path = $sv0.PathName } } $routeProbeRowsV5 = @([PSCustomObject]@{ Target = $routeSourceProbe.Target; Connected = $routeSourceProbe.Connected; FindNetRouteIf = $routeSourceProbe.RouteIf; SocketSourceIf = $routeSourceProbe.SocketIf; Source = $routeSourceProbe.Source; Mismatch = $routeSourceProbe.Mismatch }) $assessmentHtmlV5 = '
Raw evidence level' + (Enc $interceptLevel) + '
Score' + [string]$interceptScore + '
Signals' + (Enc ((@($interceptSignals)) -join ' | ')) + '
' $viewChain += '
V5.2 adapter role assessment
' + (Table-Html $adapterAssessmentRows) + '
' $viewChain += '
V5.2 proxy candidate processes (entity-level)
' + (Table-Html $candidateProcessRowsV52) + '
' $viewChain += '
V5.2 all local listener inventory (audit / collapsed)
' + (Table-Html $listenerRowsV52) + '
' $viewChain += '
V5.2 interception drivers / services
' + (Table-Html $interceptRowsV5) + '
' $viewChain += '
V5.2 active route/source consistency probe
' + (Table-Html $routeProbeRowsV5) + '
' $viewChain += '
V5.2 raw interception evidence assessment
' + $assessmentHtmlV5 + '
' # Product-family processes are an inventory, not a single chosen $mh. The older # $mh is retained only for the legacy detail-chain view above. $coreRegex = '(?i)(mihomo|clash|verge-mihomo|sing[- ]?box|singbox|xray|v2ray|gost|trojan|hysteria|naive|shadowsocks|ssr|tun2socks|wireguard|openvpn|tailscale|zerotier|proxy|tunnel)' # Do not rely on the executable *name* alone. GUI wrappers, renamed binaries and # service-launched cores often expose the useful identity only in path/command line. # Candidate discovery is deliberately broad, but candidates are still confidence- # weighted later before a TUN->process relationship is drawn. $corePidSet = @{} foreach ($pp in @($procs)) { if ($pp -and $pp.Id) { $corePidSet[[string]$pp.Id] = $true } } foreach ($pl0 in @($proxyLikeListeners)) { if ($pl0.PID -and [int]$pl0.PID -gt 0) { $corePidSet[[string]$pl0.PID] = $true } } $listenerPids = @($tcpListeners | ForEach-Object OwningProcess) + @($udpAll | ForEach-Object OwningProcess) foreach ($pid0 in @($listenerPids | Where-Object { $_ -and [int]$_ -gt 0 } | Sort-Object -Unique)) { $pf0 = Get-ProcessFact ([int]$pid0) if (-not $pf0) { continue } $identity = ([string]$pf0.Name + ' ' + [string]$pf0.Path + ' ' + [string]$pf0.CommandLine) $commonApp0 = [bool]($identity -match $commonNonProxyIdentityRegex) $strongProxy0 = [bool]($identity -match $proxyStrongIdentityRegex) # Generic words like `proxy` in a browser/game command line are not enough to make # that process a proxy-core entity. Strong identity or listener evidence can still # promote a common application through the earlier candidate path. if ($identity -match $coreRegex -and ((-not $commonApp0) -or $strongProxy0)) { $corePidSet[[string]$pid0] = $true } } $coreProcs = @($corePidSet.Keys | ForEach-Object { Get-Process -Id ([int]$_) -ErrorAction SilentlyContinue } | Where-Object { $_ } | Sort-Object Id) $coreInfos = New-Object System.Collections.ArrayList $coreInfoByPid = @{} foreach ($cp in $coreProcs) { $pf = Get-ProcessFact ([int]$cp.Id) if (-not $pf) { continue } $isMihomoFamily = [bool]($pf.Name -match '(?i)mihomo|clash|verge-mihomo') # Avoid `$HOME` as a scratch variable; it is a PowerShell automatic variable. $coreHome = ''; $cfgPath = ''; $cfgLines = @(); $controller = ''; $secret = ''; $stack = ''; $findProc = '' $apiBase = ''; $apiOk = $false; $apiConnections = @(); $localDefs = @() if ($isMihomoFamily) { $coreHome = Get-CommandArgValue $pf.CommandLine 'd' $cf = Get-CommandArgValue $pf.CommandLine 'f' if ($cf) { if ([System.IO.Path]::IsPathRooted($cf)) { $cfgPath = $cf } elseif ($coreHome) { $cfgPath = Join-Path $coreHome $cf } else { $cfgPath = $cf } } elseif ($coreHome) { $cfgPath = Join-Path $coreHome 'config.yaml' } if ($cfgPath -and (Test-Path -LiteralPath $cfgPath)) { $cfgLines = @(Get-Content -LiteralPath $cfgPath -ErrorAction SilentlyContinue) } $controller = Get-CommandArgValue $pf.CommandLine 'ext-ctl' if (-not $controller) { $controller = Get-CommandArgValue $pf.CommandLine 'external-controller' } if (-not $controller) { $controller = Read-TopYamlValue $cfgLines 'external-controller' } $secret = Get-CommandArgValue $pf.CommandLine 'secret' if (-not $secret) { $secret = Read-TopYamlValue $cfgLines 'secret' } $stack = Read-TunStack $cfgLines $findProc = Read-TopYamlValue $cfgLines 'find-process-mode' $localDefs = @(Get-LocalProxyDefs $cfgLines | Where-Object { Test-IsLocalHostAddress ([string]$_.Server) }) # Runtime controller discovery order: explicit process/config value -> known # controller ports -> only then process listeners as a heuristic fallback. $ctlCandidates = New-Object System.Collections.ArrayList if ($controller -and $controller -notmatch '^\\') { [void]$ctlCandidates.Add($controller) } foreach ($pp0 in @(9097, 9090)) { [void]$ctlCandidates.Add('127.0.0.1:' + [string]$pp0) } foreach ($ll in $pf.TcpListeners) { if ($ll.LocalPort -gt 1024 -and ((Test-LoopbackAddr ([string]$ll.LocalAddress)) -or (Test-UnspecifiedAddr ([string]$ll.LocalAddress)))) { [void]$ctlCandidates.Add('127.0.0.1:' + [string]$ll.LocalPort) } } foreach ($cc0 in @($ctlCandidates | Select-Object -Unique)) { $cc = [string]$cc0 if (-not $cc) { continue } if ($cc -notmatch '^https?://') { $cc = 'http://' + $cc } $cc = $cc -replace '://0\.0\.0\.0:', '://127.0.0.1:' $cc = $cc -replace '://\[::\]:', '://127.0.0.1:' $hdr = @{}; if ($secret) { $hdr['Authorization'] = 'Bearer ' + $secret } try { $vv = Invoke-RestMethod -Uri ($cc.TrimEnd('/') + '/version') -Headers $hdr -TimeoutSec 1 -ErrorAction Stop if ($vv) { $apiBase = $cc.TrimEnd('/'); $apiOk = $true; break } } catch { } } if ($apiOk) { try { $hdr = @{}; if ($secret) { $hdr['Authorization'] = 'Bearer ' + $secret } $cs = Invoke-RestMethod -Uri ($apiBase + '/connections') -Headers $hdr -TimeoutSec 2 -ErrorAction Stop if ($cs -and $cs.connections) { $apiConnections = @($cs.connections) } } catch { $apiConnections = @() } } } $info = [PSCustomObject]@{ PID = [int]$pf.PID; Name = [string]$pf.Name; Path = [string]$pf.Path; Fact = $pf IsMihomo = $isMihomoFamily; ApiOk = $apiOk; ApiBase = $apiBase; Connections = @($apiConnections) LocalProxyDefs = @($localDefs); TunStack = $stack; FindProcess = $findProc; ConfigPath = $cfgPath ListenerEvidence = @($proxyLikeListeners | Where-Object { [int]$_.PID -eq [int]$pf.PID }) } [void]$coreInfos.Add($info); $coreInfoByPid[[string]$info.PID] = $info } function Get-CoreConnectionsForProcess($coreInfo, $processFact) { if (-not $coreInfo -or -not $processFact -or -not $coreInfo.Connections) { return @() } $name = [string]$processFact.Name; $path = [string]$processFact.Path $bn = if ($path) { [System.IO.Path]::GetFileName($path) } else { '' } $out = New-Object System.Collections.ArrayList foreach ($conn in @($coreInfo.Connections)) { $pn = Get-MetaField $conn.metadata @('processName','process') $pp = Get-MetaField $conn.metadata @('processPath','processPathName') $c = 0.0; $ev = '' if ($path -and $pp -and $pp -eq $path) { $c = 0.99; $ev = 'runtime API exact process path' } elseif ($bn -and $pp -and [System.IO.Path]::GetFileName($pp) -eq $bn) { $c = 0.92; $ev = 'runtime API executable basename' } elseif ($name -and ($pn -eq $name -or $pn -eq ($name + '.exe'))) { $c = 0.86; $ev = 'runtime API process name' } if ($c -gt 0) { [void]$out.Add([PSCustomObject]@{ Connection = $conn; Confidence = $c; Evidence = $ev }) } } return @($out) } function Get-CoreScoreForAdapter($coreInfo, $adapter) { if (-not $coreInfo) { return 0 } $score = 0 $ct = ([string]$coreInfo.Name + ' ' + [string]$coreInfo.Path).ToLowerInvariant() $at = if ($adapter) { ([string]$adapter.Name + ' ' + [string]$adapter.InterfaceDescription).ToLowerInvariant() } else { '' } foreach ($token in @('mihomo','clash','sing-box','singbox','xray','v2ray','gost','hysteria','trojan','tun2socks','wireguard','openvpn','tailscale','zerotier','hiddify','surge','nordvpn','expressvpn','windscribe')) { if ($ct -match [regex]::Escape($token) -and $at -match [regex]::Escape($token)) { $score += 100 } } if ($coreInfo.ApiOk) { $score += 30 } if ($coreInfo.Name -match '(?i)^(mihomo|verge-mihomo|clash|sing-box|singbox|xray|v2ray|gost|hysteria|trojan|wireguard|openvpn|tailscale|zerotier|hiddify|surge|nordvpn|expressvpn|windscribe)') { $score += 20 } $ple = @($coreInfo.ListenerEvidence) if (@($ple | Where-Object { $_.Signature -match 'SOCKS5|HTTP CONNECT' }).Count -gt 0) { $score += 70 } elseif ($ple.Count -gt 0) { $score += 25 } if ($coreInfo.Fact.TcpListeners.Count -gt 0) { $score += 5 } return $score } function Get-TunnelCaptureCandidates([int]$ifIndex, $sourceFact) { $out = New-Object System.Collections.ArrayList $ad = Get-NetAdapter -InterfaceIndex $ifIndex -ErrorAction SilentlyContinue if ($sourceFact) { foreach ($ci in $coreInfos) { $connMatches = @(Get-CoreConnectionsForProcess $ci $sourceFact) if ($connMatches.Count -eq 0) { continue } # One process may have simultaneous flows that hit different rules/outbounds. # Preserve those as separate logical passes instead of concatenating # `Proxy | DIRECT` into one ambiguous pass that would hide one branch. $byRule = @{} foreach ($mm in $connMatches) { $ruleKey = Format-MihomoRule $mm.Connection if (-not $ruleKey) { $ruleKey = '(runtime connection; rule unavailable)' } if (-not $byRule.ContainsKey($ruleKey)) { $byRule[$ruleKey] = New-Object System.Collections.ArrayList } [void]$byRule[$ruleKey].Add($mm) } $rg = 0 foreach ($ruleKey in @($byRule.Keys | Sort-Object)) { $rg++; if ($rg -gt 6) { break } $gm = @($byRule[$ruleKey]) $bestMatch = $gm | Sort-Object @{ Expression = 'Confidence'; Descending = $true } | Select-Object -First 1 $displayRule = if ($ruleKey -match '^\(runtime connection') { '' } else { [string]$ruleKey } [void]$out.Add([PSCustomObject]@{ Core = $ci; Confidence = [double]$bestMatch.Confidence; Evidence = ([string]$bestMatch.Evidence + ' · ' + [string]$gm.Count + ' flow(s)') Rule = $displayRule }) } } if ($out.Count -gt 0) { return @($out) } } $ranked = @($coreInfos | ForEach-Object { [PSCustomObject]@{ Core = $_; Score = (Get-CoreScoreForAdapter $_ $ad) } } | Sort-Object @{ Expression = 'Score'; Descending = $true }, @{ Expression = { $_.Core.PID }; Descending = $false }) if (-not $ranked) { return @() } $max = [int]$ranked[0].Score # Zero-score processes have no evidence linking them to this TUN. Do not draw # arbitrary proxy-core edges merely because a proxy-looking process exists. if ($max -le 0) { return @() } $keep = @($ranked | Where-Object { $_.Score -eq $max -or $_.Score -ge ($max - 10) } | Select-Object -First 3) foreach ($r in $keep) { $conf = if ($r.Score -ge 100) { 0.90 } elseif ($keep.Count -eq 1 -and $r.Score -ge 30) { 0.72 } elseif ($keep.Count -eq 1) { 0.45 } else { 0.35 } $protoHit = @($r.Core.ListenerEvidence | Where-Object { $_.Signature -match 'SOCKS5|HTTP CONNECT' }).Count -gt 0 $ev = if ($r.Score -ge 100) { 'adapter/process identity match' } elseif ($protoHit) { 'local proxy protocol listener owner; TUN ownership not exposed by Windows' } elseif ($r.Core.ApiOk) { 'unique active proxy core/API candidate' } else { 'proxy-core candidate; TUN owner not exposed by Windows' } [void]$out.Add([PSCustomObject]@{ Core = $r.Core; Confidence = $conf; Evidence = $ev; Rule = '' }) } return @($out) } function Get-LocalProcessRelations([int]$processId, [string]$ruleHint = '') { $rels = @{} $src = Get-ProcessFact $processId if (-not $src) { return @() } foreach ($cc in @($tcpAll | Where-Object { $_.OwningProcess -eq $processId -and $_.State -eq 'Established' -and (Test-IsLocalHostAddress ([string]$_.RemoteAddress)) })) { $peer = Find-LocalPeerConnection $cc $targetPid = 0; $conf = 0.0; $ev = '' if ($peer -and [int]$peer.OwningProcess -gt 0 -and [int]$peer.OwningProcess -ne $processId) { $targetPid = [int]$peer.OwningProcess; $conf = 1.0; $ev = 'live local TCP + reverse peer owner' } else { $ll = Find-LocalListener ([string]$cc.RemoteAddress) ([int]$cc.RemotePort) if ($ll -and [int]$ll.OwningProcess -gt 0 -and [int]$ll.OwningProcess -ne $processId) { $targetPid = [int]$ll.OwningProcess; $conf = 0.96; $ev = 'live local TCP + listener owner fallback' } } if ($targetPid -le 0) { continue } $ep = Format-Endpoint ([string]$cc.RemoteAddress) ([int]$cc.RemotePort) $key = [string]$targetPid + '|' + $ep $rels[$key] = [PSCustomObject]@{ TargetPID = $targetPid; Endpoint = $ep; ProxyName = ''; ProxyType = '' Confidence = $conf; Evidence = $ev; Rule = '' } } $ci = if ($coreInfoByPid.ContainsKey([string]$processId)) { $coreInfoByPid[[string]$processId] } else { $null } if ($ci) { foreach ($pd in $ci.LocalProxyDefs) { $ll = Find-LocalListener ([string]$pd.Server) ([int]$pd.Port) if (-not $ll -or [int]$ll.OwningProcess -le 0 -or [int]$ll.OwningProcess -eq $processId) { continue } $ep = Format-Endpoint ([string]$pd.Server) ([int]$pd.Port) $key = [string]$ll.OwningProcess + '|' + $ep $rule = '' if ($pd.Name -and $ci.Connections) { $rules = @($ci.Connections | Where-Object { @($_.chains) -contains [string]$pd.Name } | ForEach-Object { Format-MihomoRule $_ } | Where-Object { $_ } | Select-Object -Unique | Select-Object -First 3) if ($rules.Count -gt 0) { $rule = ($rules -join ' | ') } } if ($rels.ContainsKey($key)) { # Live socket evidence wins; config only annotates the endpoint. $rr = $rels[$key] $rr.ProxyName = [string]$pd.Name; $rr.ProxyType = [string]$pd.Type $rr.Evidence = $rr.Evidence + ' + runtime-config hint'; if ($rule) { $rr.Rule = $rule } } else { # A pass-specific runtime rule must not be overwritten by every local # proxy definition in the file. This prevents a DIRECT/runtime-rule pass # from being incorrectly projected through an unrelated local connector. if ($ruleHint -and $pd.Name -and $ruleHint -notmatch [regex]::Escape([string]$pd.Name)) { continue } $rels[$key] = [PSCustomObject]@{ TargetPID = [int]$ll.OwningProcess; Endpoint = $ep; ProxyName = [string]$pd.Name; ProxyType = [string]$pd.Type Confidence = 0.72; Evidence = 'runtime-config local endpoint + listener owner'; Rule = $rule } } } } return @($rels.Values | Sort-Object TargetPID, Endpoint) } function Get-ProcessRouteRelations([int]$processId) { $key = [string]$processId if ($routeFactCache.ContainsKey($key)) { return @($routeFactCache[$key]) } $groups = @{} foreach ($cc in @($tcpAll | Where-Object { $_.OwningProcess -eq $processId -and $_.State -eq 'Established' -and $_.RemoteAddress -and -not (Test-IsLocalHostAddress ([string]$_.RemoteAddress)) -and -not (Test-UnspecifiedAddr ([string]$_.RemoteAddress)) })) { $remote = [string]$cc.RemoteAddress $local = [string]$cc.LocalAddress $af = if ($remote -match ':') { 'IPv6' } else { 'IPv4' } $rt = Find-NetRoute -RemoteIPAddress $remote -ErrorAction SilentlyContinue | Select-Object -First 1 # Prefer the established socket's concrete local source address. This catches # interface-bound/bypass sockets that differ from the host's current best route. # Find-NetRoute(remote) remains the fallback when Windows reports no usable # source address or the source cannot be mapped back to an interface. $srcIp = $null if ($local -and -not (Test-UnspecifiedAddr $local) -and -not (Test-LoopbackAddr $local)) { $srcIp = Get-NetIPAddress -IPAddress $local -ErrorAction SilentlyContinue | Select-Object -First 1 } $ifx = 0; $alias = ''; $routeEvidence = '' if ($srcIp) { $ifx = [int]$srcIp.InterfaceIndex $alias = [string]$srcIp.InterfaceAlias $routeEvidence = 'live established socket + local source/interface' } elseif ($rt) { $ifx = [int]$rt.InterfaceIndex $alias = [string]$rt.InterfaceAlias $routeEvidence = 'live established socket + Find-NetRoute' } else { continue } $nh = '' if ($rt -and [int]$rt.InterfaceIndex -eq $ifx -and $rt.PSObject.Properties['NextHop'] -and $rt.NextHop -and [string]$rt.NextHop -notin @('0.0.0.0','::')) { $nh = [string]$rt.NextHop } else { # If the source-address interface differs from Find-NetRoute's host-wide # choice, use that interface's own default next hop rather than silently # reassigning the socket to another adapter. $dp = if ($af -eq 'IPv6') { '::/0' } else { '0.0.0.0/0' } $dr = Get-NetRoute -DestinationPrefix $dp -InterfaceIndex $ifx -ErrorAction SilentlyContinue | Sort-Object RouteMetric | Select-Object -First 1 if ($dr -and $dr.NextHop -and [string]$dr.NextHop -notin @('0.0.0.0','::')) { $nh = [string]$dr.NextHop } } $gk = [string]$ifx + '|' + $af + '|' + $nh if (-not $groups.ContainsKey($gk)) { $ad = Get-NetAdapter -InterfaceIndex $ifx -ErrorAction SilentlyContinue if (-not $alias -and $ad) { $alias = [string]$ad.Name } $aa0 = Get-AdapterAssessment $ad $groups[$gk] = [PSCustomObject]@{ InterfaceIndex = $ifx; InterfaceAlias = $alias; AddressFamily = $af; NextHop = $nh IsTunnel = [bool](Test-IsTunnelAdapter $ad); IsPhysical = [bool](Test-IsPhysicalAdapter $ad); AdapterRole = $(if ($aa0) { [string]$aa0.Role } else { 'Unknown' }); AdapterConfidence = $(if ($aa0) { [double]$aa0.Confidence } else { 0.0 }) Remotes = New-Object System.Collections.ArrayList; Sources = New-Object System.Collections.ArrayList Count = 0; Confidence = 1.0; Evidence = $routeEvidence } } $gr = $groups[$gk]; $gr.Count++ $ep = Format-Endpoint $remote ([int]$cc.RemotePort) if ($gr.Remotes.Count -lt 5 -and -not $gr.Remotes.Contains($ep)) { [void]$gr.Remotes.Add($ep) } if ($local -and $gr.Sources.Count -lt 3 -and -not $gr.Sources.Contains($local)) { [void]$gr.Sources.Add($local) } if ($routeEvidence -match 'local source/interface') { $gr.Evidence = $routeEvidence } } $arr = @($groups.Values | Sort-Object InterfaceIndex, AddressFamily, NextHop) $routeFactCache[$key] = $arr return $arr } # ---------- Resolver and local-adapter nested detail helpers ---------- function New-DnsDetailGeneral([string]$addr, [int]$order, [string]$prefix) { $pr = Get-CachedDns $addr $st = GStatus $pr.Ok $role = if ($order -eq 0) { 'primary' } else { 'backup ' + [string]$order } $items = @( (GItem 'resolve' 'resolve' 'www.baidu.com' $st '' 'prop'), (GItem 'answer' 'answer' ([string]$pr.Answer) $st '' 'prop'), (GItem 'time' 'time' $(if ($pr.Ok -and $pr.Ms -ge 0) { [string]$pr.Ms + ' ms' } else { 'T/O' }) $st '' 'prop') ) return GDetail ($prefix + ' ' + $addr) ('resolver · ' + $role) 'dns' $st $items } function Get-DnsItemsForInterface([int]$ifIndex, [string]$prefix) { $items = @(); $list = @((Get-DnsClientServerAddress -InterfaceIndex $ifIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue).ServerAddresses | Where-Object { $_ } | Select-Object -Unique) for ($i = 0; $i -lt $list.Count; $i++) { $addr = [string]$list[$i]; $pr = Get-CachedDns $addr; $st = GStatus $pr.Ok $key = if ($i -eq 0) { 'DNS' } else { 'DNS(备)' } $items += GItem ('dns-' + $i) $key $addr $st (GProbeMeta $pr.Ok $pr) 'prop' $true (New-DnsDetailGeneral $addr $i $prefix) } return @($items) } function New-AdapterDetailGeneral($ad, [string]$roleText) { $cfgx = Get-NetIPConfiguration -InterfaceIndex $ad.InterfaceIndex -ErrorAction SilentlyContinue $ipx = Get-IPv4Text ([int]$ad.InterfaceIndex) $gwx = if ($cfgx) { (($cfgx.IPv4DefaultGateway | ForEach-Object NextHop) -join ', ') } else { '' } $st = if ([string]$ad.Status -eq 'Up') { 'OK' } else { 'DOWN' } $aa = Get-AdapterAssessment $ad $items = @( (GItem 'ipv4' 'IPv4' $(if ($ipx) { $ipx } else { '--' }) $st '' 'addr'), (GItem 'gateway' 'gateway' $(if ($gwx) { $gwx } else { '--' }) '' '' 'prop'), (GItem 'link' 'link' (Get-LinkText $ad) '' '' 'prop'), (GItem 'ifindex' 'ifIndex' ([string]$ad.InterfaceIndex) '' '' 'prop') ) if ($aa) { $items += GItem 'role' 'role' ([string]$aa.Role) $(if ($aa.Role -eq 'SuspectedTunnel' -or $aa.Role -eq 'AmbiguousRoute') { 'WARN' } else { '' }) ('confidence ' + [string]$aa.Confidence) 'prop' if ($aa.ServiceName) { $items += GItem 'service' 'service' ([string]$aa.ServiceName) '' '' 'prop' } if ($aa.DriverProvider) { $items += GItem 'driver' 'driver' (([string]$aa.DriverProvider) + $(if ($aa.InfName) { ' · ' + [string]$aa.InfName } else { '' })) '' '' 'prop' } if ($aa.Signals.Count -gt 0) { $items += GItem 'signals' 'signals' ((@($aa.Signals | Select-Object -First 4)) -join ' | ') $(if ($aa.Role -eq 'SuspectedTunnel') { 'WARN' } else { '' }) '' 'prop' } } return GDetail ([string]$ad.Name) (([string]$ad.InterfaceDescription) + ' · ' + $roleText) 'off' $st $items } # ---------- Presentation graph primitives ---------- $ndNodes = New-Object System.Collections.ArrayList $ndEdges = New-Object System.Collections.ArrayList $ndNodeMap = @{} $ndEdgeSeen = @{} $counters = @{ Process = 0; Tunnel = 0 } $processPassCount = @{} $tunnelPassCount = @{} # V5.2 visual entities are stable per graph layer. Logical flow contexts are retained # inside the entity instead of cloning a full process/TUN card for every socket/pass. $processNodeByLayerPid = @{} $processNodeByLayerName = @{} $processNodePids = @{} $tunnelNodeByLayerIf = @{} $processEntryContexts = @{} $tunnelEntryContexts = @{} $localPeerContexts = @{} $tunnelCaptureContexts = @{} $projectedProcessPids = @{} $physicalNodeByIf = @{} $gatewayNodeByKey = @{} $ispNodeByPath = @{} $remoteNodeByPath = @{} $usedPhysicalIf = @{} $usedPhysicalPath = @{} function Add-GNode([string]$id, [string]$label, [string]$sub, [string]$kind, [string]$status, [bool]$sel, $items) { if ($ndNodeMap.ContainsKey($id)) { return $ndNodeMap[$id] } $n = [ordered]@{ id = $id; label = $label; sub = $sub; kind = $kind; status = $status; sel = $sel; items = @($items) } [void]$ndNodes.Add($n); $ndNodeMap[$id] = $n return $n } function Add-GItemToNode([string]$nodeId, $item) { if (-not $ndNodeMap.ContainsKey($nodeId)) { return } $n = $ndNodeMap[$nodeId] foreach ($old in @($n['items'])) { if ([string]$old.id -eq [string]$item.id) { return } } $n['items'] = @($n['items']) + @($item) } function Set-GItemOnNode([string]$nodeId, [string]$itemId, $item) { if (-not $ndNodeMap.ContainsKey($nodeId)) { return } $n = $ndNodeMap[$nodeId]; $arr = @($n['items']); $found = $false for ($ii = 0; $ii -lt $arr.Count; $ii++) { if ([string]$arr[$ii].id -eq $itemId) { $arr[$ii] = $item; $found = $true; break } } if (-not $found) { $arr += $item } $n['items'] = $arr } function Add-GEdge([string]$from, [string]$fromItem, [string]$to, [string]$kind = 'main', [double]$confidence = 1.0, [string]$evidence = '', [bool]$bad = $false) { if (-not $from -or -not $to -or $from -eq $to) { return } $k = $from + '|' + $fromItem + '|' + $to if ($ndEdgeSeen.ContainsKey($k)) { $old = $ndEdgeSeen[$k] if ([double]$confidence -gt [double]$old['confidence']) { $old['confidence'] = [math]::Round($confidence, 2); $old['evidence'] = $evidence; $old['bad'] = $bad; $old['kind'] = $kind } return } $edge = [ordered]@{ from = $from; fromItem = $fromItem; to = $to; kind = $kind; dead = $false; bad = $bad confidence = [math]::Round($confidence, 2); evidence = $evidence } $ndEdgeSeen[$k] = $edge; [void]$ndEdges.Add($edge) } function Confidence-Status([double]$c) { if ($c -ge 0.80) { 'OK' } elseif ($c -ge 0.50) { 'WARN' } else { '' } } function Confidence-Meta([double]$c, [string]$evidence) { $tag = if ($c -ge 0.80) { 'confirmed' } elseif ($c -ge 0.50) { 'likely' } else { 'possible' } if ($evidence) { return $tag + ' · ' + $evidence } return $tag } function Ensure-RemoteEndpointProjection([string]$ispId, [string]$pathKey, [string[]]$remoteSamples) { $rr = @($remoteSamples | Where-Object { $_ } | Select-Object -Unique | Select-Object -First 8) if (-not $ispId -or $rr.Count -eq 0) { return '' } $rid = 'remote-' + (Safe-GraphId $pathKey) if (-not $remoteNodeByPath.ContainsKey($pathKey)) { $ri = @((GItem 'address' 'remote' ([string]$rr[0]) 'OK' 'passively observed established socket · not probed' 'addr')) for ($ri0 = 1; $ri0 -lt $rr.Count; $ri0++) { $ri += GItem ('endpoint-' + [string]$ri0) 'remote' ([string]$rr[$ri0]) '' 'passive socket observation' 'prop' } $ri += GItem 'mode' 'mode' 'passive only' '' 'no reachability probe issued' 'prop' [void](Add-GNode $rid 'Remote endpoint(s)' 'observed beyond ISP · identity/role not assumed' 'remote' 'OK' $false $ri) $remoteNodeByPath[$pathKey] = $rid Set-GItemOnNode $ispId 'remote-hop' (GItem 'remote-hop' 'remote' ([string]$rr[0]) 'OK' 'passively observed; no probe' 'out') Add-GEdge $ispId 'remote-hop' $rid 'main' 1.0 'passive established socket endpoint' $false } else { $rid = [string]$remoteNodeByPath[$pathKey] Set-GItemOnNode $ispId 'remote-hop' (GItem 'remote-hop' 'remote' ([string]$rr[0]) 'OK' 'passively observed; no probe' 'out') if ($ndNodeMap.ContainsKey($rid)) { $rn = $ndNodeMap[$rid]; $known = @{} foreach ($it in @($rn['items'])) { if ($it.value) { $known[[string]$it.value] = $true } } foreach ($rv in $rr) { if ($known.ContainsKey([string]$rv)) { continue } Add-GItemToNode $rid (GItem ('endpoint-' + (Safe-GraphId ([string]$rv))) 'remote' ([string]$rv) '' 'passive socket observation' 'prop') } } Add-GEdge $ispId 'remote-hop' $rid 'main' 1.0 'passive established socket endpoint' $false } return $rid } function Ensure-PhysicalPath([int]$ifIndex, [string]$nextHop, [bool]$observed, [string[]]$remoteSamples, [string]$addressFamily = 'IPv4', [bool]$createIsp = $true) { $ad = Get-NetAdapter -InterfaceIndex $ifIndex -ErrorAction SilentlyContinue if (-not $ad) { return $null } $cfgx = Get-NetIPConfiguration -InterfaceIndex $ifIndex -ErrorAction SilentlyContinue $ip4x = Get-IPv4Text $ifIndex; $ip6x = Get-IPv6Text $ifIndex $fam = if ($addressFamily -eq 'IPv6') { 'IPv6' } else { 'IPv4' } if (-not $nextHop -and $cfgx -and $fam -eq 'IPv4') { $nextHop = (($cfgx.IPv4DefaultGateway | ForEach-Object NextHop | Where-Object { $_ -and $_ -ne '0.0.0.0' }) -join ', ') } if (-not $nextHop -and $fam -eq 'IPv6') { $v6dr = Get-NetRoute -DestinationPrefix '::/0' -InterfaceIndex $ifIndex -ErrorAction SilentlyContinue | Sort-Object RouteMetric | Select-Object -First 1 if ($v6dr -and $v6dr.NextHop -and $v6dr.NextHop -ne '::') { $nextHop = [string]$v6dr.NextHop } } $pc = $allPhysicalRouteCandidates | Where-Object { $_.IfIndex -eq $ifIndex -and $_.AddressFamily -eq $fam -and ((-not $nextHop) -or $_.Gateway -eq $nextHop) } | Sort-Object EffectiveMetric | Select-Object -First 1 if (-not $pc) { $pc = $allPhysicalRouteCandidates | Where-Object { $_.IfIndex -eq $ifIndex -and $_.AddressFamily -eq $fam } | Sort-Object EffectiveMetric | Select-Object -First 1 } $metric = if ($pc) { [string]$pc.EffectiveMetric } else { '' } $nicId = 'nic-' + [string]$ifIndex if (-not $physicalNodeByIf.ContainsKey([string]$ifIndex)) { $nicItems = @((GItem 'ipv4' 'IPv4' $(if ($ip4x) { $ip4x } else { '--' }) $(if ($ad.Status -eq 'Up') { 'OK' } else { 'DOWN' }) '' 'addr')) if ($ip6x) { $nicItems += GItem 'ipv6' 'IPv6' $ip6x '' '' 'prop' } $nicItems += GItem 'ifindex' 'ifIndex' ([string]$ifIndex) '' '' 'prop' if ($metric) { $nicItems += GItem 'metric' 'metric' $metric '' '' 'prop' } $lt = Get-LinkText $ad; if ($lt) { $nicItems += GItem 'link' 'link' $lt '' '' 'prop' } $nicItems += @(Get-DnsItemsForInterface $ifIndex 'Physical DNS') $aaNic = Get-AdapterAssessment $ad $nicSub = 'carrier / route interface' + $(if ($aaNic) { ' · assessed ' + [string]$aaNic.Role + ' ' + [string]$aaNic.Confidence } else { '' }) [void](Add-GNode $nicId ([string]$ad.Name) $nicSub 'nic' $(if ($ad.Status -eq 'Up') { 'OK' } else { 'DOWN' }) $false $nicItems) $physicalNodeByIf[[string]$ifIndex] = $nicId } if (-not $nextHop) { # Point-to-point, PPP/cellular and some bridged/virtual carriers expose no # conventional next-hop address. Do not truncate a proven route just because # there is no Gateway object; project NIC -> ISP directly and label it on-link. if (-not $createIsp) { return [PSCustomObject]@{ Nic = $nicId; Gateway = ''; Isp = '' } } $directKey = [string]$ifIndex + '|' + $fam + '|DIRECT' $directIspId = 'isp-' + [string]$ifIndex + '-' + $fam.ToLowerInvariant() + '-direct' $directItem = 'internet-' + $fam.ToLowerInvariant() + '-direct' # Active-probe identity is the complete selected route path, not merely the # interface name. One interface can carry several default next hops. if ($fam -eq 'IPv6') { $isActiveProbePath = [bool]($eg6 -and [int]$eg6.InterfaceIndex -eq $ifIndex -and ((-not $nh6) -or $nextHop -eq [string]$nh6)) } else { $isActiveProbePath = [bool]($eg4 -and [int]$eg4.InterfaceIndex -eq $ifIndex -and ((-not $nh4) -or $nextHop -eq [string]$nh4)) } if (-not $ispNodeByPath.ContainsKey($directKey)) { if ($isActiveProbePath) { $probeAddr = if ($fam -eq 'IPv6') { '2400:3200::1' } else { '223.5.5.5' } $pp = Test-PingProbe $probeAddr; $pst = GStatus $pp.Ok $ispItems = @((GItem 'probe' $fam $probeAddr $pst (GProbeMeta $pp.Ok $pp) 'addr' $true)) } elseif ($observed -and $remoteSamples.Count -gt 0) { $pst = 'OK'; $ispItems = @((GItem 'probe' 'remote' ([string]$remoteSamples[0]) 'OK' 'established · passive' 'addr')) } else { $pst = 'WARN'; $ispItems = @((GItem 'probe' 'route' ([string]$ad.Name) 'WARN' ($fam + ' on-link candidate · not actively probed') 'addr')) } Add-GItemToNode $nicId (GItem $directItem 'Internet' 'on-link / point-to-point' $pst $(if ($observed) { 'established socket route' } else { 'no conventional gateway' }) 'out') [void](Add-GNode $directIspId 'Internet / ISP' ('gateway-less ' + $fam + ' carrier via ' + [string]$ad.Name) 'isp' $pst $false $ispItems) $ispNodeByPath[$directKey] = $directIspId Add-GEdge $nicId $directItem $directIspId $(if ($observed -or $isActiveProbePath) { 'main' } else { 'alt' }) $(if ($observed -or $isActiveProbePath) { 1.0 } else { 0.45 }) $(if ($observed) { 'established socket on gateway-less carrier' } elseif ($isActiveProbePath) { 'active internet probe on gateway-less carrier' } else { 'gateway-less route candidate' }) $false } elseif ($observed -and $remoteSamples.Count -gt 0) { $din = $ndNodeMap[$directIspId]; $din['status'] = 'OK'; $din['sub'] = 'observed routed connection · gateway-less carrier' Set-GItemOnNode $directIspId 'probe' (GItem 'probe' 'remote' ([string]$remoteSamples[0]) 'OK' 'established · passive' 'addr') Set-GItemOnNode $nicId $directItem (GItem $directItem 'Internet' 'on-link / point-to-point' 'OK' 'established socket route' 'out') Add-GEdge $nicId $directItem $directIspId 'main' 1.0 'established socket on gateway-less carrier' $false } if ($observed -and $remoteSamples.Count -gt 0) { [void](Ensure-RemoteEndpointProjection $directIspId $directKey $remoteSamples) } return [PSCustomObject]@{ Nic = $nicId; Gateway = ''; Isp = $directIspId } } $gwKey = [string]$ifIndex + '|' + $fam + '|' + $nextHop $gwId = 'gw-' + [string]$ifIndex + '-' + $fam.ToLowerInvariant() + '-' + (Safe-GraphId $nextHop) $nicGwItem = 'gateway-' + $fam.ToLowerInvariant() + '-' + (Safe-GraphId $nextHop) if (-not $gatewayNodeByKey.ContainsKey($gwKey)) { $probeTarget = if ($fam -eq 'IPv6' -and $nextHop -match '^fe80:' -and $nextHop -notmatch '%') { $nextHop + '%' + [string]$ifIndex } else { $nextHop } $gp = Get-CachedPing $probeTarget; $gst = GStatus $gp.Ok $dh = if ($fam -eq 'IPv4' -and $cfgx) { $cimcfg = Get-CimInstance Win32_NetworkAdapterConfiguration -Filter ('InterfaceIndex=' + [string]$ifIndex) -ErrorAction SilentlyContinue if ($cimcfg) { [string]$cimcfg.DHCPServer } else { '' } } else { '' } Add-GItemToNode $nicId (GItem $nicGwItem ('gateway ' + $fam) $nextHop $gst (GProbeMeta $gp.Ok $gp) 'out' $true) $gwItems = @( (GItem 'address' $fam $nextHop $gst (GProbeMeta $gp.Ok $gp) 'addr' $true), (GItem 'internet' 'Internet' $(if ($observed -and $remoteSamples.Count -gt 0) { [string]$remoteSamples[0] } else { 'route candidate' }) $(if ($observed) { 'OK' } else { 'WARN' }) $(if ($observed) { 'established socket' } else { 'not constrained/probed' }) 'out'), (GItem 'ifindex' 'ifIndex' ([string]$ifIndex) '' '' 'prop') ) if ($dh) { $gwItems += GItem 'dhcp' 'DHCP' $dh '' '' 'prop' } [void](Add-GNode $gwId 'Gateway' ($nextHop + ' · ' + $fam + ' via ' + [string]$ad.Name) 'gw' $gst $false $gwItems) $gatewayNodeByKey[$gwKey] = $gwId Add-GEdge $nicId $nicGwItem $gwId 'main' 1.0 ('interface ' + $fam + ' next hop') ($gst -eq 'FAIL') } elseif ($observed -and $remoteSamples.Count -gt 0) { Set-GItemOnNode $gwId 'internet' (GItem 'internet' 'Internet' ([string]$remoteSamples[0]) 'OK' 'established socket' 'out') } if (-not $createIsp) { return [PSCustomObject]@{ Nic = $nicId; Gateway = $gwId; Isp = '' } } # ISP projection is keyed by the actual route path, not merely by interface. # One NIC can legitimately have multiple gateways/next-hops. $ispKey = [string]$ifIndex + '|' + $fam + '|' + $nextHop $ispId = 'isp-' + [string]$ifIndex + '-' + $fam.ToLowerInvariant() + '-' + (Safe-GraphId $nextHop) if (-not $ispNodeByPath.ContainsKey($ispKey)) { if ($fam -eq 'IPv6') { $isActiveProbePath = [bool]($eg6 -and [int]$eg6.InterfaceIndex -eq $ifIndex -and ((-not $nh6) -or $nextHop -eq [string]$nh6)) } else { $isActiveProbePath = [bool]($eg4 -and [int]$eg4.InterfaceIndex -eq $ifIndex -and ((-not $nh4) -or $nextHop -eq [string]$nh4)) } if ($isActiveProbePath) { $probeAddr = if ($fam -eq 'IPv6') { '2400:3200::1' } else { '223.5.5.5' } $pp = Test-PingProbe $probeAddr; $pst = GStatus $pp.Ok $ispItems = @((GItem 'probe' $fam $probeAddr $pst (GProbeMeta $pp.Ok $pp) 'addr' $true)) } elseif ($observed -and $remoteSamples.Count -gt 0) { $pst = 'OK'; $ispItems = @((GItem 'probe' 'remote' ([string]$remoteSamples[0]) 'OK' 'established · passive' 'addr')) } else { $pst = 'WARN'; $ispItems = @((GItem 'probe' 'route' ([string]$ad.Name) 'WARN' ($fam + ' candidate · not actively probed') 'addr')) } foreach ($re in @($remoteSamples | Select-Object -First 3)) { $ispItems += GItem ('remote-' + (Safe-GraphId $re)) 'observed' ([string]$re) '' 'passive socket' 'prop' } [void](Add-GNode $ispId 'Internet / ISP' $(if ($isActiveProbePath) { 'active ' + $fam + ' reachability' } elseif ($observed) { 'observed routed connection' } else { 'alternate route candidate' }) 'isp' $pst $false $ispItems) $ispNodeByPath[$ispKey] = $ispId Add-GEdge $gwId 'internet' $ispId $(if ($observed -or $isActiveProbePath) { 'main' } else { 'alt' }) $(if ($observed -or $isActiveProbePath) { 1.0 } else { 0.45 }) $(if ($observed) { 'established socket beyond gateway' } elseif ($isActiveProbePath) { 'active internet probe' } else { 'standby route candidate' }) $false } elseif ($observed -and $remoteSamples.Count -gt 0) { $in = $ndNodeMap[$ispId]; $in['status'] = 'OK'; $in['sub'] = 'observed routed connection' Set-GItemOnNode $ispId 'probe' (GItem 'probe' 'remote' ([string]$remoteSamples[0]) 'OK' 'established · passive' 'addr') foreach ($re in @($remoteSamples | Select-Object -First 3)) { Add-GItemToNode $ispId (GItem ('remote-' + (Safe-GraphId $re)) 'observed' ([string]$re) '' 'passive socket' 'prop') } Add-GEdge $gwId 'internet' $ispId 'main' 1.0 'established socket beyond gateway' $false } if ($observed -and $remoteSamples.Count -gt 0) { [void](Ensure-RemoteEndpointProjection $ispId $ispKey $remoteSamples) } return [PSCustomObject]@{ Nic = $nicId; Gateway = $gwId; Isp = $ispId } } function Update-EntityEntryContext([string]$nodeId, [string]$mapKind, [string]$endpoint, [string]$rule, [double]$confidence, [string]$evidence) { if (-not $nodeId -or -not $ndNodeMap.ContainsKey($nodeId)) { return } $map = if ($mapKind -eq 'tun') { $tunnelEntryContexts } else { $processEntryContexts } if (-not $map.ContainsKey($nodeId)) { $map[$nodeId] = New-Object System.Collections.ArrayList } $key = ([string]$endpoint) + '|' + ([string]$rule) + '|' + ([string]$evidence) $exists = @($map[$nodeId] | Where-Object { [string]$_.Key -eq $key }).Count -gt 0 if (-not $exists) { [void]$map[$nodeId].Add([PSCustomObject]@{ Key = $key; Endpoint = $endpoint; Rule = $rule; Confidence = $confidence; Evidence = $evidence }) } $ctx = @($map[$nodeId]) if ($ctx.Count -eq 0) { return } $di = @(); $ix = 0 foreach ($cc in @($ctx | Select-Object -First 12)) { $ix++ $val = if ($cc.Endpoint) { [string]$cc.Endpoint } elseif ($cc.Rule) { [string]$cc.Rule } else { 'runtime capture' } $meta = '' if ($cc.Rule -and $cc.Endpoint) { $meta = 'rule ' + [string]$cc.Rule } if ($cc.Evidence) { $meta = (($meta + ' · ' + [string]$cc.Evidence) -replace '^[ ·]+','') } $di += GItem ('ctx-' + [string]$ix) ('flow ' + [string]$ix) $val (Confidence-Status ([double]$cc.Confidence)) $meta 'prop' } if ($ctx.Count -gt 12) { $di += GItem 'ctx-more' 'more' ([string]($ctx.Count - 12) + ' additional contexts') '' 'kept in runtime evidence; compact visual cap' 'prop' } $dv = if ($ctx.Count -eq 1) { if ($ctx[0].Endpoint) { [string]$ctx[0].Endpoint } elseif ($ctx[0].Rule) { [string]$ctx[0].Rule } else { '1 context' } } else { [string]$ctx.Count + ' flow contexts' } $best = $ctx | Sort-Object Confidence -Descending | Select-Object -First 1 $detail = GDetail 'Flow contexts' 'merged into one entity at this graph layer' 'flow' (Confidence-Status ([double]$best.Confidence)) $di Set-GItemOnNode $nodeId 'entry' (GItem 'entry' 'entry' $dv (Confidence-Status ([double]$best.Confidence)) 'click to inspect merged logical flow contexts' 'prop' $false $detail) } function New-TunnelPass([int]$ifIndex, [string]$entryText, [double]$confidence, [string]$evidence, [int]$layer = 0) { if ($layer -lt 0) { $layer = 0 } $tk = [string]$layer + '|' + [string]$ifIndex if ($tunnelNodeByLayerIf.ContainsKey($tk)) { $eid = [string]$tunnelNodeByLayerIf[$tk] Update-EntityEntryContext $eid 'tun' $entryText '' $confidence $evidence return $eid } $counters.Tunnel++ if (-not $tunnelPassCount.ContainsKey([string]$ifIndex)) { $tunnelPassCount[[string]$ifIndex] = 0 } $tunnelPassCount[[string]$ifIndex] = [int]$tunnelPassCount[[string]$ifIndex] + 1 $id = 'tun-' + [string]$ifIndex + '-l' + [string]$layer $ad = Get-NetAdapter -InterfaceIndex $ifIndex -ErrorAction SilentlyContinue $ipx = Get-IPv4Text $ifIndex $ip6x = Get-IPv6Text $ifIndex $items = @((GItem 'ipv4' 'IPv4' $(if ($ipx) { $ipx } else { '--' }) (Confidence-Status $confidence) (Confidence-Meta $confidence $evidence) 'addr')) if ($ip6x) { $items += GItem 'ipv6' 'IPv6' $ip6x '' '' 'prop' } $items += GItem 'ifindex' 'ifIndex' ([string]$ifIndex) '' ('graph layer ' + [string]$layer) 'prop' $aaTun = if ($ad) { Get-AdapterAssessment $ad } else { $null } if ($aaTun) { $items += GItem 'role' 'role' ([string]$aaTun.Role) $(if ($aaTun.Role -eq 'SuspectedTunnel') { 'WARN' } else { '' }) ('confidence ' + [string]$aaTun.Confidence) 'prop' if ($aaTun.ServiceName) { $items += GItem 'service' 'service' ([string]$aaTun.ServiceName) '' '' 'prop' } if ($aaTun.Signals.Count -gt 0) { $items += GItem 'signals' 'signals' ((@($aaTun.Signals | Select-Object -First 4)) -join ' | ') $(if ($aaTun.Role -eq 'SuspectedTunnel') { 'WARN' } else { '' }) '' 'prop' } } $stackVals = @(Get-TunnelCaptureCandidates $ifIndex $null | ForEach-Object { [string]$_.Core.TunStack } | Where-Object { $_ } | Select-Object -Unique) if ($stackVals.Count -eq 1) { $items += GItem 'stack' 'stack' ([string]$stackVals[0]) '' '' 'prop' } elseif ($stackVals.Count -gt 1) { $items += GItem 'stack' 'stack' (($stackVals | Select-Object -First 3) -join ' | ') 'WARN' 'multiple core candidates' 'prop' } $items += @(Get-DnsItemsForInterface $ifIndex 'TUN DNS') $label = if ($ad) { [string]$ad.Name } else { 'Tunnel ifIndex ' + [string]$ifIndex } $roleLabel = if ($aaTun -and $aaTun.Role -eq 'SuspectedTunnel') { 'tunnel-like / ambiguous route adapter' } else { 'virtual/tunnel adapter' } $nn = Add-GNode $id $label ($roleLabel + ' · layer ' + [string]$layer) 'tun' (Confidence-Status $confidence) ($ifIndex -eq $selIdx) $items if ($nn) { $nn['ifIndex'] = $ifIndex; $nn['layer'] = $layer; $tunnelNodeByLayerIf[$tk] = $id } Update-EntityEntryContext $id 'tun' $entryText '' $confidence $evidence return $id } function New-ProcessPass([int]$processId, [string]$entryEndpoint, [string]$entryRule, [double]$entryConfidence, [string]$entryEvidence, [int]$layer = 0) { $pf = Get-ProcessFact $processId if (-not $pf) { return '' } $procName = ([string]$pf.Name).Trim().ToLowerInvariant() -replace '\.exe$', '' if ($procName -eq 'svchost') { return '' } if ($layer -lt 0) { $layer = 0 } $pk = [string]$layer + '|' + [string]$processId if ($processNodeByLayerPid.ContainsKey($pk)) { $eid = [string]$processNodeByLayerPid[$pk] Update-EntityEntryContext $eid 'proc' $entryEndpoint $entryRule $entryConfidence $entryEvidence return $eid } $nk = [string]$layer + '|' + $(if ($procName) { $procName } else { 'pid-' + [string]$processId }) if ($processNodeByLayerName.ContainsKey($nk)) { $eid = [string]$processNodeByLayerName[$nk] $processNodeByLayerPid[$pk] = $eid $projectedProcessPids[[string]$processId] = $true $allPids = @(@($processNodePids[$eid]) + $processId | Sort-Object -Unique) $processNodePids[$eid] = $allPids $pidItems = @($allPids | ForEach-Object { GItem ('pid-' + [string]$_) 'pid' ([string]$_) '' '' 'prop' }) Set-GItemOnNode $eid 'pid' (GItem 'pid' 'PIDs' ($allPids -join ' · ') '' ('entity layer ' + [string]$layer + ' · ' + [string]$allPids.Count + ' processes') 'prop' $false (GDetail 'Merged processes' 'same image name · same graph layer' 'flow' '' $pidItems)) Update-EntityEntryContext $eid 'proc' $entryEndpoint $entryRule $entryConfidence $entryEvidence return $eid } $counters.Process++ if (-not $processPassCount.ContainsKey([string]$processId)) { $processPassCount[[string]$processId] = 0 } $processPassCount[[string]$processId] = [int]$processPassCount[[string]$processId] + 1 $nodeSlug = if ($procName) { Safe-GraphId $procName } else { 'pid-' + [string]$processId } $id = 'proc-' + $nodeSlug + '-l' + [string]$layer $ci = if ($coreInfoByPid.ContainsKey([string]$processId)) { $coreInfoByPid[[string]$processId] } else { $null } $items = @((GItem 'pid' 'PIDs' ([string]$processId) '' ('entity layer ' + [string]$layer + ' · 1 process') 'prop' $false (GDetail 'Merged processes' 'same image name · same graph layer' 'flow' '' @((GItem ('pid-' + [string]$processId) 'pid' ([string]$processId) '' '' 'prop'))))) if ($pf.TcpListeners.Count -gt 0) { $li = @(); $ln = 0 foreach ($ll in @($pf.TcpListeners | Select-Object -First 24)) { $ln++; $li += GItem ('listen-' + [string]$ln) 'listen' (Format-Endpoint ([string]$ll.LocalAddress) ([int]$ll.LocalPort)) '' '' 'prop' } if ($pf.TcpListeners.Count -gt 24) { $li += GItem 'listen-more' 'more' ([string]($pf.TcpListeners.Count - 24) + ' additional listeners') '' 'visual detail capped; full inventory remains in report table' 'prop' } $firstL = $pf.TcpListeners | Select-Object -First 1 $lv = [string]$pf.TcpListeners.Count + ' · ' + (Format-Endpoint ([string]$firstL.LocalAddress) ([int]$firstL.LocalPort)) $items += GItem 'listeners' 'listeners' $lv '' 'click to inspect; endpoints merged by process' 'prop' $false (GDetail 'TCP listeners' ([string]$pf.Name + ' · PID ' + [string]$processId) 'socket' '' $li) } if ($pf.UdpEndpoints.Count -gt 0) { $ui = @(); $un = 0 foreach ($uu in @($pf.UdpEndpoints | Select-Object -First 16)) { $un++; $ui += GItem ('udp-' + [string]$un) 'UDP' (Format-Endpoint ([string]$uu.LocalAddress) ([int]$uu.LocalPort)) '' '' 'prop' } if ($pf.UdpEndpoints.Count -gt 16) { $ui += GItem 'udp-more' 'more' ([string]($pf.UdpEndpoints.Count - 16) + ' additional bindings') '' 'visual detail capped' 'prop' } $items += GItem 'udp' 'UDP binds' ([string]$pf.UdpEndpoints.Count) '' 'click to inspect' 'prop' $false (GDetail 'UDP bindings' ([string]$pf.Name + ' · PID ' + [string]$processId) 'socket' '' $ui) } $prs = @(Get-ProcessRouteRelations $processId) $remoteTotal = 0; $ri = @(); $rn = 0 foreach ($rr in $prs) { $remoteTotal += [int]$rr.Count; $rn++ $sample = (@($rr.Remotes | Select-Object -First 3) -join ' | ') $ri += GItem ('remote-route-' + [string]$rn) (([string]$rr.AddressFamily) + ' · ' + [string]$rr.InterfaceAlias) ([string]$rr.Count + ' socket(s)') '' $sample 'prop' } if ($remoteTotal -gt 0) { $items += GItem 'remote-sockets' 'remote sockets' ([string]$remoteTotal) '' 'process-wide established sockets; click to inspect route groups' 'prop' $false (GDetail 'Remote socket groups' 'passive process-wide evidence' 'socket' '' $ri) } if ($ci -and $ci.ApiOk) { $items += GItem 'api' 'API' ([string]$ci.ApiBase) 'OK' '' 'prop' } if ($ci -and $ci.FindProcess) { $items += GItem 'findproc' 'find-process' ([string]$ci.FindProcess) '' '' 'prop' } $sub = if ($ci) { 'proxy core · entity layer ' + [string]$layer } else { 'local connector/process · entity layer ' + [string]$layer } $nn = Add-GNode $id ([string]$pf.Name) $sub 'core' 'OK' $false $items if ($nn) { $projectedProcessPids[[string]$processId] = $true $nn['processId'] = $processId; $nn['layer'] = $layer $processNodeByLayerPid[$pk] = $id $processNodeByLayerName[$nk] = $id $processNodePids[$id] = @($processId) } Update-EntityEntryContext $id 'proc' $entryEndpoint $entryRule $entryConfidence $entryEvidence return $id } # ---------- Root/Application node and host interface inventory ---------- # V5.2 keeps the root focused on *traffic paths*. Transparent-interception # corroboration is added later as a low-priority diagnostic sidecar only when it # cannot already be explained by an explicit local proxy chain. $appItems = @() [void](Add-GNode 'app' 'Applications' 'outbound connections · traffic paths first' 'source' '' $false $appItems) # Non-route adapters are inventory rows, not free-standing nodes. UP physical # default-route candidates are intentionally *not* hidden here: they get real route # branches below, even when they are not selected. $physRouteIfSet = @{}; foreach ($pc in $allPhysicalRouteCandidates) { $physRouteIfSet[[string]$pc.IfIndex] = $true } $otherAdapterItems = New-Object System.Collections.ArrayList foreach ($ad0 in @(Get-NetAdapter | Where-Object { $_.Name -notmatch 'Loopback' } | Sort-Object InterfaceIndex)) { $ifk = [string]$ad0.InterfaceIndex if (($eg4 -and $ad0.InterfaceIndex -eq $selIdx) -or $physRouteIfSet.ContainsKey($ifk)) { continue } $roleText = if ($ad0.Status -eq 'Up' -and (Test-IsTunnelAdapter $ad0)) { 'available tunnel / no selected default route' } elseif ($ad0.Status -eq 'Up') { 'up / no default route' } else { 'disconnected' } $ak = if ($ad0.Status -eq 'Up' -and (Test-IsTunnelAdapter $ad0)) { 'tunnel' } elseif ($ad0.Status -eq 'Up') { 'adapter(up)' } else { 'adapter' } $ast = if ($ad0.Status -eq 'Up') { 'OK' } else { 'DOWN' } $aa0 = Get-AdapterAssessment $ad0 $ameta = $roleText + ' · ifIndex ' + [string]$ad0.InterfaceIndex if ($aa0) { $ameta += ' · assessed ' + [string]$aa0.Role + ' ' + [string]$aa0.Confidence } [void]$otherAdapterItems.Add((GItem ('if-' + [string]$ad0.InterfaceIndex) $ak ([string]$ad0.Name) $ast $ameta 'prop')) } if ($otherAdapterItems.Count -gt 0) { $otherAdapterDetail = GDetail 'Other adapters' 'inventory only · not current traffic-path hops' 'adapter' '' @($otherAdapterItems) Add-GItemToNode 'app' (GItem 'adapter-inventory' 'other adapters' ([string]$otherAdapterItems.Count) '' 'collapsed inventory · not a traffic hop' 'prop' $false $otherAdapterDetail) } # Queue states are logical flow contexts attached to entity-level process nodes. The # same process name at the same graph layer is one visual node; rule/config contexts may still # be expanded independently when they carry materially different routing semantics. $queue = New-Object System.Collections.ArrayList $maxDepth = 10; $maxNodes = 90; $maxRepeatPerPid = 3 $usedLocalRelation = @{} $usedRouteRelation = @{} $queuedFlowState = @{} function Enqueue-ProcessPass( [int]$processId, [string]$nodeId, [int]$depth, [int[]]$history, [string]$entryRule = '', [string]$entryEndpoint = '', [double]$entryConfidence = 0.0, [string]$entryEvidence = '' ) { if (-not $nodeId -or $depth -gt $maxDepth -or $ndNodes.Count -ge $maxNodes) { return } $flowClass = if ($entryEvidence -match '(?i)configured endpoint.*listener owner|configured endpoint \+ local listener owner') { 'configured' } elseif ($entryRule) { 'rule' } else { 'generic' } # Endpoint multiplicity alone does not create a new downstream semantic pass. This # is what collapses 48 SOCKS listener ports of one connector into one entity flow. $qk = $nodeId + '|' + $flowClass + '|' + [string]$entryRule if ($queuedFlowState.ContainsKey($qk)) { return } $queuedFlowState[$qk] = $true [void]$queue.Add([PSCustomObject]@{ ProcessId = $processId; NodeId = $nodeId; Depth = $depth; History = @($history) EntryRule = $entryRule; EntryEndpoint = $entryEndpoint; EntryConfidence = $entryConfidence; EntryEvidence = $entryEvidence }) } function Add-TunnelCaptureFrom([string]$tunNode, [int]$ifIndex, $sourceFact, [int]$depth, [int[]]$history) { $caps = @(Get-TunnelCaptureCandidates $ifIndex $sourceFact) if ($caps.Count -eq 0) { Add-GItemToNode $tunNode (GItem 'owner' 'capture' 'owner not exposed' 'WARN' 'no matching runtime API/process evidence' 'prop') return } # Group by process entity. Different runtime rules remain visible inside the nested # capture detail and as queue flow contexts; they do not clone the process card. foreach ($cg in @($caps | Group-Object { [string]$_.Core.PID })) { if ($ndNodes.Count -ge $maxNodes) { break } $grp = @($cg.Group) $best = $grp | Sort-Object Confidence -Descending | Select-Object -First 1 $ci = $best.Core $count = @($history | Where-Object { $_ -eq [int]$ci.PID }).Count $capId = 'capture-' + [string]$ci.PID $capCtxKey = [string]$tunNode + '|' + [string]$ci.PID if (-not $tunnelCaptureContexts.ContainsKey($capCtxKey)) { $tunnelCaptureContexts[$capCtxKey] = New-Object System.Collections.ArrayList } foreach ($cap in $grp) { $ck = [string]$cap.Rule + '|' + [string]$cap.Evidence + '|' + [string]$cap.Confidence if (@($tunnelCaptureContexts[$capCtxKey] | Where-Object { [string]$_.Key -eq $ck }).Count -eq 0) { [void]$tunnelCaptureContexts[$capCtxKey].Add([PSCustomObject]@{ Key = $ck; Rule = [string]$cap.Rule; Evidence = [string]$cap.Evidence; Confidence = [double]$cap.Confidence }) } } $allCaps = @($tunnelCaptureContexts[$capCtxKey]); $capDetails = @(); $cn = 0 foreach ($cap0 in @($allCaps | Select-Object -First 12)) { $cn++ $rv = if ($cap0.Rule) { [string]$cap0.Rule } else { 'runtime capture' } $capDetails += GItem ('flow-' + [string]$cn) ('flow ' + [string]$cn) $rv (Confidence-Status ([double]$cap0.Confidence)) ([string]$cap0.Evidence) 'prop' } if ($allCaps.Count -gt 12) { $capDetails += GItem 'more' 'more' ([string]($allCaps.Count - 12) + ' additional contexts') '' 'visual detail capped' 'prop' } $bestAllCap = $allCaps | Sort-Object Confidence -Descending | Select-Object -First 1 $capDetail = GDetail ([string]$ci.Name) ('TUN capture · PID ' + [string]$ci.PID + ' · merged by entity') 'flow' (Confidence-Status ([double]$bestAllCap.Confidence)) $capDetails Set-GItemOnNode $tunNode $capId (GItem $capId 'process' (([string]$ci.Name) + $(if ($allCaps.Count -gt 1) { ' · ' + [string]$allCaps.Count + ' flows' } else { '' })) (Confidence-Status ([double]$bestAllCap.Confidence)) (Confidence-Meta ([double]$bestAllCap.Confidence) ([string]$bestAllCap.Evidence)) 'out' $false $capDetail) $pn = '' foreach ($cap in $grp) { $pn = New-ProcessPass ([int]$ci.PID) '' ([string]$cap.Rule) ([double]$cap.Confidence) ([string]$cap.Evidence) ($depth + 1) } if (-not $pn) { continue } Add-GEdge $tunNode $capId $pn 'main' ([double]$best.Confidence) ([string]$best.Evidence) $false if ($count -lt $maxRepeatPerPid) { foreach ($cap in $grp) { Enqueue-ProcessPass ([int]$ci.PID) $pn ($depth + 1) (@($history) + [int]$ci.PID) ([string]$cap.Rule) '' ([double]$cap.Confidence) ([string]$cap.Evidence) } } else { Add-GItemToNode $pn (GItem 'cyclecap' 'trace' 'repeat limit reached' 'WARN' 'same process already observed repeatedly in this path' 'prop') } } } # Default application route. If it is a TUN, TUN -> core ownership is confidence- # weighted rather than asserted. If it is physical, use that interface's own gateway. if ($eg4) { if ($egIsTun) { $tunConf = if ($egAssessment) { [double]$egAssessment.Confidence } else { 0.70 } $tunEv = 'Find-NetRoute default egress + adapter assessment' + $(if ($egAssessment -and $egAssessment.Signals.Count -gt 0) { ' · ' + ((@($egAssessment.Signals | Select-Object -First 3)) -join '; ') } else { '' }) $tun0 = New-TunnelPass ([int]$eg4.InterfaceIndex) 'OS selected default route' $tunConf $tunEv 1 Add-GItemToNode 'app' (GItem 'default' 'default' ([string]$eg4.InterfaceAlias) 'OK' ('selected route · adapter role ' + $(if ($egAssessment) { [string]$egAssessment.Role } else { 'tunnel-like' })) 'out') Add-GEdge 'app' 'default' $tun0 'main' 1.0 'OS selected default route (route selection confirmed; adapter role separately scored)' $false Add-TunnelCaptureFrom $tun0 ([int]$eg4.InterfaceIndex) $null 1 @() } elseif (Test-IsPhysicalAdapter $egAd) { $dr0 = $selRoute4 $nh0 = $nh4 $ph0 = Ensure-PhysicalPath ([int]$eg4.InterfaceIndex) $nh0 $true @('223.5.5.5') if ($ph0) { Add-GItemToNode 'app' (GItem 'default' 'default' ([string]$eg4.InterfaceAlias) 'OK' 'selected route · assessed carrier' 'out') Add-GEdge 'app' 'default' $ph0.Nic 'main' 1.0 'OS selected default route' $false $usedPhysicalIf[[string]$eg4.InterfaceIndex] = $true; $usedPhysicalPath[([string]$eg4.InterfaceIndex + '|IPv4|' + $nh0)] = $true } } else { $aaU = if ($egAd) { Get-AdapterAssessment $egAd } else { $null } Add-GItemToNode 'app' (GItem 'default' 'default?' ([string]$eg4.InterfaceAlias) 'WARN' ('selected OS route · adapter role ' + $(if ($aaU) { [string]$aaU.Role } else { 'unknown' }) + '; not labelled direct/physical') 'prop') } } # IPv6 is an independent route family. If it uses a different interface, expose a # separate root branch; if it shares the IPv4 carrier/TUN, keep one interface node # and add the IPv6 gateway/ISP leg there instead of duplicating the adapter. if ($eg6) { $eg6Idx = [int]$eg6.InterfaceIndex $eg6Ad = Get-NetAdapter -InterfaceIndex $eg6Idx -ErrorAction SilentlyContinue $sameAsV4 = [bool]($eg4 -and [int]$eg4.InterfaceIndex -eq $eg6Idx) $eg6IsTun = [bool]($eg6Ad -and (Test-IsTunnelAdapter $eg6Ad)) $dr6 = $selRoute6 $nh6Now = $nh6 if ($sameAsV4) { Add-GItemToNode 'app' (GItem 'default-v6' 'IPv6 default' ([string]$eg6.InterfaceAlias) 'OK' 'same interface as IPv4 selected route' 'prop') if (-not $eg6IsTun -and (Test-IsPhysicalAdapter $eg6Ad)) { [void](Ensure-PhysicalPath $eg6Idx $nh6Now ([bool]$r6.PingSucceeded) @('2400:3200::1') 'IPv6') $usedPhysicalIf[[string]$eg6Idx] = $true; $usedPhysicalPath[([string]$eg6Idx + '|IPv6|' + $nh6Now)] = $true } } else { if ($eg6IsTun) { $aa6 = if ($eg6Ad) { Get-AdapterAssessment $eg6Ad } else { $null } $tun6 = New-TunnelPass $eg6Idx 'OS selected IPv6 default route' $(if ($aa6) { [double]$aa6.Confidence } else { 0.70 }) 'Find-NetRoute IPv6 default egress + adapter assessment' 1 Add-GItemToNode 'app' (GItem 'default-v6' 'IPv6 default' ([string]$eg6.InterfaceAlias) 'OK' 'selected IPv6 route' 'out') Add-GEdge 'app' 'default-v6' $tun6 'main' 1.0 'OS selected IPv6 default route' $false Add-TunnelCaptureFrom $tun6 $eg6Idx $null 1 @() } elseif ($eg6Ad -and (Test-IsPhysicalAdapter $eg6Ad)) { $ph6 = Ensure-PhysicalPath $eg6Idx $nh6Now ([bool]$r6.PingSucceeded) @('2400:3200::1') 'IPv6' if ($ph6) { Add-GItemToNode 'app' (GItem 'default-v6' 'IPv6 default' ([string]$eg6.InterfaceAlias) 'OK' 'selected IPv6 route' 'out') Add-GEdge 'app' 'default-v6' $ph6.Nic 'main' 1.0 'OS selected IPv6 default route' $false $usedPhysicalIf[[string]$eg6Idx] = $true; $usedPhysicalPath[([string]$eg6Idx + '|IPv6|' + $nh6Now)] = $true } } else { Add-GItemToNode 'app' (GItem 'default-v6' 'IPv6 default' ([string]$eg6.InterfaceAlias) 'WARN' 'selected IPv6 route · interface type unclassified' 'prop') } } } # Configured proxy policies are application-policy branches, not replacements for the # OS route. Preserve every endpoint instead of collapsing WinINET to the first one. # WinHTTP and environment proxies are also shown because different application stacks # honor different policy sources. $policyProxyEndpoints = New-Object System.Collections.ArrayList if ($sysProxyOn -and $p.ProxyServer) { foreach ($ep in @(Get-ConfiguredProxyEndpoints ([string]$p.ProxyServer) 'WinINET')) { [void]$policyProxyEndpoints.Add($ep) } } $winhttpRawGraph = (netsh winhttp show proxy 2>$null) -join "`n" foreach ($ep in @(Get-ConfiguredProxyEndpoints $winhttpRawGraph 'WinHTTP')) { [void]$policyProxyEndpoints.Add($ep) } foreach ($envName in @('HTTP_PROXY','HTTPS_PROXY','ALL_PROXY','FTP_PROXY','SOCKS_PROXY')) { $ev = [Environment]::GetEnvironmentVariable($envName, 'Process') if (-not $ev) { $ev = [Environment]::GetEnvironmentVariable($envName, 'User') } if (-not $ev) { continue } foreach ($ep in @(Get-ConfiguredProxyEndpoints $ev ('ENV:' + $envName))) { [void]$policyProxyEndpoints.Add($ep) } } # Multiple policy sources often point to the same local endpoint (for example # WinINET + HTTP_PROXY + HTTPS_PROXY). The graph should show one logical proxy # entry, not three duplicate copies of the same process. Keep the detailed tables # source-complete, but collapse identical graph endpoints here. $policyEndpointGroups = @{} foreach ($ep0 in @($policyProxyEndpoints)) { $hk = [string]$ep0.Host # Collapse only syntactically equivalent endpoints. Different local addresses on # the same port can legally belong to different processes (for example IPv4 vs # IPv6-only binds), so do not normalize every loopback/wildcard to one '@local'. $hostKey = $hk.ToLowerInvariant() $gk = $hostKey + '|' + [string]$ep0.Port if (-not $policyEndpointGroups.ContainsKey($gk)) { $policyEndpointGroups[$gk] = [PSCustomObject]@{ Host = [string]$ep0.Host; Port = [int]$ep0.Port; Endpoint = [string]$ep0.Endpoint Policies = (New-Object System.Collections.ArrayList); Schemes = (New-Object System.Collections.ArrayList) } } $gg = $policyEndpointGroups[$gk] if (-not $gg.Policies.Contains([string]$ep0.Policy)) { [void]$gg.Policies.Add([string]$ep0.Policy) } if ($ep0.Scheme -and -not $gg.Schemes.Contains(([string]$ep0.Scheme).ToUpperInvariant())) { [void]$gg.Schemes.Add(([string]$ep0.Scheme).ToUpperInvariant()) } } $resolvedPolicyProxyPids = @{} $resolvedPolicyProxyEndpoints = @{} $policyNo = 0 foreach ($ep in @($policyEndpointGroups.Values | Sort-Object Endpoint)) { $policyNo++ $itemId = 'policy-' + [string]$policyNo $policyText = (@($ep.Policies) -join ' + ') $schemeText = if ($ep.Schemes.Count -gt 0) { (@($ep.Schemes) -join '/') + ' ' } else { '' } $owner = Resolve-ProxyEndpointOwner $ep if ($owner -and [int]$owner.OwningProcess -gt 0) { # Do not use `$pid`: `$PID` is an automatic read-only PowerShell variable. $ownerPid = [int]$owner.OwningProcess $pn = New-ProcessPass $ownerPid ([string]$ep.Endpoint) '' 1.0 ($policyText + ' configured endpoint + local listener owner') 1 if ($pn) { $resolvedPolicyProxyPids[[string]$ownerPid] = $true $resolvedPolicyProxyEndpoints[[string]$ep.Endpoint] = $true Add-GItemToNode 'app' (GItem $itemId 'proxy' ($schemeText + [string]$ep.Endpoint) 'OK' ($policyText + ' · configured local endpoint; listener owner resolved') 'out') Add-GItemToNode $pn (GItem 'policy' 'policy' $policyText 'OK' 'application proxy policy entry' 'prop') Add-GEdge 'app' $itemId $pn 'policy' 1.0 ($policyText + ' configured endpoint + listener owner') $false Enqueue-ProcessPass $ownerPid $pn 1 @($ownerPid) '' ([string]$ep.Endpoint) 1.0 ($policyText + ' configured endpoint + local listener owner') } } elseif (Test-LoopbackAddr ([string]$ep.Host)) { $deadId = 'cfgproxy-dead-' + (Safe-GraphId ([string]$ep.Endpoint)) if (-not $ndNodeMap.ContainsKey($deadId)) { $deadItems = @((GItem 'address' 'addr' ([string]$ep.Endpoint) 'FAIL' 'configured local endpoint has no TCP listener' 'addr')) [void](Add-GNode $deadId 'Configured Proxy' ($policyText + ' · local endpoint unavailable') 'core' 'FAIL' $false $deadItems) } Add-GItemToNode 'app' (GItem $itemId 'proxy' ($schemeText + [string]$ep.Endpoint) 'FAIL' ($policyText + ' · configured but unavailable') 'out') Add-GEdge 'app' $itemId $deadId 'policy' 1.0 ($policyText + ' configuration') $true } else { # Remote configured proxies are real policy objects but not necessarily active. # Do not probe or invent their downstream path. $remoteId = 'cfgproxy-' + (Safe-GraphId ([string]$ep.Endpoint)) if (-not $ndNodeMap.ContainsKey($remoteId)) { $ri = @( (GItem 'address' 'addr' ([string]$ep.Endpoint) 'WARN' 'configured remote endpoint · not actively probed' 'addr'), (GItem 'policy' 'policy' $policyText '' '' 'prop') ) [void](Add-GNode $remoteId 'Configured Proxy' 'remote policy endpoint · application dependent' 'core' 'WARN' $false $ri) } Add-GItemToNode 'app' (GItem $itemId 'proxy?' ($schemeText + [string]$ep.Endpoint) 'WARN' ($policyText + ' · configuration only; runtime use not observed') 'out') Add-GEdge 'app' $itemId $remoteId 'policy' 0.65 ($policyText + ' configuration only') $false } } $hasResolvedPolicyProxy = [bool]($resolvedPolicyProxyPids.Count -gt 0) if ($hasResolvedPolicyProxy) { # Once an application proxy endpoint is positively resolved to a local process, # the application's policy path is the visually dominant semantic chain. The OS # default route still matters for bypassed/direct traffic and for the proxy core's # own transport, but showing it as a second solid-green first hop makes the graph # look as if the proxy were optional noise. Keep the route, relabel it as such, # and render only this root-level branch as ALT; downstream process -> adapter # socket evidence remains MAIN/green. foreach ($ee0 in @($ndEdges | Where-Object { [string]$_['from'] -eq 'app' -and [string]$_['fromItem'] -eq 'default' })) { $ee0['kind'] = 'alt' $ee0['evidence'] = (([string]$ee0['evidence'] + ' · direct/bypass OS route; explicit local proxy policy resolved') -replace '^[ ·]+|[ ·]+$','') } if ($eg4 -and $egAd -and (Test-IsPhysicalAdapter $egAd)) { Set-GItemOnNode 'app' 'default' (GItem 'default' 'OS route' ([string]$eg4.InterfaceAlias) 'OK' 'direct/bypass branch · also carrier transport for local proxy-core outbound sockets' 'out') } elseif ($eg4 -and $egIsTun) { Set-GItemOnNode 'app' 'default' (GItem 'default' 'OS/TUN route' ([string]$eg4.InterfaceAlias) 'OK' 'direct/non-policy branch · local proxy process may itself egress through this tunnel' 'out') } } # PAC/WPAD can choose a proxy per URL and therefore cannot be safely projected to one # endpoint without observing a specific application's request. Keep them as inventory. if ($p.AutoConfigURL) { Add-GItemToNode 'app' (GItem 'pac' 'PAC' ([string]$p.AutoConfigURL) 'WARN' 'dynamic per-URL proxy policy; not expanded' 'prop') } if ($p.AutoDetect) { Add-GItemToNode 'app' (GItem 'wpad' 'WPAD' 'enabled' 'WARN' 'dynamic auto-discovery; not expanded' 'prop') } if ($p.ProxyOverride) { Add-GItemToNode 'app' (GItem 'proxy-bypass' 'WinINET bypass' ([string]$p.ProxyOverride) '' 'policy exception list' 'prop') } $noProxy = [Environment]::GetEnvironmentVariable('NO_PROXY', 'Process'); if (-not $noProxy) { $noProxy = [Environment]::GetEnvironmentVariable('NO_PROXY', 'User') } if ($noProxy) { Add-GItemToNode 'app' (GItem 'no-proxy' 'NO_PROXY' ([string]$noProxy) '' 'environment bypass list' 'prop') } # Process-state expansion: preserve every live local relay sibling and every distinct # routed interface. No Select-Object -First 1 is used to collapse the topology. $qIndex = 0 while ($qIndex -lt $queue.Count -and $ndNodes.Count -lt $maxNodes) { $state = $queue[$qIndex]; $qIndex++ $pf = Get-ProcessFact ([int]$state.ProcessId) if (-not $pf -or -not $ndNodeMap.ContainsKey([string]$state.NodeId)) { continue } $entryRuleHint = [string]$state.EntryRule $entryEvidenceHint = [string]$state.EntryEvidence $entryIsConfiguredProxy = [bool]($entryEvidenceHint -match '(?i)configured endpoint.*listener owner|configured endpoint \+ local listener owner') $localsAll = @(Get-LocalProcessRelations ([int]$state.ProcessId) $entryRuleHint) $routesAll = @(Get-ProcessRouteRelations ([int]$state.ProcessId)) # When runtime rule evidence identifies a named local outbound, scope this pass to # that relation. DIRECT explicitly excludes local-proxy relations. Without such # correlation, keep evidence conservative and consume each process relation once. $ruleMatchedLocal = @() if ($entryRuleHint) { $ruleMatchedLocal = @($localsAll | Where-Object { $_.ProxyName -and $entryRuleHint -match [regex]::Escape([string]$_.ProxyName) }) } if ($ruleMatchedLocal.Count -gt 0) { $localsCandidate = $ruleMatchedLocal # A named local outbound terminates this logical core pass at the connector; # unrelated core-owned remote sockets belong to other concurrent flows/passes. $routesCandidate = @() } elseif ($entryRuleHint -match '(?i)\bDIRECT\b') { $localsCandidate = @() $routesCandidate = $routesAll } else { $localsCandidate = $localsAll $routesCandidate = $routesAll } $locals = @() foreach ($lr0 in $localsCandidate) { $lk = [string]$state.ProcessId + '|local|' + [string]$lr0.TargetPID + '|' + [string]$lr0.Endpoint # Only de-duplicate process-wide socket evidence when this logical pass has no # runtime rule attribution. A rule-attributed pass is a distinct flow and may # legitimately reuse the same connector/route as another pass. if (-not $entryRuleHint -and $usedLocalRelation.ContainsKey($lk)) { continue } if (-not $entryRuleHint) { $usedLocalRelation[$lk] = $true } $locals += $lr0 } $routes = @() foreach ($rr0 in $routesCandidate) { $rk = [string]$state.ProcessId + '|route|' + [string]$rr0.InterfaceIndex + '|' + [string]$rr0.AddressFamily + '|' + [string]$rr0.NextHop if (-not $entryRuleHint -and $usedRouteRelation.ContainsKey($rk)) { continue } if (-not $entryRuleHint) { $usedRouteRelation[$rk] = $true } $routes += $rr0 } $outIndex = 0 $stateCoreInfo = if ($coreInfoByPid.ContainsKey([string]$state.ProcessId)) { $coreInfoByPid[[string]$state.ProcessId] } else { $null } # Entity-level local relay projection: many endpoints from one source process to the # same target PID become one row/edge. Endpoint/rule detail remains expandable. foreach ($lg in @($locals | Group-Object TargetPID)) { if ($ndNodes.Count -ge $maxNodes) { break } $grp = @($lg.Group); if ($grp.Count -eq 0) { continue } $targetPid = [int]$grp[0].TargetPID $tf = Get-ProcessFact $targetPid; if (-not $tf) { continue } $adjusted = @(); $li = @(); $ln = 0 foreach ($lr in $grp) { $lrConf = [double]$lr.Confidence; $lrEvidence = [string]$lr.Evidence if ($stateCoreInfo -and -not $entryRuleHint -and -not $lr.Rule) { $lrConf = [math]::Min($lrConf, 0.72) $lrEvidence += ' · process-wide relation; logical flow not correlated' } $adjusted += [PSCustomObject]@{ Relation = $lr; Confidence = $lrConf; Evidence = $lrEvidence } $ln++ $lm = Confidence-Meta $lrConf $lrEvidence if ($lr.Rule) { $lm += ' · ' + [string]$lr.Rule } $lk = if ($lr.ProxyName) { [string]$lr.ProxyName } elseif ($lr.ProxyType) { ([string]$lr.ProxyType).ToUpperInvariant() } else { 'local' } $li += GItem ('endpoint-' + [string]$ln) $lk ([string]$lr.Endpoint) (Confidence-Status $lrConf) $lm 'prop' } $best = $adjusted | Sort-Object Confidence -Descending | Select-Object -First 1 $names = @($grp | ForEach-Object ProxyName | Where-Object { $_ } | Select-Object -Unique) $types = @($grp | ForEach-Object ProxyType | Where-Object { $_ } | Select-Object -Unique) $keyText = if ($names.Count -eq 1) { [string]$names[0] } elseif ($types.Count -eq 1) { ([string]$types[0]).ToUpperInvariant() } else { 'local peer' } $valueText = if ($grp.Count -eq 1) { ([string]$tf.Name + ' · ' + [string]$grp[0].Endpoint) } else { ([string]$tf.Name + ' · ' + [string]$grp.Count + ' endpoints') } $itemId = 'local-pid-' + [string]$targetPid $ctxKey = [string]$state.NodeId + '|' + [string]$targetPid if (-not $localPeerContexts.ContainsKey($ctxKey)) { $localPeerContexts[$ctxKey] = New-Object System.Collections.ArrayList } foreach ($aa0 in $adjusted) { $lr0 = $aa0.Relation $ck0 = [string]$lr0.Endpoint + '|' + [string]$lr0.Rule + '|' + [string]$aa0.Evidence if (@($localPeerContexts[$ctxKey] | Where-Object { [string]$_.Key -eq $ck0 }).Count -eq 0) { [void]$localPeerContexts[$ctxKey].Add([PSCustomObject]@{ Key = $ck0; Relation = $lr0; Confidence = [double]$aa0.Confidence; Evidence = [string]$aa0.Evidence }) } } $allCtx = @($localPeerContexts[$ctxKey]); $liAll = @(); $cx = 0 foreach ($cc0 in @($allCtx | Select-Object -First 20)) { $cx++; $lr0 = $cc0.Relation $lm0 = Confidence-Meta ([double]$cc0.Confidence) ([string]$cc0.Evidence) if ($lr0.Rule) { $lm0 += ' · ' + [string]$lr0.Rule } $lk0 = if ($lr0.ProxyName) { [string]$lr0.ProxyName } elseif ($lr0.ProxyType) { ([string]$lr0.ProxyType).ToUpperInvariant() } else { 'local' } $liAll += GItem ('endpoint-' + [string]$cx) $lk0 ([string]$lr0.Endpoint) (Confidence-Status ([double]$cc0.Confidence)) $lm0 'prop' } if ($allCtx.Count -gt 20) { $liAll += GItem 'more' 'more' ([string]($allCtx.Count - 20) + ' additional relation contexts') '' 'visual detail capped' 'prop' } $bestAll = $allCtx | Sort-Object Confidence -Descending | Select-Object -First 1 $valueText = if ($allCtx.Count -eq 1) { ([string]$tf.Name + ' · ' + [string]$allCtx[0].Relation.Endpoint) } else { ([string]$tf.Name + ' · ' + [string]$allCtx.Count + ' contexts') } $detail = GDetail ([string]$tf.Name) ('local process relation · PID ' + [string]$targetPid + ' · merged by entity') 'flow' (Confidence-Status ([double]$bestAll.Confidence)) $liAll Set-GItemOnNode $state.NodeId $itemId (GItem $itemId $keyText $valueText (Confidence-Status ([double]$bestAll.Confidence)) ('merged by target process · ' + (Confidence-Meta ([double]$bestAll.Confidence) ([string]$bestAll.Evidence))) 'out' $false $detail) $child = '' foreach ($aa in $adjusted) { $lr = $aa.Relation; $lrConf = [double]$aa.Confidence; $lrEvidence = [string]$aa.Evidence $child = New-ProcessPass $targetPid ([string]$lr.Endpoint) ([string]$lr.Rule) $lrConf $lrEvidence ($state.Depth + 1) if ($child) { $cnt = @($state.History | Where-Object { $_ -eq $targetPid }).Count if ($cnt -lt $maxRepeatPerPid) { Enqueue-ProcessPass $targetPid $child ($state.Depth + 1) (@($state.History) + $targetPid) ([string]$lr.Rule) ([string]$lr.Endpoint) $lrConf $lrEvidence } } } if ($child) { Add-GEdge $state.NodeId $itemId $child 'main' ([double]$best.Confidence) ([string]$best.Evidence) $false } } foreach ($rr in $routes) { if ($ndNodes.Count -ge $maxNodes) { break } $outIndex++; $itemId = 'route-' + [string]$rr.InterfaceIndex + '-' + ([string]$rr.AddressFamily).ToLowerInvariant() + '-' + (Safe-GraphId ([string]$rr.NextHop)) $samples = @($rr.Remotes) $routeConf = 1.0 $routeEvidence = [string]$rr.Evidence if ($stateCoreInfo) { if ($entryRuleHint) { $routeConf = 0.84; $routeEvidence += ' · runtime rule present; socket-to-flow pairing inferred' } elseif ($entryIsConfiguredProxy) { # The application request -> proxy listener relation is explicit. A live # outbound socket owned by that proxy process therefore strongly proves # the process's carrier egress, even though Windows cannot correlate one # particular remote socket back to one particular application request. $routeConf = 0.92; $routeEvidence += ' · configured local proxy owner + live proxy-process outbound socket' } else { $routeConf = 0.58; $routeEvidence += ' · process-wide socket; logical pass not correlated' } } if ($rr.IsTunnel) { $ad = Get-NetAdapter -InterfaceIndex $rr.InterfaceIndex -ErrorAction SilentlyContinue Add-GItemToNode $state.NodeId (GItem $itemId 'TUN' $(if ($ad) { [string]$ad.Name } else { 'ifIndex ' + [string]$rr.InterfaceIndex }) (Confidence-Status $routeConf) (Confidence-Meta $routeConf $routeEvidence) 'out') $tn = New-TunnelPass ([int]$rr.InterfaceIndex) $(if ($samples.Count -gt 0) { [string]$samples[0] } else { 'process socket' }) $routeConf $routeEvidence ($state.Depth + 1) Add-GEdge $state.NodeId $itemId $tn 'main' $routeConf $routeEvidence $false Add-TunnelCaptureFrom $tn ([int]$rr.InterfaceIndex) $pf ($state.Depth + 1) @($state.History) } elseif ($rr.IsPhysical) { $ph = Ensure-PhysicalPath ([int]$rr.InterfaceIndex) ([string]$rr.NextHop) $true $samples ([string]$rr.AddressFamily) if ($ph) { Add-GItemToNode $state.NodeId (GItem $itemId 'carrier' ([string]$rr.InterfaceAlias) (Confidence-Status $routeConf) (Confidence-Meta $routeConf $routeEvidence) 'out') Add-GEdge $state.NodeId $itemId $ph.Nic 'main' $routeConf $routeEvidence $false $usedPhysicalIf[[string]$rr.InterfaceIndex] = $true; $usedPhysicalPath[([string]$rr.InterfaceIndex + '|' + [string]$rr.AddressFamily + '|' + [string]$rr.NextHop)] = $true } } else { Add-GItemToNode $state.NodeId (GItem $itemId 'route?' ([string]$rr.InterfaceAlias) 'WARN' ('adapter role ' + [string]$rr.AdapterRole + ' · ifIndex ' + [string]$rr.InterfaceIndex + ' · not labelled direct/physical') 'out') } } # No active egress snapshot: show a conservative possibility rather than silently # truncating the chain. For a proxy core, prefer a physical route candidate instead # of asserting that the core re-enters the system's selected TUN. if ($locals.Count -eq 0 -and $routes.Count -eq 0) { $ci = if ($coreInfoByPid.ContainsKey([string]$state.ProcessId)) { $coreInfoByPid[[string]$state.ProcessId] } else { $null } if ($ci -and $allPhysicalRouteCandidates.Count -gt 0) { # With no live socket there is no evidence for *which* carrier an idle core # would choose. Preserve all bounded candidates instead of inventing one. $idleNo = 0 foreach ($pc in @($allPhysicalRouteCandidates | Sort-Object EffectiveMetric, AddressFamily, IfIndex | Select-Object -First 6)) { $idleNo++ $ph = Ensure-PhysicalPath ([int]$pc.IfIndex) ([string]$pc.Gateway) $false @() ([string]$pc.AddressFamily) if (-not $ph) { continue } $iidIdle = 'idle-route-' + [string]$idleNo Add-GItemToNode $state.NodeId (GItem $iidIdle 'egress?' (([string]$pc.AddressFamily) + ' · ' + [string]$pc.Name) '' ('possible · metric ' + [string]$pc.EffectiveMetric + ' · no live outbound socket') 'out') Add-GEdge $state.NodeId $iidIdle $ph.Nic 'possible' 0.30 'idle core: viable route candidate only' $false } } elseif ($eg4) { if ($egIsTun) { $apiCaps = @(Get-TunnelCaptureCandidates ([int]$eg4.InterfaceIndex) $pf | Where-Object { $_.Confidence -ge 0.80 }) if ($apiCaps.Count -gt 0) { Add-GItemToNode $state.NodeId (GItem 'idle-route' 'TUN' ([string]$eg4.InterfaceAlias) 'OK' 'runtime API captured process' 'out') $tn = New-TunnelPass ([int]$eg4.InterfaceIndex) 'API-observed process capture' 0.95 'runtime API captured process' ($state.Depth + 1) Add-GEdge $state.NodeId 'idle-route' $tn 'main' 0.95 'runtime API captured process' $false Add-TunnelCaptureFrom $tn ([int]$eg4.InterfaceIndex) $pf ($state.Depth + 1) @($state.History) } else { Add-GItemToNode $state.NodeId (GItem 'idle-route' 'route?' ([string]$eg4.InterfaceAlias) '' 'possible · OS default only' 'out') $tn = New-TunnelPass ([int]$eg4.InterfaceIndex) 'no active socket' 0.30 'system default route only' ($state.Depth + 1) Add-GEdge $state.NodeId 'idle-route' $tn 'possible' 0.30 'system default route only' $false # Do not recurse from default-route-only evidence: it would invent a # capture loop. Runtime API/process attribution above is sufficient # to continue when the short-lived socket itself was missed. } } else { $dr = Get-NetRoute -DestinationPrefix '0.0.0.0/0' -InterfaceIndex $eg4.InterfaceIndex -ErrorAction SilentlyContinue | Sort-Object RouteMetric | Select-Object -First 1 $nh = if ($dr) { [string]$dr.NextHop } else { '' } $ph = Ensure-PhysicalPath ([int]$eg4.InterfaceIndex) $nh $false @() if ($ph) { Add-GItemToNode $state.NodeId (GItem 'idle-route' 'route?' ([string]$eg4.InterfaceAlias) '' 'possible · OS default only' 'out') Add-GEdge $state.NodeId 'idle-route' $ph.Nic 'possible' 0.30 'system default route only' $false } } } } } # Every UP physical default-route candidate is visible. Candidates not already proven # by a process socket get a dashed route branch from Applications; they are never # mislabeled as DOWN or placed inside another gateway card. $altNo = 0 foreach ($pc in @($physCandidates | Sort-Object EffectiveMetric, IfIndex)) { $ifKey = [string]$pc.IfIndex $pathKey = [string]$pc.IfIndex + '|IPv4|' + [string]$pc.Gateway if ($usedPhysicalPath.ContainsKey($pathKey)) { continue } $ph = Ensure-PhysicalPath ([int]$pc.IfIndex) ([string]$pc.Gateway) $false @() if (-not $ph) { continue } $altNo++; $iid = 'alt-' + [string]$pc.IfIndex + '-' + (Safe-GraphId ([string]$pc.Gateway)) Add-GItemToNode 'app' (GItem $iid 'route(alt)' ([string]$pc.Name) 'WARN' ('metric ' + [string]$pc.EffectiveMetric) 'out') Add-GEdge 'app' $iid $ph.Nic 'alt' 0.45 ('UP default-route candidate · effective metric ' + [string]$pc.EffectiveMetric) $false } # IPv6 route candidates are independent of IPv4 selection. Show every UP physical # default route that is not already the active IPv6 probe path. $alt6No = 0 foreach ($pc6 in @($physCandidatesV6 | Sort-Object EffectiveMetric, IfIndex)) { $pathKey6 = [string]$pc6.IfIndex + '|IPv6|' + [string]$pc6.Gateway if ($usedPhysicalPath.ContainsKey($pathKey6)) { continue } $isActive6 = [bool]($eg6 -and [int]$eg6.InterfaceIndex -eq [int]$pc6.IfIndex -and ((-not $nh6) -or [string]$pc6.Gateway -eq [string]$nh6)) $ph6 = Ensure-PhysicalPath ([int]$pc6.IfIndex) ([string]$pc6.Gateway) $isActive6 @() 'IPv6' if (-not $ph6) { continue } $alt6No++; $iid6 = 'route6-' + [string]$pc6.IfIndex + '-' + (Safe-GraphId ([string]$pc6.Gateway)) $st6 = if ($isActive6) { 'OK' } else { 'WARN' } $lab6 = if ($isActive6) { 'route6' } else { 'route6(alt)' } Add-GItemToNode 'app' (GItem $iid6 $lab6 ([string]$pc6.Name) $st6 ('metric ' + [string]$pc6.EffectiveMetric) 'out') Add-GEdge 'app' $iid6 $ph6.Nic $(if ($isActive6) { 'main' } else { 'alt' }) $(if ($isActive6) { 1.0 } else { 0.45 }) $(if ($isActive6) { 'selected IPv6 default route' } else { 'UP IPv6 default-route candidate' }) $false } # ---------- Diagnostic interception sidecar ---------- # Detection evidence is *not a hop*. If an explicit configured local proxy already # explains the proxy-like listeners/services, do not create a competing first-hop node. # Only keep the sidecar when there is independent evidence for transparent capture. $strongTransparentEvidence = $false if ($routeSourceProbe.Mismatch) { $strongTransparentEvidence = $true } if ($egAssessment -and ($egAssessment.Role -eq 'SuspectedTunnel' -or $egAssessment.FakeIP -or $egAssessment.FakeDNS)) { $strongTransparentEvidence = $true } $unclaimedProtocolProxyListeners = @($protocolProxyListeners | Where-Object { -not $resolvedPolicyProxyPids.ContainsKey([string]$_.PID) -and -not $projectedProcessPids.ContainsKey([string]$_.PID) }) $unclaimedProtocolProxyPids = @($unclaimedProtocolProxyListeners | ForEach-Object PID | Sort-Object -Unique) if ($unclaimedProtocolProxyPids.Count -gt 0) { $strongTransparentEvidence = $true } $showInterceptSidecar = [bool]( $interceptLevel -ne 'NONE' -and -not ($egAssessment -and $egAssessment.Role -eq 'Tunnel') -and ((-not $hasResolvedPolicyProxy) -or $strongTransparentEvidence) ) if ($showInterceptSidecar) { Add-GItemToNode 'app' (GItem 'intercept-evidence' 'evidence' ($interceptLevel.ToLowerInvariant()) 'WARN' ('diagnostic only · score ' + [string]$interceptScore + ' · not a traffic hop') 'out') $ii = @((GItem 'score' 'assessment' $interceptLevel 'WARN' ('score ' + [string]$interceptScore) 'prop')) $sn = 0 foreach ($sg in @($interceptSignals | Select-Object -First 6)) { $sn++; $ii += GItem ('signal-' + [string]$sn) 'signal' ([string]$sg) 'WARN' '' 'prop' } $evProcesses = if ($hasResolvedPolicyProxy) { @($proxyCandidateProcessRows | Where-Object { $unclaimedProtocolProxyPids -contains [int]$_.PID }) } else { @($proxyCandidateProcesses | Sort-Object MaxScore -Descending) } foreach ($ppx in @($evProcesses | Select-Object -First 3)) { $ers = @($listenerEvidenceRows | Where-Object { [int]$_.PID -eq [int]$ppx.PID -and $_.Candidate } | Sort-Object ProxyScore -Descending) $edi = @(); $en = 0 foreach ($er in @($ers | Select-Object -First 12)) { $en++; $edi += GItem ('ep-' + [string]$en) 'endpoint' ([string]$er.Local) $(if ($er.Signature -match 'SOCKS5|HTTP CONNECT') { 'OK' } else { 'WARN' }) ([string]$er.Signature) 'prop' } if ($ers.Count -gt 12) { $edi += GItem 'more' 'more' ([string]($ers.Count - 12) + ' additional endpoints') '' 'collapsed by process' 'prop' } $ed = GDetail ([string]$ppx.Process) ('proxy candidate · PID ' + [string]$ppx.PID) 'flow' 'WARN' $edi $ii += GItem ('candidate-' + [string]$ppx.PID) 'process' (([string]$ppx.Process) + ' · ' + [string]$ppx.CandidateEndpoints + ' endpoints') 'WARN' ([string]$ppx.Evidence) 'prop' $false $ed } $evn = Add-GNode 'intercept-evidence' 'Interception evidence' 'diagnostic sidecar · NOT a traffic hop' 'core' 'WARN' $false $ii if ($evn) { $evn['layoutLane'] = 'evidence' } Add-GEdge 'app' 'intercept-evidence' 'intercept-evidence' 'evidence' $interceptConfidence 'host-level interception evidence; diagnostic relation only' $false } # Reorder the Applications rows so actual traffic entries remain visually dominant. # TUN/default and explicit proxy flows come first; inventory and evidence stay below. if ($ndNodeMap.ContainsKey('app')) { $appNode = $ndNodeMap['app'] $appNode['items'] = @($appNode['items'] | Sort-Object @{Expression={ $iid = [string]$_.id if ($iid -eq 'default') { if ($egIsTun) { 10 } else { 20 } } elseif ($iid -like 'policy-*') { if ($egIsTun) { 20 } else { 10 } } elseif ($iid -eq 'default-v6') { 25 } elseif ($iid -like 'alt-*' -or $iid -like 'route6-*') { 40 } elseif ($iid -eq 'adapter-inventory' -or $iid -like 'adapter-*') { 60 } elseif ($iid -in @('proxy-bypass','no-proxy','pac')) { 70 } elseif ($iid -eq 'intercept-evidence') { 90 } else { 50 } }}, @{Expression={ [string]$_.id }}) } # Header/UI wording distinguishes unexplained transparent interception from an # explicit, successfully resolved application proxy. Raw evidence remains in the # detail section for auditability. $displayInterceptLevel = if ($hasResolvedPolicyProxy -and -not $strongTransparentEvidence -and -not $showInterceptSidecar) { 'EXPLICIT-PROXY' } else { $interceptLevel } # ---------- BIT campus branch ---------- # Bind the HTTP target to the physical gateway that Windows would use for the target. # If the route first enters a tunnel, attach to the best underlying physical candidate # as a clearly lower-confidence projection; campus DNS remains nested in Portal. $portalStatus = if ($portalHttp) { 'OK' } else { 'FAIL' } $apiStatus = if ($bitApi.Ok) { 'OK' } else { 'FAIL' } $portalProbe = [PSCustomObject]@{ Ok = $portalHttp; Ms = $portalHttpMs } $apiProbe = if ($bitApi.Http -gt 0 -and $bitApiMs -ge 0) { [PSCustomObject]@{ Ok = $bitApi.Ok; Ms = $bitApiMs } } else { Test-TcpProbe '10.0.0.54' 8800 } $bitRt = Find-NetRoute -RemoteIPAddress '10.0.0.55' -ErrorAction SilentlyContinue | Select-Object -First 1 $bitParents = New-Object System.Collections.ArrayList $bitParentSeen = @{} function Add-BitParent([string]$nodeId, [double]$confidence, [string]$evidence) { if (-not $nodeId -or $bitParentSeen.ContainsKey($nodeId)) { return } $bitParentSeen[$nodeId] = $true [void]$bitParents.Add([PSCustomObject]@{ Node = $nodeId; Confidence = $confidence; Evidence = $evidence }) } if ($bitRt) { $bad = Get-NetAdapter -InterfaceIndex $bitRt.InterfaceIndex -ErrorAction SilentlyContinue if ($bad -and (Test-IsPhysicalAdapter $bad)) { $bnh = if ($bitRt.NextHop -and [string]$bitRt.NextHop -notin @('0.0.0.0','::')) { [string]$bitRt.NextHop } else { '' } if (-not $bnh) { $bdr = Get-NetRoute -DestinationPrefix '0.0.0.0/0' -InterfaceIndex $bitRt.InterfaceIndex -ErrorAction SilentlyContinue | Sort-Object RouteMetric | Select-Object -First 1 if ($bdr -and $bdr.NextHop -and [string]$bdr.NextHop -ne '0.0.0.0') { $bnh = [string]$bdr.NextHop } } $bph = Ensure-PhysicalPath ([int]$bitRt.InterfaceIndex) $bnh $false @() 'IPv4' $false if ($bph) { if ($bph.Gateway) { Add-BitParent ([string]$bph.Gateway) 1.0 'Find-NetRoute(10.0.0.55) -> carrier gateway' } elseif ($bph.Nic) { Add-BitParent ([string]$bph.Nic) 0.90 'Find-NetRoute(10.0.0.55) -> gateway-less carrier' } } } elseif ($bad -and (Test-IsTunnelAdapter $bad)) { # The target is first routed into a TUN. Without a target-specific runtime # connection we cannot know which underlying carrier the proxy core will pick. # Keep all viable IPv4 carrier gateways as bounded possibilities. $bi = 0 foreach ($pc in @($physCandidates | Sort-Object EffectiveMetric, IfIndex | Select-Object -First 6)) { $bi++ $bph = Ensure-PhysicalPath ([int]$pc.IfIndex) ([string]$pc.Gateway) $false @() 'IPv4' $false if (-not $bph) { continue } $targetNode = if ($bph.Gateway) { [string]$bph.Gateway } else { [string]$bph.Nic } if (-not $targetNode) { continue } $bc = if ($bi -eq 1) { 0.58 } else { 0.42 } Add-BitParent $targetNode $bc ('target route enters TUN; viable underlying carrier candidate · metric ' + [string]$pc.EffectiveMetric) } } } if ($bitParents.Count -eq 0) { foreach ($gwNode in @($gatewayNodeByKey.Values | Select-Object -Unique | Select-Object -First 6)) { Add-BitParent ([string]$gwNode) 0.30 'no target-specific carrier evidence; existing gateway candidate' } } $bitDnsOrder = @('10.0.32.32', '10.0.32.33') $portalItems = @( (GItem 'address' 'IPv4' '10.0.0.55' $portalStatus (GProbeMeta $portalHttp $portalProbe) 'addr' $true), (GItem 'api' 'BIT API' '10.0.0.54:8800' $apiStatus (GProbeMeta ($apiStatus -eq 'OK') $apiProbe) 'out' $true), (GItem 'http' 'HTTP' 'srun_portal' $portalStatus '' 'prop'), (GItem 'login' 'login' $(if ($loginInfo.Ok) { [string]$loginInfo.Id } else { 'not detected' }) $(if ($loginInfo.Ok) { 'OK' } else { 'WARN' }) '' 'prop') ) for ($i = 0; $i -lt $bitDnsOrder.Count; $i++) { $addr = [string]$bitDnsOrder[$i]; $pr = Get-CachedDns $addr; $st = GStatus $pr.Ok $old = $bitDns[$addr]; $answer = if ($old -and $old.Answer) { [string]$old.Answer } else { [string]$pr.Answer }; $flag = if ($old -and $old.Flag) { [string]$old.Flag } else { '' } $detailItems = @( (GItem 'resolve' 'resolve' 'www.baidu.com' $st '' 'prop'), (GItem 'answer' 'answer' $answer $st '' 'prop'), (GItem 'flag' 'flag' $flag '' '' 'prop'), (GItem 'time' 'time' $(if ($pr.Ok -and $pr.Ms -ge 0) { [string]$pr.Ms + ' ms' } else { 'T/O' }) $st '' 'prop') ) $detail = GDetail ('DNS ' + $addr) $(if ($i -eq 0) { 'BIT resolver · primary' } else { 'BIT resolver · backup' }) 'dns' $st $detailItems $portalItems += GItem ('dns-' + [string]$i) $(if ($i -eq 0) { 'DNS' } else { 'DNS(备)' }) $addr $st (GProbeMeta $pr.Ok $pr) 'prop' $true $detail } [void](Add-GNode 'bitportal' 'BIT Portal' 'HTTP probe · srun login' 'bit' $portalStatus $false $portalItems) $bpNo = 0 foreach ($bp in @($bitParents)) { $bpNo++ $bpItem = 'bitportal-' + [string]$bpNo Add-GItemToNode ([string]$bp.Node) (GItem $bpItem 'BIT Portal' '10.0.0.55' $portalStatus (GProbeMeta $portalHttp $portalProbe) 'out' $true) Add-GEdge ([string]$bp.Node) $bpItem 'bitportal' 'bit' ([double]$bp.Confidence) ([string]$bp.Evidence) ($portalStatus -ne 'OK') } $apiItems = @( (GItem 'address' 'IPv4' '10.0.0.54:8800' $apiStatus (GProbeMeta ($apiStatus -eq 'OK') $apiProbe) 'addr' $true), (GItem 'http8800' 'HTTP:8800' $(if ($bitApi.Http -gt 0) { [string]$bitApi.Http } else { 'closed' }) $apiStatus '' 'prop'), (GItem 'title' 'title' $bitApi.Title '' '' 'prop') ) [void](Add-GNode 'bitapi' 'BIT API' 'MsgApi' 'bit' $apiStatus $false $apiItems) Add-GEdge 'bitportal' 'api' 'bitapi' 'bit' 1.0 'Portal-associated API probe' ($apiStatus -ne 'OK') $nd = [ordered]@{ version = 5.2 profile = 'general-fit-flow-first-entity-compact' evidenceModel = 'entity-level topology; same process name+layer merged with full PID inventory; svchost nodes excluded; strong-evidence proxy scoring with common-app negative prior; multi-snapshot runtime sockets/routes; adapter/PnP identity; interception corroboration' interception = [ordered]@{ level = $interceptLevel; displayLevel = $displayInterceptLevel; score = [math]::Round($interceptScore,2); signals = @($interceptSignals); proxyLikeListeners = $proxyLikeListeners.Count; proxyCandidateProcesses = $proxyCandidateProcesses.Count; protocolProxyListeners = $protocolProxyListeners.Count; protocolProxyProcesses = $protocolProxyPids.Count; driverHits = $interceptDrivers.Count; serviceHits = $interceptServices.Count; routeSourceMismatch = [bool]$routeSourceProbe.Mismatch } tcpSnapshots = $tcpSnapshotCount limits = [ordered]@{ maxDepth = $maxDepth; maxNodes = $maxNodes; maxRepeatPerPid = $maxRepeatPerPid } nodes = $ndNodes edges = $ndEdges } $ndJson = $nd | ConvertTo-Json -Depth 16 -Compress $chips = '' $chips += 'Host ' + (Enc $hostname) + '' $chips += 'Egress IPv4 ' + (Enc $selAlias) + '' $chips += 'Egress IPv6 ' + (Enc $(if ($eg6) { $eg6.InterfaceAlias } else { '' })) + '' $chips += 'IPv4 Internet ' + $v4txt + '' $chips += 'WinINET proxy ' + $(if ($p.ProxyEnable) { 'on (' + $p.ProxyServer + ')' } else { 'off' }) + '' $chips += 'Graph V5.2 entity-compact' $chips += 'TCP evidence ' + [string]$tcpSnapshotCount + ' snapshots' $chips += 'Interception ' + (Enc $displayInterceptLevel) + '' $chips += 'Proxy candidates ' + [string]$proxyCandidateProcesses.Count + ' proc / ' + [string]$proxyLikeListeners.Count + ' endpoints' $css = @' *{box-sizing:border-box} .extlinks{display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin-top:12px} .extlinks .lbl{color:#8b949e;font-size:12px} .extbtn{display:inline-flex;align-items:center;gap:5px;background:#1c2128;border:1px solid #2d333b;color:#8b949e;border-radius:999px;padding:4px 12px;font-size:12px;text-decoration:none} .extbtn:hover{border-color:#58a6ff;color:#e6edf3} .extbtn::after{content:'\2197';font-size:11px;color:#58a6ff} .extlinks{display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin-top:12px} .extlinks .lbl{color:#8b949e;font-size:12px} .extbtn{display:inline-flex;align-items:center;gap:5px;background:#1c2128;border:1px solid #2d333b;color:#8b949e;border-radius:999px;padding:4px 12px;font-size:12px;text-decoration:none} .extbtn:hover{border-color:#58a6ff;color:#e6edf3} .extbtn::after{content:'\2197';font-size:11px;color:#58a6ff} body{margin:0;background:#0d1117;color:#e6edf3;font:14px/1.5 'Segoe UI',system-ui,-apple-system,'Microsoft YaHei',sans-serif} header{padding:20px 26px;border-bottom:1px solid #2d333b;background:linear-gradient(180deg,#161b22,#0d1117)} h1{font-size:19px;margin:0 0 6px} h1 small{font-size:12px;color:#8b949e;font-weight:400} .sub{color:#8b949e;font-size:12.5px} .chips{display:flex;flex-wrap:wrap;gap:8px;margin-top:14px} .chip{background:#1c2128;border:1px solid #2d333b;border-radius:999px;padding:4px 12px;font-size:12px} .chip b{color:#58a6ff} .chip .ok{color:#3fb950} .chip .fail{color:#f85149} .chip .warn{color:#d29922} main{padding:26px;max-width:1240px;margin:0 auto} .tabs{display:flex;gap:8px;margin-bottom:16px} .tab{background:#1c2128;border:1px solid #2d333b;color:#8b949e;border-radius:999px;padding:6px 16px;font-size:13px;cursor:pointer} .tab:hover{border-color:#58a6ff} .tab.on{color:#3fb950;border-color:#3fb950;font-weight:600} .hidden{display:none} h2{font-size:15px;color:#58a6ff;margin:0 0 4px} .chain{display:flex;align-items:stretch;overflow-x:auto;padding:14px 0 20px} .conn{flex-shrink:0;align-self:center;margin:0 -2px} .block{min-width:220px;max-width:300px;flex:1 1 240px;background:#1c2128;border:1px solid #2d333b;border-radius:10px;padding:12px 14px;box-shadow:inset 0 1px 0 rgba(255,255,255,.04)} .block.selected{border-color:#3fb950;box-shadow:0 0 0 1px #3fb950,0 0 22px rgba(63,185,80,.22)} .bhead{display:flex;justify-content:space-between;align-items:center;margin-bottom:8px} .height{font:700 12px Consolas,monospace;color:#8b949e} .pill{font:600 11px Consolas,monospace;padding:2px 8px;border-radius:999px} .pill.ok{color:#3fb950;background:rgba(63,185,80,.15)} .pill.fail{color:#f85149;background:rgba(248,81,73,.15)} .btitle{font-size:15px;font-weight:600} .bsub{font-size:11px;color:#8b949e;margin-bottom:10px} .brows{margin-top:6px} .row{display:flex;justify-content:space-between;gap:10px;font:12px Consolas,monospace;padding:3px 0;border-top:1px dashed #2d333b} .row .k{color:#8b949e} .row .v{color:#e6edf3;text-align:right;word-break:break-all} .bfoot{margin-top:10px;border-top:1px solid #2d333b;padding-top:8px} .hrow{display:flex;justify-content:space-between;font:11px Consolas,monospace;color:#8b949e;padding:1px 0} .hrow .hval{color:#7ee787;cursor:help} details{background:#1c2128;border:1px solid #2d333b;border-radius:10px;margin:0 0 10px;overflow:hidden} summary{padding:10px 14px;cursor:pointer;font-weight:600;font-size:13px;user-select:none;list-style:none} summary::-webkit-details-marker{display:none} summary::before{content:'▸ ';color:#58a6ff} details[open] summary::before{content:'▾ '} details[open] summary{border-bottom:1px solid #2d333b} .dbody{padding:12px 14px;overflow-x:auto} table{border-collapse:collapse;width:100%;font-size:12.5px} th,td{text-align:left;padding:5px 10px;border-bottom:1px solid #2d333b;white-space:nowrap} th{color:#8b949e;font-weight:600;font-size:11.5px} tr:hover td{background:#161b22} .mono{font-family:Consolas,monospace;font-size:12.5px} .empty{color:#8b949e;font-size:12px} .kv{font:12.5px Consolas,monospace} .kv div{display:flex;padding:3px 0} .kv .k{color:#8b949e;width:150px;flex-shrink:0} .kv .v{color:#e6edf3;word-break:break-all} .ok{color:#3fb950;font-weight:600} .fail{color:#f85149;font-weight:600} #view-graph{background:#0d1117;border:1px solid #2d333b;border-radius:10px;overflow:hidden;min-height:540px} #gcanvas{display:block;width:100%;height:min(78vh,820px);min-height:520px;cursor:grab;touch-action:none;background:radial-gradient(circle,rgba(88,166,255,.10) 1px,transparent 1px) 0 0/26px 26px,#0d1117} #view-graph.full{position:fixed;left:0;right:0;bottom:0;border:none;border-radius:0;background:#0d1117;display:flex;flex-direction:column;min-height:0;z-index:20} #view-graph.full #gcanvas{height:auto;min-height:0;flex:1 1 auto} #gcanvas.grabbing{cursor:grabbing} .node{cursor:grab}.node.grabbing{cursor:grabbing} .node rect.bg{fill:#1c2128;stroke:#2d333b;stroke-width:1.2} .node.sel rect.bg{stroke:#3fb950;stroke-width:1.7;filter:drop-shadow(0 0 10px rgba(63,185,80,.32))} .node.fail rect.bg{stroke:#f85149;stroke-width:3.2;filter:drop-shadow(0 0 6px rgba(248,81,73,.28))}.node.warn rect.bg{stroke:#d29922} .node text{font:11px Consolas,monospace;fill:#e6edf3;pointer-events:none} .node text.title{font-size:12.5px;font-weight:700;fill:#0d1117}.node text.sub{fill:#8b949e;font-size:10px} .node text.st,.nested-st{font-weight:700;text-anchor:end;fill:#0d1117}.node text.st.fail,.nested-st.fail{fill:#fff}.node text.st.down,.nested-st.down{fill:#e6edf3} .item{cursor:default}.item.expandable{cursor:pointer} .item rect.itembg{fill:#161b22;stroke:#2d333b;stroke-width:.85;transition:stroke .12s,fill .12s} .item.linked rect.itembg{fill:#20252c;stroke:#484f58}.item.linked:hover rect.itembg,.item.expandable:hover rect.itembg{stroke:#58a6ff;fill:#242b33} .item.expandable.open rect.itembg{stroke:#58a6ff} .item text.k,.nested-item text.k{fill:#8b949e;font-size:10.5px}.item text.v,.nested-item text.v{fill:#e6edf3;font-size:10.5px;text-anchor:end} .item text.meta,.nested-item text.meta{fill:#8b949e;font-size:9.5px}.item text.probemeta,.nested-item text.probemeta{text-anchor:start;font-variant-numeric:tabular-nums} .item text.probev,.nested-item text.probev{font-variant-numeric:tabular-nums}.chev{fill:#58a6ff;font-size:10px} .statusdot{stroke:#0d1117;stroke-width:1}.statusdot.ok{fill:#3fb950}.statusdot.fail{fill:#f85149}.statusdot.warn{fill:#d29922}.statusdot.down{fill:#8b949e} .port{fill:#58a6ff;stroke:#0d1117;stroke-width:1.2;pointer-events:none}.port.out{fill:#3fb950}.port.bit{fill:#f778ba}.port.dead{fill:#8b949e} .edge{fill:none;stroke:#6e7681;stroke-width:1.55;transition:stroke .15s,stroke-width .15s,opacity .15s;opacity:.92;pointer-events:stroke}.edge.main{stroke:#3fb950}.edge.bit{stroke:#f778ba} .edge.alt{stroke:#79c0ff;stroke-dasharray:6 5;opacity:.72}.edge.policy,.edge.policy.confirmed,.edge.policy.likely,.edge.policy.possible{stroke:#58a6ff;stroke-width:2.15;stroke-dasharray:none;opacity:1}.edge.evidence,.edge.evidence.confirmed,.edge.evidence.likely,.edge.evidence.possible{stroke:#8b949e;stroke-width:1.35;stroke-dasharray:2 7;opacity:.52}.edge.likely{stroke:#d29922;stroke-dasharray:8 5}.edge.possible{stroke:#8b949e;stroke-dasharray:3 6;opacity:.70} .edge-wrap.problem{transform-box:fill-box;transform-origin:center}.edge-wrap.problem .edge{stroke:#8b949e!important;stroke-width:3.2;stroke-dasharray:none;opacity:1}.edge-cross{pointer-events:none}.edge-cross line{stroke:#f85149;stroke-width:2.8;stroke-linecap:round;vector-effect:non-scaling-stroke;filter:drop-shadow(0 0 2px rgba(248,81,73,.55))} .edge-wrap.problem:hover{animation:problem-shake .64s linear infinite}.edge-wrap.problem:hover .edge{stroke:#f85149!important;stroke-dasharray:8 6;animation:problem-dash .64s linear infinite} .edge.hl{stroke-width:2.8;opacity:1;filter:drop-shadow(0 0 3px currentColor)}.edge.main.hl,.edge.bit.hl,.edge.alt.hl,.edge.policy.hl,.edge.evidence.hl,.edge.likely.hl,.edge.possible.hl{animation:dash .9s linear infinite} .node.dimmed{opacity:.38}.edge-wrap.dimmed{opacity:.18}.edge.dimmed{opacity:.18} @keyframes dash{to{stroke-dashoffset:-14}}@keyframes problem-dash{to{stroke-dashoffset:-28}}@keyframes problem-shake{0%{transform:translateX(-2px)}50%{transform:translateX(2px)}100%{transform:translateX(-2px)}} .nested-card{cursor:default}.nested-bg{fill:#11161d;stroke:#3d444d;stroke-width:1}.nested-title{font:700 11px Consolas,monospace;fill:#0d1117}.nested-sub{font:9.5px Consolas,monospace;fill:#8b949e}.nested-st{font:700 10px Consolas,monospace} .nested-itembg{fill:#161b22;stroke:#2d333b;stroke-width:.8}.nested-item text.k,.nested-item text.v{font-size:9.8px}.nested-item text.meta{font-size:9px} .gnotes{font:11px 'Segoe UI',sans-serif;color:#8b949e;padding:8px 12px;border-top:1px solid #2d333b;background:#161b22;display:flex;align-items:center;gap:12px;flex-wrap:wrap;flex:0 0 auto} .gnotes .legend{display:inline-flex;align-items:center;gap:10px;flex-wrap:wrap}.gnotes .lg{display:inline-flex;align-items:center;gap:4px}.gnotes .sw{width:14px;height:2px;border-radius:2px;background:#6e7681}.gnotes .sw.main{background:#3fb950}.gnotes .sw.policy{background:#58a6ff;height:3px}.gnotes .sw.evidence{background:repeating-linear-gradient(90deg,#8b949e 0 2px,transparent 2px 5px)}.gnotes .sw.bit{background:#f778ba} .greset{margin-left:auto;background:#1c2128;border:1px solid #3d444d;color:#c9d1d9;border-radius:999px;padding:3px 10px;font:11px 'Segoe UI',sans-serif;cursor:pointer}.greset:hover{border-color:#58a6ff;color:#fff}.greset.hidden{display:none} .bv{position:relative} span.bv{display:inline-block} .bv>.real{transition:filter .15s} body:not(.revealed) .bv>.real{filter:blur(4px);user-select:none} body:not(.revealed) #gcanvas text.v{filter:blur(3px)} .bv>.bg{position:absolute;left:0;top:0;width:100%;color:transparent;user-select:text;white-space:inherit} .bv>.bg::selection{background:#1668dc;color:#fff} body.revealed .bv>.bg{display:none} body.revealed .bv>.real{filter:none} body.revealed #gcanvas text.v{filter:none} .revealbtn{border-style:dashed} footer{color:#8b949e;font-size:11px;padding:16px 26px;border-top:1px solid #2d333b} @media (max-width:1000px){main{padding:16px}header{padding:16px}.block{flex:1 1 215px}.chip{font-size:11px}#gcanvas{min-height:460px}.gnotes{gap:8px}.greset{margin-left:0}} @media (max-width:640px){main{padding:10px}.block{flex:1 1 190px}.chain{padding:10px 0 14px}} '@ $graphHtml = @' '@ $js = @' (function () { var ND = window.ND || { nodes: [], edges: [] }; var svg = document.getElementById('gcanvas'); if (!svg) { return; } var world = document.getElementById('gworld'); var NW = 320, TOP = 49, ITEM_H = 21, ITEM_STEP = 24, BOTTOM = 9; var NEST_X = 14, NEST_TOP = 43, NEST_ITEM_H = 19, NEST_STEP = 22, NEST_BOTTOM = 8, NEST_AFTER = 8; var H_GAP = 78, V_GAP = 34, X0 = 70, ROOT_Y = 125; var K = { source: '#8b949e', tun: '#3fb950', core: '#58a6ff', nic: '#39c5cf', gw: '#d29922', isp: '#bc8cff', remote: '#a371f7', dns: '#ffa657', bit: '#f778ba', off: '#3d444d' }; var nodes = {}, nodeEls = {}, itemEls = {}, itemUse = {}, incoming = {}, em = []; var st = { x: 0, y: 0, s: 1 }; var drag = null, manualMoved = false; var graphOpened = false, isFitView = false, viewW = 0, viewH = 0, viewAnimation = 0; var expanded = {}; function svgEl(tag, attrs) { var el = document.createElementNS('http://www.w3.org/2000/svg', tag); for (var k in attrs) { if (attrs[k] !== null && attrs[k] !== undefined) { el.setAttribute(k, attrs[k]); } } return el; } function statusClass(s) { s = String(s || '').toLowerCase(); return s === 'ok' ? 'ok' : s === 'fail' ? 'fail' : s === 'down' ? 'down' : s === 'warn' ? 'warn' : ''; } function compactStatus(s) { return s === 'WARN' ? 'CHECK' : s; } function trimText(s, n) { s = String(s == null ? '' : s); return s.length > n ? s.slice(0, n - 1) + '…' : s; } function rowValueLimit(w, nested, probe) { var charWidth = nested ? 5.9 : 6.3; var reserved = probe ? 144 : 72; return Math.max(probe ? 17 : 25, Math.floor((w - reserved) / charWidth)); } function rowValueText(it, limit) { var value = String(it.v || ''), meta = String(it.meta || ''); if (!meta) { return trimText(value, limit); } // Prefer the complete address/value over auxiliary metadata. This keeps long // IPv6 endpoints readable while the title tooltip still carries both fields. if (value.length >= limit - 1) { return value.length <= limit ? value : trimText(value, limit); } return trimText(value + ' · ' + meta, limit); } function useKey(nodeId, itemId) { return nodeId + '::' + (itemId || ''); } function expandKey(nodeId, itemId) { return nodeId + '::' + itemId; } function roleOf(it) { return String(it.role || 'prop'); } ND.nodes.forEach(function (n, ni) { n._order = ni; n._baseItems = (n.items || []).map(function (it, ii) { it._order = ii; return it; }); nodes[n.id] = n; incoming[n.id] = []; }); ND.edges.forEach(function (e, ei) { e._order = ei; e._fromItem = e.fromItem || ''; if (incoming[e.to]) { incoming[e.to].push(e); } }); // Address/IP is row 1 for any node with an inbound edge. Additional parents reserve // subsequent inbound rows. Output rows then immediately follow those input rows; // all ordinary properties and expandable attributes come afterwards. ND.nodes.forEach(function (n) { var base = n._baseItems.slice(); var addr = base.filter(function (it) { return roleOf(it) === 'addr'; }); var outs = base.filter(function (it) { return roleOf(it) === 'out'; }); var props = base.filter(function (it) { var r = roleOf(it); return r !== 'addr' && r !== 'out'; }); var ins = incoming[n.id] || []; var arranged = []; if (ins.length) { if (addr.length) { arranged.push(addr.shift()); } else { arranged.push({ id: '__in0', k: 'in', v: nodes[ins[0].from] ? nodes[ins[0].from].label : ins[0].from, role: 'in', status: '', meta: '' }); } for (var j = 1; j < ins.length; j++) { arranged.push({ id: '__in' + j, k: 'in', v: nodes[ins[j].from] ? nodes[ins[j].from].label : ins[j].from, role: 'in', status: '', meta: '' }); } } addr.forEach(function (it) { arranged.push(it); }); outs.forEach(function (it) { arranged.push(it); }); props.forEach(function (it) { arranged.push(it); }); n.items = arranged; n.itemById = {}; n.items.forEach(function (it) { n.itemById[it.id] = it; }); ins.forEach(function (e, i) { var target = n.items[Math.min(i, n.items.length - 1)]; e._toItem = target ? target.id : ''; }); }); function rebuildUse() { itemUse = {}; ND.edges.forEach(function (e) { if (e._fromItem) { var k1 = useKey(e.from, e._fromItem); itemUse[k1] = itemUse[k1] || {}; itemUse[k1].out = true; itemUse[k1].outKind = e.kind || 'main'; itemUse[k1].outDead = !!e.dead; } if (e._toItem) { var k2 = useKey(e.to, e._toItem); itemUse[k2] = itemUse[k2] || {}; itemUse[k2].in = true; itemUse[k2].inKind = e.kind || 'main'; itemUse[k2].inDead = !!e.dead; } }); } rebuildUse(); function detailHeight(detail) { return NEST_TOP + ((detail && detail.items) ? detail.items.length : 0) * NEST_STEP + NEST_BOTTOM; } function measureNode(n) { var y = TOP; n.itemIndex = {}; n.items.forEach(function (it, i) { n.itemIndex[it.id] = i; it._y = y; it._detailY = null; it._detailH = 0; y += ITEM_STEP; if (it.detail && expanded[expandKey(n.id, it.id)]) { it._detailY = y + 1; it._detailH = detailHeight(it.detail); y += it._detailH + NEST_AFTER; } }); n.h = y + BOTTOM; } function measureAll() { ND.nodes.forEach(measureNode); } function itemCenterRel(n, itemId) { var it = n.itemById[itemId]; return it ? it._y + ITEM_H / 2 : n.h / 2; } // Generic layered layout: every edge advances one column. The preferred Y of a // child makes parent.out and child.first-in exactly horizontal. If two nodes want // the same vertical space, the first keeps that alignment and later peers stack down. function autoLayout() { measureAll(); var depth = {}, maxDepth = 0; ND.nodes.forEach(function (n) { depth[n.id] = 0; }); for (var pass = 0; pass < ND.nodes.length; pass++) { var changed = false; ND.edges.forEach(function (e) { if (depth[e.from] === undefined || depth[e.to] === undefined) { return; } if (e.kind === 'evidence') { return; } // diagnostics must not distort traffic-path rank var d = depth[e.from] + 1; if (d > depth[e.to]) { depth[e.to] = d; maxDepth = Math.max(maxDepth, d); changed = true; } }); if (!changed) { break; } } var layers = {}; ND.nodes.forEach(function (n) { var d = depth[n.id] || 0; if (n.layoutLane === 'evidence') { d = Math.max(1, d); depth[n.id] = d; } (layers[d] = layers[d] || []).push(n); maxDepth = Math.max(maxDepth, d); }); for (var d = 0; d <= maxDepth; d++) { var layer = layers[d] || []; var candidates = layer.map(function (n) { var ins = incoming[n.id] || []; var desired = ROOT_Y + n._order * 0.01; if (ins.length) { var trafficIns = ins.filter(function (e) { return e.kind !== 'evidence'; }); var pool = trafficIns.length ? trafficIns.slice() : ins.slice(); // A node can have a short bypass edge and a longer proxy/TUN path at the // same time. Align it to the deepest predecessor so the actual multi-hop // chain stays visually horizontal; otherwise an earlier app->NIC edge can // pull the NIC away from proxy->NIC and make the proxy chain look secondary. var kindRank = { main: 4, policy: 3, bit: 3, likely: 2, possible: 1, alt: 0, evidence: -1 }; pool.sort(function (a, b) { var da = depth[a.from] || 0, db = depth[b.from] || 0; if (db !== da) { return db - da; } var ka = kindRank[a.kind] === undefined ? 1 : kindRank[a.kind]; var kb = kindRank[b.kind] === undefined ? 1 : kindRank[b.kind]; return kb - ka; }); var e = pool[0], p = nodes[e.from]; if (p && typeof p.y === 'number') { desired = p.y + itemCenterRel(p, e._fromItem) - itemCenterRel(n, e._toItem); } } if (n.layoutLane === 'evidence') { desired += 460; } return { n: n, desired: desired }; }); candidates.sort(function (a, b) { return a.desired === b.desired ? a.n._order - b.n._order : a.desired - b.desired; }); var bottom = -Infinity; candidates.forEach(function (c, i) { var n = c.n; n.x = X0 + d * (NW + H_GAP); var y = c.desired; if (i > 0 && y < bottom + V_GAP) { y = bottom + V_GAP; } n.y = y; bottom = y + n.h; }); } var minY = Infinity; ND.nodes.forEach(function (n) { minY = Math.min(minY, n.y); }); if (isFinite(minY) && minY < 55) { var shift = 55 - minY; ND.nodes.forEach(function (n) { n.y += shift; }); } manualMoved = false; } function rowAnchor(n, itemId, from) { var it = n.itemById[itemId]; var y = n.y + (it ? it._y + ITEM_H / 2 : n.h / 2); return { x: n.x + (from ? NW : 0), y: y }; } function edgePath(a, b) { var dx = b.x - a.x, sign = dx >= 0 ? 1 : -1; var c = Math.max(24, Math.min(60, Math.abs(dx) * 0.42)); return 'M ' + a.x + ' ' + a.y + ' C ' + (a.x + sign * c) + ' ' + a.y + ', ' + (b.x - sign * c) + ' ' + b.y + ', ' + b.x + ' ' + b.y; } function confidenceClass(e) { if (e.kind === 'alt') { return 'alt'; } var c = Number(e.confidence == null ? 1 : e.confidence); if (c >= 0.80) { return 'confirmed'; } if (c >= 0.50) { return 'likely'; } return 'possible'; } function markerFor(e, bad) { if (e.dead || bad) { return 'url(#arrow-problem)'; } if (e.kind === 'bit') { return 'url(#arrow-bit)'; } if (e.kind === 'policy') { return 'url(#arrow-policy)'; } if (e.kind === 'evidence') { return 'url(#arrow-evidence)'; } if (e.kind === 'alt') { return 'url(#arrow-alt)'; } var cc = confidenceClass(e); if (cc === 'likely') { return 'url(#arrow-likely)'; } if (cc === 'possible') { return 'url(#arrow-possible)'; } return 'url(#arrow-main)'; } function portClass(kind, dead, out) { var c = 'port' + (out ? ' out' : ''); if (dead) { c += ' dead'; } else if (kind === 'bit') { c += ' bit'; } return c; } function drawRow(g, n, it, x, y, w, nested) { var use = nested ? {} : (itemUse[useKey(n.id, it.id)] || {}); var linked = !!(use.in || use.out); var expandable = !!it.detail; var cls = nested ? 'nested-item' : 'item'; if (linked) { cls += ' linked'; } if (expandable) { cls += ' expandable'; } if (expandable && expanded[expandKey(n.id, it.id)]) { cls += ' open'; } var ig = svgEl('g', { 'class': cls, 'data-node': n.id, 'data-item': it.id }); if (!nested) { itemEls[useKey(n.id, it.id)] = ig; } ig.appendChild(svgEl('rect', { 'class': nested ? 'nested-itembg' : 'itembg', x: x, y: y, width: w, height: nested ? NEST_ITEM_H : ITEM_H, rx: (nested ? NEST_ITEM_H : ITEM_H) / 2 })); var h = nested ? NEST_ITEM_H : ITEM_H; var cy = y + h / 2; var keyX = x + 7; if (expandable) { var ch = svgEl('text', { 'class': 'chev', x: x + 7, y: y + (nested ? 13.2 : 14.2) }); ch.textContent = expanded[expandKey(n.id, it.id)] ? '▾' : '▸'; ig.appendChild(ch); keyX += 12; } var kt = svgEl('text', { 'class': 'k', x: keyX, y: y + (nested ? 13.2 : 14.3) }); kt.textContent = trimText(it.k || '', expandable ? 9 : 11); ig.appendChild(kt); if (it.probe) { var addrRight = x + w - 66; var dotX = x + w - 55; var metaX = x + w - 46; var vt = svgEl('text', { 'class': 'v probev', x: addrRight, y: y + (nested ? 13.2 : 14.3) }); vt.textContent = rowValueText({ v: it.v, meta: '' }, rowValueLimit(w, nested, true)); ig.appendChild(vt); if (it.status) { ig.appendChild(svgEl('circle', { 'class': 'statusdot ' + statusClass(it.status), cx: dotX, cy: cy, r: nested ? 3.2 : 3.6 })); } var mt = svgEl('text', { 'class': 'meta probemeta', x: metaX, y: y + (nested ? 13.2 : 14.3) }); mt.textContent = String(it.meta || ''); ig.appendChild(mt); } else { var dot = !!it.status; var dotX2 = x + w - 9; var valRight = x + w - (dot ? 18 : 7); if (dot) { ig.appendChild(svgEl('circle', { 'class': 'statusdot ' + statusClass(it.status), cx: dotX2, cy: cy, r: nested ? 3.2 : 3.6 })); } var vt2 = svgEl('text', { 'class': 'v', x: valRight, y: y + (nested ? 13.2 : 14.3) }); vt2.textContent = rowValueText(it, rowValueLimit(w, nested, false)); ig.appendChild(vt2); } var full = [it.k, it.v, it.status, it.meta].filter(Boolean).join(' · '); if (full) { var tt = svgEl('title', {}); tt.textContent = full; ig.appendChild(tt); } if (!nested) { if (use.in) { ig.appendChild(svgEl('circle', { 'class': portClass(use.inKind, use.inDead, false), cx: 0, cy: cy, r: 4.6 })); } if (use.out) { ig.appendChild(svgEl('circle', { 'class': portClass(use.outKind, use.outDead, true), cx: NW, cy: cy, r: 4.6 })); } ig.addEventListener('mouseenter', function (ev) { setHighlight(n.id, it.id, true); ev.stopPropagation(); }); ig.addEventListener('mouseleave', function (ev) { setHighlight(n.id, it.id, false); ev.stopPropagation(); }); if (expandable) { ig.addEventListener('pointerdown', function (ev) { ev.preventDefault(); ev.stopPropagation(); cancelViewAnimation(); setFitState(false); var ek = expandKey(n.id, it.id); expanded[ek] = !expanded[ek]; measureAll(); if (!manualMoved) { autoLayout(); } renderScene(false); }); } } g.appendChild(ig); } function drawNestedCard(g, n, it) { if (!it.detail || !expanded[expandKey(n.id, it.id)] || it._detailY === null) { return; } var d = it.detail, x = NEST_X, y = it._detailY, w = NW - NEST_X * 2, h = it._detailH; var ng = svgEl('g', { 'class': 'nested-card' }); ng.appendChild(svgEl('rect', { 'class': 'nested-bg', x: x, y: y, width: w, height: h, rx: 8 })); ng.appendChild(svgEl('rect', { x: x, y: y, width: w, height: 22, rx: 8, fill: K[d.kind] || '#58a6ff' })); ng.appendChild(svgEl('rect', { x: x, y: y + 11, width: w, height: 11, fill: K[d.kind] || '#58a6ff' })); var title = svgEl('text', { 'class': 'nested-title', x: x + 8, y: y + 15 }); title.textContent = trimText(d.label || '', 38); ng.appendChild(title); if (d.status) { var stt = svgEl('text', { 'class': 'nested-st ' + statusClass(d.status), x: x + w - 8, y: y + 15 }); stt.textContent = compactStatus(d.status); ng.appendChild(stt); } var sub = svgEl('text', { 'class': 'nested-sub', x: x + 8, y: y + 37 }); sub.textContent = trimText(d.sub || '', 47); ng.appendChild(sub); (d.items || []).forEach(function (di, i) { drawRow(ng, n, di, x + 7, y + NEST_TOP + i * NEST_STEP, w - 14, true); }); g.appendChild(ng); } function drawNode(n) { var sc = statusClass(n.status); var g = svgEl('g', { 'class': 'node' + (n.sel ? ' sel' : '') + (sc === 'fail' || sc === 'down' ? ' fail' : '') + (sc === 'warn' ? ' warn' : ''), 'data-id': n.id }); nodeEls[n.id] = g; g.setAttribute('transform', 'translate(' + n.x + ',' + n.y + ')'); g.appendChild(svgEl('rect', { 'class': 'bg', x: 0, y: 0, width: NW, height: n.h, rx: 9 })); g.appendChild(svgEl('rect', { x: 0, y: 0, width: NW, height: 24, rx: 9, fill: K[n.kind] || '#58a6ff' })); g.appendChild(svgEl('rect', { x: 0, y: 12, width: NW, height: 12, fill: K[n.kind] || '#58a6ff' })); var title = svgEl('text', { 'class': 'title', x: 9, y: 16 }); title.textContent = trimText(n.label, 39); g.appendChild(title); if (n.status) { var tst = svgEl('text', { 'class': 'st ' + sc, x: NW - 9, y: 16 }); tst.textContent = compactStatus(n.status); g.appendChild(tst); } var sub = svgEl('text', { 'class': 'sub', x: 9, y: 40 }); sub.textContent = trimText(n.sub || '', 53); g.appendChild(sub); n.items.forEach(function (it) { drawRow(g, n, it, 7, it._y, NW - 14, false); drawNestedCard(g, n, it); }); g.addEventListener('mouseenter', function (ev) { if (!ev.target.closest || !ev.target.closest('.item')) { setHighlight(n.id, '', true); } }); g.addEventListener('mouseleave', function () { setHighlight(n.id, '', false); }); world.appendChild(g); } function isProblemNode(n) { if (!n) { return false; } var sc = statusClass(n.status); return sc === 'fail' || sc === 'down'; } function makeEdges() { em = ND.edges.map(function (e) { var a = nodes[e.from], b = nodes[e.to]; var bad = !!e.bad || isProblemNode(a) || isProblemNode(b); var problem = !!e.dead || bad; var cc = confidenceClass(e); var cls = 'edge ' + (e.kind || 'main') + ' ' + cc; var wrap = svgEl('g', { 'class': 'edge-wrap' + (problem ? ' problem' : '') }); var p = svgEl('path', { 'class': cls, 'marker-end': markerFor(e, problem), 'data-a': e.from, 'data-b': e.to, 'data-ai': e._fromItem || '', 'data-bi': e._toItem || '' }); var pct = Math.round(Number(e.confidence == null ? 1 : e.confidence) * 100); var tip = (problem ? 'problem/disconnected · ' : '') + cc + ' ' + pct + '%' + (e.evidence ? ' · ' + e.evidence : ''); var tt = svgEl('title', {}); tt.textContent = tip; p.appendChild(tt); wrap.appendChild(p); var cross = null; if (problem) { cross = svgEl('g', { 'class': 'edge-cross' }); cross.appendChild(svgEl('line', { x1: -6, y1: -6, x2: 6, y2: 6 })); cross.appendChild(svgEl('line', { x1: 6, y1: -6, x2: -6, y2: 6 })); wrap.appendChild(cross); } world.appendChild(wrap); return { e: e, a: a, b: b, p: p, g: wrap, cross: cross, problem: problem }; }); } function renderEdges() { em.forEach(function (ee) { if (!ee.a || !ee.b) { return; } var aa = rowAnchor(ee.a, ee.e._fromItem, true), bb = rowAnchor(ee.b, ee.e._toItem, false); ee.p.setAttribute('d', edgePath(aa, bb)); if (ee.cross) { try { var len = ee.p.getTotalLength(), pt = ee.p.getPointAtLength(len / 2); ee.cross.setAttribute('transform', 'translate(' + pt.x + ',' + pt.y + ')'); } catch (_) { } } }); } function setHighlight(nodeId, itemId, on) { var connected = {}; if (on) { connected[nodeId] = true; em.forEach(function (ee) { var hit = itemId ? ((ee.e.from === nodeId && ee.e._fromItem === itemId) || (ee.e.to === nodeId && ee.e._toItem === itemId)) : (ee.e.from === nodeId || ee.e.to === nodeId); ee.p.classList.toggle('hl', hit); ee.p.classList.toggle('dimmed', !hit); if (ee.g) { ee.g.classList.toggle('dimmed', !hit); } if (hit) { connected[ee.e.from] = true; connected[ee.e.to] = true; } }); Object.keys(nodeEls).forEach(function (id) { nodeEls[id].classList.toggle('dimmed', !connected[id]); }); } else { em.forEach(function (ee) { ee.p.classList.remove('hl'); ee.p.classList.remove('dimmed'); if (ee.g) { ee.g.classList.remove('dimmed'); } }); Object.keys(nodeEls).forEach(function (id) { nodeEls[id].classList.remove('dimmed'); }); } } function renderScene(reflow) { measureAll(); if (reflow) { autoLayout(); } while (world.firstChild) { world.removeChild(world.firstChild); } nodeEls = {}; itemEls = {}; makeEdges(); ND.nodes.forEach(drawNode); renderEdges(); } function updateNodeTransform(n) { var g = nodeEls[n.id]; if (g) { g.setAttribute('transform', 'translate(' + n.x + ',' + n.y + ')'); } } function applyView() { world.setAttribute('transform', 'translate(' + st.x + ',' + st.y + ') scale(' + st.s + ')'); } var reset = document.getElementById('greset'); function cancelViewAnimation() { viewAnimation++; } function setFitState(on) { isFitView = !!on; if (reset) { reset.classList.toggle('hidden', isFitView); } } function canvasSize() { return { w: svg.clientWidth || 1000, h: svg.clientHeight || 650 }; } function fitView() { if (!ND.nodes.length) { return; } cancelViewAnimation(); var xs = [], ys = []; ND.nodes.forEach(function (n) { xs.push(n.x, n.x + NW); ys.push(n.y, n.y + n.h); }); var minx = Math.min.apply(null, xs), maxx = Math.max.apply(null, xs), miny = Math.min.apply(null, ys), maxy = Math.max.apply(null, ys); var size = canvasSize(), w = size.w, h = size.h, pad = 42; var spanX = Math.max(1, maxx - minx), spanY = Math.max(1, maxy - miny); var s = Math.min(1.28, (w - pad * 2) / spanX, (h - pad * 2) / spanY); st.s = Math.max(0.22, s); st.x = (w - st.s * spanX) / 2 - st.s * minx; st.y = (h - st.s * spanY) / 2 - st.s * miny; viewW = w; viewH = h; applyView(); setFitState(true); } function resetLayout() { autoLayout(); renderScene(false); fitView(); } function nodeText(n) { return [n.id, n.label, n.sub].concat((n.items || []).map(function (it) { return [it.k, it.v].join(' '); })).join(' ').toLowerCase(); } function lastOk(match) { var found = null; ND.nodes.forEach(function (n) { if (statusClass(n.status) === 'ok' && match(n)) { found = n; } }); return found; } function autoFocusTarget() { var priorities = [ function (n) { return n.id === 'bitapi' || /^bit api$/i.test(String(n.label || '')); }, function (n) { return n.id === 'bitportal' || /^bit portal$/i.test(String(n.label || '')); }, function (n) { return n.kind === 'isp' && /ipv6/.test(nodeText(n)); }, function (n) { return n.kind === 'isp' && !/ipv6/.test(nodeText(n)); }, function (n) { return n.kind === 'gw'; }, function (n) { return n.kind === 'nic' && /\bcarrier\b/.test(nodeText(n)); } ]; for (var i = 0; i < priorities.length; i++) { var found = lastOk(priorities[i]); if (found) { return found; } } return null; } function animateViewTo(next, duration) { var token = ++viewAnimation; var start = { x: st.x, y: st.y, s: st.s }, begun = null; function frame(now) { if (token !== viewAnimation) { return; } if (begun === null) { begun = now; } var t = Math.min(1, (now - begun) / duration); var eased = 1 - Math.pow(1 - t, 3); st.x = start.x + (next.x - start.x) * eased; st.y = start.y + (next.y - start.y) * eased; st.s = start.s + (next.s - start.s) * eased; applyView(); if (t < 1) { requestAnimationFrame(frame); } } requestAnimationFrame(frame); } function focusNode(n, animate) { if (!n) { return; } var size = canvasSize(), pad = 48; var targetScale = Math.min(1.4, 320 / NW, (size.w - pad) / NW, (size.h - pad) / Math.max(1, n.h)); targetScale = Math.max(0.35, targetScale); var next = { s: targetScale, x: size.w / 2 - targetScale * (n.x + NW / 2), y: size.h / 2 - targetScale * (n.y + n.h / 2) }; viewW = size.w; viewH = size.h; setFitState(false); if (animate) { animateViewTo(next, 500); } else { cancelViewAnimation(); st = next; applyView(); } } function preserveViewAfterResize(markChanged) { var size = canvasSize(); if (viewW > 0 && viewH > 0) { var dx = size.w - viewW, dy = size.h - viewH; st.x += dx / 2; st.y += dy / 2; if (markChanged && (Math.abs(dx) > 0.5 || Math.abs(dy) > 0.5)) { setFitState(false); } } viewW = size.w; viewH = size.h; applyView(); } window.fitNetGraph = resetLayout; window.resetNetGraph = resetLayout; window.netdiagGraphState = function () { return { x: st.x, y: st.y, scale: st.s, fit: isFitView, cardWidth: NW, viewportWidth: viewW, viewportHeight: viewH }; }; function findNodeEl(el) { while (el && el !== svg) { if (el.getAttribute && el.getAttribute('data-id')) { return el; } el = el.parentNode; } return null; } svg.addEventListener('pointerdown', function (ev) { cancelViewAnimation(); setFitState(false); var ne = findNodeEl(ev.target); if (ne) { var n = nodes[ne.getAttribute('data-id')]; drag = { t: 'node', id: n.id, sx: ev.clientX, sy: ev.clientY, ox: n.x, oy: n.y }; ne.classList.add('grabbing'); } else { drag = { t: 'pan', sx: ev.clientX, sy: ev.clientY, ox: st.x, oy: st.y }; } svg.classList.add('grabbing'); ev.preventDefault(); }); window.addEventListener('pointermove', function (ev) { if (!drag) { return; } if (drag.t === 'pan') { st.x = drag.ox + (ev.clientX - drag.sx); st.y = drag.oy + (ev.clientY - drag.sy); applyView(); } else { var n = nodes[drag.id]; n.x = drag.ox + (ev.clientX - drag.sx) / st.s; n.y = drag.oy + (ev.clientY - drag.sy) / st.s; updateNodeTransform(n); manualMoved = true; renderEdges(); } }); window.addEventListener('pointerup', function () { if (drag && drag.t === 'node') { var ge = nodeEls[drag.id]; if (ge) { ge.classList.remove('grabbing'); } } drag = null; svg.classList.remove('grabbing'); }); svg.addEventListener('wheel', function (ev) { ev.preventDefault(); cancelViewAnimation(); setFitState(false); var r = svg.getBoundingClientRect(), mx = ev.clientX - r.left, my = ev.clientY - r.top; var f = ev.deltaY < 0 ? 1.15 : 0.87, ns = Math.min(2.7, Math.max(0.25, st.s * f)); f = ns / st.s; st.x = mx - (mx - st.x) * f; st.y = my - (my - st.y) * f; st.s = ns; applyView(); }, { passive: false }); svg.addEventListener('dblclick', function (ev) { ev.preventDefault(); if (!findNodeEl(ev.target)) { resetLayout(); } }); if (reset) { reset.addEventListener('click', resetLayout); } autoLayout(); renderScene(false); applyView(); var tabs = document.querySelectorAll('.tab[data-view]'); var graphSec = document.getElementById('view-graph'); function setFullTop() { if (!graphSec || !graphSec.classList.contains('full')) { return; } var tr = document.querySelector('.tabs').getBoundingClientRect(); graphSec.style.top = (tr.bottom + 8) + 'px'; } tabs.forEach(function (b) { b.addEventListener('click', function () { var v = b.getAttribute('data-view'); tabs.forEach(function (x) { x.classList.toggle('on', x === b); }); document.getElementById('view-chain').classList.toggle('hidden', v !== 'chain'); document.getElementById('view-graph').classList.toggle('hidden', v !== 'graph'); if (v === 'graph') { if (graphSec) { graphSec.classList.add('full'); } setFullTop(); if (!graphOpened) { graphOpened = true; setTimeout(function () { resetLayout(); var target = autoFocusTarget(); if (target) { focusNode(target, true); } }, 30); } else { setTimeout(function () { preserveViewAfterResize(false); }, 30); } } else { if (graphSec) { graphSec.classList.remove('full'); } } }); }); window.addEventListener('resize', function () { var on = document.querySelector('.tab.on'); if (on && on.getAttribute('data-view') === 'graph') { cancelViewAnimation(); setFullTop(); setTimeout(function () { preserveViewAfterResize(true); }, 20); } }); })(); (function () { var rb = document.getElementById('revealbtn'); if (!rb) { return; } rb.addEventListener('click', function () { var on = document.body.classList.toggle('revealed'); rb.textContent = on ? 'Hide info' : 'Show info'; }); document.querySelectorAll('.dbody table td, .kv .v, .brows .v, .mono').forEach(function (el) { if (el.querySelector('.real') || !el.textContent.trim()) { return; } el.classList.add('bv'); var html = el.innerHTML; el.innerHTML = ''; var real = document.createElement('span'); real.className = 'real'; real.innerHTML = html; var g = document.createElement('span'); g.className = 'bg'; g.innerHTML = html; el.appendChild(real); el.appendChild(g); }); })(); '@ $doc = @" NetDiag Report - $hostname

NetDiag Report default egress + evidence graph

$hostname · $os · generated $ts
$chips
$viewChain
$graphHtml
Hash-linked blocks: each block stores the SHA256 of its own content plus the previous block hash; any change to the chain breaks every following hash. Node graph V5.2 entity-compact keeps explicit proxy/TUN paths in the traffic topology, merges same-layer entities, and places endpoint/socket evidence behind expandable details; unexplained interception evidence remains a non-hop sidecar; zero-dependency vanilla SVG. Generated by netdiag.ps1.
"@ $outPath = Join-Path $PSScriptRoot ("netdiag-report-" + (Get-Date -Format 'yyyyMMdd-HHmmss') + '.html') [System.IO.File]::WriteAllText($outPath, $doc, (New-Object System.Text.UTF8Encoding($true))) Write-Host '' Write-Host (' HTML report -> ' + $outPath) -ForegroundColor Green Start-Process $outPath