#requires -Version 5.1 #requires -RunAsAdministrator # Development bootstrap only. Never creates jobs or approval, changes service # accounts/ACLs/PKI/journals, or reactivates the preserved active configuration. [CmdletBinding()] param( [Parameter(Mandatory)][ValidateSet('PrepareStopped','InstallStoppedPassive','PrepareProfile','PublishProfile','Read')][string]$Action, [Parameter(Mandatory)][string]$ManifestSha256 ) $ErrorActionPreference='Stop' if ($ManifestSha256 -cnotmatch '^[0-9a-f]{64}$') { throw 'Expected exact pair manifest digest.' } $bootstrap='C:\ProgramData\RustDiscoveryBootstrap' $inputFolder=Join-Path $bootstrap $ManifestSha256 $manifestPath=Join-Path $inputFolder 'pair-successor.json' if ((Get-FileHash -LiteralPath $manifestPath).Hash.ToLowerInvariant() -cne $ManifestSha256) { throw 'Pair manifest changed.' } $m=Get-Content -LiteralPath $manifestPath -Raw | ConvertFrom-Json $expectedFields='alignment_verification_sha256,case_id,linux_proof_sha256,new_agent_sha256,new_helper_sha256,old_agent_sha256,old_config_sha256,old_helper_sha256,old_pin_sha256,old_profile_sha256,old_settings_sha256,pair_build_sha256,previous_case_id,previous_publication_sha256,previous_revision,schema_version,windows_proof_sha256' if ((($m.PSObject.Properties.Name|Sort-Object)-join ',') -cne $expectedFields -or $m.schema_version -ne 1 -or $m.previous_revision -ne 6) { throw 'Expected exact revision6 to7 pair manifest.' } foreach ($name in @('case_id','previous_case_id')) { if ([guid]::ParseExact($m.$name,'D').ToString() -cne $m.$name) { throw 'Canonical case identity required.' } } foreach ($p in $m.PSObject.Properties) { if ($p.Name -notin @('case_id','previous_case_id','previous_revision','schema_version') -and $p.Value -cnotmatch '^[0-9a-f]{64}$') { throw 'Expected bound digest fields.' } } if ($m.old_config_sha256 -cne '5cd4cb9802d0dd20b961de7e3cd4e5874a1e9a72fc57b577e075e2d2918baac6' -or $m.old_helper_sha256 -cne '59675a3cbb3a5d213fc764f38379d6b81baaf9d47a7124470cc2767d4985763e' -or $m.old_agent_sha256 -ceq $m.new_agent_sha256 -or $m.old_helper_sha256 -ceq $m.new_helper_sha256) { throw 'Expected actual active predecessor and two distinct successor images.' } # Reuse only hash-sealed native declarations/file-ID/ACL/SCM primitives. None # of the old agent-only Prepare/Install/Restore action bodies are evaluated. $prior=Join-Path $bootstrap 'mvp-successor-prerequisites' $common=Join-Path $prior 'Set-PassiveJobPair.ps1' if ((Get-FileHash -LiteralPath $common).Hash.ToLowerInvariant() -cne 'b70313bfec6e2f055e0f9554d69a9a44acec4abc8afea457a059d33db3e5e410') { throw 'Qualified native primitives changed.' } $text=[Text.Encoding]::UTF8.GetString([IO.File]::ReadAllBytes($common)) $i=$text.IndexOf("`n`$originalCase = ",[StringComparison]::Ordinal) $j=$text.IndexOf("`nif (`$Mode -eq 'Read') {",[StringComparison]::Ordinal) if ($i -lt 0 -or $j -le $i -or $i -ne $text.LastIndexOf("`n`$originalCase = ",[StringComparison]::Ordinal) -or $j -ne $text.LastIndexOf("`nif (`$Mode -eq 'Read') {",[StringComparison]::Ordinal)) { throw 'Native declaration boundary.' } $Mode='Read';$EchoPassive=$false . ([scriptblock]::Create($text.Substring($i,$j-$i))) CheckControl $bootstrap $true;CheckControl $inputFolder $true;CheckControl $manifestPath $false $id=$m.case_id $work=Join-Path $bootstrap ('job-stopped-pair-'+$id) $locations=[ordered]@{agent=$agentBinary;helper=$helperBinary;settings=$settings;pin=$pin;config=$config} $oldHashes=[ordered]@{agent=$m.old_agent_sha256;helper=$m.old_helper_sha256;settings=$m.old_settings_sha256;pin=$m.old_pin_sha256;config=$m.old_config_sha256} $newHashes=[ordered]@{agent=$m.new_agent_sha256;helper=$m.new_helper_sha256} $profileHash=$m.old_profile_sha256 $previousRevision=6 $previousCase=Join-Path $bootstrap ('job-passive-pair-'+$m.previous_case_id) $previousPublication=Join-Path $previousCase 'profile-published.json' CheckControl $previousCase $true;CheckControl $previousPublication $false if ((Hash $previousPublication) -cne $m.previous_publication_sha256) { throw 'Actual revision6 publication changed.' } $previous=Get-Content -LiteralPath $previousPublication -Raw | ConvertFrom-Json if ($previous.successor_revision -ne 6 -or $previous.configuration.sha256 -cne $profileHash -or $previous.agent.image_file.sha256 -cne $m.old_agent_sha256 -or $previous.helper.image_file.sha256 -cne $m.old_helper_sha256) { throw 'Actual predecessor publication differs.' } foreach ($entry in @(@('alignment-verification.json',$m.alignment_verification_sha256),@('pair-build.json',$m.pair_build_sha256),@('linux-proof.json',$m.linux_proof_sha256),@('windows-proof.json',$m.windows_proof_sha256))) { $path=Join-Path $inputFolder $entry[0];CheckControl $path $false if ((Hash $path) -cne $entry[1]) { throw 'Reviewed pair prerequisite changed.' } } $alignment=Get-Content -LiteralPath (Join-Path $inputFolder 'alignment-verification.json') -Raw | ConvertFrom-Json if ($alignment.read_only -ne $true -or $alignment.admin_archive_verified -ne $true -or $alignment.helper_checkpoint -ne 201 -or $alignment.agent_checkpoint -ne 10137 -or $alignment.helper_last_decision -cne '2af359c5-5b5c-4992-b445-1c00e271a288' -or $alignment.ready -ne $false -or $alignment.helper_ready -ne $false -or $alignment.unlock -ne $false) { throw 'Actual closed G205 verification required.' } foreach ($name in @('linux-proof.json','windows-proof.json')) { $proof=Get-Content -LiteralPath (Join-Path $inputFolder $name) -Raw|ConvertFrom-Json;if ($proof.verified -ne $true -or $proof.passed -ne 3 -or $proof.failed -ne 0) { throw 'Native targeted units have not passed.' } } $build=Get-Content -LiteralPath (Join-Path $inputFolder 'pair-build.json') -Raw|ConvertFrom-Json if ($build.artifacts.'rmm-agent-windows.exe' -cne $m.new_agent_sha256 -or $build.artifacts.'rmm-helper-windows.exe' -cne $m.new_helper_sha256) { throw 'Pair images not bound to actual isolated build.' } function Baseline($name) { $copy=Join-Path $work ('old-'+$name);if (Test-Path -LiteralPath $copy) {CheckControl $copy $false;return $copy};return $locations[$name] } function BytesHash([byte[]]$data) { $sha=[Security.Cryptography.SHA256]::Create();try{return [BitConverter]::ToString($sha.ComputeHash($data)).Replace('-','').ToLowerInvariant()}finally{$sha.Dispose()} } function ReplaceOnce([string]$text,[string]$old,[string]$new) { $at=$text.IndexOf($old,[StringComparison]::Ordinal);if($at -lt 0 -or $at -ne $text.LastIndexOf($old,[StringComparison]::Ordinal)){throw 'Expected unique original binding.'};return $text.Replace($old,$new) } function RenderPairFiles { foreach ($name in $oldHashes.Keys) { if ((Hash (Baseline $name)) -cne $oldHashes[$name]) { throw 'Original pair bytes changed.' } } $utf8=[Text.UTF8Encoding]::new($false,$true) $s=$utf8.GetString([IO.File]::ReadAllBytes((Baseline 'settings'))) $old=$s|ConvertFrom-Json if ($old.enable_effects -ne $false -or $old.allow_reboot -ne $false -or $old.agent.binary_sha256 -cne $m.old_agent_sha256 -or $old.helper.binary_sha256 -cne $m.old_helper_sha256) { throw 'Expected passive original helper and actual old pins.' } $s=ReplaceOnce $s $m.old_agent_sha256 $m.new_agent_sha256 $s=ReplaceOnce $s $m.old_helper_sha256 $m.new_helper_sha256 $newHashes.settings=BytesHash ($utf8.GetBytes($s)) $p=$utf8.GetString([IO.File]::ReadAllBytes((Baseline 'pin'))) $oldPin=$p|ConvertFrom-Json if ($oldPin.policy_sha256 -cne $m.old_settings_sha256 -or !(JsonEqual $old.binding $oldPin.binding)) { throw 'Original canonical settings/pin binding changed.' } $p=ReplaceOnce $p $m.old_agent_sha256 $m.new_agent_sha256 $p=ReplaceOnce $p $m.old_helper_sha256 $m.new_helper_sha256 $p=ReplaceOnce $p $m.old_settings_sha256 $newHashes.settings $newHashes.pin=BytesHash ($utf8.GetBytes($p)) $c=Get-Content -LiteralPath (Baseline 'config') -Raw|ConvertFrom-Json if ($c.enable_jobs -ne $true -or $c.server_name -cne 'discovery.ease-technologies.de' -or $c.state_directory -cne $agentState -or $c.windows_execution_profile -cne 'powershell_51_remote_signed' -or ($null -ne $c.PSObject.Properties['windows_echo_probe_only'] -and $c.windows_echo_probe_only -ne $false)) { throw 'Actual unrestricted active predecessor configuration required.' } $c.enable_jobs=$false $c.PSObject.Properties.Remove('windows_execution_profile') $configBytes=$utf8.GetBytes(($c|ConvertTo-Json -Depth 12 -Compress)) $newHashes.config=BytesHash $configBytes return [ordered]@{settings=$utf8.GetBytes($s);pin=$utf8.GetBytes($p);config=$configBytes} } $rendered=RenderPairFiles $originalPreservedDevice=(Get-Item Function:\PreservedDevice).ScriptBlock function PreservedNativeState { $was=$EchoPassive;$EchoPassive=$true try { $v=& $originalPreservedDevice } finally { $EchoPassive=$was } foreach ($name in @('config','helper','time_profile')) {$v.Remove($name)} $v['private_key_generations']=@() foreach ($key in @(Get-ChildItem -LiteralPath $agentState -File -Filter 'device*.key'|Sort-Object Name)) { $v.private_key_generations+=FileIdentityMetadata $key.FullName } $v['intent_journal']=FileIdentityMetadata 'C:\ProgramData\RustDiscoverySystem\agent-intents\system-intents.sqlite' $v['agent_lock']=FileIdentityMetadata (Join-Path $agentState 'agent.lock') $v['helper_lock']=FileIdentityMetadata (Join-Path $helperState 'executor.lock') return $v } # Fixed original lifetime locks. Closing releases the range; never stop/start a # service while holding a lock that the new service must acquire. Add-Type -TypeDefinition @' using System; using System.IO; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; public sealed class RmmStoppedPairLocks : IDisposable { [StructLayout(LayoutKind.Sequential)] struct Ov { public UIntPtr Internal,InternalHigh;public uint Offset,OffsetHigh;public IntPtr Event; } [DllImport("kernel32.dll",SetLastError=true)] static extern bool LockFileEx(SafeFileHandle h,uint flags,uint zero,uint low,uint high,ref Ov ov); readonly FileStream[] held=new FileStream[2]; public RmmStoppedPairLocks(){string[] paths={@"C:\ProgramData\RustDiscovery\state\agent.lock",@"C:\ProgramData\RustDiscoverySystem\state\executor.lock"};try{for(int i=0;i<2;i++){held[i]=new FileStream(paths[i],FileMode.Open,FileAccess.Read,FileShare.ReadWrite);Ov ov=new Ov();if(!LockFileEx(held[i].SafeFileHandle,3,0,uint.MaxValue,uint.MaxValue,ref ov))throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());}}catch{Dispose();throw;}} public void Dispose(){foreach(FileStream f in held)if(f!=null)f.Dispose();} } '@ function RequirePredecessorStopped { StopCheck if ((Hash $target) -cne $profileHash) { throw 'Revision6 time profile changed.' } VerifyFiles (CurrentFiles) $oldHashes } if ($Action -ceq 'Read') { [ordered]@{id=$id;files=(CurrentFiles);device=(PreservedNativeState);agent=(Service 'agent');helper=(Service 'helper');successor_hashes=$newHashes;markers=@(Get-ChildItem -LiteralPath $work -File -Filter '*.json' -ErrorAction SilentlyContinue|Select-Object -ExpandProperty Name)}|ConvertTo-Json -Depth 16 -Compress;return } if ($Action -ceq 'PrepareStopped') { RequirePredecessorStopped if (Test-Path -LiteralPath $work) { throw 'Existing case: Read only.' } $locks=[RmmStoppedPairLocks]::new() try { RequirePredecessorStopped [RmmTimeProfileCase]::CreatePrivateOnce($work) $before=CurrentFiles;$device=PreservedNativeState foreach ($name in $locations.Keys) { WriteBytes (Join-Path $work ('old-'+$name)) ([IO.File]::ReadAllBytes($locations[$name])) if ((Hash (Join-Path $work ('old-'+$name))) -cne $oldHashes[$name]) { throw 'Original public backup differs.' } } foreach ($name in $rendered.Keys) { WriteBytes (Join-Path $work ('new-'+$name)) $rendered[$name] } foreach ($role in @('agent','helper')) { $binary=Join-Path (Join-Path $bootstrap $newHashes[$role]) ('rmm-'+$role+'-windows.exe');CheckControl $binary $false;if((Hash $binary)-cne$newHashes[$role]){throw 'Exact staged successor image required.'} } if (!(JsonEqual $before (CurrentFiles)) -or !(JsonEqual $device (PreservedNativeState))) { throw 'Original pair changed during preparation.' } Record 'prepared' ([ordered]@{id=$id;manifest_sha256=$ManifestSha256;files=$before;device=$device;old_active_config_sha256=$m.old_config_sha256;new_hashes=$newHashes;original_services_stopped=$true;successor_revision=7;job_mode=$false;privileged_effects=$false}) } finally { $locks.Dispose() } Write-Output 'Prepared stopped code-pair successor; no service or original target changed.';return } $preparedPair=LoadRecord 'prepared' if ($preparedPair.id -cne $id -or $preparedPair.manifest_sha256 -cne $ManifestSha256 -or !(JsonEqual $preparedPair.new_hashes $newHashes)) { throw 'Different reviewed pair preparation.' } if ($Action -ceq 'InstallStoppedPassive') { RequirePredecessorStopped if (Test-Path -LiteralPath (Marker 'install-intent')) { throw 'Existing transition: Read only; no blind retry.' } $locks=[RmmStoppedPairLocks]::new() try { RequirePredecessorStopped if (!(JsonEqual $preparedPair.files (CurrentFiles)) -or !(JsonEqual $preparedPair.device (PreservedNativeState))) { throw 'Stopped original pair or identity changed.' } Record 'install-intent' @{id=$id;manifest_sha256=$ManifestSha256;original_services_stopped=$true} foreach ($name in $locations.Keys) { $inputPath=Join-Path $work ('new-'+$name) if ($name -in @('agent','helper')) {$inputPath=Join-Path (Join-Path $bootstrap $newHashes[$name]) ('rmm-'+$name+'-windows.exe')} SwapFile $name $inputPath $preparedPair.files.$name $newHashes[$name] 'install' } if (!(JsonEqual $preparedPair.device (PreservedNativeState))) { throw 'Original identity/journal metadata changed.' } Record 'files-installed' @{id=$id;files=(CurrentFiles);device=(PreservedNativeState);job_mode=$false;privileged_effects=$false} } finally { $locks.Dispose() } # No old-pair intermediate start. Only the actual new passive pair starts. StartKnownRole 'helper' $helperName $newHashes.helper 'install' StartKnownRole 'agent' $agentName $newHashes.agent 'install' Record 'installed' @{id=$id;files=(CurrentFiles);device=(PreservedNativeState);agent=(LiveRole 'agent' $newHashes.agent);helper=(LiveRole 'helper' $newHashes.helper);job_mode=$false;clock_qualified=$false;privileged_effects=$false} Write-Output 'Installed both new images with passive configuration; active original retained.';return } # The qualified publisher's action bodies are excluded. Its unchanged native # swap/readback/start functions remain the implementation; the two changed # image bindings and per-role build provenance are explicit below. $publisher=Join-Path $prior 'Publish-JobPairTimeProfile.ps1' CheckControl $publisher $false if ((Hash $publisher) -cne '6b6f64192d82f98c449ea3c36c5da0f8b179ecd5d6f944f36151969d645b9fb5') { throw 'Qualified publication primitives changed.' } $pub=[Text.Encoding]::UTF8.GetString([IO.File]::ReadAllBytes($publisher)) $i=$pub.IndexOf('function RequireNewPassivePair {',[StringComparison]::Ordinal) $j=$pub.IndexOf("`nif (`$Action -ceq 'Read') {",[StringComparison]::Ordinal) if($i -lt 0 -or $j -le $i){throw 'Publication declaration boundary.'} . ([scriptblock]::Create($pub.Substring($i,$j-$i))) $helperHash=$newHashes.helper $configHash=$newHashes.config $previousPublicationHash=$m.previous_publication_sha256 $platformArchive=Join-Path $previousCase 'profile-platform.json' $roleArchive=Join-Path $previousCase 'profile-role-{0}.json' $agentBuildHash=$m.pair_build_sha256 $linuxProofHash=$m.linux_proof_sha256 $unitHash=$m.windows_proof_sha256 $unitProof=Join-Path $inputFolder 'windows-proof.json' $activation=Marker 'profile-publish-intent';$ready=Marker 'profile-prepared';$success=Marker 'profile-published' function PreservedDevice { return (PreservedNativeState) } # The source/build proof now belongs to BOTH actual successor images. The old # publisher's hard-coded unchanged-helper build receipt is deliberately unused. function RoleDigests($platformHash,$installedHash,$independentHash,$previous) { $out=@{} foreach($name in @('agent','system_helper')) { $bound=$installed.agent;if($name -ceq 'system_helper'){$bound=$installed.helper} $old=@($previous.trusted_os_active_guest.qualifications|Where-Object{$_.role -ceq $name}) if($old.Count -ne 1){throw 'Expected exactly one prior qualification for each actual role.'} $archive=$roleArchive -f $name;CheckControl $archive $false if((Hash $archive)-cne$old[0].qualification_sha256){throw 'Prior role qualification changed.'} $archived=Get-Content -LiteralPath $archive -Raw|ConvertFrom-Json $expectedImage=$newHashes.agent;if($name -ceq 'system_helper'){$expectedImage=$newHashes.helper} if($bound.image_file.sha256-cne$expectedImage){throw 'Actual new role image differs.'} Record ('profile-role-'+$name) ([ordered]@{ profile='rmm.windows.trusted-os.product-role-prerequisite.v1';role=$name binary_sha256=$bound.image_file.sha256;service=$bound.service;kernel=$bound.kernel image_file=$bound.image_file;predecessor_qualification_sha256=$old[0].qualification_sha256 pair_case_id=$id;pair_result_sha256=$installedHash;independent_pair_readback_sha256=$independentHash product_build_receipt_sha256=$m.pair_build_sha256;platform_provenance_sha256=$platformHash raw_capture=$archived.raw_capture;signed_runtime_verified=$false;physical_calibration_claimed=$false }) $out[$name]=Hash (Marker ('profile-role-'+$name)) } return $out } # Exact, reviewed changes to the hash-sealed one-image renderer: additionally # bind the new helper image, and therefore expect five unique substitutions. $builder=(Get-Item Function:\BuildSuccessor).ScriptBlock.ToString() $needle='$changes[$oldHashes.agent]=$newHashes.agent' if($builder.IndexOf($needle,[StringComparison]::Ordinal)-lt 0 -or $builder.IndexOf($needle,[StringComparison]::Ordinal)-ne$builder.LastIndexOf($needle,[StringComparison]::Ordinal) -or !$builder.Contains('$changes.Count -ne 4')){throw 'Exact publisher renderer changed.'} $builder=$builder.Replace($needle,$needle+"`n "+'$changes[$oldHashes.helper]=$newHashes.helper').Replace('$changes.Count -ne 4','$changes.Count -ne 5') Set-Item Function:\BuildSuccessor ([scriptblock]::Create($builder)) RequireNewPassivePair $installed=LoadRecord 'installed' if($installed.id-cne$id -or $installed.job_mode-ne$false -or $installed.clock_qualified-ne$false){throw 'Actual new passive pair is required.'} if($Action-ceq'PrepareProfile') { if(Test-Path -LiteralPath $ready){throw 'Existing profile preparation: Read only.'} BuildSuccessor Write-Output 'Prepared profile7 from independently observed new Agent AND Helper; no target profile changed.';return } if($Action-cne'PublishProfile'){throw 'Unsupported action.'} $prepared=LoadRecord 'profile-prepared';CheckPrepared;RequireNewPassivePair $held=LoadRecord 'profile-independent-native-read' if(!(JsonEqual $held.agent (LiveRole 'agent' $newHashes.agent))-or!(JsonEqual $held.helper (LiveRole 'helper' $newHashes.helper))-or!(JsonEqual $held.device (PreservedNativeState))){throw 'Actual new passive role observations changed.'} if(Test-Path -LiteralPath $activation){throw 'Existing profile publication: Read only; no blind retry.'} Record 'profile-publish-intent' ([ordered]@{id=$id;utc=[DateTime]::UtcNow.ToString('o');prepared_sha256=(Hash $ready)}) StopKnownRole 'agent' $agentName $held.agent 'time' StopKnownRole 'helper' $helperName $held.helper 'time' $locks=[RmmStoppedPairLocks]::new() try { StopCheck if(!(JsonEqual $held.device (PreservedNativeState))){throw 'Original journal identity changed before profile replacement.'} $locations.Add('time',$target) try { SwapFile 'time' (Join-Path $work 'new-time-profile') $prepared.predecessor $prepared.successor_sha256 'time' } finally { $locations.Remove('time') } } finally { $locks.Dispose() } FinishPublication