Files

508 lines
34 KiB
PowerShell
Raw Permalink Normal View History

#requires -Version 7.0
# Independent production installation backup/restore. No process stop/start or network operations.
# Production targets are derived from the current Windows identity, never supplied by a journal.
# Fixture entry points use separate TEMP roots and JSON registration; they never open HKCU.
Set-StrictMode -Version Latest
# Shared with independent rollback: no destination pre-delete, no cross-volume copy.
if (-not ('UCVL.Recovery.SiblingRename' -as [type])) {
Add-Type -TypeDefinition @'
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Threading;
namespace UCVL.Recovery {
public static class SiblingRename {
[DllImport("kernel32.dll",CharSet=CharSet.Unicode,SetLastError=true)]
static extern bool MoveFileExW(string from,string to,uint flags);
public static void Commit(string source,string target) {
source=Path.GetFullPath(source);target=Path.GetFullPath(target);
if(!String.Equals(Path.GetDirectoryName(source),Path.GetDirectoryName(target),StringComparison.OrdinalIgnoreCase)
|| String.Equals(source,target,StringComparison.OrdinalIgnoreCase))throw new IOException("Sibling stage required");
foreach(var file in new[]{source,target})
for(var part=file;!String.IsNullOrEmpty(part);part=Path.GetDirectoryName(part))
if((File.Exists(part)||Directory.Exists(part)) && (File.GetAttributes(part)&FileAttributes.ReparsePoint)!=0)
throw new IOException("Linked replacement refused");
if(File.Exists(target)) {
const AccessControlSections parts=AccessControlSections.Access|AccessControlSections.Owner|AccessControlSections.Group;
var acl=new FileSecurity();
acl.SetSecurityDescriptorBinaryForm(new FileInfo(target).GetAccessControl(parts).GetSecurityDescriptorBinaryForm(),parts);
new FileInfo(source).SetAccessControl(acl);
}
for(int attempt=0;;attempt++) {
if(MoveFileExW(source,target,1|8))return;
int error=Marshal.GetLastWin32Error();
if(attempt>=24 || (error!=5 && error!=32 && error!=33) || !File.Exists(source) || !File.Exists(target))
throw new IOException("Sibling rename failed; original destination was not pre-deleted",new System.ComponentModel.Win32Exception(error));
Thread.Sleep(20);
}
}
}
}
'@
}
function Assert-PIBPlain([string]$Path) {
$full=[IO.Path]::GetFullPath($Path)
for($part=$full; $part; $part=[IO.Path]::GetDirectoryName($part)) {
if((Test-Path -LiteralPath $part) -and ((Get-Item -LiteralPath $part -Force).Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw 'Rollback paths may not contain reparse points' }
}
return $full
}
function Get-PIBHash([string]$Path) {
$null=Assert-PIBPlain $Path
if(Test-Path -LiteralPath $Path -PathType Leaf) { return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash }
if(Test-Path -LiteralPath $Path) { throw 'Expected a file, not a directory' }
return $null
}
function Test-PIBEqual($A,$B) { return (($A | ConvertTo-Json -Depth 16 -Compress) -ceq ($B | ConvertTo-Json -Depth 16 -Compress)) }
function Write-PIBJson([string]$Path,$Value) {
$null=Assert-PIBPlain $Path
$temp=$Path+'.'+[guid]::NewGuid().ToString('N')+'.tmp'
try {
[IO.File]::WriteAllText($temp,($Value | ConvertTo-Json -Depth 24),[Text.UTF8Encoding]::new($false))
$handle=[IO.File]::Open($temp,[IO.FileMode]::Open,[IO.FileAccess]::ReadWrite,[IO.FileShare]::None)
try { $handle.Flush($true) } finally { $handle.Dispose() }
[UCVL.Recovery.SiblingRename]::Commit($temp,$Path)
} finally { if([IO.File]::Exists($temp)) { [IO.File]::Delete($temp) } }
}
function Get-PIBPayload($Manifest) {
$rows=@($Manifest)
if($rows.Count -lt 3 -or $rows.Count -gt 10000) { throw 'Invalid payload manifest size' }
$seen=[Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
foreach($row in $rows) {
if($row.Path -cnotmatch '^(VPNPlus\.exe|README\.md|THIRD_PARTY_NOTICES\.md|(assets|xray|licenses)/[^:]+)$' -or
$row.Path.Contains('\') -or $row.Path -match '(^|/)(\.?\.?|[^/]*[. ])(/|$)' -or
$row.Sha256 -notmatch '^[A-Fa-f0-9]{64}$' -or -not $seen.Add($row.Path)) { throw 'Invalid or duplicate payload path/digest' }
}
foreach($name in @('VPNPlus.exe','xray/xray.exe','xray/wintun.dll')) { if(-not $seen.Contains($name)) { throw 'Incomplete executable manifest' } }
return ,$rows
}
function Get-PIBNames { return @('','Path','DisplayName','DisplayIcon','DisplayVersion','Publisher','URLInfoAbout','UninstallString','NoModify','NoRepair') }
function Get-PIBValue($Hive,[string]$Key,[string]$Name) {
$handle=$Hive.OpenSubKey($Key)
try {
if($null -eq $handle -or $Name -notin $handle.GetValueNames()) { return $null }
$kind=$handle.GetValueKind($Name)
$value=$handle.GetValue($Name,$null,[Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
# String form for 64-bit integers avoids JSON precision loss. Base64 for bytes.
$data=switch($kind.ToString()) {
'QWord' { ([long]$value).ToString([Globalization.CultureInfo]::InvariantCulture); break }
'Binary' { [Convert]::ToBase64String($value); break }
'None' { [Convert]::ToBase64String($value); break }
'MultiString' { ,([string[]]$value); break }
default { $value }
}
return [ordered]@{ Kind=$kind.ToString(); Data=$data }
} finally { if($handle) { $handle.Dispose() } }
}
function Convert-PIBValue($Value) {
switch($Value.Kind) {
'String' { return [string]$Value.Data }
'ExpandString' { return [string]$Value.Data }
'DWord' { return [int]$Value.Data }
'QWord' { return [long]::Parse($Value.Data,[Globalization.CultureInfo]::InvariantCulture) }
'MultiString' { return ,([string[]]$Value.Data) }
'Binary' { return ,([Convert]::FromBase64String($Value.Data)) }
'None' { return ,([Convert]::FromBase64String($Value.Data)) }
default { throw 'Unsupported registry kind' }
}
}
function Copy-PIBAtomic([string]$Source,[string]$Destination,[string]$ExpectedHash) {
$null=Assert-PIBPlain $Source; $null=Assert-PIBPlain $Destination
[IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($Destination)) | Out-Null
$temporary=$Destination+'.rollback-'+[guid]::NewGuid().ToString('N')+'.tmp'
try {
[IO.File]::Copy($Source,$temporary)
if($ExpectedHash -notmatch '^[A-Fa-f0-9]{64}$' -or (Get-PIBHash $temporary) -ne $ExpectedHash){throw 'Backup changed during replacement; destination untouched'}
$stream=[IO.File]::Open($temporary,[IO.FileMode]::Open,[IO.FileAccess]::ReadWrite,[IO.FileShare]::None)
try {$stream.Flush($true)} finally {$stream.Dispose()}
[UCVL.Recovery.SiblingRename]::Commit($temporary,$Destination)
} finally {if([IO.File]::Exists($temporary)){[IO.File]::Delete($temporary)}}
}
function Assert-PIBScopedRoot([string]$Path,[string]$Prefix) {
$full=[IO.Path]::TrimEndingDirectorySeparator((Assert-PIBPlain $Path))
$temp=[IO.Path]::TrimEndingDirectorySeparator([IO.Path]::GetTempPath())
if([IO.Path]::GetDirectoryName($full) -ine $temp -or
[IO.Path]::GetFileName($full) -cnotmatch ('^'+[regex]::Escape($Prefix)+'[a-f0-9]{32}$')) { throw 'Unscoped independent baseline directory' }
return $full
}
function Assert-PIBJob([string]$JobDirectory) { return (Assert-PIBScopedRoot $JobDirectory 'ucvl-production-install-guard-') }
function Get-PIBSid { return [Security.Principal.WindowsIdentity]::GetCurrent().User.Value }
function Get-PIBProductionProfile {
$local=[Environment]::GetFolderPath([Environment+SpecialFolder]::LocalApplicationData)
$desktop=[Environment]::GetFolderPath([Environment+SpecialFolder]::DesktopDirectory)
$programs=[Environment]::GetFolderPath([Environment+SpecialFolder]::Programs)
if(-not $local -or -not $desktop -or -not $programs) { throw 'Current-user KnownFolder unavailable' }
return [ordered]@{Mode='production-current-user';Sid=(Get-PIBSid);FixtureRoot=$null;
Target=(Assert-PIBPlain (Join-Path $local 'Programs/UCVL/VPNPlus'));
Desktop=(Assert-PIBPlain (Join-Path $desktop '优创⁺纵横家.lnk'));
StartMenu=(Assert-PIBPlain (Join-Path $programs '优创未来/优创⁺纵横家.lnk'));
RegistryView='Registry32';RegistryKeys=@('Software\Microsoft\Windows\CurrentVersion\App Paths\VPNPlus.exe','Software\Microsoft\Windows\CurrentVersion\Uninstall\UCVL.VPNPlus')}
}
function Get-PIBFixtureProfile([string]$FixtureRoot) {
$root=Assert-PIBScopedRoot $FixtureRoot 'ucvl-production-baseline-test-'
if(-not(Test-Path -LiteralPath $root -PathType Container)) { throw 'Fixture root must already exist' }
return [ordered]@{Mode='fixture-only';Sid=(Get-PIBSid);FixtureRoot=$root;
Target=(Assert-PIBPlain (Join-Path $root 'installed'));
Desktop=(Assert-PIBPlain (Join-Path $root 'shell/Desktop.lnk'));
StartMenu=(Assert-PIBPlain (Join-Path $root 'shell/StartMenu.lnk'));
RegistryView='JSON-fixture';RegistryKeys=@('fixture-app','fixture-uninstall')}
}
function Assert-PIBProfile($Profile) {
$expected=switch -Exact ($Profile.Mode) {
'production-current-user' { Get-PIBProductionProfile; break }
'fixture-only' { Get-PIBFixtureProfile $Profile.FixtureRoot; break }
default { throw 'Unrecognized installation profile' }
}
if(-not(Test-PIBEqual $Profile $expected)) { throw 'Installation identity, SID, path or registration mapping changed' }
return $expected
}
function Get-PIBDestination($Profile,[string]$Key) {
$profile=Assert-PIBProfile $Profile
if($Key.StartsWith('payload:',[StringComparison]::Ordinal)) {
$relative=$Key.Substring(8)
if($relative -match '[<>"|?*\x00-\x1f]' -or @($relative.Split('/') | Where-Object {$_ -match '^(?i:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)'}).Count -gt 0) { throw 'Invalid Windows payload filename' }
$null=Get-PIBPayload @(@{Path=$relative;Sha256=('0'*64)},@{Path='VPNPlus.exe';Sha256=('0'*64)},@{Path='xray/xray.exe';Sha256=('0'*64)},@{Path='xray/wintun.dll';Sha256=('0'*64)} | Sort-Object Path -Unique)
$destination=Assert-PIBPlain (Join-Path $profile.Target $relative)
if(-not $destination.StartsWith($profile.Target+[IO.Path]::DirectorySeparatorChar,[StringComparison]::OrdinalIgnoreCase)) { throw 'Payload escaped fixed installation' }
return $destination
}
return (Assert-PIBPlain $(switch -Exact ($Key) {
'component:0' { Join-Path $profile.Target 'Uninstall.exe'; break }
'component:1' { $profile.Desktop; break }
'component:2' { $profile.StartMenu; break }
'metadata:journal' { Join-Path $profile.Target '.ucvl-installer/journal.json'; break }
'metadata:uninstall' { Join-Path $profile.Target '.ucvl-installer/uninstall-journal.json'; break }
default { throw 'Unowned installation component' }
}))
}
function Assert-PIBRegistrationShape($Registration) {
if($Registration.Keys.Count -ne 2 -or $Registration.Values.Count -ne 10) { throw 'Incomplete registration baseline' }
foreach($key in $Registration.Keys) { if($key -isnot [bool]) { throw 'Invalid registration key presence' } }
foreach($value in $Registration.Values) { if($null -ne $value) { $null=Convert-PIBValue $value } }
}
function Get-PIBRegistration($Profile) {
$profile=Assert-PIBProfile $Profile
if($profile.Mode -eq 'fixture-only') {
$path=Assert-PIBPlain (Join-Path $profile.FixtureRoot 'registration.fixture.json')
if(-not(Test-Path -LiteralPath $path)) { return [ordered]@{Keys=@($false,$false);Values=@($null)*10} }
$stored=Get-Content -LiteralPath $path -Raw | ConvertFrom-Json
$result=[ordered]@{Keys=@($stored.Keys);Values=@($stored.Values)}
Assert-PIBRegistrationShape $result
return $result
}
$hive=[Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::CurrentUser,[Microsoft.Win32.RegistryView]::Registry32)
try {
$keys=@(foreach($path in $profile.RegistryKeys) { $key=$hive.OpenSubKey($path); try {$null -ne $key} finally {if($key){$key.Dispose()}} })
$names=Get-PIBNames
return [ordered]@{Keys=$keys;Values=@(for($i=0;$i -lt 10;$i++){Get-PIBValue $hive $profile.RegistryKeys[$(if($i -lt 2){0}else{1})] $names[$i]})}
} finally {$hive.Dispose()}
}
function Get-PIBCandidateRegistration($Profile,[string]$Version) {
$p=Assert-PIBProfile $Profile
$data=@((Join-Path $p.Target 'VPNPlus.exe'),$p.Target,'优创⁺纵横家',(Join-Path $p.Target 'VPNPlus.exe'),$Version,
'优创未来(UCVL)','https://vpn.example.invalid/',('"'+(Join-Path $p.Target 'Uninstall.exe')+'"'),1,1)
return [ordered]@{Keys=@($true,$true);Values=@(for($i=0;$i -lt 10;$i++){[ordered]@{Kind=$(if($i -lt 8){'String'}else{'DWord'});Data=$data[$i]}})}
}
function Get-PIBComponents($Manifest) {
$rows=@($Manifest | Sort-Object Id)
if($rows.Count -ne 3 -or ($rows.Id -join ',') -ne '0,1,2') { throw 'Candidate integration requires exactly three independent hashes' }
foreach($row in $rows) {
if($row.Id -isnot [int] -and $row.Id -isnot [long]) { throw 'Invalid component ID' }
if($row.Sha256 -notmatch '^[a-fA-F0-9]{64}$') { throw 'Invalid component hash' }
}
return ,$rows
}
function Get-PIBKeys($Old,$Candidate) {
return @(@(@($Old.Path)+@($Candidate.Path) | Sort-Object -Unique) | ForEach-Object {'payload:'+$_}) +
@('component:0','component:1','component:2','metadata:journal','metadata:uninstall')
}
function Assert-PIBTerminalJournal([string]$Path,[bool]$Uninstall=$false) {
if(-not(Test-Path -LiteralPath $Path)) { return }
if((Get-Item -LiteralPath $Path).Length -gt 2097152) { throw 'Oversized installation journal' }
$journal=Get-Content -LiteralPath $Path -Raw | ConvertFrom-Json
$allowed=if($Uninstall){@('removed','rolled-back')}else{@('committed','rolled-back')}
if($journal.State -notin $allowed) { throw 'Cannot capture an incomplete installation transaction' }
}
function New-PIBBaselineCore($Profile,[string]$JobDirectory,[string]$OldManifestPath,[string]$CandidateManifestPath,
[string]$CandidateComponentsManifestPath,[string]$CandidateVersion) {
$profile=Assert-PIBProfile $Profile; $job=Assert-PIBJob $JobDirectory
if(Test-Path -LiteralPath $job) { throw 'Snapshot job already exists' }
if($CandidateVersion -notmatch '^\d+\.\d+\.\d+[A-Za-z0-9.+-]*$') { throw 'Invalid candidate version' }
$inputPaths=@($OldManifestPath,$CandidateManifestPath,$CandidateComponentsManifestPath)
$inputHashes=@(foreach($path in $inputPaths){$hash=Get-PIBHash $path;if(-not $hash){throw 'Manifest missing'};$hash})
$old=Get-PIBPayload (Get-Content -LiteralPath $OldManifestPath -Raw | ConvertFrom-Json)
$next=Get-PIBPayload (Get-Content -LiteralPath $CandidateManifestPath -Raw | ConvertFrom-Json)
$components=Get-PIBComponents (Get-Content -LiteralPath $CandidateComponentsManifestPath -Raw | ConvertFrom-Json)
foreach($row in $old) { if((Get-PIBHash (Get-PIBDestination $profile ('payload:'+$row.Path))) -ne $row.Sha256) { throw 'Old manifest differs from installed payload' } }
$candidateSource=Assert-PIBPlain ([IO.Path]::GetDirectoryName([IO.Path]::GetFullPath($CandidateManifestPath)))
if($candidateSource -ieq $profile.Target -or $candidateSource.StartsWith($profile.Target+'\',[StringComparison]::OrdinalIgnoreCase) -or
$profile.Target.StartsWith($candidateSource+'\',[StringComparison]::OrdinalIgnoreCase)) { throw 'Candidate payload must be separate from installed directory' }
foreach($row in $next) {
$null=Get-PIBDestination $profile ('payload:'+$row.Path)
if((Get-PIBHash (Join-Path $candidateSource $row.Path)) -ne $row.Sha256) { throw 'Candidate manifest differs from staged payload bytes' }
}
$componentSource=Assert-PIBPlain ([IO.Path]::GetDirectoryName([IO.Path]::GetFullPath($CandidateComponentsManifestPath)))
if($componentSource -ieq $profile.Target -or $componentSource.StartsWith($profile.Target+'\',[StringComparison]::OrdinalIgnoreCase) -or
$profile.Target.StartsWith($componentSource+'\',[StringComparison]::OrdinalIgnoreCase)) { throw 'Candidate components must be staged independently' }
$componentNames=@('Uninstall.exe','Desktop.lnk','StartMenu.lnk')
foreach($row in $components) { if((Get-PIBHash (Join-Path $componentSource $componentNames[$row.Id])) -ne $row.Sha256) { throw 'Candidate component differs from staged bytes' } }
Assert-PIBTerminalJournal (Get-PIBDestination $profile 'metadata:journal')
Assert-PIBTerminalJournal (Get-PIBDestination $profile 'metadata:uninstall') $true
$registration=Get-PIBRegistration $profile
if($profile.Mode -eq 'production-current-user') {
if($null -eq $registration.Values[0] -or $null -eq $registration.Values[1] -or
$registration.Values[0].Kind -ne 'String' -or $registration.Values[1].Kind -ne 'String' -or
$registration.Values[0].Data -ine (Join-Path $profile.Target 'VPNPlus.exe') -or
$registration.Values[1].Data -ine $profile.Target) { throw 'Actual registered installation does not match fixed current-user target' }
}
$keys=Get-PIBKeys $old $next
$null=New-Item -ItemType Directory -Path (Join-Path $job 'baseline')
$entries=@(for($i=0;$i -lt $keys.Count;$i++) {
$dest=Get-PIBDestination $profile $keys[$i]; $hash=Get-PIBHash $dest
if($hash) {
$backup=Join-Path $job "baseline/$i.bin";[IO.File]::Copy($dest,$backup)
if((Get-PIBHash $backup) -ne $hash -or (Get-PIBHash $dest) -ne $hash) { throw 'File changed during capture' }
}
[ordered]@{Id=$i;Key=$keys[$i];Sha256=$hash}
})
$snapshot=[ordered]@{Schema=2;Mode=$profile.Mode;Profile=$profile;Target=$profile.Target;CapturedAt=[DateTimeOffset]::Now.ToString('O');
Old=$old;Candidate=$next;CandidateComponents=$components;CandidateVersion=$CandidateVersion;ManifestHashes=$inputHashes;Entries=$entries;Registration=$registration}
Assert-ProductionInstallationRestored $snapshot
for($i=0;$i -lt 3;$i++) { if((Get-PIBHash $inputPaths[$i]) -ne $inputHashes[$i]) { throw 'Input manifest changed during capture' } }
foreach($row in $next) { if((Get-PIBHash (Join-Path $candidateSource $row.Path)) -ne $row.Sha256) { throw 'Candidate payload changed during capture' } }
foreach($row in $components) { if((Get-PIBHash (Join-Path $componentSource $componentNames[$row.Id])) -ne $row.Sha256) { throw 'Candidate component changed during capture' } }
Write-PIBJson (Join-Path $job 'baseline.json') $snapshot
return (Get-PIBHash (Join-Path $job 'baseline.json'))
}
function New-ProductionInstallationBaseline {
param([Parameter(Mandatory)][string]$JobDirectory,[Parameter(Mandatory)][string]$OldManifestPath,
[Parameter(Mandatory)][string]$CandidateManifestPath,[Parameter(Mandatory)][string]$CandidateComponentsManifestPath,[Parameter(Mandatory)][string]$CandidateVersion)
return (New-PIBBaselineCore (Get-PIBProductionProfile) $JobDirectory $OldManifestPath $CandidateManifestPath $CandidateComponentsManifestPath $CandidateVersion)
}
function New-PIBFixtureBaseline {
param([Parameter(Mandatory)][string]$JobDirectory,[Parameter(Mandatory)][string]$FixtureRoot,[Parameter(Mandatory)][string]$OldManifestPath,
[Parameter(Mandatory)][string]$CandidateManifestPath,[Parameter(Mandatory)][string]$CandidateComponentsManifestPath,[Parameter(Mandatory)][string]$CandidateVersion)
return (New-PIBBaselineCore (Get-PIBFixtureProfile $FixtureRoot) $JobDirectory $OldManifestPath $CandidateManifestPath $CandidateComponentsManifestPath $CandidateVersion)
}
function Read-PIBBaselineCore([string]$JobDirectory,[string]$BaselineSha256,[string]$RequiredMode) {
$job=Assert-PIBJob $JobDirectory;$path=Join-Path $job 'baseline.json'
if($BaselineSha256 -notmatch '^[a-fA-F0-9]{64}$' -or (Get-PIBHash $path) -ne $BaselineSha256) { throw 'Independent snapshot digest mismatch' }
$s=Get-Content -LiteralPath $path -Raw | ConvertFrom-Json
if($s.Schema -ne 2 -or $s.Mode -cne $RequiredMode -or $s.Profile.Mode -cne $RequiredMode) { throw 'Baseline mode cannot cross production/fixture boundary' }
$p=Assert-PIBProfile $s.Profile
if($s.Target -cne $p.Target -or $s.CandidateVersion -notmatch '^\d+\.\d+\.\d+[A-Za-z0-9.+-]*$') { throw 'Invalid baseline target or version' }
$null=Get-PIBPayload $s.Old;$null=Get-PIBPayload $s.Candidate;$null=Get-PIBComponents $s.CandidateComponents
Assert-PIBRegistrationShape $s.Registration
if($s.ManifestHashes.Count -ne 3 -or @($s.ManifestHashes | Where-Object {$_ -notmatch '^[a-fA-F0-9]{64}$'}).Count) { throw 'Invalid manifest digest binding' }
$keys=Get-PIBKeys $s.Old $s.Candidate
if($s.Entries.Count -ne $keys.Count) { throw 'Incomplete snapshot entries' }
for($i=0;$i -lt $keys.Count;$i++) {
$entry=$s.Entries[$i]
if($entry.Id -ne $i -or $entry.Key -cne $keys[$i] -or ($null -ne $entry.Sha256 -and $entry.Sha256 -notmatch '^[a-fA-F0-9]{64}$')) { throw 'Malformed snapshot entry' }
$null=Get-PIBDestination $p $entry.Key
if($entry.Sha256 -and (Get-PIBHash (Join-Path $job "baseline/$i.bin")) -ne $entry.Sha256) { throw 'Independent backup corrupt or missing' }
}
foreach($row in $s.Old) {
$entry=@($s.Entries | Where-Object Key -ceq ('payload:'+$row.Path))
if($entry.Count -ne 1 -or $entry[0].Sha256 -ne $row.Sha256) { throw 'Old manifest is not bound to baseline bytes' }
}
return $s
}
function Read-ProductionInstallationBaseline([string]$JobDirectory,[string]$BaselineSha256) { return (Read-PIBBaselineCore $JobDirectory $BaselineSha256 'production-current-user') }
function Read-PIBFixtureBaseline([string]$JobDirectory,[string]$BaselineSha256) { return (Read-PIBBaselineCore $JobDirectory $BaselineSha256 'fixture-only') }
function Assert-ProductionInstallationRestored($Snapshot) {
$p=Assert-PIBProfile $Snapshot.Profile
if($Snapshot.Target -cne $p.Target -or $Snapshot.Mode -cne $p.Mode) { throw 'Snapshot target/profile mismatch' }
foreach($entry in $Snapshot.Entries) { if((Get-PIBHash (Get-PIBDestination $p $entry.Key)) -ne $entry.Sha256) { throw "Old installation mismatch: $($entry.Key)" } }
if(-not(Test-PIBEqual (Get-PIBRegistration $p) $Snapshot.Registration)) { throw 'Old registration mismatch' }
}
function Convert-PIBJournalValue($Value) {
if($null -eq $Value) { return $null }
$kind=[Microsoft.Win32.RegistryValueKind]$Value.Kind
if(-not [Enum]::IsDefined([Microsoft.Win32.RegistryValueKind],$kind) -or $Value.Data -isnot [string]) { throw 'Invalid typed transaction value' }
$decoded=ConvertFrom-Json -InputObject $Value.Data -NoEnumerate
$data=switch($kind.ToString()) {
'QWord' { ([long]$decoded).ToString([Globalization.CultureInfo]::InvariantCulture); break }
'Binary' { [Convert]::ToBase64String([Convert]::FromBase64String([string]$decoded)); break }
'None' { [Convert]::ToBase64String([Convert]::FromBase64String([string]$decoded)); break }
'MultiString' { ,([string[]]$decoded); break }
'DWord' { [int]$decoded; break }
'String' { if($decoded -isnot [string]){throw 'Invalid registry string'};$decoded;break }
'ExpandString' { if($decoded -isnot [string]){throw 'Invalid registry string'};$decoded;break }
default { throw 'Unsupported transaction registry kind' }
}
return [ordered]@{Kind=$kind.ToString();Data=$data}
}
function Assert-PIBCandidateJournal($Snapshot,$Journal) {
if($Journal.State -notin @('pending','committed','rolled-back','external-rollback-pending') -or
$Journal.BackupId -cnotmatch '^[a-f0-9]{32}$' -or $Journal.Files.Count -ne $Snapshot.Candidate.Count -or
$null -eq $Journal.Integration -or $Journal.Integration.Isolated -isnot [bool] -or
$Journal.Integration.Isolated -ne ($Snapshot.Mode -eq 'fixture-only') -or
$Journal.Integration.Components.Count -ne 3 -or $Journal.Integration.Values.Count -ne 10 -or
-not(Test-PIBEqual @($Journal.Integration.KeysExisted) @($Snapshot.Registration.Keys))) { throw 'Unexpected transaction shape or installation scope' }
$old=@{};foreach($entry in $Snapshot.Entries){$old[$entry.Key]=$entry.Sha256}
$next=@{};foreach($row in $Snapshot.Candidate){$next['payload:'+$row.Path]=$row.Sha256}
foreach($row in $Snapshot.CandidateComponents){$next['component:'+$row.Id]=$row.Sha256}
$seen=[Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
foreach($row in $Journal.Files) {
$key='payload:'+$row.Path
if(-not $seen.Add($key) -or -not $next.ContainsKey($key) -or $row.Sha256 -ne $next[$key] -or
$row.PreviousSha256 -ne $old[$key]) { throw 'Transaction not bound to exact old/new manifests' }
}
$seen.Clear()
foreach($row in $Journal.Integration.Components) {
$key='component:'+$row.Id
if($row.Id -isnot [int] -and $row.Id -isnot [long]) { throw 'Invalid transaction component ID' }
if(-not $seen.Add($key) -or -not $next.ContainsKey($key) -or $row.Sha256 -ne $next[$key] -or
$row.PreviousSha256 -ne $old[$key]) { throw 'Transaction component not bound to independent manifest' }
}
$expected=Get-PIBCandidateRegistration $Snapshot.Profile $Snapshot.CandidateVersion
$seen.Clear()
foreach($row in $Journal.Integration.Values) {
if(($row.Id -isnot [int] -and $row.Id -isnot [long]) -or $row.Id -lt 0 -or $row.Id -gt 9 -or -not $seen.Add([string]$row.Id)) { throw 'Invalid transaction registration ID' }
if(-not(Test-PIBEqual (Convert-PIBJournalValue $row.Next) $expected.Values[$row.Id]) -or
-not(Test-PIBEqual (Convert-PIBJournalValue $row.Previous) $Snapshot.Registration.Values[$row.Id])) { throw 'Transaction registry not bound to independently calculated values' }
}
return $next
}
function Restore-PIBRegistration($Profile,$Previous,$Candidate) {
$p=Assert-PIBProfile $Profile;$names=Get-PIBNames
if($p.Mode -eq 'fixture-only') {
$path=Assert-PIBPlain (Join-Path $p.FixtureRoot 'registration.fixture.json')
$stored=if(Test-Path -LiteralPath $path){Get-Content -LiteralPath $path -Raw | ConvertFrom-Json}else{[pscustomobject]@{Keys=@($false,$false);Values=@($null)*10}}
for($i=0;$i -lt 10;$i++) {
$current=(Get-PIBRegistration $p).Values[$i]
if(Test-PIBEqual $current $Previous.Values[$i]) { continue }
if(-not(Test-PIBEqual $current $Candidate.Values[$i])) { throw 'Registry changed during restore' }
$stored.Values[$i]=$Previous.Values[$i]
}
$stored.Keys=@($Previous.Keys)
Write-PIBJson $path $stored # Preserve unowned JSON properties.
return
}
$hive=[Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::CurrentUser,[Microsoft.Win32.RegistryView]::Registry32)
try {
for($i=0;$i -lt 10;$i++) {
$path=$p.RegistryKeys[$(if($i -lt 2){0}else{1})];$current=Get-PIBValue $hive $path $names[$i];$old=$Previous.Values[$i]
if(Test-PIBEqual $current $old) { continue }
if(-not(Test-PIBEqual $current $Candidate.Values[$i])) { throw 'Registry changed during restore' }
$key=$hive.CreateSubKey($path,$true)
try {
if($null -eq $old){$key.DeleteValue($names[$i],$false)}
else{$key.SetValue($names[$i],(Convert-PIBValue $old),[Microsoft.Win32.RegistryValueKind]::$($old.Kind))}
$key.Flush()
} finally {$key.Dispose()}
}
for($i=0;$i -lt 2;$i++) {
if($Previous.Keys[$i]) { continue }
$path=$p.RegistryKeys[$i];$key=$hive.OpenSubKey($path)
try {$empty=$null -ne $key -and $key.ValueCount -eq 0 -and $key.SubKeyCount -eq 0} finally {if($key){$key.Dispose()}}
if($empty){$hive.DeleteSubKey($path,$false)}
}
} finally {$hive.Dispose()}
}
function Restore-PIBBaselineCore([string]$JobDirectory,[string]$BaselineSha256,[string]$RequiredMode,[int]$FixtureInterruptAfter=-1) {
$job=Assert-PIBJob $JobDirectory
$s=Read-PIBBaselineCore $job $BaselineSha256 $RequiredMode
$p=Assert-PIBProfile $s.Profile
if($FixtureInterruptAfter -ne -1 -and $RequiredMode -ne 'fixture-only') { throw 'Fault injection cannot target production' }
$client=$null;$clientAcquired=$false;$transactionLock=$null;$jobLock=$null
try {
$jobLock=[IO.File]::Open((Join-Path $job 'restore.lock'),[IO.FileMode]::OpenOrCreate,[IO.FileAccess]::ReadWrite,[IO.FileShare]::None)
if($RequiredMode -eq 'production-current-user') {
$client=[Threading.Mutex]::new($false,'Local\UCVL.VPNPlus.Client')
try {$clientAcquired=$client.WaitOne(0)}catch [Threading.AbandonedMutexException]{$clientAcquired=$true}
if(-not $clientAcquired) { throw 'Current client owns the installation; no forced takeover' }
}
$lockPath=Assert-PIBPlain (Join-Path $p.Target '.ucvl-installer/install.lock')
[IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($lockPath)) | Out-Null
$transactionLock=[IO.File]::Open($lockPath,[IO.FileMode]::OpenOrCreate,[IO.FileAccess]::ReadWrite,[IO.FileShare]::None)
$byKey=@{};foreach($entry in $s.Entries){$byKey[$entry.Key]=$entry}
$journalPath=Get-PIBDestination $p 'metadata:journal';$journalHash=Get-PIBHash $journalPath
if($journalHash -eq $byKey['metadata:journal'].Sha256) {
Assert-ProductionInstallationRestored $s
return [ordered]@{Passed=$true;AlreadyRestored=$true;Writes=0;Mode=$RequiredMode}
}
if(-not $journalHash -or (Get-Item -LiteralPath $journalPath).Length -gt 2097152) { throw 'Missing or oversized candidate transaction journal' }
$journal=Get-Content -LiteralPath $journalPath -Raw | ConvertFrom-Json
$next=Assert-PIBCandidateJournal $s $journal
# Validate all targets and backup bytes before writing the launch barrier.
foreach($entry in $s.Entries) {
if($entry.Key -eq 'metadata:journal') { continue }
$dest=Get-PIBDestination $p $entry.Key;$current=Get-PIBHash $dest
if($current -ne $entry.Sha256 -and (-not $next.ContainsKey($entry.Key) -or $current -ne $next[$entry.Key])) { throw "External modification; no overwrite: $($entry.Key)" }
if($current -ne $entry.Sha256 -and [IO.File]::Exists($dest)) {
$probe=[IO.File]::Open($dest,[IO.FileMode]::Open,[IO.FileAccess]::ReadWrite,[IO.FileShare]::None);$probe.Dispose()
}
}
$candidateRegistration=Get-PIBCandidateRegistration $p $s.CandidateVersion
$currentRegistration=Get-PIBRegistration $p
for($i=0;$i -lt 10;$i++) {
if(-not(Test-PIBEqual $currentRegistration.Values[$i] $s.Registration.Values[$i]) -and
-not(Test-PIBEqual $currentRegistration.Values[$i] $candidateRegistration.Values[$i])) { throw 'External registry modification; no overwrite' }
}
# Re-read every pinned backup immediately before the first owned write.
$null=Read-PIBBaselineCore $job $BaselineSha256 $RequiredMode
if((Get-PIBHash $journalPath) -ne $journalHash) { throw 'Transaction changed before restore' }
$evidence=Join-Path $job ('observed-journal-'+$journalHash+'.json')
if(-not(Test-Path -LiteralPath $evidence)){[IO.File]::Copy($journalPath,$evidence)}
if($journal.State -ne 'external-rollback-pending') {
$journal.State='external-rollback-pending';Write-PIBJson $journalPath $journal
$journalHash=Get-PIBHash $journalPath
}
$writes=0
# Restore program dependencies and shell first; main EXE is last among
# payload files. The original durable journal is the FINAL mutation.
$sequence=@($s.Entries | Where-Object {$_.Key -notin @('payload:VPNPlus.exe','metadata:journal','metadata:uninstall')})
foreach($entry in $sequence) {
$dest=Get-PIBDestination $p $entry.Key;$current=Get-PIBHash $dest
if($current -eq $entry.Sha256){continue}
if(-not $next.ContainsKey($entry.Key) -or $current -ne $next[$entry.Key]) { throw 'Destination changed during restore; no overwrite' }
if($entry.Sha256){Copy-PIBAtomic (Join-Path $job "baseline/$($entry.Id).bin") $dest $entry.Sha256}else{[IO.File]::Delete($dest)}
if((Get-PIBHash $dest) -ne $entry.Sha256){throw 'Replacement verification failed'}
$writes++
if($FixtureInterruptAfter -eq $writes){throw 'Injected fixture interruption during rollback'}
}
Restore-PIBRegistration $p $s.Registration $candidateRegistration
$main=$byKey['payload:VPNPlus.exe'];$mainPath=Get-PIBDestination $p $main.Key;$current=Get-PIBHash $mainPath
if($current -ne $main.Sha256) {
if($current -ne $next[$main.Key]) { throw 'Main executable changed during restore' }
Copy-PIBAtomic (Join-Path $job "baseline/$($main.Id).bin") $mainPath $main.Sha256;$writes++
if($FixtureInterruptAfter -eq $writes){throw 'Injected fixture interruption during rollback'}
}
foreach($entry in $s.Entries | Where-Object Key -ne 'metadata:journal') {
if((Get-PIBHash (Get-PIBDestination $p $entry.Key)) -ne $entry.Sha256){throw 'Incomplete restore; launch barrier retained'}
}
if(-not(Test-PIBEqual (Get-PIBRegistration $p) $s.Registration)){throw 'Incomplete registry restore; launch barrier retained'}
if((Get-PIBHash $journalPath) -ne $journalHash){throw 'Transaction changed during restore'}
$oldJournal=$byKey['metadata:journal']
if($oldJournal.Sha256){Copy-PIBAtomic (Join-Path $job "baseline/$($oldJournal.Id).bin") $journalPath $oldJournal.Sha256}else{[IO.File]::Delete($journalPath)}
$writes++
Assert-ProductionInstallationRestored $s
return [ordered]@{Passed=$true;AlreadyRestored=$false;Writes=$writes;Mode=$RequiredMode;ObservedJournalSha256=$journalHash}
} finally {
if($transactionLock){$transactionLock.Dispose()}
if($clientAcquired){$client.ReleaseMutex()}
if($client){$client.Dispose()}
if($jobLock){$jobLock.Dispose()}
}
}
function Restore-ProductionInstallationBaseline([string]$JobDirectory,[string]$BaselineSha256) {
return (Restore-PIBBaselineCore $JobDirectory $BaselineSha256 'production-current-user')
}
function Restore-PIBFixtureBaseline([string]$JobDirectory,[string]$BaselineSha256,[int]$FixtureInterruptAfter=-1) {
return (Restore-PIBBaselineCore $JobDirectory $BaselineSha256 'fixture-only' $FixtureInterruptAfter)
}