Files
rust-discovery/deploy/windows_system_script_successor_prepare.py
2026-11-16 21:07:24 +01:00

177 lines
18 KiB
Python

#!/usr/bin/env python3
"""Prepare the existing stopped-pair8 controller; never invoke its effects.
Only fixed SDK/source/public evidence files may be staged separately. Final pair
and native nonstart221 proof are required before sealing any deployment input.
"""
import argparse
import hashlib
import json
from pathlib import Path
import uuid
ROOT=Path(__file__).resolve().parents[1]
BASE=ROOT/'deploy/windows/Install-DevelopmentPairSuccessor.ps1'
BASE_SHA='78e0e0111c08ab0c91774d7ef87e2f1e6ddf272629859af92c48292a289a42a4'
def sha(raw):return hashlib.sha256(raw).hexdigest()
def replace_once(text,old,new):
assert text.count(old)==1,'exact reviewed predecessor delta'
return text.replace(old,new,1)
def controller():
raw=BASE.read_bytes();assert sha(raw)==BASE_SHA,'reviewed original pair7 controller'
text=raw.decode()
text=replace_once(text,"$m.previous_revision -ne 6", "$m.previous_revision -ne 7")
text=replace_once(text,"'PrepareStopped','InstallStoppedPassive','PrepareProfile','PublishProfile','Read'","'PrepareStopped','InstallStoppedPassive','PrepareProfile','PublishProfile','RestoreActiveStopped','Read'")
text=text.replace('revision6 to7','revision7 to8').replace('revision6','revision7')
text=replace_once(text,"$m.old_helper_sha256 -cne '59675a3cbb3a5d213fc764f38379d6b81baaf9d47a7124470cc2767d4985763e'", "$m.old_helper_sha256 -cne '0502d6c87bd74c99f1665f3cc4b9d74b8e31d0f829d2ce1a1597d72e9be1e726'")
text=replace_once(text,"$previousRevision=6", "$previousRevision=7")
text=replace_once(text,"$previousCase=Join-Path $bootstrap ('job-passive-pair-'+$m.previous_case_id)","$previousCase=Join-Path $bootstrap ('job-stopped-pair-'+$m.previous_case_id)")
text=replace_once(text,"$previous.successor_revision -ne 6", "$previous.successor_revision -ne 7")
marker=". ([scriptblock]::Create($text.Substring($i,$j-$i)))"
auto_observer=r"""
# The previously authorized SYSTEM-script bootstrap already set Helper Auto.
# Bind this existing observed definition; do not change SCM configuration.
$serviceSource=(Get-Item Function:\Service).ScriptBlock.ToString()
$manualToken="`$mode='Manual'"
$at=$serviceSource.IndexOf($manualToken,[StringComparison]::Ordinal)
if($at-lt0-or$at-ne$serviceSource.LastIndexOf($manualToken,[StringComparison]::Ordinal)){throw 'Exact historical helper-mode observer changed.'}
Set-Item Function:\Service ([scriptblock]::Create($serviceSource.Replace($manualToken,"`$mode='Auto'")))
"""
text=replace_once(text,marker,marker+'\n'+auto_observer)
text=text.replace('successor_revision=7','successor_revision=8').replace('profile7','profile8')
old="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"
new="alignment_verification_sha256,case_id,linux_proof_sha256,new_agent_sha256,new_helper_sha256,old_agent_sha256,old_config_sha256,old_helper_sha256,old_native_result_sha256,old_pin_sha256,old_profile_sha256,old_qualification_sha256,old_settings_sha256,pair_build_sha256,passive_codec_sha256,passive_render_input_sha256,passive_render_sha256,previous_case_id,previous_publication_sha256,previous_revision,schema_version,windows_proof_sha256"
text=replace_once(text,old,new)
old="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.' }"
# Private, fixed bootstrap witness from actual native221 verification; not a
# product wire protocol, permission, retry, sync lease or approval.
new="""$expectedVerification='active_pending_job_events,grant_id,incident,not_started,old_grant_executed_again,original_unknown_preserved,original_unknown_sha256,raw_retained_job_events,ready,receipt_id,receipt_sha256,revision,state,helper_ready,unlock'
if((($alignment.PSObject.Properties.Name|Sort-Object)-join',')-cne(($expectedVerification.Split(',')|Sort-Object)-join',')-or$alignment.incident-ne221-or$alignment.grant_id-cne'97e705b8-fb2b-4158-84d9-d90595d1ce6e'-or$alignment.state-cne'failed'-or$alignment.revision-ne3-or$alignment.not_started-ne$true-or$alignment.original_unknown_preserved-ne$true-or$alignment.old_grant_executed_again-ne$false-or$alignment.original_unknown_sha256-cne'1f284b66578d61c4364cc0060a67ce9b467e1d661ed8885804391b51a6f18b1a'-or$alignment.raw_retained_job_events-ne1-or$alignment.active_pending_job_events-ne0-or$alignment.receipt_sha256-cnotmatch'^[0-9a-f]{64}$'-or[guid]::ParseExact($alignment.receipt_id,'D').ToString()-cne$alignment.receipt_id-or$alignment.ready-ne$false-or$alignment.helper_ready-ne$false-or$alignment.unlock-ne$false){throw 'Exact actual SDK verify_applied221 output required; no projected wrapper or fabricated witness.'}"""
text=replace_once(text,old,new)
old="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.' } }"
new=r"""foreach($name in @('linux-proof.json','windows-proof.json')){
$proof=Get-Content -LiteralPath (Join-Path $inputFolder $name) -Raw|ConvertFrom-Json
if($name-ceq'linux-proof.json'){
if($proof.native_platform-cne'cloud-linux-x86_64'-or$proof.exit_code-ne0-or$proof.verified-ne$true-or$proof.uid-ne65534-or$proof.isolated_network-ne$true-or$proof.no_new_privs-ne$true-or$proof.stderr-cne''-or$proof.binary_sha256-cnotmatch'^[0-9a-f]{64}$'){throw 'Actual original Cloud Linux receipt-contract result required.'}
$contract=$proof.stdout|ConvertFrom-Json
}else{
if($proof.native_platform-cne'windows11-amd64'-or$proof.sdk_sha256-cnotmatch'^[0-9a-f]{64}$'-or$null-eq$proof.actual_result){throw 'Actual original native Windows receipt-contract result required.'}
$contract=$proof.actual_result
}
foreach($field in @('valid_actual_signed_receipt','wrong_grant_rejected','wrong_original_hash_rejected','wrong_signature_rejected','original_helper_cache_refreshed_once','stale_cache_failure_reproduced','resolved_unlock_storage_guard_preserves_original','original_placeholder_retired','other_message_not_retired','other_raw_not_retired','physical_placeholder_preserved')){if($contract.$field-ne$true){throw 'Actual current nonstart221 contract incomplete.'}}
if($contract.effects-ne$false-or$contract.product_databases_opened-ne$false){throw 'Receipt-contract must have no product effects.'}
}"""
text=replace_once(text,old,new)
start=text.index(' $s=$utf8.GetString([IO.File]::ReadAllBytes((Baseline \'settings\')))')
end=text.index(" $c=Get-Content -LiteralPath (Baseline 'config')",start)
replacement=r''' $renderInputPath=Join-Path $inputFolder 'passive-input.json'
$renderPath=Join-Path $inputFolder 'passive-render.json'
foreach($entry in @(@($renderInputPath,$m.passive_render_input_sha256),@($renderPath,$m.passive_render_sha256))){CheckControl $entry[0] $false;if((Hash $entry[0])-cne$entry[1]){throw 'Typed passive renderer evidence changed.'}}
$ri=Get-Content -LiteralPath $renderInputPath -Raw|ConvertFrom-Json
$ro=Get-Content -LiteralPath $renderPath -Raw|ConvertFrom-Json
if($ri.schema_version-ne1-or$ri.current_settings_sha256-cne$m.old_settings_sha256-or(BytesHash ([byte[]]$ri.current_settings))-cne$m.old_settings_sha256-or$ri.new_agent_sha256-cne$m.new_agent_sha256-or$ri.new_helper_sha256-cne$m.new_helper_sha256-or$ro.source-cne'actual_rust_settings_codec'-or$ro.prepared_only-ne$true-or$ro.target_mutations-ne$false-or$ro.target_job_executed-ne$false-or$ro.effects_enabled-ne$false){throw 'Exact deny-only typed passive pair render required.'}
$codec=Join-Path (Join-Path $bootstrap $m.passive_codec_sha256) 'windows_script_pair_prepare.exe';CheckControl $codec $false
if((Hash $codec)-cne$m.passive_codec_sha256){throw 'Actual readonly typed codec artifact changed.'}
$settingsBytes=[byte[]]$ro.settings_bytes;$pinBytes=[byte[]]$ro.pin_bytes
$newHashes.settings=BytesHash $settingsBytes;$newHashes.pin=BytesHash $pinBytes
if($newHashes.settings-cne$ro.settings_sha256-or$newHashes.pin-cne$ro.pin_sha256){throw 'Actual typed passive bytes changed.'}
$old=Get-Content -LiteralPath (Baseline 'settings') -Raw|ConvertFrom-Json
$ns=$utf8.GetString($settingsBytes)|ConvertFrom-Json;$np=$utf8.GetString($pinBytes)|ConvertFrom-Json
if($old.schema_version-ne3-or$old.enable_effects-ne$true-or$old.max_runtime_seconds-ne30-or($old.allowed_script_profiles-join',')-cne'full_maintenance_v1'-or$ns.enable_effects-ne$false-or$ns.allow_reboot-ne$false-or$ns.max_runtime_seconds-ne30-or@($ns.allowed_services).Count-ne0-or$null-ne$ns.PSObject.Properties['allowed_script_profiles']-or$null-ne$ns.PSObject.Properties['allowed_msi_recipe_sha256']-or$ns.agent.binary_sha256-cne$m.new_agent_sha256-or$ns.helper.binary_sha256-cne$m.new_helper_sha256-or$np.policy_sha256-cne$newHashes.settings-or!(JsonEqual $ns.binding $old.binding)-or!(JsonEqual $np.binding $old.binding)){throw 'Only same-identity passive script pair transition.'}
'''
text=text[:start]+replacement+text[end:]
text=replace_once(text,"return [ordered]@{settings=$utf8.GetBytes($s);pin=$utf8.GetBytes($p);config=$configBytes}","return [ordered]@{settings=$settingsBytes;pin=$pinBytes;config=$configBytes}")
# The old script qualification belongs to the old image/policy. Keep its
# bytes, native file IDs AND ACL while retiring the active names, under
# both original locks before any new passive component can start.
declaration=r"""
function OriginalScriptQualification {
$q=[ordered]@{}
foreach($entry in @(@('qualification','system-qualification.json',$m.old_qualification_sha256),@('native_result','system-native-result.json',$m.old_native_result_sha256))){
$path=Join-Path $helperRoot $entry[1];$v=FileIdentity $path
if($v.sha256-cne$entry[2]){throw 'Exact old script qualification CAS required.'}
$q[$entry[0]]=$v
}
return $q
}
function ArchiveOriginalScriptQualification($original) {
StopCheck
if(Test-Path -LiteralPath (Marker 'qualification-archive-intent')){throw 'Existing qualification archive intent: readback only.'}
if(!(JsonEqual $original (OriginalScriptQualification))){throw 'Old script qualification changed after preparation.'}
Record 'qualification-archive-intent' @{id=$id;files=$original;manifest_sha256=$ManifestSha256}
$after=[ordered]@{}
foreach($entry in @(@('qualification','system-qualification.json'),@('native_result','system-native-result.json'))){
$name=$entry[0];$source=Join-Path $helperRoot $entry[1];$dest=Join-Path $work ('archived-'+$entry[1])
if(Test-Path -LiteralPath $dest){throw 'Original qualification archive already exists.'}
if(!(JsonEqual $original.$name (FileIdentity $source))){throw 'Original qualification CAS changed.'}
[IO.File]::Move($source,$dest)
$v=FileIdentity $dest
# Same-volume rename must retain bytes, file identity AND security;
# do not restrict/change the original descriptor or reconstruct a file.
foreach($field in @('sha256','file_id','volume_serial','acl_sha256')){if($v.$field-cne$original.$name.$field){throw 'Original qualification archive identity or ACL changed.'}}
if(Test-Path -LiteralPath $source){throw 'Old active qualification name still present.'}
$after[$name]=$v
}
Record 'qualification-archived' @{id=$id;files=$after;originals=$original;active_names_absent=$true;new_qualification_created=$false}
}
"""
text=replace_once(text,'$rendered=RenderPairFiles',declaration+'\n$rendered=RenderPairFiles')
text=replace_once(text,'$before=CurrentFiles;$device=PreservedNativeState','$before=CurrentFiles;$device=PreservedNativeState;$scriptQualification=OriginalScriptQualification')
text=replace_once(text,'new_hashes=$newHashes;original_services_stopped=$true;successor_revision=8;','new_hashes=$newHashes;script_qualification=$scriptQualification;original_services_stopped=$true;successor_revision=8;')
text=replace_once(text," foreach ($name in $locations.Keys) {\n $inputPath=Join-Path $work ('new-'+$name)"," ArchiveOriginalScriptQualification $preparedPair.script_qualification\n foreach ($name in $locations.Keys) {\n $inputPath=Join-Path $work ('new-'+$name)")
restore=r"""
if($Action-ceq'RestoreActiveStopped') {
StopCheck
$publication=LoadRecord 'profile-published';$installedPair=LoadRecord 'installed'
if($publication.id-cne$id-or$publication.successor_revision-ne8-or(Hash $target)-cne$publication.configuration.sha256){throw 'Actual published profile8 required before original config restoration.'}
foreach($name in @('agent','helper','settings','pin')){if((Hash $locations[$name])-cne$newHashes[$name]){throw 'Exact passive final pair required.'}}
if((Hash $config)-cne$newHashes.config-or(Hash (Join-Path $work 'old-config'))-cne$m.old_config_sha256){throw 'Exact current passive and preserved original active config required.'}
if(!(Test-Path -LiteralPath (Marker 'qualification-archived'))-or(Test-Path -LiteralPath (Join-Path $helperRoot 'system-qualification.json'))-or(Test-Path -LiteralPath (Join-Path $helperRoot 'system-native-result.json'))){throw 'Old qualification must remain archived; no new scope before actual native prerequisites.'}
if(Test-Path -LiteralPath (Marker 'active-config-restore-intent')){throw 'Existing restore intent means readback-only.'}
$locks=[RmmStoppedPairLocks]::new()
try {
StopCheck
$before=FileIdentity $config;$retained=PreservedNativeState
if(!(JsonEqual $before $installedPair.files.config)){throw 'Actual original passive config identity changed.'}
$active=Get-Content -LiteralPath (Join-Path $work 'old-config') -Raw|ConvertFrom-Json
if($active.enable_jobs-ne$true-or$active.windows_execution_profile-cne'powershell_51_remote_signed'-or$active.server_name-cne'discovery.ease-technologies.de'-or$active.state_directory-cne$agentState){throw 'Only original already authorized active client configuration.'}
Record 'active-config-restore-intent' @{id=$id;original_active_sha256=$m.old_config_sha256;current=$before;preserved=$retained;services_stopped=$true}
SwapFile 'config' (Join-Path $work 'old-config') $before $m.old_config_sha256 'active-config'
if(!(JsonEqual $retained (PreservedNativeState))){throw 'Original state changed during config restoration.'}
Record 'active-config-restored' @{id=$id;config=(FileIdentity $config);preserved=$retained;services_started=$false;scope_activated=$false;job_created=$false}
} finally {$locks.Dispose()}
Write-Output 'Original active config restored under original locks; pair remains stopped and SYSTEM scope unconfigured.';return
}
"""
text=replace_once(text,'# The qualified publisher\'s action bodies are excluded.',restore+'\n# The qualified publisher\'s action bodies are excluded.')
return text.encode()
def policy_controller():
# Same four typed public files and preservation/locking implementation as
# the first native script-scope bootstrap, without its already-completed
# Manual->Auto transition or its one historical no-effect resume exception.
import windows_system_job_bootstrap as base
text=base.APPLY_STOPPED
text=replace_once(text,'param([switch]$ResumeNoEffectEb285544)','$ResumeNoEffectEb285544=$false')
text=text.replace('windows_system_script_scope_stopped_v1','windows_system_script_successor_scope_stopped_v1')
text=replace_once(text,"$p.helper_start_transition.before-cne'Manual'-or$p.helper_start_transition.after-cne'Auto'-or$definitions.RmmDiscoverySystemHelper.start_mode-cne'Manual'","$p.helper_start_transition.before-cne'Auto'-or$p.helper_start_transition.after-cne'Auto'-or$definitions.RmmDiscoverySystemHelper.start_mode-cne'Auto'")
text=text.replace("Exact Manual to Auto helper transition only","Existing Helper Auto must remain Auto")
start=text.index("$stage='helper-autostart'\n")
end=text.index("$stage='final-preservation'",start)
text=text[:start]+r"""$stage='helper-autostart-unchanged'
$automatic=ServiceDefinitions
if(($automatic|ConvertTo-Json -Depth 6 -Compress)-cne($definitions|ConvertTo-Json -Depth 6 -Compress)-or$automatic.RmmDiscoverySystemHelper.start_mode-cne'Auto'-or$automatic.RmmDiscoveryWindows.start_mode-cne'Auto'){throw 'Original automatic SCM definitions must remain unchanged'}
"""+text[end:]
text=replace_once(text,"helper_autostart='Auto';services=$automatic;","helper_autostart='Auto';helper_start_mode_changed=$false;services=$automatic;")
return text.encode()
def main():
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=['controller','policy-controller']);parser.add_argument('folder');args=parser.parse_args()
folder=Path(args.folder);folder.mkdir(mode=0o700,parents=True,exist_ok=True)
data=controller() if args.action=='controller' else policy_controller();path=folder/('Install-SystemScriptPairSuccessor.ps1' if args.action=='controller' else 'Install-SystemScriptSuccessorScope.ps1')
with path.open('xb')as f:f.write(data)
path.chmod(0o600)
print(json.dumps({'controller':str(path),'sha256':sha(data),'prepared_only':True,'target_mutated':False,'native_221_witness_pending':True,'final_pair_pending':True}))
if __name__=='__main__':main()