Files
rust-discovery/deploy/windows/Set-PassiveJobPair.ps1
T
2026-11-15 23:54:35 +01:00

400 lines
21 KiB
PowerShell

#requires -Version 5.1
#requires -RunAsAdministrator
# Fixed console maintenance of the passive test guest. No queue, network, or script job.
[CmdletBinding()]
param(
[Parameter(Mandatory)][ValidateSet('StageEchoInputs','Prepare','InstallPassive','Read','RestorePrevious')][string]$Mode,
[switch]$EchoPassive
)
$ErrorActionPreference = 'Stop'
if ($Mode -ceq 'StageEchoInputs' -and !$EchoPassive) { throw 'Staging applies only to the sealed passive successor' }
$originalCase = 'ad9fd154-b2be-4f5d-9e17-65abb721ceaf'
$originalHash = 'd8b4fd4fd9ca5310cc1591ce3c2ccae5bd72a2ade43b21a8187cfdfb960b3427'
$bootstrap = 'C:\ProgramData\RustDiscoveryBootstrap'
$oldFolder = Join-Path $bootstrap "time-profile-$originalCase"
$original = Join-Path (Join-Path $bootstrap $originalHash) 'InstallPublicTimeProfile.ps1'
$raw = [IO.File]::ReadAllBytes($original)
$digest = [Security.Cryptography.SHA256]::Create()
try { $actual = [BitConverter]::ToString($digest.ComputeHash($raw)).Replace('-','') }
finally { $digest.Dispose() }
if ($actual -ne $originalHash) { throw 'Original controller hash changed' }
$src = [Text.Encoding]::UTF8.GetString($raw)
$boundary = "`nCheckControl `$boot `$true`n"
$end = $src.IndexOf($boundary,[StringComparison]::Ordinal)
if ($end -le 0 -or $end -ne $src.LastIndexOf($boundary,[StringComparison]::Ordinal)) {
throw 'Expected the original fixed definition boundary'
}
$originalIntent = Get-Content -LiteralPath (Join-Path $oldFolder 'intent.json') -Raw | ConvertFrom-Json
if ($originalIntent.id -cne $originalCase -or $originalIntent.request.script_sha256 -cne $originalHash) {
throw 'Unexpected original case'
}
$global:RmmTimeProfilePayload = $originalIntent.request
. ([scriptblock]::Create($src.Substring(0,$end)))
$id = '49c230d8-fb5d-4c64-96b6-e0edce03ed90'
$work = Join-Path $boot "job-passive-pair-$id"
$oldHashes = [ordered]@{
agent='0549d9ebea73cff996938f859b92192cc333de194128d7c6859a3f1d2e85893c'
settings='bbccd710fd564eb5ad57eec5732b413359d09bcb5953f5de9501ccfe826bd3c2'
pin='66ef481bd9ded320d6f3dcc82b0ddaf34fdef7d80ac15d06820ff7da75a18c56'
}
$newHashes = [ordered]@{
agent='df80b00fc2119b973d690053b9f9e4bdedd8fbc211f67599c3301eeb42e7702f'
settings='7172456d56a55cced2f6ed4af1e9141499f09e67cbb16db32e2308396f9de929'
pin='b9517517cec801b10adb5d53e470fc143b8909c45e3bb95b8e4a34281f303623'
}
$locations = [ordered]@{agent=$agentBinary;settings=$settings;pin=$pin}
$profileHash = '2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b'
$helperHash = '59675a3cbb3a5d213fc764f38379d6b81baaf9d47a7124470cc2767d4985763e'
$configHash = '7c9f6f3642ef84337c3cd761d8a4788c4babe81522fdd987a3eb9b819bc8d851'
$unitProof = Join-Path $boot 'profile-unit-fcec400-result.json'
$unitHash = '48de474d842ebc87550ba2e27b66086e6aa573973f252f4b8e19ac7b12b75a63'
$linuxProofHash = 'ee3a2c99651491a2fd876f1a3463919dc32d9509d9f9ef4eb73a36aa848bb56d'
$agentBuildHash = 'a003dfa8cc2397a99933aceeb2d8dab51f883ab9cdf27876fbfc94a78873044c'
$previousPublicationHash = '62a04be9c7d08d3687b51eacd6adbe290b91e16ba934d6b5bb531e8764a56cf5'
$previousRevision = 1
$platformArchive = Join-Path $oldFolder 'platform-provenance.json'
$roleArchive = Join-Path $oldFolder '{0}-qualification.json'
function Get-SuccessorPinBytes($name,$path) {
if ((Hash $path) -cne $oldHashes.$name) { throw "Changed predecessor: $name" }
$utf8=[Text.UTF8Encoding]::new($false,$true)
$data=$utf8.GetString([IO.File]::ReadAllBytes($path)).Replace($oldHashes.agent,$newHashes.agent)
if ($name -ceq 'pin') { $data=$data.Replace($oldHashes.settings,$newHashes.settings) }
return ,$utf8.GetBytes($data)
}
function Copy-EchoInput($folder,$name,$digest,[long]$maxBytes) {
$inputFile=Join-Path $PSScriptRoot $name
$entry=Get-Item -LiteralPath $inputFile -Force
if ($entry.PSIsContainer -or $entry.Attributes -band [IO.FileAttributes]::ReparsePoint -or
$entry.Length -lt 1 -or $entry.Length -gt $maxBytes) { throw 'Unexpected passive release input' }
$bytes=[IO.File]::ReadAllBytes($inputFile)
$sha=[Security.Cryptography.SHA256]::Create()
try { $observed=[BitConverter]::ToString($sha.ComputeHash($bytes)).Replace('-','').ToLowerInvariant() }
finally { $sha.Dispose() }
if ($observed -cne $digest) { throw "Passive media input changed: $name" }
if (!(Test-Path -LiteralPath $folder)) { [RmmTimeProfileCase]::CreatePrivateOnce($folder) }
CheckControl $folder $true
$dest=Join-Path $folder $name
if (!(Test-Path -LiteralPath $dest)) { WriteBytes $dest $bytes }
CheckControl $dest $false
if ((Hash $dest) -cne $digest) { throw "Different previously staged input: $name" }
}
if ($EchoPassive) {
$manifestHash = '7c331501e40c57597624ed889ea12f34a9b16d8d10f41a2a5a73d8b7d01280a1'
if ($manifestHash -cnotmatch '^[0-9a-f]{64}$') { throw 'Echo passive build has not been sealed' }
$proofDir = Join-Path $boot $manifestHash
$manifest = Join-Path $proofDir 'passive-build.json'
CheckControl $boot $true
if ($Mode -ceq 'StageEchoInputs') { Copy-EchoInput $proofDir 'passive-build.json' $manifestHash 8192 }
CheckControl $proofDir $true
CheckControl $manifest $false
if ((Hash $manifest) -cne $manifestHash) { throw 'Unrecognized passive build manifest' }
$build = Get-Content -LiteralPath $manifest -Raw | ConvertFrom-Json
$previousCase = $work
$previousSample = Join-Path $previousCase 'samples-after-restart-a1959583-44f4-47db-aff4-f0229468a15b.json'
CheckControl $previousCase $true
CheckControl $previousSample $false
if ((Hash $previousSample) -cne '34fe01eb8413c37f7e5269e1465d764bf730aa46b1a6cc371f113c7f9d285c9a') {
throw 'Predecessor role sample changed'
}
$sample = Get-Content -LiteralPath $previousSample -Raw | ConvertFrom-Json
$previousPublication = Join-Path $previousCase 'profile-published.json'
CheckControl $previousPublication $false
$previousPublicationHash = Hash $previousPublication
if ($sample.pair_case_id -cne $id -or $sample.profile_receipt_sha256 -cne $previousPublicationHash) {
throw 'Predecessor profile does not match the native role sample'
}
$id = '1d61d88b-ab17-49b1-9a8d-2427348313b4'
if ($build.case_id -cne $id -or $build.kind -cne 'rmm.windows.echo-passive-build.v1') { throw 'Wrong passive build case' }
foreach ($field in @('agent_sha256','agent_build_sha256','linux_fixture_sha256','windows_fixture_sha256','cargo_inputs_sha256','cross_crate_inputs_sha256')) {
if ($build.$field -isnot [string] -or $build.$field -cnotmatch '^[0-9a-f]{64}$') { throw "Invalid manifest digest: $field" }
}
$oldHashes = $newHashes
$newHashes = [ordered]@{agent=$build.agent_sha256}
$work = Join-Path $boot "job-passive-pair-$id"
foreach ($name in @('settings','pin')) {
$baseline = Join-Path $work ('old-'+$name)
if (Test-Path -LiteralPath $baseline) { CheckControl $work $true; CheckControl $baseline $false }
elseif ($name -ceq 'settings') { $baseline=$settings } else { $baseline=$pin }
$sha=[Security.Cryptography.SHA256]::Create()
try { $newHashes[$name]=[BitConverter]::ToString($sha.ComputeHash((Get-SuccessorPinBytes $name $baseline))).Replace('-','').ToLowerInvariant() }
finally { $sha.Dispose() }
}
foreach ($name in $oldHashes.Keys) {
if ($oldHashes[$name] -ceq $newHashes[$name]) { throw "Unchanged target generation: $name" }
}
$profileHash = $sample.profile_sha256
$previousRevision = 2
$platformArchive = Join-Path $previousCase 'profile-platform.json'
$roleArchive = Join-Path $previousCase 'profile-role-{0}.json'
$unitProof = Join-Path $proofDir 'windows-fixture.json'
$unitHash = $build.windows_fixture_sha256
$linuxProofHash = $build.linux_fixture_sha256
$agentBuildHash = $build.agent_build_sha256
foreach ($entry in @(@('agent-build.json',$agentBuildHash),@('linux-fixture.json',$linuxProofHash),@('windows-fixture.json',$unitHash),
@('cargo-inputs.json',$build.cargo_inputs_sha256),@('cross-crate-inputs.json',$build.cross_crate_inputs_sha256))) {
if ($Mode -ceq 'StageEchoInputs') { Copy-EchoInput $proofDir $entry[0] $entry[1] 1048576 }
$proof = Join-Path $proofDir $entry[0]
CheckControl $proof $false
if ((Hash $proof) -cne $entry[1]) { throw 'Passive candidate evidence differs from the reviewed manifest' }
}
if ($Mode -ceq 'StageEchoInputs') {
Copy-EchoInput (Join-Path $boot $newHashes.agent) 'rmm-agent-windows.exe' $newHashes.agent 100663296
Write-Output "Staged passive release $manifestHash"
return
}
}
$source = Join-Path (Join-Path $boot $newHashes.agent) 'rmm-agent-windows.exe'
CheckControl $boot $true
CheckControl $oldFolder $true
if ((Hash (Join-Path $oldFolder 'console-resume-empty-result.json')) -cne '62a04be9c7d08d3687b51eacd6adbe290b91e16ba934d6b5bb531e8764a56cf5') {
throw 'Unexpected original publication result'
}
function Marker($name) { Join-Path $work ($name+'.json') }
function Record($name,$value) { WriteNew (Marker $name) $value }
function LoadRecord($name) {
$path = Marker $name
CheckControl $path $false
return (Get-Content -LiteralPath $path -Raw | ConvertFrom-Json)
}
function VerifyPassiveContext {
if ((Hash $config) -cne $configHash -or (Hash $target) -cne $profileHash -or
(Hash $helperBinary) -cne $helperHash) { throw 'Passive config, predecessor time profile or unchanged helper differs' }
foreach ($dir in @((Split-Path $agentBinary),$agentRoot,$helperRoot)) { $null=ReadAcl $dir $true }
foreach ($file in @($config,$settings,$pin,$target,$agentBinary,$helperBinary)) { $null=ReadAcl $file $false }
CheckControl $unitProof $false
if ((Hash $unitProof) -cne $unitHash) {
throw 'Current native Windows profile unit receipt differs'
}
}
function CurrentFiles {
$files=[ordered]@{}
foreach ($name in $locations.Keys) { $files[$name]=FileIdentity $locations[$name] }
return $files
}
function VerifyFiles($files,$hashes) {
foreach ($name in $locations.Keys) {
if ($files.$name.sha256 -cne $hashes.$name) { throw "Unexpected $name bytes" }
}
}
function LiveRole($role,$expectedHash) {
$s=Service $role
if ($s.state -cne 'Running') { throw "$role must be running" }
$handle=[RmmPipeNative]::Open([int]$s.pid)
try {
$k=Kernel $role $s $handle
$f=FileIdentity $k.image
if ($f.sha256 -cne $expectedHash -or !(JsonEqual $s (Service $role)) -or ![RmmPipeNative]::Alive($handle)) {
throw "$role generation or image changed"
}
return [ordered]@{service=$s; kernel=$k; image_file=$f}
} finally { $handle.Dispose() }
}
function PreservedDevice {
$device = [ordered]@{
config=(FileIdentity $config)
identity=(FileIdentity (Join-Path $agentState 'identity.json') $true)
certificate=(FileIdentity (Join-Path $agentState 'device.pem') $true)
private_key_metadata=(FileIdentityMetadata (Join-Path $agentState 'device.key'))
helper=(FileIdentity $helperBinary)
time_profile=(FileIdentity $target)
}
if ($EchoPassive) {
$device['journals'] = [ordered]@{}
foreach ($journal in @((Join-Path $agentState 'telemetry.sqlite'),(Join-Path $agentState 'consumption.sqlite'),(Join-Path $helperState 'ledger.sqlite'))) {
$item=Get-Item -LiteralPath $journal -Force
if ($item.PSIsContainer) { throw 'Unexpected journal directory' }
for ($ancestor=$item; $null -ne $ancestor; ) {
if ($ancestor.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Journal path is a reparse point' }
if ($ancestor -is [IO.FileInfo]) { $ancestor=$ancestor.Directory } else { $ancestor=$ancestor.Parent }
}
# FILE_READ_ATTRIBUTES with read/write/delete sharing permits the passive
# runtime to append. No journal contents are opened or copied.
$handle=[RmmPipeNative]::CreateFile($journal,0x80,7,[IntPtr]::Zero,3,0,[IntPtr]::Zero)
try {
$identity=New-Object RmmPipeNative+FileId
if ($handle.IsInvalid -or ![RmmPipeNative]::GetFileInformationByHandleEx($handle,18,[ref]$identity,24)) {
throw 'Cannot bind native journal identity'
}
$device.journals[$journal]=[ordered]@{volume=$identity.Volume.ToString();file_id=[BitConverter]::ToString($identity.Id);acl_sha256=(AclHash $journal)}
} finally { $handle.Dispose() }
}
}
return $device
}
function FlushFile($path) {
$f=[IO.File]::Open($path,'Open','ReadWrite','Read')
try { $f.Flush($true) } finally { $f.Dispose() }
}
function StopKnownRole($role,$name,$bound,$prefix) {
$s=Service $role
if (!(JsonEqual $s $bound.service)) { throw "$role changed before stop" }
$h=[RmmPipeNative]::Open([int]$s.pid)
try {
if (!(JsonEqual (Kernel $role $s $h) $bound.kernel)) { throw 'Kernel role changed' }
Record ($prefix+'-stop-'+$role) $bound
Stop-Service -Name $name
(Get-Service -Name $name).WaitForStatus('Stopped',[TimeSpan]::FromSeconds(30))
if (![RmmPipeNative]::Exited($h,5000)) { throw "$role did not exit" }
} finally { $h.Dispose() }
}
function StopCheck {
if ((Service 'agent').state -cne 'Stopped' -or (Service 'helper').state -cne 'Stopped') {
throw 'Both services must be stopped'
}
}
function SwapFile($name,$inputPath,$oldId,$newHash,$prefix) {
StopCheck
$dest=$locations[$name]
$backup=Join-Path $work ($prefix+'-replaced-'+$name)
$stage=Join-Path $work ($prefix+'-stage-'+$name)
CheckControl $inputPath $false
if (!(JsonEqual $oldId (FileIdentity $dest)) -or (Hash $inputPath) -cne $newHash -or (Test-Path -LiteralPath $backup)) {
throw "Replacement precondition $name"
}
# A new independently written stage preserves the case directory ACL and
# avoids inheriting a read-only ISO file attribute.
WriteBytes $stage ([IO.File]::ReadAllBytes($inputPath))
FlushFile $stage
$candidate=FileIdentity $stage
if ($candidate.sha256 -cne $newHash -or $candidate.volume_serial -cne $oldId.volume_serial) { throw 'Invalid same-volume candidate' }
$originalAcl=Get-Acl -LiteralPath $dest
Record ($prefix+'-replace-'+$name) ([ordered]@{previous=$oldId;candidate=$candidate})
if (!(JsonEqual $oldId (FileIdentity $dest)) -or !(JsonEqual $candidate (FileIdentity $stage))) { throw 'Changed replacement identities' }
[IO.File]::Replace($stage,$dest,$backup)
$privateAcl=New-Object Security.AccessControl.FileSecurity
$privateAcl.SetSecurityDescriptorSddlForm('O:BAG:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)')
Set-Acl -LiteralPath $backup -AclObject $privateAcl
CheckControl $backup $false
if ((AclHash $dest) -cne $oldId.acl_sha256) {
Set-Acl -LiteralPath $dest -AclObject $originalAcl
}
FlushFile $dest
$new=FileIdentity $dest
if ($new.sha256 -cne $newHash -or $new.acl_sha256 -cne $oldId.acl_sha256 -or (Hash $backup) -cne $oldId.sha256) {
throw "Replacement readback $name"
}
Record ($prefix+'-installed-'+$name) $new
}
function StartKnownRole($role,$name,$hash,$prefix) {
if ((Service $role).state -cne 'Stopped') { throw "$role not stopped" }
Record ($prefix+'-start-'+$role) @{old_state='Stopped';expected_hash=$hash}
Start-Service -Name $name
(Get-Service -Name $name).WaitForStatus('Running',[TimeSpan]::FromSeconds(30))
Record ($prefix+'-started-'+$role) (LiveRole $role $hash)
}
function PrepareFiles($before) {
CheckControl (Split-Path $source) $true
CheckControl $source $false
if ((FileIdentity $source).sha256 -cne $newHashes.agent) { throw 'New agent hash' }
foreach ($name in $locations.Keys) {
$copy=Join-Path $work ('old-'+$name)
[IO.File]::Copy($locations[$name],$copy,$false)
# Copy can retain the source descriptor. Restrict backups to the case.
$acl=New-Object Security.AccessControl.FileSecurity
$acl.SetSecurityDescriptorSddlForm('O:BAG:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)')
Set-Acl -LiteralPath $copy -AclObject $acl
CheckControl $copy $false
FlushFile $copy
if ((Hash $copy) -cne $oldHashes.$name) { throw "Backup $name" }
}
foreach ($name in @('settings','pin')) {
$path=Join-Path $work ('new-'+$name)
WriteBytes $path (Get-SuccessorPinBytes $name $locations[$name])
if ((Hash $path) -cne $newHashes.$name) { throw "Closed successor bytes $name" }
}
if (!(JsonEqual $before (CurrentFiles))) { throw 'Original inputs changed during copy' }
}
if ($Mode -eq 'Read') {
$r=[ordered]@{id=$id;mode='read_only';files=(CurrentFiles);agent=(Service 'agent');helper=(Service 'helper');markers=@()}
if (Test-Path -LiteralPath $work) {
CheckControl $work $true
$r.markers=@(Get-ChildItem -LiteralPath $work -Filter '*.json' -File | Select-Object -ExpandProperty Name)
if ((Test-Path -LiteralPath (Marker 'installed')) -and $r.files.agent.sha256 -ceq $newHashes.agent -and
$r.agent.state -ceq 'Running' -and $r.helper.state -ceq 'Running') {
$r.new_agent=LiveRole 'agent' $newHashes.agent
$r.unchanged_helper=LiveRole 'helper' $helperHash
}
}
$r|ConvertTo-Json -Depth 12 -Compress
return
}
VerifyPassiveContext
if ($Mode -eq 'Prepare') {
$before=CurrentFiles
VerifyFiles $before $oldHashes
$agent=LiveRole 'agent' $oldHashes.agent
$helper=LiveRole 'helper' $helperHash
$device=PreservedDevice
CheckControl (Split-Path $source) $true
CheckControl $source $false
if ((Hash $source) -cne $newHashes.agent) { throw 'Candidate absent or incorrect before preparation' }
[RmmTimeProfileCase]::CreatePrivateOnce($work)
CheckControl $work $true
PrepareFiles $before
Record 'prepared' ([ordered]@{id=$id;utc=[DateTime]::UtcNow.ToString('o');files=$before;device=$device;agent=$agent;helper=$helper})
Write-Output "Prepared passive pair $id"
return
}
CheckControl $work $true
$prep=LoadRecord 'prepared'
if ($prep.id -cne $id -or !(JsonEqual $prep.device (PreservedDevice))) { throw 'Prepared case or preserved device changed' }
if ($Mode -eq 'InstallPassive') {
if (!(JsonEqual $prep.files (CurrentFiles)) -or !(JsonEqual $prep.agent (LiveRole 'agent' $oldHashes.agent)) -or
!(JsonEqual $prep.helper (LiveRole 'helper' $helperHash))) { throw 'Prepared baseline changed' }
foreach ($name in $locations.Keys) {
if ((Hash (Join-Path $work ('old-'+$name))) -cne $oldHashes.$name) { throw 'Recovery backup changed' }
}
foreach ($name in @('settings','pin')) {
if ((Hash (Join-Path $work ('new-'+$name))) -cne $newHashes.$name) { throw 'Prepared successor changed' }
}
CheckControl $source $false
if ((Hash $source) -cne $newHashes.agent) { throw 'New binary changed' }
Record 'install-intent' @{id=$id;utc=[DateTime]::UtcNow.ToString('o')}
StopKnownRole 'agent' $agentName $prep.agent 'install'
StopKnownRole 'helper' $helperName $prep.helper 'install'
foreach ($name in $locations.Keys) {
$inputPath=Join-Path $work ('new-'+$name)
if ($name -eq 'agent') { $inputPath=$source }
SwapFile $name $inputPath $prep.files.$name $newHashes.$name 'install'
}
VerifyFiles (CurrentFiles) $newHashes
StartKnownRole 'helper' $helperName $helperHash 'install'
StartKnownRole 'agent' $agentName $newHashes.agent 'install'
$a=LiveRole 'agent' $newHashes.agent
$h=LiveRole 'helper' $helperHash
if (!(JsonEqual $prep.device (PreservedDevice))) { throw 'Device changed after passive restart' }
Record 'installed' ([ordered]@{id=$id;utc=[DateTime]::UtcNow.ToString('o');agent=$a;helper=$h;files=(CurrentFiles);device=$prep.device;job_mode=$false;clock_qualified=$false})
Write-Output "Installed passive pair $id"
return
}
# An explicit recovery is valid only before publishing any successor time profile
# or enabling jobs. Verify all present files against the two known generations.
$null=LoadRecord 'install-intent'
$observed=CurrentFiles
foreach ($name in $locations.Keys) {
$hash=$observed.$name.sha256
if ($hash -cnotin @($oldHashes.$name,$newHashes.$name) -or
(Hash (Join-Path $work ('old-'+$name))) -cne $oldHashes.$name) { throw "Unknown recovery input $name" }
}
Record 'restore-intent' @{id=$id;utc=[DateTime]::UtcNow.ToString('o')}
foreach ($role in @('agent','helper')) {
$service=(Service $role)
$name=$agentName
$imageHash=$observed.agent.sha256
if ($role -eq 'helper') { $name=$helperName; $imageHash=$helperHash }
if ($service.state -ceq 'Running') { StopKnownRole $role $name (LiveRole $role $imageHash) 'restore' }
elseif ($service.state -cne 'Stopped') { throw "Unknown service transition $role" }
}
StopCheck
foreach ($name in $locations.Keys) {
if ($observed.$name.sha256 -cne $oldHashes.$name) {
SwapFile $name (Join-Path $work ('old-'+$name)) $observed.$name $oldHashes.$name 'restore'
}
}
VerifyFiles (CurrentFiles) $oldHashes
StartKnownRole 'helper' $helperName $helperHash 'restore'
StartKnownRole 'agent' $agentName $oldHashes.agent 'restore'
Record 'restored' @{id=$id;agent=(LiveRole 'agent' $oldHashes.agent);helper=(LiveRole 'helper' $helperHash)}
Write-Output "Restored passive predecessor $id"