diff --git a/deploy/windows/Publish-JobPairTimeProfile.ps1 b/deploy/windows/Publish-JobPairTimeProfile.ps1 index 846a12a..f6a8e2d 100644 --- a/deploy/windows/Publish-JobPairTimeProfile.ps1 +++ b/deploy/windows/Publish-JobPairTimeProfile.ps1 @@ -2,9 +2,12 @@ #requires -RunAsAdministrator # Publish the next trusted-OS profile from actual passive service observations. [CmdletBinding()] -param([Parameter(Mandatory)][ValidateSet('Prepare','Publish','Read','FinishStarts')][string]$Action) +param( + [Parameter(Mandatory)][ValidateSet('Prepare','Publish','Read','FinishStarts')][string]$Action, + [switch]$EchoPassive +) $ErrorActionPreference='Stop' -$commonHash='c54e36b32a2fcccb072f2cca52a38b6c4da31755d86205599016c5d180f5cec4' +$commonHash='723bd03d809191455f5909644f518ae2bebabbbb9ce6399f3007cb4cc0bc9341' $common=Join-Path $PSScriptRoot 'Set-PassiveJobPair.ps1' if ((Get-FileHash -LiteralPath $common -Algorithm SHA256).Hash -ne $commonHash) { throw 'The reviewed passive-pair controller must be next to this script' @@ -17,6 +20,7 @@ $j=$text.IndexOf($last,[StringComparison]::Ordinal) if ($i -lt 0 -or $j -le $i -or $i -ne $text.LastIndexOf($first,[StringComparison]::Ordinal) -or $j -ne $text.LastIndexOf($last,[StringComparison]::Ordinal)) { throw 'Passive-pair definition boundary' } # Fixed declarations and functions only. Its Prepare, Install and Restore bodies are excluded. +$Mode='Read' . ([scriptblock]::Create($text.Substring($i,$j-$i))) CheckControl $work $true $activation=(Marker 'profile-publish-intent') @@ -34,11 +38,11 @@ function RoleDigests($platformHash,$installedHash,$independentHash,$previous) { 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 one predecessor witness per role' } - $archive=Join-Path $oldFolder ($name+'-qualification.json') + $archive=$roleArchive -f $name CheckControl $archive $false if ((Hash $archive) -cne $old[0].qualification_sha256) { throw 'Original role provenance changed' } $archived=Get-Content -LiteralPath $archive -Raw | ConvertFrom-Json - $build='a003dfa8cc2397a99933aceeb2d8dab51f883ab9cdf27876fbfc94a78873044c' + $build=$agentBuildHash if ($name -ceq 'system_helper') { # The old pair receipt linked the later agent and referenced the # separately built helper. Identify the actual helper link itself. @@ -58,8 +62,7 @@ function RoleDigests($platformHash,$installedHash,$independentHash,$previous) { } function BuildSuccessor { $installedHash=Hash (Marker 'installed') - $unit=Join-Path $boot 'profile-unit-fcec400-result.json' - if ((Hash $unit) -cne '48de474d842ebc87550ba2e27b66086e6aa573973f252f4b8e19ac7b12b75a63') { throw 'Windows unit evidence changed' } + if ((Hash $unitProof) -cne $unitHash) { throw 'Windows unit evidence changed' } $independent=[ordered]@{agent=(LiveRole 'agent' $newHashes.agent);helper=(LiveRole 'helper' $helperHash);files=(CurrentFiles);device=(PreservedDevice)} foreach ($field in $independent.Keys) { if (!(JsonEqual $installed.$field $independent.$field)) { throw "Independent native pair read differs: $field" } @@ -74,7 +77,7 @@ function BuildSuccessor { $old.trusted_os_active_guest.operating_assumption -cne 'active_guest_no_pause_save_restore_snapshot_migration_host_suspend' -or $old.trusted_os_active_guest.platform -cne 'kvm_qemu_hypervclock' -or @($old.trusted_os_active_guest.qualifications).Count -ne 2) { throw 'Unexpected original V2 contract' } - $platform=Join-Path $oldFolder 'platform-provenance.json' + $platform=$platformArchive CheckControl $platform $false $oldPlatformHash=Hash $platform if ($oldPlatformHash -cne $old.trusted_os_active_guest.platform_provenance_sha256) { throw 'Original platform provenance changed' } @@ -83,9 +86,8 @@ function BuildSuccessor { platform=$old.trusted_os_active_guest.platform;previous_platform_provenance_sha256=$oldPlatformHash predecessor_profile_sha256=$profileHash;pair_case_id=$id;pair_result_sha256=$installedHash independent_pair_readback_sha256=$independentHash;independent_physical_calibration_claimed=$false - agent_build_receipt_sha256='a003dfa8cc2397a99933aceeb2d8dab51f883ab9cdf27876fbfc94a78873044c' - linux_profile_unit_sha256='ee3a2c99651491a2fd876f1a3463919dc32d9509d9f9ef4eb73a36aa848bb56d' - windows_profile_unit_sha256=(Hash $unit) + agent_build_receipt_sha256=$agentBuildHash;linux_profile_unit_sha256=$linuxProofHash + windows_profile_unit_sha256=(Hash $unitProof) }) $platformHash=Hash (Marker 'profile-platform') $roles=RoleDigests $platformHash $installedHash $independentHash $old @@ -116,13 +118,14 @@ function BuildSuccessor { Record 'profile-prepared' ([ordered]@{ id=$id;utc=[DateTime]::UtcNow.ToString('o');predecessor=(FileIdentity $target);successor_sha256=(Hash $draft) source_sha256=$installedHash;independent_sha256=$independentHash;platform_sha256=$platformHash;role_sha256=$roles - original_publish_result_sha256='62a04be9c7d08d3687b51eacd6adbe290b91e16ba934d6b5bb531e8764a56cf5' - predecessor_revision=1;successor_revision=2;signing_key_generation=$old.key_generation;clock_qualified=$false + original_publish_result_sha256=$previousPublicationHash + predecessor_revision=$previousRevision;successor_revision=($previousRevision+1);signing_key_generation=$old.key_generation;clock_qualified=$false }) } function CheckPrepared { if ($prepared.id -cne $id -or $prepared.predecessor.sha256 -cne $profileHash -or - $prepared.successor_revision -ne 2 -or $prepared.predecessor_revision -ne 1 -or $prepared.signing_key_generation -ne 1 -or + $prepared.successor_revision -ne ($previousRevision+1) -or $prepared.predecessor_revision -ne $previousRevision -or $prepared.signing_key_generation -ne 1 -or + $prepared.original_publish_result_sha256 -cne $previousPublicationHash -or $prepared.source_sha256 -cne (Hash (Marker 'installed')) -or $prepared.independent_sha256 -cne (Hash (Marker 'profile-independent-native-read')) -or $prepared.platform_sha256 -cne (Hash (Marker 'profile-platform')) -or @@ -169,7 +172,7 @@ function FinishPublication { } Record 'profile-published' ([ordered]@{ id=$id;utc=[DateTime]::UtcNow.ToString('o');configuration=(FileIdentity $target) - predecessor=$prepared.predecessor; successor_revision=2; signing_key_generation=1 + predecessor=$prepared.predecessor; successor_revision=($previousRevision+1); signing_key_generation=1 role_proofs=$prepared.role_sha256; publication_since=$intent.utc agent=(LiveRole 'agent' $newHashes.agent); helper=(LiveRole 'helper' $helperHash) signed_runtime_verified=$false; job_mode=$false;privileged_effects=$false diff --git a/deploy/windows/Read-JobPairTimeSamples.ps1 b/deploy/windows/Read-JobPairTimeSamples.ps1 index 4b60aac..4bf9b4c 100644 --- a/deploy/windows/Read-JobPairTimeSamples.ps1 +++ b/deploy/windows/Read-JobPairTimeSamples.ps1 @@ -3,18 +3,30 @@ [CmdletBinding()] param( [Parameter(Mandatory)][ValidateRange(1,9223372036854775807)][long]$Generation, - [switch]$AfterRestart + [switch]$AfterRestart, + [switch]$EchoPassive ) $ErrorActionPreference = 'Stop' Add-Type -AssemblyName System.Runtime.Serialization $caseId = '49c230d8-fb5d-4c64-96b6-e0edce03ed90' +$revision = 2 +$agentHash = 'df80b00fc2119b973d690053b9f9e4bdedd8fbc211f67599c3301eeb42e7702f' +if ($EchoPassive) { + $pair = Join-Path $PSScriptRoot 'Set-PassiveJobPair.ps1' + if ((Get-FileHash -LiteralPath $pair).Hash -ne '723bd03d809191455f5909644f518ae2bebabbbb9ce6399f3007cb4cc0bc9341') { throw 'Passive controller changed' } + $observed = (& $pair -Mode Read -EchoPassive) | ConvertFrom-Json + if ($observed.id -cne '1d61d88b-ab17-49b1-9a8d-2427348313b4' -or + $observed.new_agent.image_file.sha256 -cnotmatch '^[0-9a-f]{64}$') { throw 'Passive successor missing' } + $caseId = $observed.id + $agentHash = $observed.new_agent.image_file.sha256 + $revision = 3 +} $bootDir = 'C:\ProgramData\RustDiscoveryBootstrap' $caseDir = Join-Path $bootDir "job-passive-pair-$caseId" $publication = Join-Path $caseDir 'profile-published.json' $profile = 'C:\ProgramData\RustDiscoverySystem\time-attestation.json' $reader = Join-Path $PSScriptRoot 'Read-PassiveTimeSamples.ps1' $readerHash = 'd9e2b9344c19af1296b86ec70ba754ef820f369ac5ec897979bd4233e0722d04' -$agentHash = 'df80b00fc2119b973d690053b9f9e4bdedd8fbc211f67599c3301eeb42e7702f' $helperHash = '59675a3cbb3a5d213fc764f38379d6b81baaf9d47a7124470cc2767d4985763e' $sessionId = [guid]::NewGuid().ToString() @@ -128,7 +140,7 @@ $pub = Get-Content -LiteralPath $publication -Raw | ConvertFrom-Json $profileHash = Get-FileDigest $profile if ($pub.id -cne $caseId -or $pub.configuration.sha256 -cne $profileHash -or $pub.agent.image_file.sha256 -cne $agentHash -or $pub.helper.image_file.sha256 -cne $helperHash -or - $pub.successor_revision -ne 2 -or $pub.job_mode -ne $false) { throw 'Unexpected pair publication' } + $pub.successor_revision -ne $revision -or $pub.job_mode -ne $false) { throw 'Unexpected pair publication' } $since = Get-UtcNs $pub.publication_since $request = @{id=$sessionId;agent_sha256=$agentHash;helper_sha256=$helperHash} | ConvertTo-Json -Compress $clock = [Diagnostics.Stopwatch]::StartNew() diff --git a/deploy/windows/Resume-PassiveJobPairCopy.ps1 b/deploy/windows/Resume-PassiveJobPairCopy.ps1 index a9e0845..93286a1 100644 --- a/deploy/windows/Resume-PassiveJobPairCopy.ps1 +++ b/deploy/windows/Resume-PassiveJobPairCopy.ps1 @@ -5,12 +5,14 @@ param([Parameter(Mandatory)][ValidateSet('Read','Resume')][string]$Action) $ErrorActionPreference='Stop' $base=Join-Path $PSScriptRoot 'Set-PassiveJobPair.ps1' -$baseHash='c54e36b32a2fcccb072f2cca52a38b6c4da31755d86205599016c5d180f5cec4' +$baseHash='723bd03d809191455f5909644f518ae2bebabbbb9ce6399f3007cb4cc0bc9341' if ((Get-FileHash -LiteralPath $base).Hash -ne $baseHash) { throw 'Original passive-pair controller differs' } $text=[IO.File]::ReadAllText($base) $i=$text.IndexOf("`n`$originalCase = ",[StringComparison]::Ordinal) $j=$text.IndexOf("`nif (`$Mode -eq 'Read') {",[StringComparison]::Ordinal) if ($i -le 0 -or $j -le $i) { throw 'Original fixed declaration boundary' } +$Mode='Read' +$EchoPassive=$false . ([scriptblock]::Create($text.Substring($i,$j-$i))) Add-Type -TypeDefinition @' using System; diff --git a/deploy/windows/Set-PassiveJobPair.ps1 b/deploy/windows/Set-PassiveJobPair.ps1 index 796d133..16cadd1 100644 --- a/deploy/windows/Set-PassiveJobPair.ps1 +++ b/deploy/windows/Set-PassiveJobPair.ps1 @@ -2,8 +2,12 @@ #requires -RunAsAdministrator # Fixed console maintenance of the passive test guest. No queue, network, or script job. [CmdletBinding()] -param([Parameter(Mandatory)][ValidateSet('Prepare','InstallPassive','Read','RestorePrevious')][string]$Mode) +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' @@ -42,6 +46,103 @@ $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 @@ -61,9 +162,8 @@ function VerifyPassiveContext { (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 } - $unitProof=Join-Path $boot 'profile-unit-fcec400-result.json' CheckControl $unitProof $false - if ((Hash $unitProof) -cne '48de474d842ebc87550ba2e27b66086e6aa573973f252f4b8e19ac7b12b75a63') { + if ((Hash $unitProof) -cne $unitHash) { throw 'Current native Windows profile unit receipt differs' } } @@ -91,7 +191,7 @@ function LiveRole($role,$expectedHash) { } finally { $handle.Dispose() } } function PreservedDevice { - return [ordered]@{ + $device = [ordered]@{ config=(FileIdentity $config) identity=(FileIdentity (Join-Path $agentState 'identity.json') $true) certificate=(FileIdentity (Join-Path $agentState 'device.pem') $true) @@ -99,6 +199,28 @@ function PreservedDevice { 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') @@ -130,7 +252,9 @@ function SwapFile($name,$inputPath,$oldId,$newHash,$prefix) { if (!(JsonEqual $oldId (FileIdentity $dest)) -or (Hash $inputPath) -cne $newHash -or (Test-Path -LiteralPath $backup)) { throw "Replacement precondition $name" } - [IO.File]::Copy($inputPath,$stage,$false) + # 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' } @@ -174,12 +298,9 @@ function PrepareFiles($before) { FlushFile $copy if ((Hash $copy) -cne $oldHashes.$name) { throw "Backup $name" } } - $utf8=[Text.UTF8Encoding]::new($false,$true) foreach ($name in @('settings','pin')) { - $data=$utf8.GetString([IO.File]::ReadAllBytes($locations[$name])).Replace($oldHashes.agent,$newHashes.agent) - if ($name -eq 'pin') { $data=$data.Replace($oldHashes.settings,$newHashes.settings) } $path=Join-Path $work ('new-'+$name) - WriteBytes $path ($utf8.GetBytes($data)) + 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' } diff --git a/deploy/windows/prepare_passive_echo_media.py b/deploy/windows/prepare_passive_echo_media.py new file mode 100644 index 0000000..db274f3 --- /dev/null +++ b/deploy/windows/prepare_passive_echo_media.py @@ -0,0 +1,95 @@ +"""Assemble the passive Windows test release from independently checked evidence.""" + +import argparse +import hashlib +import json +import os +from pathlib import Path +from tempfile import TemporaryDirectory + + +HERE = Path(__file__).resolve().parent +CASE = "1d61d88b-ab17-49b1-9a8d-2427348313b4" +AGENT_SHA256 = "78c16dcaee53fe9a04d4d84c7a1475330c5a1af30c104f8f9d6f56b5b7408513" +BUILD_SHA256 = "44ac22b926b4f860da2280dbcefe0d2b3f22fb07c3ad37e856e435296a75a6b3" +LINUX_FIXTURE_SHA256 = "54aa6430c0b1eb2415ee3f888b015c05faa536d07d96f4bacf01152f1236b7db" +WINDOWS_FIXTURE_SHA256 = "4228c05aafb3cbf5d0cbbc06cb211bfb82b0d084e8c509db3afea159bef82c7f" +CARGO_INPUTS_SHA256 = "e35a907ebd0c4a9af70bb93460e3490aa67ab9f6c94b6e8b77059cb17c027812" +CROSS_CRATE_INPUTS_SHA256 = "9bb9aa28b9b02e2a05a90546ef0208757ff2c856c848fd1ed33b64a2a313b0ef" +PAIR = "Set-PassiveJobPair.ps1" + + +def digest(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def public_input(path: Path, expected: str, limit: int) -> bytes: + if path.is_symlink() or not path.is_file() or not 0 < path.stat().st_size <= limit: + raise ValueError(f"Unexpected public input at {path}") + data = path.read_bytes() + if digest(data) != expected: + raise ValueError(f"Digest mismatch at {path}") + return data + + +def assemble(args: argparse.Namespace) -> None: + # The media can be mounted read-only. No credentials or network access are needed. + files = { + "rmm-agent-windows.exe": public_input(args.agent, AGENT_SHA256, 96 << 20), + "agent-build.json": public_input(args.build_receipt, BUILD_SHA256, 1 << 20), + "linux-fixture.json": public_input(args.linux_receipt, LINUX_FIXTURE_SHA256, 1 << 20), + "windows-fixture.json": public_input(args.windows_receipt, WINDOWS_FIXTURE_SHA256, 1 << 20), + "cargo-inputs.json": public_input(args.build_receipt.with_name("cargo-inputs.json"), CARGO_INPUTS_SHA256, 1 << 20), + "cross-crate-inputs.json": public_input(args.build_receipt.with_name("cross-crate-inputs.json"), CROSS_CRATE_INPUTS_SHA256, 1 << 20), + } + for name, data in files.items(): + if name.endswith(".json") and not isinstance(json.loads(data), dict): + raise ValueError(f"Expected a public JSON receipt in {name}") + manifest = { + "kind": "rmm.windows.echo-passive-build.v1", + "case_id": CASE, + "agent_sha256": AGENT_SHA256, + "agent_build_sha256": BUILD_SHA256, + "linux_fixture_sha256": LINUX_FIXTURE_SHA256, + "windows_fixture_sha256": WINDOWS_FIXTURE_SHA256, + "cargo_inputs_sha256": CARGO_INPUTS_SHA256, + "cross_crate_inputs_sha256": CROSS_CRATE_INPUTS_SHA256, + } + files["passive-build.json"] = json.dumps(manifest, sort_keys=True, separators=(",", ":")).encode() + manifest_sha = digest(files["passive-build.json"]) + template = (HERE / PAIR).read_bytes() + files[PAIR] = template + if template.count(manifest_sha.encode()) != 1: + raise ValueError("Passive installer does not bind this exact manifest") + for name in ["Publish-JobPairTimeProfile.ps1", "Read-JobPairTimeSamples.ps1"]: + files[name] = (HERE / name).read_bytes() + if files[name].count(digest(template).encode()) != 1: + raise ValueError(f"Passive installer pin changed in {name}") + reader = "Read-PassiveTimeSamples.ps1" + files[reader] = (HERE / reader).read_bytes() + if files["Read-JobPairTimeSamples.ps1"].count(digest(files[reader]).encode()) != 1: + raise ValueError("Native time reader pin mismatch") + checksums = "".join(f"{digest(data)} {name}\n" for name, data in sorted(files.items())) + files["SHA256SUMS"] = checksums.encode() + with TemporaryDirectory(dir=args.output.parent) as temporary: + stage = Path(temporary) / "media" + stage.mkdir(mode=0o700) + for name, data in files.items(): + (stage / name).write_bytes(data) + # A completed destination is always nonempty. Never merge or update it. + if args.output.exists() or args.output.is_symlink(): + raise FileExistsError(args.output) + os.rename(stage, args.output) + print(f"passive-build.json {manifest_sha}") + print(f"SHA256SUMS {digest(files['SHA256SUMS'])}") + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + for name in ("agent", "build-receipt", "linux-receipt", "windows-receipt", "output"): + parser.add_argument("--" + name, type=Path, required=True) + assemble(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/windows-profile-acceptance.md b/docs/windows-profile-acceptance.md index 7bbfc12..b6997bc 100644 --- a/docs/windows-profile-acceptance.md +++ b/docs/windows-profile-acceptance.md @@ -588,3 +588,11 @@ sind ergänzend durch Beleg erfasst. Der Windows-Fixture-Nachweis für den passiven Medienbau ist ausdrücklich eine protokollierte Konsolenablesung mit Foto-/Testbinaryhash, SHA-256 `4228c05aafb3cbf5d0cbbc06cb211bfb82b0d084e8c509db3afea159bef82c7f`. + +Der passive Nachfolger wird im eigenen Fall `0d0179bf-cd40-4c05-b3c2-537aebd0c8ed` +installiert. Das Medienmanifest hat SHA-256 +`7c331501e40c57597624ed889ea12f34a9b16d8d10f41a2a5a73d8b7d01280a1`. +Elf Eingaben wurden gehasht, eine unabhängige Neuassemblierung war bytegleich. +Abweichender Windowsbeleg und Überschreiben eines vorhandenen Medienverzeichnisses +wurden verweigert. PowerShell-Parser und der Pintransformationscheck bestanden +lokal. Die native Dienst-/ACL-/Zeitabnahme ist der nachfolgende Schritt.