#requires -Version 7.0 # READ-ONLY gates, not a network recovery engine. The caller owns its bounded # process/deadline and performs shutdown/recovery before invoking the clean gate. # No app exit, network mutation, lock acquisition, or file write occurs here. Set-StrictMode -Version Latest function Get-PNBHash([byte[]]$Bytes) { return [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData($Bytes)).ToLowerInvariant() } function Get-PNBJsonHash($Value) { return Get-PNBHash ([Text.Encoding]::UTF8.GetBytes((ConvertTo-Json -InputObject $Value -Depth 24 -Compress))) } function Copy-PNBObject($Value) { # JSON round-trips can silently turn ISO strings into DateTime objects, # changing both their hash and comparison semantics on PowerShell 7. if($Value -is [Collections.IDictionary]){ $copy=[ordered]@{};foreach($key in $Value.Keys){$copy[$key]=Copy-PNBObject $Value[$key]};return ,$copy } if($Value -is [array]){$copy=@(foreach($item in $Value){,(Copy-PNBObject $item)});return ,$copy} return $Value } function Sort-PNBRows($Rows) { return ,@($Rows | Sort-Object { $_ | ConvertTo-Json -Depth 16 -Compress }) } function Test-PNBEqual($Left, $Right) { return (Get-PNBJsonHash $Left) -ceq (Get-PNBJsonHash $Right) } function Test-PNBPhysicalInterfacesEquivalent($Expected, $Observation) { # Read-only exception for OS automatic metrics, NEVER a rebaseline. Raw # snapshots/hashes stay unchanged. Legacy observations remain strict. try { foreach($side in @($Expected,$Observation)){ Assert-PNBFields $side @('PhysicalInterfaces','PhysicalAdapters','PhysicalAddresses','PhysicalDns','Routes') 'metric comparison' } $expectedOwned=@(if($Expected.Contains('OwnedInterfaces')){$Expected.OwnedInterfaces}) $observedOwned=@(if($Observation.Contains('OwnedInterfaces')){$Observation.OwnedInterfaces}) if(-not(Test-PNBEqual $expectedOwned $observedOwned)){return $false} if(Test-PNBEqual $Expected.PhysicalInterfaces $Observation.PhysicalInterfaces){return $true} foreach($field in @('PhysicalAdapters','PhysicalAddresses','PhysicalDns','Routes')){ if(-not(Test-PNBEqual $Expected[$field] $Observation[$field])){return $false} } $maps=@();$changedKeys=[Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) foreach($side in @($Expected,$Observation)){ $map=[Collections.Generic.Dictionary[string,object]]::new([StringComparer]::Ordinal) if($side.PhysicalInterfaces -isnot [array]){return $false} $ownedRows=@(if($side.Contains('OwnedInterfaces')){$side.OwnedInterfaces}) if($ownedRows.Count){ Assert-PNBFields $side @('OwnedAdapters') 'owned metric binding' foreach($row in $ownedRows){ if(@($side.OwnedAdapters | Where-Object { $_.InterfaceIndex -eq $row.InterfaceIndex -and (Test-PNBOwnedAdapter $_) }).Count -ne 1){return $false} } } foreach($row in @($side.PhysicalInterfaces)+$ownedRows){ Assert-PNBFields $row @('InterfaceIndex','AddressFamily','Dhcp','ConnectionState','InterfaceMetric','CompartmentId','AutomaticMetric') 'automatic metric evidence' if(-not(Test-PNBInteger $row.InterfaceIndex 1) -or -not(Test-PNBInteger $row.CompartmentId 1) -or -not(Test-PNBInteger $row.InterfaceMetric 0) -or $row.AddressFamily -cnotin @('IPv4','IPv6') -or $row.AutomaticMetric -cnotin @('Enabled','Disabled') -or $row.ConnectionState -cnotin @('Connected','Disconnected')){return $false} $key='{0}|{1}|{2}' -f $row.CompartmentId,$row.AddressFamily,$row.InterfaceIndex if(-not $map.TryAdd($key,$row)){return $false} } $maps+=,$map } if($maps[0].Count -ne $maps[1].Count){return $false} # Owned interface metrics are additional REAL evidence, not inferred # from journal routes. Any change there remains a strict rejection. if(-not(Test-PNBEqual $expectedOwned $observedOwned)){return $false} foreach($key in $maps[0].Keys){ if(-not $maps[1].ContainsKey($key)){return $false} $left=$maps[0][$key];$right=$maps[1][$key] $leftRest=Copy-PNBObject $left;$rightRest=Copy-PNBObject $right $leftRest.Remove('InterfaceMetric');$rightRest.Remove('InterfaceMetric') if(-not(Test-PNBEqual $leftRest $rightRest)){return $false} if($left.InterfaceMetric -ne $right.InterfaceMetric){ if($left.AutomaticMetric -cne 'Enabled' -or $right.AutomaticMetric -cne 'Enabled' -or $left.ConnectionState -cne 'Connected' -or $right.ConnectionState -cne 'Connected'){return $false} [void]$changedKeys.Add($key) } } if($changedKeys.Count -eq 0){return $false} $routeStateCount=@($Expected.Routes | Where-Object { $_.Contains('State') }).Count if($routeStateCount -notin @(0,$Expected.Routes.Count)){return $false} $stateProven=$Expected.Routes.Count -gt 0 -and $routeStateCount -eq $Expected.Routes.Count if($stateProven -and @($Expected.Routes | Where-Object { $_.State -cnotin @('Alive','Dead') }).Count){return $false} $rankings=@() foreach($map in $maps){ $groups=[Collections.Generic.Dictionary[string,object]]::new([StringComparer]::Ordinal) $affectedGroups=[Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) $routeKeys=[Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) foreach($route in $Expected.Routes){ Assert-PNBFields $route @('PolicyStore','AddressFamily','DestinationPrefix','InterfaceIndex','NextHop','RouteMetric','CompartmentId','Protocol') 'metric route' if($route.PolicyStore -cnotin @('ActiveStore','PersistentStore') -or $route.AddressFamily -cnotin @('IPv4','IPv6') -or -not(Test-PNBInteger $route.InterfaceIndex 1) -or -not(Test-PNBInteger $route.CompartmentId 1) -or -not(Test-PNBInteger $route.RouteMetric 0) -or -not $routeKeys.Add((Get-PNBRouteKey $route))){return $false} $binding='{0}|{1}|{2}' -f $route.CompartmentId,$route.AddressFamily,$route.InterfaceIndex if(-not $map.ContainsKey($binding)){return $false} $groupKey='{0}|{1}|{2}|{3}' -f $route.PolicyStore,$route.CompartmentId,$route.AddressFamily,$route.DestinationPrefix if(-not $groups.ContainsKey($groupKey)){$groups.Add($groupKey,[Collections.Generic.List[object]]::new())} if($changedKeys.Contains($binding)){[void]$affectedGroups.Add($groupKey)} # Disconnected residual routes must not mask live exit changes. if($route.PolicyStore -ceq 'PersistentStore' -or ($map[$binding].ConnectionState -ceq 'Connected' -and (-not $stateProven -or $route.State -ceq 'Alive'))){ $groups[$groupKey].Add([ordered]@{Score=([decimal]$route.RouteMetric+[decimal]$map[$binding].InterfaceMetric);Path=('{0}|{1}' -f $route.InterfaceIndex,$route.NextHop)}) } } $set=[ordered]@{} # An unrelated, unchanged disconnected-only prefix cannot be # affected by these metrics. Every route still needs a real unique # binding above; never discard a competitor of an affected prefix. foreach($groupKey in @($affectedGroups | Sort-Object)){ if($groups[$groupKey].Count -eq 0){return $false} # Current ActiveStore paths may use the cheapest complete tie # set ONLY when both raw observations prove route viability. # Missing legacy State and PersistentStore retain every tier; # no dead/probing route can hide a changed working exit. $levels=[Collections.Generic.List[object]]::new() $paths=[Collections.Generic.List[string]]::new();$score=$null foreach($candidate in @($groups[$groupKey] | Sort-Object { $_.Score }, { $_.Path })){ if($null -ne $score -and $candidate.Score -ne $score){ $levels.Add(@($paths.ToArray() | Sort-Object -Unique));$paths.Clear() } $score=$candidate.Score;$paths.Add($candidate.Path) } $levels.Add(@($paths.ToArray() | Sort-Object -Unique)) $set[$groupKey]=if($stateProven -and $groupKey.StartsWith('ActiveStore|',[StringComparison]::Ordinal)){@($levels[0])}else{@($levels.ToArray())} } $rankings+=,$set } return Test-PNBEqual $rankings[0] $rankings[1] } catch { return $false } } function Assert-PNBPath([string]$Path) { # A drive-qualified canonical local path is required. UNC, device paths, # ADS, relative paths and lexical parent traversal are not trusted inputs. if ($Path -cnotmatch '^[A-Za-z]:\\[^:]*$' -or $Path -match '(^|\\)\.\.?($|\\)' -or [IO.Path]::GetFullPath($Path) -cne $Path -or $Path.TrimEnd('\') -cne $Path) { throw 'Unknown or noncanonical evidence path' } } function Assert-PNBPathChain([string]$Path) { Assert-PNBPath $Path $part=$Path while ($part) { if (Test-Path -LiteralPath $part -ErrorAction Stop) { $item=Get-Item -LiteralPath $part -Force -ErrorAction Stop if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Reparse point in evidence path' } } $part=[IO.Path]::GetDirectoryName($part) } } function Get-PNBFileEvidence([string]$Path) { Assert-PNBPathChain $Path if (-not (Test-Path -LiteralPath $Path -ErrorAction Stop)) { return [ordered]@{ Exists=$false; Sha256=$null } } $item=Get-Item -LiteralPath $Path -Force -ErrorAction Stop if ($item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw 'Unverifiable data file' } return [ordered]@{ Exists=$true; Sha256=(Get-FileHash -LiteralPath $Path -Algorithm SHA256 -ErrorAction Stop).Hash.ToLowerInvariant() } } function New-PNBProxyValue([string]$Name, [bool]$Exists, [string]$Kind, $Value) { return [ordered]@{ Name=$Name; Exists=$Exists; Kind=$(if($Exists){$Kind}else{$null}); ValueSha256=$(if($Exists){Get-PNBJsonHash $Value}else{$null}) } } function Get-PNBRouteKey($Route) { return '{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}' -f $Route.PolicyStore,$Route.AddressFamily,$Route.DestinationPrefix,$Route.InterfaceIndex,$Route.NextHop,$Route.CompartmentId,$Route.RouteMetric,$Route.Protocol } function Get-PNBOwnedDeviceId { $bytes=[Security.Cryptography.MD5]::HashData([Text.Encoding]::UTF8.GetBytes('UCVL VPNPlus')) return 'SWD\Wintun\{'+([guid]::new($bytes)).ToString().ToUpperInvariant()+'}' } function Test-PNBOwnedAdapter($Adapter) { return $Adapter.PnPDeviceID -ieq (Get-PNBOwnedDeviceId) } function Convert-PNBJournalRoute($Route) { Assert-PNBFields $Route @('Destination','Mask','NextHop','InterfaceIndex','Metric') 'route journal' foreach ($name in @('Destination','Mask','NextHop')) { $ip=$null if (-not [Net.IPAddress]::TryParse([string]$Route[$name],[ref]$ip) -or $ip.AddressFamily -ne [Net.Sockets.AddressFamily]::InterNetwork) { throw 'Invalid route journal address' } } if (-not (Test-PNBInteger $Route.InterfaceIndex 1) -or -not (Test-PNBInteger $Route.Metric 0)) { throw 'Invalid route journal interface/metric' } $bits=([Net.IPAddress]::Parse($Route.Mask).GetAddressBytes() | ForEach-Object { [Convert]::ToString($_,2).PadLeft(8,'0') }) -join '' if ($bits -notmatch '^1*0*$') { throw 'Noncontiguous journal mask' } $prefix=($bits -replace '0','').Length # This client uses the default native IPv4 route table (compartment 1). # Never infer ownership of a matching route in another compartment/store. $addressBytes=[Net.IPAddress]::Parse($Route.Destination).GetAddressBytes() $maskBytes=[Net.IPAddress]::Parse($Route.Mask).GetAddressBytes() for($i=0;$i -lt 4;$i++){if(($addressBytes[$i] -band $maskBytes[$i]) -ne $addressBytes[$i]){throw 'Noncanonical journal destination'}} return 'ActiveStore|IPv4|{0}/{1}|{2}|{3}|1|{4}|NetMgmt' -f $Route.Destination,$prefix,$Route.InterfaceIndex,$Route.NextHop,$Route.Metric } function Get-PNBJournalRouteKeys($Journal,[array]$Routes,[array]$OwnedAdapters) { if($null -eq $Journal){return ,@()} if($Journal.Contains('SchemaVersion')){ Assert-PNBFields $Journal @('SchemaVersion','Routes') 'route journal' if($Journal.SchemaVersion -ne 2 -or $Journal.Routes -isnot [array]){throw 'Unknown route journal schema'} $keys=@($Journal.Routes | ForEach-Object {Convert-PNBJournalRoute $_} | Sort-Object) }else{ # The still-shipped PUBLIC transport writes TunState, whereas private/ # tailnet transport writes NetworkRouteLease v2 to the SAME file. This # is not a separate journal. Bind legacy intent to exact observed paths; # never authorize deletion merely from a destination or adapter name. Assert-PNBFields $Journal @('InterfaceIndex','PhysicalInterfaceIndex','BypassIpv4Addresses','Ipv4RoutesAdded','Ipv6RoutesAdded') 'legacy route journal' if($Journal.Count -ne 5 -or -not(Test-PNBInteger $Journal.InterfaceIndex 1) -or -not(Test-PNBInteger $Journal.PhysicalInterfaceIndex 1) -or $Journal.InterfaceIndex -eq $Journal.PhysicalInterfaceIndex -or $Journal.BypassIpv4Addresses -isnot [array] -or $Journal.Ipv4RoutesAdded -isnot [bool] -or $Journal.Ipv6RoutesAdded -isnot [bool] -or $Journal.Ipv6RoutesAdded){throw 'Unsupported legacy route intent'} if($OwnedAdapters.Count -ne 1 -or -not(Test-PNBOwnedAdapter $OwnedAdapters[0]) -or $OwnedAdapters[0].InterfaceIndex -ne $Journal.InterfaceIndex){throw 'Legacy journal lacks exact owned adapter'} $destinations=@($Journal.BypassIpv4Addresses) foreach($ip in $destinations){Assert-PNBAddress $ip 'IPv4'} if(@($destinations | Sort-Object -Unique).Count -ne $destinations.Count){throw 'Duplicate legacy bypass intent'} $keys=@(foreach($route in $Routes){ $split=$route.InterfaceIndex -eq $Journal.InterfaceIndex -and $route.DestinationPrefix -in @('0.0.0.0/1','128.0.0.0/1') $bypass=$route.InterfaceIndex -eq $Journal.PhysicalInterfaceIndex -and $route.DestinationPrefix -in @($destinations | ForEach-Object {$_+'/32'}) if(-not($split -or $bypass) -or $route.PolicyStore -ne 'ActiveStore' -or $route.CompartmentId -ne 1){continue} if($route.AddressFamily -ne 'IPv4' -or $route.Protocol -ne 'NetMgmt' -or ($split -and ($route.NextHop -ne '0.0.0.0' -or $route.RouteMetric -ne 5)) -or ($bypass -and $route.RouteMetric -ne 1)){throw 'Legacy route differs from client-owned path'} if($bypass -and $route.NextHop -ne '0.0.0.0'){ $gateways=@($Routes | Where-Object { $_.PolicyStore -eq 'ActiveStore' -and $_.CompartmentId -eq 1 -and $_.InterfaceIndex -eq $Journal.PhysicalInterfaceIndex -and $_.DestinationPrefix -eq '0.0.0.0/0' -and $_.NextHop -eq $route.NextHop }) if($gateways.Count -ne 1){throw 'Legacy bypass gateway cannot be verified'} } Get-PNBRouteKey $route }) foreach($destination in $destinations){ if(@($keys | Where-Object { $_ -like ('ActiveStore|IPv4|'+$destination+'/32|*') }).Count -gt 1){throw 'Ambiguous legacy bypass path'} } } if(@($keys | Sort-Object -Unique).Count -ne $keys.Count){throw 'Duplicate route journal identities'} return ,@($keys | Sort-Object) } function Get-PNBOwnedLocalRouteKeys([array]$Routes,[array]$OwnedAdapters,[array]$OwnedAddresses) { # Windows creates link-local, multicast and broadcast routes during the # dedicated Wintun device lifecycle. Match only those exact OS paths, not # all routes on this interface; foreign static/unicast routes still refuse. if($OwnedAdapters.Count -eq 0){if($OwnedAddresses.Count){throw 'Owned address lacks adapter'};return ,@()} if($OwnedAdapters.Count -ne 1 -or -not(Test-PNBOwnedAdapter $OwnedAdapters[0])){throw 'Unproven local-route adapter'} $index=$OwnedAdapters[0].InterfaceIndex $prefixes=@('IPv4|224.0.0.0/4','IPv4|255.255.255.255/32','IPv4|127.255.255.255/32','IPv6|ff00::/8') foreach($address in $OwnedAddresses){ Assert-PNBFields $address @('InterfaceIndex','AddressFamily','IPAddress','PrefixLength','CompartmentId') 'owned link address' if($address.InterfaceIndex -ne $index -or $address.CompartmentId -ne 1){throw 'Unknown owned address interface/compartment'} Assert-PNBAddress $address.IPAddress $address.AddressFamily $ip=[Net.IPAddress]::Parse($address.IPAddress);$bytes=$ip.GetAddressBytes() if($address.AddressFamily -eq 'IPv4' -and $bytes[0] -eq 169 -and $bytes[1] -eq 254 -and $address.PrefixLength -eq 16){ $prefixes+=@('IPv4|169.254.0.0/16','IPv4|169.254.255.255/32',('IPv4|'+$ip.ToString()+'/32')) }elseif($address.AddressFamily -eq 'IPv6' -and $ip.IsIPv6LinkLocal -and $address.PrefixLength -eq 64){ $hostAddress=[Net.IPAddress]::new($bytes).ToString() [Array]::Clear($bytes,8,8);$network=[Net.IPAddress]::new($bytes).ToString() $prefixes+=@(('IPv6|'+$network+'/64'),('IPv6|'+$hostAddress+'/128')) }else{throw 'Unexpected address on owned Wintun device'} } return ,@($Routes | Where-Object { $_.InterfaceIndex -eq $index -and $_.PolicyStore -eq 'ActiveStore' -and $_.CompartmentId -eq 1 -and $_.Protocol -eq 'Local' -and $_.RouteMetric -eq 256 -and $_.NextHop -eq $(if($_.AddressFamily -eq 'IPv4'){'0.0.0.0'}else{'::'}) -and ($_.AddressFamily+'|'+$_.DestinationPrefix) -in $prefixes } | ForEach-Object {Get-PNBRouteKey $_} | Sort-Object) } function Read-PNBJsonJournal([string]$Path, $Evidence) { if (-not $Evidence.Exists) { return $null } Assert-PNBPathChain $Path $info=Get-Item -LiteralPath $Path -ErrorAction Stop if ($info.Length -gt 1048576) { throw 'Recovery journal exceeds diagnostic limit' } $bytes=[IO.File]::ReadAllBytes($Path) if ((Get-PNBHash $bytes) -cne $Evidence.Sha256) { throw 'Recovery journal changed while sampling' } return ([Text.Encoding]::UTF8.GetString($bytes) | ConvertFrom-Json -AsHashtable -ErrorAction Stop) } function Assert-PNBFields($Value,[string[]]$Names,[string]$Label) { if ($Value -isnot [Collections.IDictionary]) { throw "Invalid $Label object" } foreach($name in $Names){if(-not $Value.Contains($name)){throw "Incomplete ${Label}: $name"}} } function Test-PNBInteger($Value,[long]$Minimum) { return ($Value -is [int] -or $Value -is [long]) -and $Value -ge $Minimum } function Assert-PNBAddress([string]$Value,[string]$Family) { $address=$null $expected=if($Family -in @('IPv4','2')){[Net.Sockets.AddressFamily]::InterNetwork}elseif($Family -in @('IPv6','23')){[Net.Sockets.AddressFamily]::InterNetworkV6}else{throw 'Unknown address family'} if(-not [Net.IPAddress]::TryParse($Value,[ref]$address) -or $address.AddressFamily -ne $expected){throw 'Invalid network address evidence'} } function Assert-PNBProcess($Process) { Assert-PNBFields $Process @('Name','Pid','StartTicks','SessionId','Path','OwnerSid') 'process identity' if([string]::IsNullOrWhiteSpace($Process.Name) -or -not (Test-PNBInteger $Process.Pid 1) -or -not (Test-PNBInteger $Process.StartTicks 1) -or -not (Test-PNBInteger $Process.SessionId 0) -or $Process.OwnerSid -cnotmatch '^S-1-\d+(?:-\d+)+$'){throw 'Unverifiable process identity'} Assert-PNBPath $Process.Path if([IO.Path]::GetFileName($Process.Path) -ine ($Process.Name+'.exe')){throw 'Process name/path mismatch'} } function Get-PNBOwnedNrptKeys($Nrpt,$Journal) { $owned=@($Nrpt | Where-Object Comment -ceq 'UCVL.VPNPlus.ProxyDNS.v1') if($null -eq $Journal){if($owned.Count){throw 'Owned NRPT marker lacks journal'};return ,@()} Assert-PNBFields $Journal @('owner','names') 'NRPT journal' if($Journal.owner -cne 'UCVL.VPNPlus.ProxyDNS.v1' -or $Journal.names -isnot [array] -or @($Journal.names).Count -eq 0){throw 'Unknown NRPT journal'} $names=@($Journal.names | Sort-Object -Unique) if($names.Count -ne $Journal.names.Count -or @($names | Where-Object {$_ -isnot [string] -or $_ -cnotmatch '^\.?[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+$'}).Count){throw 'Invalid NRPT namespaces'} if($owned.Count -gt 1){throw 'Ambiguous owned NRPT instances'} if($owned.Count -and (-not (Test-PNBEqual @($owned[0].Namespace | Sort-Object) $names) -or -not (Test-PNBEqual @($owned[0].NameServers | Sort-Object) @('1.1.1.1','8.8.8.8')))){throw 'NRPT marker does not prove this rule is owned'} return ,@($owned | ForEach-Object {Get-PNBJsonHash $_}) } function Get-PNBAddressFamily($Value) { switch -CaseSensitive ([string]$Value) { 'IPv4' {return 'IPv4'} '2' {return 'IPv4'} 'IPv6' {return 'IPv6'} '23' {return 'IPv6'} default {throw 'Unknown sampled address family'} } } function Convert-PNBNameServers([array]$Values) { return ,@($Values | ForEach-Object { # NRPT CIM exposes System.Net.IPAddress, not strings, on this host. # Hashing its object properties would miscompare a correct owned rule. $address=$null if(-not [Net.IPAddress]::TryParse([string]$_,[ref]$address)){throw 'Invalid NRPT server address'} $address.ToString() } | Sort-Object) } function Get-PNBAddressCompartment($Address,[array]$Interfaces) { # MSFT_NetIPAddress has no CompartmentId on supported Windows builds. # Derive only from a unique exact interface-index/family binding. Never # assume the default compartment when association is absent/ambiguous. $family=Get-PNBAddressFamily $Address.AddressFamily $matches=@($Interfaces | Where-Object { $_.InterfaceIndex -eq $Address.InterfaceIndex -and (Get-PNBAddressFamily $_.AddressFamily) -eq $family }) if($matches.Count -ne 1 -or $null -eq $matches[0].CompartmentId -or [long]$matches[0].CompartmentId -lt 1){throw 'Address compartment association is missing or ambiguous'} return [int]$matches[0].CompartmentId } function Select-PNBObservedProcesses([array]$Processes,[array]$VerifiedInstallerHelpers=@()) { # Only the independent observer may supply helpers after its live identity, # image, parent and Job checks. Retain the evidence; project exact identities # out of the proxy-owner list, never a name/path pattern. $remaining=[Collections.Generic.List[object]]::new() foreach($helper in $VerifiedInstallerHelpers){ Assert-PNBProcess $helper Assert-PNBFields $helper @('Sha256','ParentPid','ParentStartTicks','JobName','JobMembershipVerified') 'installer helper' if($helper.Name -cne 'VPNPlus' -or $helper.Sha256 -cnotmatch '^[A-Fa-f0-9]{64}$' -or -not(Test-PNBInteger $helper.ParentPid 1) -or -not(Test-PNBInteger $helper.ParentStartTicks 1) -or $helper.JobName -cnotmatch '^Local\\UCVL-Maintenance-[a-f0-9]{32}$' -or $helper.JobMembershipVerified -isnot [bool] -or -not $helper.JobMembershipVerified){throw 'Unverified installer helper'} $matches=@($Processes | Where-Object {Test-PNBEqual $_ $helper}) if($matches.Count -ne 1){throw 'Exact installer helper missing from process sample'} } if(@($VerifiedInstallerHelpers | ForEach-Object Pid | Sort-Object -Unique).Count -ne $VerifiedInstallerHelpers.Count){throw 'Duplicate installer helper identity'} foreach($process in $Processes){ if(-not @($VerifiedInstallerHelpers | Where-Object {Test-PNBEqual $_ $process}).Count){$remaining.Add($process)} } return ,$remaining.ToArray() } function Get-ProductionNetworkObservation { [CmdletBinding()] param([array]$VerifiedInstallerHelpers=@()) # Intentionally no caller-selected account/data root: production recovery # must inspect the same HKCU/LocalAppData used by the recovered client. $started=[DateTimeOffset]::UtcNow $identity=[Security.Principal.WindowsIdentity]::GetCurrent() $data=Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) 'UCVL\VPNPlus' Assert-PNBPathChain $data $userFiles=[ordered]@{} foreach ($name in @('session.bin','device-id.txt','settings.json','client-settings.json')) { $userFiles[$name]=Get-PNBFileEvidence (Join-Path $data $name) } $journals=[ordered]@{} foreach ($name in @('tun-state.json','proxy-state.json','proxy-dns-owned.json','xray.pid')) { $journals[$name]=Get-PNBFileEvidence (Join-Path $data $name) } $key=[Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Software\Microsoft\Windows\CurrentVersion\Internet Settings') if (-not $key) { throw 'Cannot read current-user proxy configuration' } $proxy=@();$rawProxy=@{} try { foreach ($name in @('ProxyEnable','ProxyServer','ProxyOverride','AutoConfigURL','AutoDetect')) { $exists=$name -in $key.GetValueNames() $value=if($exists){$key.GetValue($name,$null,[Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)}else{$null} $kind=if($exists){$key.GetValueKind($name).ToString()}else{''} $rawProxy[$name]=$value $proxy+=New-PNBProxyValue $name $exists $kind $value } } finally { $key.Dispose() } $expectedProxy=Copy-PNBObject $proxy $proxyJournal=Read-PNBJsonJournal (Join-Path $data 'proxy-state.json') $journals['proxy-state.json'] if ($null -ne $proxyJournal) { foreach($name in @('ProxyEnable','HadProxyServer','ProxyServer','HadProxyOverride','ProxyOverride')) { if(-not $proxyJournal.Contains($name)){throw 'Incomplete proxy journal'} } if ($proxyJournal.ProxyEnable -notin @(0,1) -or $proxyJournal.HadProxyServer -isnot [bool] -or $proxyJournal.HadProxyOverride -isnot [bool]) { throw 'Invalid proxy journal' } # Do not probe/normalize a previous loopback proxy here. If recovery # legitimately normalizes it, an exact mismatch requires explicit review. $expectedProxy=@($proxy | Where-Object Name -notin @('ProxyEnable','ProxyServer','ProxyOverride')) + @( (New-PNBProxyValue 'ProxyEnable' $true 'DWord' ([int]$proxyJournal.ProxyEnable)), (New-PNBProxyValue 'ProxyServer' $proxyJournal.HadProxyServer 'String' $(if($null -eq $proxyJournal.ProxyServer){''}else{$proxyJournal.ProxyServer})), (New-PNBProxyValue 'ProxyOverride' $proxyJournal.HadProxyOverride 'String' $(if($null -eq $proxyJournal.ProxyOverride){''}else{$proxyJournal.ProxyOverride}))) } $tunJournal=Read-PNBJsonJournal (Join-Path $data 'tun-state.json') $journals['tun-state.json'] $adapters=@(Get-NetAdapter -IncludeHidden -ErrorAction Stop | ForEach-Object { [ordered]@{ Name=$_.Name; InterfaceIndex=[int]$_.InterfaceIndex; InterfaceGuid=[string]$_.InterfaceGuid; Status=[string]$_.Status; PnPDeviceID=[string]$_.PnPDeviceID } }) $ownedAdapters=@($adapters | Where-Object { Test-PNBOwnedAdapter $_ }) $ownedDevices=@(Get-PnpDevice -Class Net -PresentOnly -ErrorAction Stop | Where-Object InstanceId -eq (Get-PNBOwnedDeviceId) | ForEach-Object { [ordered]@{ InstanceId=$_.InstanceId; Status=[string]$_.Status } }) $ownedIf=@($ownedAdapters | ForEach-Object { $_.InterfaceIndex }) $routes=@(foreach($store in @('ActiveStore','PersistentStore')) { foreach($r in @(Get-NetRoute -PolicyStore $store -IncludeAllCompartments -ErrorAction Stop)) { [ordered]@{ PolicyStore=$store; AddressFamily=[string]$r.AddressFamily; DestinationPrefix=$r.DestinationPrefix; InterfaceIndex=[int]$r.InterfaceIndex; NextHop=$r.NextHop; RouteMetric=[int]$r.RouteMetric; CompartmentId=[int]$r.CompartmentId; Protocol=[string]$r.Protocol; State=[string]$r.State } } }) $ownedRouteKeys=Get-PNBJournalRouteKeys $tunJournal $routes $ownedAdapters $dns=@(Get-DnsClientServerAddress -ErrorAction Stop | Where-Object InterfaceIndex -notin $ownedIf | ForEach-Object { [ordered]@{ InterfaceIndex=[int]$_.InterfaceIndex; AddressFamily=(Get-PNBAddressFamily $_.AddressFamily); ServerAddresses=@($_.ServerAddresses) } }) $nrpt=@(Get-DnsClientNrptRule -ErrorAction Stop | ForEach-Object { [ordered]@{ Name=$_.Name; Namespace=@($_.Namespace | Sort-Object); NameServers=(Convert-PNBNameServers @($_.NameServers)); Comment=$_.Comment } }) $dnsJournal=Read-PNBJsonJournal (Join-Path $data 'proxy-dns-owned.json') $journals['proxy-dns-owned.json'] $ownedNrptKeys=Get-PNBOwnedNrptKeys $nrpt $dnsJournal $allInterfaces=@(Get-NetIPInterface -IncludeAllCompartments -ErrorAction Stop | ForEach-Object { [ordered]@{ InterfaceIndex=[int]$_.InterfaceIndex; AddressFamily=(Get-PNBAddressFamily $_.AddressFamily); Dhcp=[string]$_.Dhcp; ConnectionState=[string]$_.ConnectionState; InterfaceMetric=[int]$_.InterfaceMetric; CompartmentId=[int]$_.CompartmentId; AutomaticMetric=[string]$_.AutomaticMetric } }) $allAddresses=@(Get-NetIPAddress -IncludeAllCompartments -ErrorAction Stop | ForEach-Object { [ordered]@{ InterfaceIndex=[int]$_.InterfaceIndex; AddressFamily=(Get-PNBAddressFamily $_.AddressFamily); IPAddress=$_.IPAddress; PrefixLength=[int]$_.PrefixLength; AddressState=[string]$_.AddressState; PrefixOrigin=[string]$_.PrefixOrigin; SuffixOrigin=[string]$_.SuffixOrigin; CompartmentId=(Get-PNBAddressCompartment $_ $allInterfaces) } }) $interfaces=@($allInterfaces | Where-Object InterfaceIndex -notin $ownedIf) $addresses=@($allAddresses | Where-Object InterfaceIndex -notin $ownedIf) $ownedAddresses=@($allAddresses | Where-Object InterfaceIndex -in $ownedIf) $ownedLocalRouteKeys=Get-PNBOwnedLocalRouteKeys $routes $ownedAdapters $ownedAddresses # Registry evidence for WinHTTP is hashed, not formatted/localized netsh output. $winHttp=@() foreach($hive in @([Microsoft.Win32.Registry]::LocalMachine,[Microsoft.Win32.Registry]::CurrentUser)) { $h=$hive.OpenSubKey('Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections') try { $exists=$null -ne $h -and 'WinHttpSettings' -in $h.GetValueNames() $winHttp+=New-PNBProxyValue $hive.Name $exists 'Binary' $(if($exists){$h.GetValue('WinHttpSettings')}else{$null}) } finally { if($h){$h.Dispose()} } } # Materialize selection before identity checks. A simplified Where-Object # operator can wrap downstream failures as OperatorFailed and hide the # original rejecting line. This changes diagnostics, not acceptance rules. $script:PNBProcessDiagnostic=[ordered]@{Stage='process-enumeration';Pid=$null;Path=$null;StartTicks=$null;CimPath=$null;CimStartTicks=$null} $namedProxyProcesses=@(Get-Process -ErrorAction Stop | Where-Object ProcessName -in @('VPNPlus','xray','mihomo','Clash','clash-verge')) $processes=@(foreach($process in $namedProxyProcesses){ # Cannot inspect an owner means cannot prove an idle machine. Never kill it. # Reset before reading even the PID so a failed accessor cannot leave # diagnostic fields from a previous process or observation behind. $script:PNBProcessDiagnostic=[ordered]@{Stage='process-id';Pid=$null;Path=$null;StartTicks=$null;CimPath=$null;CimStartTicks=$null} $script:PNBProcessDiagnostic.Pid=$process.Id $script:PNBProcessDiagnostic.Stage='process-path' $script:PNBProcessDiagnostic.Path=$process.Path if(-not $process.Path){throw 'Cannot identify an existing proxy process'} $script:PNBProcessDiagnostic.Stage='process-start' $ticks=$process.StartTime.ToUniversalTime().Ticks $script:PNBProcessDiagnostic.StartTicks=$ticks $script:PNBProcessDiagnostic.Stage='process-cim' $cim=Get-CimInstance -ClassName Win32_Process -Filter ('ProcessId='+$process.Id) -ErrorAction Stop if($cim){$script:PNBProcessDiagnostic.CimPath=$cim.ExecutablePath;$script:PNBProcessDiagnostic.CimStartTicks=$cim.CreationDate.ToUniversalTime().Ticks} # CIM timestamps have microsecond precision; the before/after process # handles below retain the exact 100 ns creation-time identity. $script:PNBProcessDiagnostic.Stage='process-cim-identity' if($null -eq $cim -or $cim.ExecutablePath -ine $process.Path -or $cim.CreationDate.ToUniversalTime().Ticks -ne ($ticks-($ticks%10))){throw 'Process changed while sampling owner'} $script:PNBProcessDiagnostic.Stage='process-owner' $owner=Invoke-CimMethod -InputObject $cim -MethodName GetOwnerSid -ErrorAction Stop if($owner.ReturnValue -ne 0 -or -not $owner.Sid){throw 'Cannot identify process owner SID'} $script:PNBProcessDiagnostic.Stage='process-recheck' $again=Get-Process -Id $process.Id -ErrorAction Stop if($again.StartTime.ToUniversalTime().Ticks -ne $ticks -or $again.Path -ine $process.Path){throw 'Process identity changed while sampling'} $script:PNBProcessDiagnostic.Stage='process-row' $row=[ordered]@{ Name=$process.ProcessName; Pid=$process.Id; StartTicks=$ticks; SessionId=$process.SessionId; Path=$process.Path; OwnerSid=[string]$owner.Sid } $script:PNBProcessDiagnostic.Stage='process-helper' $helper=@($VerifiedInstallerHelpers | Where-Object Pid -eq $process.Id) if($helper.Count){ if($helper.Count -ne 1){throw 'Duplicate installer helper identity'} if(-not [UCVL.Maintenance.OwnedProcessGroup]::SameImageFile($helper[0].Path,$process.Path)){throw 'Installer helper canonical image changed'} $row.Path=$helper[0].Path $row.Sha256=(Get-PNBFileEvidence $row.Path).Sha256 $row.ReportedPath=$process.Path;$row.CimPath=$cim.ExecutablePath $row.ParentPid=[int]$cim.ParentProcessId $script:PNBProcessDiagnostic.Stage='process-helper-parent' $parent=Get-Process -Id $row.ParentPid -ErrorAction Stop try{$row.ParentStartTicks=$parent.StartTime.ToUniversalTime().Ticks}finally{$parent.Dispose()} $row.JobName=$helper[0].JobName $script:PNBProcessDiagnostic.Stage='process-helper-job' $row.JobMembershipVerified=[UCVL.Maintenance.OwnedProcessGroup]::VerifyMembership($row.JobName,$row.Pid,$row.StartTicks) } $script:PNBProcessDiagnostic.Stage='process-complete' $row }) $proxyProcesses=Select-PNBObservedProcesses $processes $VerifiedInstallerHelpers $observation=[ordered]@{ Schema=1; Kind='production-network-observation'; StartedAt=$started.ToString('O'); CapturedAt=[DateTimeOffset]::UtcNow.ToString('O'); Context=[ordered]@{ UserSid=$identity.User.Value; SessionId=(Get-Process -Id $PID).SessionId; Elevated=([Security.Principal.WindowsPrincipal]::new($identity)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator); DataDirectory=$data }; Processes=(Sort-PNBRows $proxyProcesses); ExcludedInstallerHelpers=(Sort-PNBRows $VerifiedInstallerHelpers); OwnedAdapters=(Sort-PNBRows $ownedAdapters); OwnedDevices=(Sort-PNBRows $ownedDevices); OwnedAddresses=(Sort-PNBRows $ownedAddresses); OwnedLocalRouteKeys=$ownedLocalRouteKeys; OwnedInterfaces=(Sort-PNBRows @($allInterfaces | Where-Object InterfaceIndex -in $ownedIf)); PhysicalAdapters=(Sort-PNBRows @($adapters | Where-Object InterfaceIndex -notin $ownedIf)); PhysicalAddresses=(Sort-PNBRows $addresses); PhysicalInterfaces=(Sort-PNBRows $interfaces); Proxy=(Sort-PNBRows $proxy); ExpectedRestoredProxy=(Sort-PNBRows $expectedProxy); WinHttp=(Sort-PNBRows $winHttp); OwnedProxyEnabled=([int]$rawProxy['ProxyEnable'] -ne 0 -and [string]$rawProxy['ProxyServer'] -match '(?i)(localhost|127\.0\.0\.1):(10808|10809)(?:[;/]|$)'); Routes=(Sort-PNBRows $routes); PhysicalDns=(Sort-PNBRows $dns); Nrpt=(Sort-PNBRows $nrpt); OwnedRouteKeys=$ownedRouteKeys; OwnedNrptKeys=$ownedNrptKeys; UserFileHashes=$userFiles; Journals=$journals } # Detect changes to recovery intent/user data while a multi-query snapshot # was being collected. No token/settings bytes are included in the result. foreach($name in $journals.Keys) { if(-not (Test-PNBEqual $journals[$name] (Get-PNBFileEvidence (Join-Path $data $name)))){throw 'Recovery intent changed during observation'} } foreach($name in $userFiles.Keys) { if(-not (Test-PNBEqual $userFiles[$name] (Get-PNBFileEvidence (Join-Path $data $name)))){throw 'User data changed during observation'} } Assert-PNBObservation $observation return $observation } function Assert-PNBObservation($Observation) { $required=@('Schema','Kind','StartedAt','CapturedAt','Context','Processes','OwnedAdapters','OwnedDevices','OwnedAddresses','OwnedLocalRouteKeys','PhysicalAdapters','PhysicalAddresses','PhysicalInterfaces','Proxy','ExpectedRestoredProxy','OwnedProxyEnabled','WinHttp','Routes','PhysicalDns','Nrpt','OwnedRouteKeys','OwnedNrptKeys','UserFileHashes','Journals') Assert-PNBFields $Observation $required 'observation' Assert-PNBFields $Observation.Context @('UserSid','SessionId','Elevated','DataDirectory') 'account context' if($Observation.Schema -ne 1 -or $Observation.Kind -cne 'production-network-observation' -or $Observation.Context.Elevated -isnot [bool] -or -not $Observation.Context.Elevated){throw 'Invalid or non-elevated observation'} if($Observation.Context.UserSid -cnotmatch '^S-1-\d+(?:-\d+)+$' -or -not (Test-PNBInteger $Observation.Context.SessionId 0) -or $Observation.OwnedProxyEnabled -isnot [bool]){throw 'Invalid account/proxy evidence'} Assert-PNBPath $Observation.Context.DataDirectory foreach($field in @('StartedAt','CapturedAt')){if($Observation[$field] -isnot [string] -or $Observation[$field] -notmatch '(Z|[+-]\d\d:\d\d)$'){throw 'Unqualified observation time'}} if([DateTimeOffset]$Observation.CapturedAt -lt [DateTimeOffset]$Observation.StartedAt){throw 'Inverted observation interval'} foreach($field in @('Processes','OwnedAdapters','OwnedDevices','OwnedAddresses','OwnedLocalRouteKeys','PhysicalAdapters','PhysicalAddresses','PhysicalInterfaces','Proxy','ExpectedRestoredProxy','WinHttp','Routes','PhysicalDns','Nrpt','OwnedRouteKeys','OwnedNrptKeys')){ if($Observation[$field] -isnot [array]){throw "Invalid observation array: $field"} } foreach($p in $Observation.Processes){Assert-PNBProcess $p} if(@($Observation.Processes | ForEach-Object Pid | Sort-Object -Unique).Count -ne $Observation.Processes.Count){throw 'Duplicate process identities'} foreach($a in @($Observation.OwnedAdapters)+@($Observation.PhysicalAdapters)){ Assert-PNBFields $a @('Name','InterfaceIndex','InterfaceGuid','Status','PnPDeviceID') 'adapter' # Foreign OS pseudo-adapters (Teredo/6to4/IP-HTTPS) can lack PnP IDs. # Retain their GUID/index/status as comparison-only evidence. Ownership # below still requires our exact, nonempty fixed Wintun PnP ID. if(-not (Test-PNBInteger $a.InterfaceIndex 1) -or [string]::IsNullOrWhiteSpace($a.InterfaceGuid) -or $a.PnPDeviceID -isnot [string]){throw 'Unverifiable adapter identity'} } if($Observation.OwnedAdapters.Count -gt 1){throw 'Ambiguous owned adapter identities'} foreach($a in $Observation.OwnedAdapters){if(-not (Test-PNBOwnedAdapter $a)){throw 'Unknown adapter claimed as owned'}} foreach($a in $Observation.PhysicalAdapters){if((Test-PNBOwnedAdapter $a) -or $a.Name -like 'UCVL VPNPlus*'){throw 'Unknown or misclassified owned adapter'}} foreach($a in $Observation.OwnedDevices){Assert-PNBFields $a @('InstanceId','Status') 'owned device';if($a.InstanceId -ine (Get-PNBOwnedDeviceId)){throw 'Unknown device claimed as owned'}} if(@(@($Observation.OwnedAdapters)+@($Observation.PhysicalAdapters) | ForEach-Object InterfaceIndex | Sort-Object -Unique).Count -ne ($Observation.OwnedAdapters.Count+$Observation.PhysicalAdapters.Count)){throw 'Duplicate adapter index'} foreach($field in @('PhysicalAddresses','PhysicalInterfaces','PhysicalDns')){ foreach($row in $Observation[$field]){ $fields=switch($field){ 'PhysicalAddresses' {@('InterfaceIndex','AddressFamily','IPAddress','PrefixLength','AddressState','PrefixOrigin','SuffixOrigin','CompartmentId')} 'PhysicalInterfaces' {@('InterfaceIndex','AddressFamily','Dhcp','ConnectionState','InterfaceMetric','CompartmentId')} 'PhysicalDns' {@('InterfaceIndex','AddressFamily','ServerAddresses')} } Assert-PNBFields $row $fields $field if(-not (Test-PNBInteger $row.InterfaceIndex 1) -or $row.InterfaceIndex -in @($Observation.OwnedAdapters | ForEach-Object InterfaceIndex)){throw 'Misclassified interface evidence'} if($field -eq 'PhysicalDns'){ if($row.ServerAddresses -isnot [array] -or $row.AddressFamily -notin @('IPv4','IPv6','2','23')){throw 'Invalid DNS evidence'} foreach($address in $row.ServerAddresses){Assert-PNBAddress $address $row.AddressFamily} }else{ if(-not (Test-PNBInteger $row.CompartmentId 1) -or $row.AddressFamily -notin @('IPv4','IPv6')){throw 'Invalid interface compartment/family'} if($field -eq 'PhysicalAddresses'){ Assert-PNBAddress $row.IPAddress $row.AddressFamily $limit=if($row.AddressFamily -eq 'IPv4'){32}else{128} if(-not (Test-PNBInteger $row.PrefixLength 0) -or $row.PrefixLength -gt $limit){throw 'Invalid address prefix'} }elseif(-not (Test-PNBInteger $row.InterfaceMetric 0)){throw 'Invalid interface metric'} if($field -eq 'PhysicalInterfaces' -and $row.Contains('AutomaticMetric') -and $row.AutomaticMetric -cnotin @('Enabled','Disabled')){throw 'Invalid automatic metric mode'} } } } if($Observation.Contains('OwnedInterfaces')){ if($Observation.OwnedInterfaces -isnot [array]){throw 'Invalid owned interface metrics'} $ownedMetricKeys=[Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) foreach($row in $Observation.OwnedInterfaces){ Assert-PNBFields $row @('InterfaceIndex','AddressFamily','Dhcp','ConnectionState','InterfaceMetric','CompartmentId','AutomaticMetric') 'owned interface metrics' if(-not(Test-PNBInteger $row.InterfaceIndex 1) -or -not(Test-PNBInteger $row.CompartmentId 1) -or -not(Test-PNBInteger $row.InterfaceMetric 0) -or $row.AddressFamily -cnotin @('IPv4','IPv6') -or $row.AutomaticMetric -cnotin @('Enabled','Disabled') -or @($Observation.OwnedAdapters | Where-Object InterfaceIndex -eq $row.InterfaceIndex).Count -ne 1 -or -not $ownedMetricKeys.Add(('{0}|{1}|{2}' -f $row.CompartmentId,$row.AddressFamily,$row.InterfaceIndex))){throw 'Unbound owned interface metrics'} } } foreach($row in $Observation.Routes){ Assert-PNBFields $row @('PolicyStore','AddressFamily','DestinationPrefix','InterfaceIndex','NextHop','RouteMetric','CompartmentId','Protocol') 'route' if($row.PolicyStore -notin @('ActiveStore','PersistentStore') -or $row.AddressFamily -notin @('IPv4','IPv6') -or -not (Test-PNBInteger $row.InterfaceIndex 1) -or -not (Test-PNBInteger $row.RouteMetric 0) -or -not (Test-PNBInteger $row.CompartmentId 1) -or [string]::IsNullOrWhiteSpace($row.Protocol)){throw 'Invalid route evidence'} if($row.Contains('State') -and $row.State -cnotin @('Alive','Dead','Probe')){throw 'Invalid route viability evidence'} $parts=([string]$row.DestinationPrefix).Split('/') $limit=if($row.AddressFamily -eq 'IPv4'){32}else{128} if($parts.Count -ne 2 -or $parts[1] -cnotmatch '^(0|[1-9][0-9]*)$' -or [long]$parts[1] -gt $limit){throw 'Invalid route destination prefix'} Assert-PNBAddress $parts[0] $row.AddressFamily Assert-PNBAddress $row.NextHop $row.AddressFamily } $routeKeys=@($Observation.Routes | ForEach-Object {Get-PNBRouteKey $_}) if(@($routeKeys | Sort-Object -Unique).Count -ne $routeKeys.Count){throw 'Duplicate route evidence'} if(-not(Test-PNBEqual $Observation.OwnedLocalRouteKeys (Get-PNBOwnedLocalRouteKeys $Observation.Routes $Observation.OwnedAdapters $Observation.OwnedAddresses))){throw 'Unproven owned local-route lifecycle'} foreach($key in $Observation.OwnedRouteKeys){if($key -isnot [string] -or $key -cnotmatch '^ActiveStore\|IPv4\|[^|]+\|[1-9][0-9]*\|[^|]+\|1\|[0-9]+\|NetMgmt$'){throw 'Invalid owned route identity'}} foreach($key in $Observation.OwnedNrptKeys){if($key -isnot [string] -or $key -cnotmatch '^[a-f0-9]{64}$'){throw 'Invalid owned NRPT identity'}} foreach($field in @('OwnedRouteKeys','OwnedNrptKeys')){if(@($Observation[$field] | Sort-Object -Unique).Count -ne $Observation[$field].Count){throw 'Duplicate ownership evidence'}} foreach($row in $Observation.Nrpt){Assert-PNBFields $row @('Name','Namespace','NameServers','Comment') 'NRPT';if([string]::IsNullOrWhiteSpace($row.Name) -or $row.Namespace -isnot [array] -or $row.NameServers -isnot [array]){throw 'Invalid NRPT evidence'}} foreach($field in @('Proxy','ExpectedRestoredProxy')) { $names=@($Observation[$field] | ForEach-Object { $_.Name } | Sort-Object -Unique) if($Observation[$field].Count -ne 5 -or ($names -join ',') -cne 'AutoConfigURL,AutoDetect,ProxyEnable,ProxyOverride,ProxyServer'){throw 'Incomplete proxy evidence'} foreach($row in $Observation[$field]){Assert-PNBValueEvidence $row} } if($Observation.WinHttp.Count -ne 2 -or (@($Observation.WinHttp | ForEach-Object Name | Sort-Object -Unique) -join ',') -cne 'HKEY_CURRENT_USER,HKEY_LOCAL_MACHINE'){throw 'Incomplete WinHTTP evidence'} foreach($row in $Observation.WinHttp){Assert-PNBValueEvidence $row} Assert-PNBFields $Observation.UserFileHashes @('session.bin','device-id.txt','settings.json','client-settings.json') 'protected user files' Assert-PNBFields $Observation.Journals @('tun-state.json','proxy-state.json','proxy-dns-owned.json','xray.pid') 'recovery journals' if($Observation.UserFileHashes.Count -ne 4 -or $Observation.Journals.Count -ne 4){throw 'Unknown evidence file inventory'} foreach($name in @('session.bin','device-id.txt','settings.json','client-settings.json')){ if(-not $Observation.UserFileHashes.Contains($name)){throw 'Missing protected user-file evidence'} $f=$Observation.UserFileHashes[$name] Assert-PNBFileRecord $f } foreach($name in @('tun-state.json','proxy-state.json','proxy-dns-owned.json','xray.pid')){ if(-not $Observation.Journals.Contains($name)){throw 'Missing recovery journal evidence'} $f=$Observation.Journals[$name] Assert-PNBFileRecord $f } } function Assert-PNBValueEvidence($Row) { Assert-PNBFields $Row @('Name','Exists','Kind','ValueSha256') 'registry value' if($Row.Exists -isnot [bool] -or ($Row.Exists -and ($Row.ValueSha256 -cnotmatch '^[a-f0-9]{64}$' -or [string]::IsNullOrWhiteSpace($Row.Kind))) -or (-not $Row.Exists -and ($null -ne $Row.ValueSha256 -or $null -ne $Row.Kind))){throw 'Invalid registry evidence'} } function Assert-PNBFileRecord($Row) { Assert-PNBFields $Row @('Exists','Sha256') 'file evidence' if($Row.Exists -isnot [bool] -or ($Row.Exists -and $Row.Sha256 -cnotmatch '^[a-f0-9]{64}$') -or (-not $Row.Exists -and $null -ne $Row.Sha256)){throw 'Invalid file evidence'} } function New-ProductionRecoveryExpectation { [CmdletBinding()] param([Parameter(Mandatory)]$BeforeStop,[array]$AuthorizedProcesses=@()) Assert-PNBObservation $BeforeStop foreach($p in $AuthorizedProcesses){ Assert-PNBProcess $p if($p.Name -cnotin @('VPNPlus','xray') -or $p.OwnerSid -cne $BeforeStop.Context.UserSid -or $p.SessionId -ne $BeforeStop.Context.SessionId){throw 'Authorized process must be an exact current-user/current-session client identity'} } if(-not (Test-PNBEqual (Sort-PNBRows $BeforeStop.Processes) (Sort-PNBRows $AuthorizedProcesses))){throw 'Existing proxy process owner/identity is not explicitly authorized'} if($BeforeStop.OwnedProxyEnabled -and -not $BeforeStop.Journals['proxy-state.json'].Exists){throw 'Owned system proxy has no restoration evidence'} if(-not $BeforeStop.Journals['proxy-state.json'].Exists -and -not (Test-PNBEqual $BeforeStop.Proxy $BeforeStop.ExpectedRestoredProxy)){throw 'Unjournaled proxy restoration intent'} $ownedIf=@($BeforeStop.OwnedAdapters | ForEach-Object { $_.InterfaceIndex }) if($BeforeStop.OwnedRouteKeys.Count -and -not $BeforeStop.Journals['tun-state.json'].Exists){throw 'Unjournaled route ownership'} $ownedKeys=@($BeforeStop.OwnedRouteKeys)+@($BeforeStop.OwnedLocalRouteKeys) $foreignRoutes=@($BeforeStop.Routes | Where-Object { (Get-PNBRouteKey $_) -cnotin $ownedKeys }) # Only the explicitly verified kernel link-local lifecycle is exempt. # A foreign/static route on the same device still blocks adapter recovery. if(@($foreignRoutes | Where-Object InterfaceIndex -in $ownedIf).Count){throw 'Unproven route on owned adapter; preserve evidence for review'} $markedNrpt=@($BeforeStop.Nrpt | Where-Object Comment -ceq 'UCVL.VPNPlus.ProxyDNS.v1') if(($BeforeStop.OwnedNrptKeys.Count -or $markedNrpt.Count) -and -not $BeforeStop.Journals['proxy-dns-owned.json'].Exists){throw 'Unjournaled NRPT ownership'} if(-not (Test-PNBEqual @($markedNrpt | ForEach-Object {Get-PNBJsonHash $_} | Sort-Object) @($BeforeStop.OwnedNrptKeys | Sort-Object))){throw 'Unproven NRPT ownership'} $expectation=[ordered]@{ Schema=1; Kind='production-recovery-expectation'; SourceCapturedAt=$BeforeStop.CapturedAt; SourceSha256=(Get-PNBJsonHash $BeforeStop); Context=(Copy-PNBObject $BeforeStop.Context); Proxy=(Copy-PNBObject $BeforeStop.ExpectedRestoredProxy); WinHttp=(Copy-PNBObject $BeforeStop.WinHttp); Routes=(Sort-PNBRows $foreignRoutes); PhysicalDns=(Copy-PNBObject $BeforeStop.PhysicalDns); Nrpt=(Sort-PNBRows @($BeforeStop.Nrpt | Where-Object { (Get-PNBJsonHash $_) -cnotin $BeforeStop.OwnedNrptKeys })); PhysicalAdapters=(Copy-PNBObject $BeforeStop.PhysicalAdapters); PhysicalAddresses=(Copy-PNBObject $BeforeStop.PhysicalAddresses); PhysicalInterfaces=(Copy-PNBObject $BeforeStop.PhysicalInterfaces); UserFileHashes=(Copy-PNBObject $BeforeStop.UserFileHashes); OwnedRouteKeys=@($BeforeStop.OwnedRouteKeys); SourceJournals=(Copy-PNBObject $BeforeStop.Journals); AuthorizedProcesses=(Sort-PNBRows (Copy-PNBObject $AuthorizedProcesses)) } $expectation['EvidenceSha256']=Get-PNBJsonHash $expectation return $expectation } function Test-PNBClean($Observation) { Assert-PNBObservation $Observation $reasons=[Collections.Generic.List[string]]::new() if(@($Observation.Processes).Count){$reasons.Add('proxy_process_or_external_owner_present')} if($Observation.OwnedProxyEnabled){$reasons.Add('owned_system_proxy_enabled')} if(@($Observation.OwnedAdapters).Count){$reasons.Add('owned_tun_adapter_present')} if(@($Observation.OwnedDevices).Count){$reasons.Add('owned_tun_device_present')} if(@($Observation.Nrpt | Where-Object Comment -eq 'UCVL.VPNPlus.ProxyDNS.v1').Count){$reasons.Add('owned_nrpt_present')} if(@($Observation.Journals.Values | Where-Object Exists).Count){$reasons.Add('recovery_journal_present')} if($Observation.OwnedRouteKeys.Count -or $Observation.OwnedNrptKeys.Count){$reasons.Add('ownership_intent_present')} if(-not (Test-PNBEqual $Observation.Proxy $Observation.ExpectedRestoredProxy)){$reasons.Add('proxy_restoration_pending')} if(@($Observation.Routes | Where-Object DestinationPrefix -in @('0.0.0.0/1','128.0.0.0/1','::/1','8000::/1')).Count){$reasons.Add('split_default_route_present')} return ,@($reasons.ToArray()) } function Compare-PNBExpected($Expected, $Observation) { $reasons=[Collections.Generic.List[string]]::new() $external=[Collections.Generic.List[string]]::new() foreach($name in @('Context','Proxy','WinHttp','UserFileHashes')) { if(-not (Test-PNBEqual $Expected[$name] $Observation[$name])){$reasons.Add($name+'_mismatch')} } foreach($name in @('Routes','PhysicalDns','Nrpt','PhysicalAdapters','PhysicalAddresses','PhysicalInterfaces')) { $equal=if($name -eq 'PhysicalInterfaces'){Test-PNBPhysicalInterfacesEquivalent $Expected $Observation}else{Test-PNBEqual $Expected[$name] $Observation[$name]} if(-not $equal){$external.Add($name+'_changed')} } # A DHCP/roaming/foreign-policy change invalidates this baseline, but is NOT # automatically blamed on the candidate or "repaired" back to a stale IP. return [ordered]@{ Reasons=@($reasons.ToArray()); ExternalNetworkChanges=@($external.ToArray()) } } function New-ChangedNetworkRestartExpectation($Observation,$OriginalExpectation) { # Restart-only reference, NEVER restoration of the pre-maintenance network. # The caller must separately prove no install/release occurred and the full # old installation/registration is intact. A later independent observation # must match this reference before the old client may be started. Assert-PNBFields $OriginalExpectation @('Schema','Kind','SourceCapturedAt','SourceSha256','Context','Proxy','WinHttp','Routes','PhysicalDns','Nrpt','PhysicalAdapters','PhysicalAddresses','PhysicalInterfaces','UserFileHashes','OwnedRouteKeys','SourceJournals','AuthorizedProcesses','EvidenceSha256') 'original recovery expectation' $verified=Copy-PNBObject $OriginalExpectation;$verified.Remove('EvidenceSha256') | Out-Null if($OriginalExpectation.Schema -ne 1 -or $OriginalExpectation.Kind -cne 'production-recovery-expectation' -or $OriginalExpectation.SourceSha256 -cnotmatch '^[a-f0-9]{64}$' -or $OriginalExpectation.EvidenceSha256 -cne (Get-PNBJsonHash $verified)){throw 'Invalid original recovery expectation'} $dirty=Test-PNBClean $Observation $comparison=Compare-PNBExpected $OriginalExpectation $Observation $allowed=@('Routes_changed','PhysicalDns_changed','PhysicalAdapters_changed','PhysicalAddresses_changed','PhysicalInterfaces_changed') if($dirty.Count -or $comparison.Reasons.Count -or -not $comparison.ExternalNetworkChanges.Count -or @($comparison.ExternalNetworkChanges | Where-Object {$_ -cnotin $allowed}).Count -or [DateTimeOffset]$Observation.StartedAt -lt [DateTimeOffset]$OriginalExpectation.SourceCapturedAt){ throw 'Changed-network restart requires clean ownership and unchanged account/proxy state' } return New-ProductionRecoveryExpectation $Observation @() } function New-ProductionNetworkBaseline { [CmdletBinding()] param([Parameter(Mandatory)]$Observation,[Parameter(Mandatory)]$Expectation,[Parameter(Mandatory)][int]$RecoveryExitCode) if($RecoveryExitCode -ne 0){throw 'Independent network recovery did not succeed'} Assert-PNBFields $Expectation @('Schema','Kind','SourceCapturedAt','SourceSha256','Context','Proxy','WinHttp','Routes','PhysicalDns','Nrpt','PhysicalAdapters','PhysicalAddresses','PhysicalInterfaces','UserFileHashes','OwnedRouteKeys','SourceJournals','AuthorizedProcesses','EvidenceSha256') 'recovery expectation' $verifiedExpectation=Copy-PNBObject $Expectation;$verifiedExpectation.Remove('EvidenceSha256') | Out-Null if($Expectation.Schema -ne 1 -or $Expectation.Kind -cne 'production-recovery-expectation' -or $Expectation.SourceSha256 -cnotmatch '^[a-f0-9]{64}$' -or $Expectation.EvidenceSha256 -cne (Get-PNBJsonHash $verifiedExpectation)){throw 'Invalid or changed recovery expectation'} $dirty=Test-PNBClean $Observation $comparison=Compare-PNBExpected $Expectation $Observation if([DateTimeOffset]$Observation.StartedAt -lt [DateTimeOffset]$Expectation.SourceCapturedAt){throw 'Stale clean observation'} if($dirty.Count -or $comparison.Reasons.Count -or $comparison.ExternalNetworkChanges.Count){ throw ('Clean baseline refused: '+((@($dirty)+@($comparison.Reasons)+@($comparison.ExternalNetworkChanges)) -join ',')) } $copy=Copy-PNBObject $Observation return [ordered]@{ Schema=1; Kind='production-clean-network-baseline'; CapturedAt=$Observation.CapturedAt; RecoveryExitCode=0; ExpectationSha256=(Get-PNBJsonHash $Expectation); ObservationSha256=(Get-PNBJsonHash $copy); Observation=$copy; ProductionAcceptance=$false } } function Compare-ProductionNetworkBaseline { [CmdletBinding()] param([Parameter(Mandatory)]$Baseline,[Parameter(Mandatory)]$Observation) Assert-PNBFields $Baseline @('Schema','Kind','CapturedAt','RecoveryExitCode','ExpectationSha256','ObservationSha256','Observation','ProductionAcceptance') 'baseline' if($Baseline.Schema -ne 1 -or $Baseline.Kind -cne 'production-clean-network-baseline' -or $Baseline.RecoveryExitCode -ne 0 -or $Baseline.ProductionAcceptance -isnot [bool] -or $Baseline.ProductionAcceptance -or $Baseline.ExpectationSha256 -cnotmatch '^[a-f0-9]{64}$' -or $Baseline.CapturedAt -cne $Baseline.Observation.CapturedAt -or (Get-PNBJsonHash $Baseline.Observation) -cne $Baseline.ObservationSha256){throw 'Baseline evidence is invalid or changed'} if((Test-PNBClean $Baseline.Observation).Count){throw 'Baseline is not clean'} $dirty=Test-PNBClean $Observation $comparison=Compare-PNBExpected $Baseline.Observation $Observation $reasons=@($dirty)+@($comparison.Reasons) if([DateTimeOffset]$Observation.StartedAt -lt [DateTimeOffset]$Baseline.CapturedAt){$reasons+=@('stale_recovery_observation')} return [ordered]@{ Passed=($reasons.Count -eq 0 -and $comparison.ExternalNetworkChanges.Count -eq 0); Reasons=$reasons; ExternalNetworkChanges=$comparison.ExternalNetworkChanges; BaselineUpdated=$false; NetworkModified=$false; ProductionAcceptance=$false } }