Merge qualified Windows pipe transport and preserved access evidence

This commit is contained in:
2026-11-14 19:31:02 +01:00
10 changed files with 1774 additions and 0 deletions
@@ -0,0 +1,72 @@
#!/usr/bin/env python3
"""Local CreateNew correction of the public recovery hash function alias clash.
The User's H/Get-History error occurred in the old pre-effect case/config guard.
Keep the same console case and untouched original files. No target/server call,
alias mutation or retry of an effect; the same case-absence guard still applies.
"""
import argparse
import os
from pathlib import Path
import re
import console_access_precision as previous
require, sha, save = previous.require, previous.sha, previous.save
CASE = '5c96d3d8-1657-40c8-a6ec-c00b63a98210'
OLD_SHA = '4977665fb092723998473f1c4be6685b1d93975176f8957bc3287d7e2f61cb69'
OLD_NAME = 'Recover-ExistingDevAccess.ps1'
NEW_NAME = 'Recover-ExistingDevAccess-HashFix.ps1'
NAME = 'Get-RmmRecoveryFileSha256'
STATE = previous.original.cb.EVIDENCE / 'dev-access-console-hash-correction'
def corrected(raw):
require(previous.original.pair.raw_sha(raw) == OLD_SHA, 'exact original reviewed 5c96 public script')
source = raw.decode('utf-8')
require(source.count('function H(') == 1 and NAME not in source, 'one original hash function and fresh unique name')
calls = re.findall(r'\(H\s', source)
require(len(calls) == source.count('(H ') and calls, 'all original H calls have the reviewed spelling')
result = source.replace('function H(', 'function ' + NAME + '(').replace('(H ', '(' + NAME + ' ')
require('function H(' not in result and not re.search(r'\(H\s', result), 'no alias-sensitive hash call remains')
require(result.replace('function ' + NAME + '(', 'function H(').replace('(' + NAME + ' ', '(H ') == source, 'only function/command spelling changed; all effects/pins/case bytes preserved')
return result.encode(), len(calls)
def build():
folder = previous.STATE / CASE
raw = (folder / OLD_NAME).read_bytes()
new, calls = corrected(raw)
STATE.mkdir(mode=0o700, parents=True, exist_ok=False)
previous.original.pair.write_bytes(STATE / NEW_NAME, new)
digest = previous.original.pair.raw_sha(new)
# Literal replacement, UTF8 without BOM, CreateNew, both independent hashes.
# No free script content, Remove-Alias, persistent policy or registry change.
patch = r'''$ErrorActionPreference='Stop'
$oldPath=Join-Path (Get-Location) 'Recover-ExistingDevAccess.ps1'
$newPath=Join-Path (Get-Location) 'Recover-ExistingDevAccess-HashFix.ps1'
if((Get-FileHash -LiteralPath $oldPath -Algorithm SHA256).Hash.ToLowerInvariant()-cne'@@OLD@@'){throw 'Falsche Originaldatei; nichts ausfuehren'}
if(Test-Path -LiteralPath $newPath){throw 'Korrekturdatei existiert bereits; nur lesend pruefen'}
$text=[Text.Encoding]::UTF8.GetString([IO.File]::ReadAllBytes($oldPath))
$text=$text.Replace('function H(','function Get-RmmRecoveryFileSha256(').Replace('(H ','(Get-RmmRecoveryFileSha256 ')
$bytes=(New-Object Text.UTF8Encoding($false)).GetBytes($text)
$out=[IO.File]::Open($newPath,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read)
try{$out.Write($bytes,0,$bytes.Length);$out.Flush($true)}finally{$out.Dispose()}
if((Get-FileHash -LiteralPath $newPath -Algorithm SHA256).Hash.ToLowerInvariant()-cne'@@NEW@@'){throw 'Korrekturhash stimmt nicht; nichts ausfuehren'}
powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File $newPath
'''.replace('@@OLD@@', OLD_SHA).replace('@@NEW@@', digest)
previous.original.pair.write_bytes(STATE / 'Create-VerifiedHashFix.ps1', patch.encode())
save(STATE / 'qualification.json', dict(source_sha256=sha(__file__), source_only=True, same_console_case=CASE, original_script_sha256=OLD_SHA, corrected_script_sha256=digest, renamed_call_count=calls, exact_inverse_spelling_transform=True, all_other_bytes_unchanged=True, original_script_and_zip_unchanged=True, case_absence_guard_retained=True, no_alias_mutation=True, no_server_or_vm_call=True, original_failure='Get-History/IdCannotConvert before New-Item/case or any effect'))
print('corrected_script_sha256=' + digest)
print('patch_sha256=' + sha(STATE / 'Create-VerifiedHashFix.ps1'))
print('renamed_hash_calls=' + str(calls))
print('patch=' + str((STATE / 'Create-VerifiedHashFix.ps1').resolve()))
def main():
os.umask(0o077)
parser = argparse.ArgumentParser(description=__doc__); parser.add_argument('phase', choices=('build',)); parser.parse_args(); build()
if __name__ == '__main__':
main()
@@ -0,0 +1,77 @@
#!/usr/bin/env python3
"""One local provenance correction: pin the actually deployed original bootstrap.
Actual User readonly values identify the published original file, not an unknown
hash. Preserve the same absent console case and every other byte/guard/effect.
No Windows/server access, new expiry, alias/policy change or effect retry.
"""
import argparse
import json
import os
from pathlib import Path
import zipfile
import console_access_hash_command as previous
require, sha, save = previous.require, previous.sha, previous.save
STATE = previous.previous.original.cb.EVIDENCE / 'dev-access-console-original-bootstrap-correction'
MAIN = Path('/home/kevin/Schreibtisch/Coding/rust-discovery')
OLD_NAME = 'Recover-ExistingDevAccess-HashFix.ps1'
NEW_NAME = 'Recover-ExistingDevAccess-OriginalBootstrap.ps1'
OLD_SCRIPT_SHA = 'd366ae1705dac3252726dedf369c04462e42534ddcf6e15dc27bba8583427d2c'
PARENT_SOURCE_SHA = 'b682ced57bf7ac71c0b1ba67eb5a51a20dde814fe361e1ae2cc17872147444ad'
REPO_BOOTSTRAP_SHA = '9e992602034026efbe17f833d4d6be694da3e223ac6b4a394c502eb140ec0189'
PUBLISHED_BOOTSTRAP_SHA = '332ceeedf49f597eac353e0ef1f6e614c85cef20a5a20cce68d947085aa9d50f'
CONFIG_SHA = '4ad28ec55027718a4e384c79ff7cc15ec9c798411a991a5d479e960310ed6823'
BUNDLE_SHA = 'cba159469efad9039562633fd60213d8f6a62f169fc3d1bba915e49d22c764d2'
REPAIR_BUNDLE_SHA = '2558448b7812b95de1612fca5f11da8f4a868764fb45666b128d03eb0c423eb4'
def build(facts_path):
require(sha(previous.__file__) == PARENT_SOURCE_SHA, 'immutable reviewed parent hash fix source')
facts = previous.previous.original.cb.contract.protected_json(facts_path)
require(set(facts) == {'case_present', 'config_sha256', 'bootstrap_sha256', 'configured_expiry', 'account_expiry_filetime'} and facts['case_present'] is False and facts['config_sha256'] == CONFIG_SHA and facts['bootstrap_sha256'] == PUBLISHED_BOOTSTRAP_SHA and facts['configured_expiry'] == '2026-11-14T12:55:31.254999+00:00' and facts['account_expiry_filetime'] == '134391345312549990', 'exact actual User readonly original baseline, no unknown hash adoption')
public = MAIN / 'devstate/windows-bootstrap'
require(sha(public / 'windows-dev-access.zip') == BUNDLE_SHA and sha(public / 'windows-dev-repair.zip') == REPAIR_BUNDLE_SHA, 'immutable originally published bundles')
with zipfile.ZipFile(public / 'windows-dev-access.zip') as archive:
bootstrap = archive.read('Bootstrap-DevAccess.ps1'); config = archive.read('bootstrap-public.json')
with zipfile.ZipFile(public / 'windows-dev-repair.zip') as archive:
repair = json.loads(archive.read('repair-public.json'))
raw_sha = previous.previous.original.pair.raw_sha
require(raw_sha(bootstrap) == PUBLISHED_BOOTSTRAP_SHA == repair['previous_bootstrap_sha256'] and raw_sha(config) == CONFIG_SHA, 'actual file equals original publication and independently pinned repair prerequisite')
original_path = previous.STATE / OLD_NAME
require(sha(original_path) == OLD_SCRIPT_SHA, 'exact reviewed parent PS1')
source = original_path.read_bytes().decode('utf-8')
old = "$expectedBootstrap='" + REPO_BOOTSTRAP_SHA + "'"
new = "$expectedBootstrap='" + PUBLISHED_BOOTSTRAP_SHA + "'"
require(source.count(old) == 1 and new not in source, 'single exact original constant')
corrected = source.replace(old, new, 1)
require(corrected.replace(new, old, 1) == source, 'all other bytes including expiry/case/alias/clock/effects unchanged')
STATE.mkdir(mode=0o700, parents=True, exist_ok=False)
save(STATE / 'actual-user-readonly.json', facts)
previous.previous.original.pair.write_bytes(STATE / NEW_NAME, corrected.encode())
digest = raw_sha(corrected.encode())
patch = r'''$ErrorActionPreference='Stop'
$inputPath=Join-Path (Get-Location) 'Recover-ExistingDevAccess-HashFix.ps1';$newPath=Join-Path (Get-Location) 'Recover-ExistingDevAccess-OriginalBootstrap.ps1'
if((Get-FileHash -LiteralPath $inputPath -Algorithm SHA256).Hash.ToLowerInvariant()-cne'@@INPUT@@'-or(Test-Path -LiteralPath $newPath)){throw 'Originalhash falsch oder neue Datei bereits vorhanden; nichts ausfuehren'}
$text=[Text.Encoding]::UTF8.GetString([IO.File]::ReadAllBytes($inputPath));$text=$text.Replace("`$expectedBootstrap='@@OLD@@'","`$expectedBootstrap='@@PIN@@'");$bytes=(New-Object Text.UTF8Encoding($false)).GetBytes($text);$file=[IO.File]::Open($newPath,'CreateNew','Write','Read');try{$file.Write($bytes,0,$bytes.Length);$file.Flush($true)}finally{$file.Dispose()}
if((Get-FileHash -LiteralPath $newPath -Algorithm SHA256).Hash.ToLowerInvariant()-cne'@@OUTPUT@@'){throw 'Neuer Hash falsch; nichts ausfuehren'}
powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File $newPath
'''
for token, value in {'INPUT': OLD_SCRIPT_SHA, 'OLD': REPO_BOOTSTRAP_SHA, 'PIN': PUBLISHED_BOOTSTRAP_SHA, 'OUTPUT': digest}.items():
patch = patch.replace('@@' + token + '@@', value)
previous.previous.original.pair.write_bytes(STATE / 'Create-VerifiedOriginalBootstrapFix.ps1', patch.encode())
save(STATE / 'qualification.json', dict(source_only=True, source_sha256=sha(__file__), parent_source_sha256=PARENT_SOURCE_SHA, actual_user_readonly_sha256=sha(STATE / 'actual-user-readonly.json'), same_console_case=previous.CASE, input_script_sha256=OLD_SCRIPT_SHA, corrected_script_sha256=digest, original_bundle_sha256=BUNDLE_SHA, repair_bundle_sha256=REPAIR_BUNDLE_SHA, published_bootstrap_sha256=PUBLISHED_BOOTSTRAP_SHA, corrected_exactly_one_constant=True, all_other_bytes_unchanged=True, no_unknown_hash_adoption=True, original_scripts_and_zip_retained=True, no_windows_or_server_access=True))
print('source_sha256=' + sha(__file__))
print('corrected_script_sha256=' + digest)
print('patch_sha256=' + sha(STATE / 'Create-VerifiedOriginalBootstrapFix.ps1'))
print('patch=' + str((STATE / 'Create-VerifiedOriginalBootstrapFix.ps1').resolve()))
def main():
os.umask(0o077)
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('phase',choices=('build',));parser.add_argument('--actual-user-readonly',required=True,type=Path);args=parser.parse_args();build(args.actual_user_readonly)
if __name__ == '__main__':
main()
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
"""New public console package correcting only the old AccountExpires guard.
Local only: reads the immutable completed server-only recovery case and its
public package, never contacts Windows/server and cannot change a server lease.
The same active server expiry/key/pins remain bound. The old package is retained.
"""
import argparse
import json
import os
from pathlib import Path
import uuid
import zipfile
import console_access_recovery as original
require, sha, save = original.require, original.sha, original.save
STATE = original.cb.EVIDENCE / 'dev-access-console-precision-correction'
PARENT_ID = '4b6506a7-6c3e-4cca-a497-618fa8666300'
PARENT_SOURCE_SHA = '703fb5e4ae04d8555bad858c5d7b2ac4880e06d6fa951010acd43f7201a58053'
PARENT_INTENT_SHA = 'cd827d4056fb0045f23bff1fd9bd21b6137b53f063fe8215ad0945c2013cc44a'
PARENT_ENTER_SHA = '2185a88fc32db72119a584d84a46fb25cfca5f32f6e0c4ee5b7cf0728a361317'
PARENT_READBACK = 'readback-754e47df-25e0-4c0b-a411-56b3d350ace5.json'
PARENT_READBACK_SHA = 'f6e3f69a6cd4f006d00c90cadd8bfd47f94e954f1297bea5f6eecc4fd27d3787'
EXPIRY = '2026-11-15T13:05:58+00:00'
AUTHORIZED_SHA = 'fef4db300dd39fba9b52428817f453451c251c7768dd2fb6a76b39dd110dbbf2'
NAMES = ('Recover-ExistingDevAccess.ps1', 'public-recovery.json', 'README.txt')
def replace_once(text, old, new):
require(text.count(old) == 1, 'one exact reviewed precision/provenance replacement')
return text.replace(old, new, 1)
def corrected_script(source, ident):
require(str(uuid.UUID(ident)) == ident, 'new canonical console UUID')
# The original cfg bytes/hash and its exact expiry string have already been
# verified before this line. Derive ONE full 64-bit FILETIME, no rounding,
# alternative value, tolerance or claim of a measured VM account value.
old = "$account=Get-LocalUser -Name 'rmm-dev';if(!$account.Enabled-or!$account.AccountExpires-or$account.AccountExpires.ToUniversalTime().ToFileTimeUtc().ToString()-cne'134391345310000000'){throw 'Existing original expired account only'}"
new = "$expectedOldAccountFiletime=[DateTimeOffset]::Parse($cfg.expires_at).UtcDateTime.ToFileTimeUtc().ToString()\n$account=Get-LocalUser -Name 'rmm-dev';if(!$account.Enabled-or!$account.AccountExpires-or$account.AccountExpires.ToUniversalTime().ToFileTimeUtc().ToString()-cne$expectedOldAccountFiletime){throw 'Existing original expired account precision mismatch; stop for readonly inspection'}"
result = replace_once(source, old, new)
result = replace_once(result, "$recoveryId='" + PARENT_ID + "'", "$recoveryId='" + ident + "'")
result = replace_once(result, "@{id=$recoveryId;new_expiry=$newExpiry;original_config_sha256=", "@{id=$recoveryId;parent_server_case='" + PARENT_ID + "';parent_server_enter_sha256='" + PARENT_ENTER_SHA + "';new_expiry=$newExpiry;original_config_sha256=")
effect = '[IO.File]::Replace($candidate,$config,$nativeBackup)'
require(result.split(effect, 1)[1] == source.split(effect, 1)[1], 'all three mutation steps/start behavior unchanged')
require(result.count('Start-ScheduledTask -TaskName $taskName') == 1 and '134391345310000000' not in result, 'one original task start, no obsolete rounded guard')
return result
def parent():
require(sha(original.__file__) == PARENT_SOURCE_SHA, 'immutable historical source, no rebase')
folder = original.STATE / PARENT_ID
require(sha(folder / 'intent.json') == PARENT_INTENT_SHA and sha(folder / 'server-entered.json') == PARENT_ENTER_SHA and sha(folder / PARENT_READBACK) == PARENT_READBACK_SHA, 'exact existing server-only CAS and independent readback')
intent = original.cb.contract.protected_json(folder / 'intent.json')
entered = original.cb.contract.protected_json(folder / 'server-entered.json')
readback = original.cb.contract.protected_json(folder / PARENT_READBACK)
require(intent['id'] == PARENT_ID and intent['source_sha256'] == PARENT_SOURCE_SHA and intent['payload']['new_expiry'] == EXPIRY and entered['completed'] is True and entered['authorized_sha256'] == readback['authorized_sha256'] == AUTHORIZED_SHA and entered['expiry'] == readback['expiry'] == '20261115130558Z' and readback['read_only'] is True and readback['completed'] is True, 'same already completed server lease; never a new CAS')
before = intent['payload']['server_before']
require(all(readback[field] == before[field] for field in ('profile_sha256', 'effective_sha256', 'server_host_key_sha256', 'tunnel_public_key_sha256', 'uid', 'gid', 'home', 'shell')), 'original forwarding authority/key/profile/account unchanged')
for name, field in ((NAMES[0], 'console_sha256'), ('README.txt', 'readme_sha256'), ('public-recovery.json', 'public_json_sha256'), ('windows-dev-access-recovery.zip', 'bundle_sha256')):
require(sha(folder / name) == intent[field], 'immutable original public package files')
return folder, intent
def build():
old_folder, old_intent = parent()
require(original.cb.contract.now() < original.dt.datetime.fromisoformat(EXPIRY), 'existing server lease still in its fixed window')
ident = str(uuid.uuid4()); folder = STATE / ident; folder.mkdir(mode=0o700, parents=True)
save(folder / 'prepare-intent.json', dict(id=ident, source_sha256=sha(__file__), parent_server_case=PARENT_ID, parent_server_enter_sha256=PARENT_ENTER_SHA, new_server_cas=False, no_windows_or_server_access=True))
script = corrected_script((old_folder / NAMES[0]).read_text(), ident)
original.pair.write_bytes(folder / NAMES[0], script.encode())
digest = original.pair.raw_sha(script.encode())
public = dict(schema_version=1, id=ident, parent_server_case=PARENT_ID, parent_source_sha256=PARENT_SOURCE_SHA, parent_server_enter_sha256=PARENT_ENTER_SHA, parent_server_readback_sha256=PARENT_READBACK_SHA, new_expiry=EXPIRY, script_sha256=digest, no_private_keys=True, new_server_cas=False, old_account_guard='exact_derived_from_verified_config_utc_filetime', actual_vm_account_filetime_measured=False)
save(folder / 'public-recovery.json', public)
readme = (old_folder / 'README.txt').read_text()
require(old_intent['console_sha256'] in readme, 'original independent PS1 hash instructions')
readme = readme.replace(old_intent['console_sha256'], digest)
readme += ('\nPraezisionskorrektur: neues Konsolenpaket, neuer Fall ' + ident + '.\n'
'Verwendet ausschliesslich den bereits bestaetigten Serverfall ' + PARENT_ID + ' und dieselbe UTC-Frist ' + EXPIRY + '. Keine neue Serververlaengerung.\n'
'Der alte AccountExpires-Sollwert wird exakt aus der unveraenderten alten Config-UTC-Zeit einschliesslich Bruchteilen abgeleitet. Dies ist kein gemessener VM-Accountwert.\n'
'Keine Rundung, Toleranz oder alternativer Sollwert. Bei Abweichung abbrechen und nur lesend pruefen lassen.\n'
'Falls ein frueheres Paket bereits erfolgreich ausgefuehrt wurde: dieses Paket NICHT als Retry verwenden; der alte Config-Hashguard muss dann verweigern.\n')
original.pair.write_bytes(folder / 'README.txt', readme.encode())
bundle = folder / 'windows-dev-access-recovery.zip'
with zipfile.ZipFile(bundle, 'x', compression=zipfile.ZIP_DEFLATED) as archive:
for name in NAMES: archive.write(folder / name, name)
bundle.chmod(0o600)
intent = dict(schema_version=1, id=ident, source_sha256=sha(__file__), parent_server_case=PARENT_ID, parent_intent_sha256=PARENT_INTENT_SHA, parent_server_enter_sha256=PARENT_ENTER_SHA, parent_server_readback_sha256=PARENT_READBACK_SHA, original_bundle_sha256=old_intent['bundle_sha256'], new_expiry=EXPIRY, console_sha256=digest, public_json_sha256=sha(folder / 'public-recovery.json'), readme_sha256=sha(folder / 'README.txt'), bundle_sha256=sha(bundle), no_windows_or_server_access=True, new_server_cas=False)
save(folder / 'intent.json', intent)
print(json.dumps(dict(id=ident, intent_sha256=sha(folder / 'intent.json'), bundle=str(bundle.resolve()), bundle_sha256=intent['bundle_sha256'], console_source=str((folder / NAMES[0]).resolve()), console_sha256=digest, new_expiry=EXPIRY, parent_server_case=PARENT_ID, new_server_cas=False, no_windows_or_server_access=True)))
def main():
os.umask(0o077)
parser = argparse.ArgumentParser(description=__doc__); parser.add_argument('phase', choices=('build',)); parser.parse_args(); build()
if __name__ == '__main__':
try: main()
except Exception as error: print('CONSOLE_PRECISION_CORRECTION_INCOMPLETE:' + type(error).__name__); raise SystemExit(2) from None
+189
View File
@@ -0,0 +1,189 @@
#!/usr/bin/env python3
"""Expired development tunnel recovery: server-only CAS + fixed public console code.
No Windows access, key generation, SSH profile edit, port/download/RMM change.
Root renews the one expired restricted authorized key first, then hands the
reviewed public PowerShell to the User's elevated Windows console.
"""
import argparse
import base64
import datetime as dt
import hashlib
import inspect
import json
import os
from pathlib import Path
import subprocess
import uuid
import zipfile
import client_bootstrap as cb
import system_pipe_upgrade as pair
import dev_access_renewal as previous
require,sha,save=pair.require,pair.sha,pair.save
STATE=cb.EVIDENCE/'dev-access-console-recovery'
OLD_EXPIRY='2026-11-14T12:55:31.254999+00:00'
def recover_server(payload):
import datetime as dt
import re
import stat
root=Path('/opt/rust-discovery/devstate/windows-bootstrap')
authorized=Path('/var/lib/rmm-win-tunnel/.ssh/authorized_keys')
profile=Path('/etc/ssh/sshd_config.d/80-rmm-windows-tunnel.conf')
ident=str(uuid.UUID(payload['id']));case=root/('console-recovery-'+ident)
require(payload['phase'] in ('state','enter','readback'),'fixed renewal phase')
def check(path,mode):
s=path.lstat();require(not path.is_symlink() and stat.S_ISREG(s.st_mode) and s.st_uid==0 and stat.S_IMODE(s.st_mode)==mode and s.st_size<65536,'protected original transport file')
def digest(path):return hashlib.sha256(path.read_bytes()).hexdigest()
check(authorized,0o644);check(profile,0o644)
account=pwd.getpwnam('rmm-win-tunnel');require(account.pw_dir=='/var/lib/rmm-win-tunnel' and account.pw_shell=='/usr/sbin/nologin','existing forwarding-only account')
public=' '.join(Path('/etc/ssh/ssh_host_ed25519_key.pub').read_text().split()[:2])
fingerprint=subprocess.run(['ssh-keygen','-lf','/etc/ssh/ssh_host_ed25519_key.pub'],capture_output=True,check=True,timeout=10).stdout.decode().split()[1]
require(fingerprint=='SHA256:+NEin4XJc3CbhjQi7/ZpMIgxOrXn8AT2tlpTaXW5quw','confirmed original server host key')
raw=authorized.read_text();match=re.fullmatch(r'restrict,port-forwarding,permitlisten="127\.0\.0\.1:22240",expiry-time="(\d{14}Z)" (ssh-ed25519 [A-Za-z0-9+/=]{68})\n',raw)
require(match is not None and match[2]==payload['tunnel_public_key'],'exact unchanged forwarding key/options')
effective=subprocess.run(['/usr/sbin/sshd','-T','-C','user=rmm-win-tunnel,host=localhost,addr=127.0.0.1'],capture_output=True,check=True,timeout=10).stdout
for line in (b'allowtcpforwarding remote\n',b'permitlisten 127.0.0.1:22240\n',b'permitopen none\n',b'gatewayports no\n',b'maxsessions 0\n',b'passwordauthentication no\n'):require(line in effective,'same restricted forwarding-only profile')
def state():return dict(read_only=True,authorized_sha256=digest(authorized),profile_sha256=digest(profile),effective_sha256=hashlib.sha256(effective).hexdigest(),server_host_key_sha256=hashlib.sha256(public.encode()).hexdigest(),tunnel_public_key_sha256=hashlib.sha256(match[2].encode()).hexdigest(),expiry=match[1],uid=account.pw_uid,gid=account.pw_gid,home=account.pw_dir,shell=account.pw_shell)
if payload['phase']=='state':return state()
if payload['phase']=='readback':
value=state();value['case_exists']=case.exists();value['replace_intent']=case.exists() and (case/'replace-intent.json').exists();value['completed']=case.exists() and (case/'completed.json').exists();return value
old=dt.datetime.fromisoformat(payload['old_expiry']).astimezone(dt.timezone.utc);new=dt.datetime.fromisoformat(payload['new_expiry']).astimezone(dt.timezone.utc)
require(old.isoformat()=='2026-11-14T12:55:31.254999+00:00' and old<dt.datetime.now(dt.timezone.utc)<new<=dt.datetime.now(dt.timezone.utc)+dt.timedelta(hours=24) and state()==payload['server_before'],'exact EXPIRED original key/CAS and bounded fresh 24h console recovery')
require(not case.exists(),'existing server renewal: readback only');case.mkdir(mode=0o700)
def write(path,data,mode=0o600):
fd=os.open(path,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,mode)
with os.fdopen(fd,'wb') as out:out.write(data);out.flush();os.fsync(out.fileno());os.fchmod(out.fileno(),mode)
write(case/'intent.json',json.dumps(payload).encode());write(case/'authorized_keys.original',raw.encode())
replacement=raw.replace('expiry-time="'+old.strftime('%Y%m%d%H%M%SZ')+'"','expiry-time="'+new.strftime('%Y%m%d%H%M%SZ')+'"')
require(replacement!=raw and replacement.replace(new.strftime('%Y%m%d%H%M%SZ'),old.strftime('%Y%m%d%H%M%SZ'))==raw,'expiry only, key/options unchanged')
candidate=authorized.parent/('renew-'+ident+'.next');write(candidate,replacement.encode(),0o644)
write(case/'replace-intent.json',json.dumps(dict(old_sha256=digest(authorized),new_sha256=hashlib.sha256(replacement.encode()).hexdigest())).encode())
require(digest(authorized)==payload['server_before']['authorized_sha256'] and digest(profile)==payload['server_before']['profile_sha256'],'immediate original server CAS')
os.replace(candidate,authorized);directory=os.open(authorized.parent,os.O_RDONLY);os.fsync(directory);os.close(directory)
require(authorized.read_text()==replacement,'actual exact renewed authorization');write(case/'completed.json',json.dumps(dict(completed=True,new_expiry=payload['new_expiry'],download_lease_changed=False)).encode())
return dict(completed=True,authorized_sha256=digest(authorized),expiry=new.strftime('%Y%m%d%H%M%SZ'),no_new_authority=True,download_lease_changed=False)
CONSOLE = r'''
# Paste this complete reviewed block into elevated Windows PowerShell 5.1.
# Bootstrap SSH recovery only. No RMM job, policy/ACL change, installation or reboot.
$ErrorActionPreference='Stop'
if(!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)){throw 'Elevated Windows console required'}
$recoveryId='@@ID@@';$newExpiry='@@EXPIRY@@';$expectedConfig='@@CONFIG@@';$expectedBootstrap='@@BOOTSTRAP@@'
$expectedTunnel='@@TUNNEL@@';$expectedWindowsHost='@@HOST@@';$root='C:\ProgramData\RmmDevAccess';$config=Join-Path $root 'bootstrap-public.json';$case=Join-Path $root ('console-recovery-'+$recoveryId);$taskName='RmmDevReverseTunnel'
function H($path){$item=Get-Item -LiteralPath $path -Force;if($item.PSIsContainer-or($item.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Only regular fixed public/bootstrap file'};$parent=$item.Directory;while($null-ne$parent){if($parent.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'No reparse ancestor'};$parent=$parent.Parent};return(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()}
function B([string]$text){$h=[Security.Cryptography.SHA256]::Create();try{return([BitConverter]::ToString($h.ComputeHash([Text.Encoding]::UTF8.GetBytes($text)))).Replace('-','').ToLowerInvariant()}finally{$h.Dispose()}}
function NewReceipt($path,$value){$bytes=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 12 -Compress));$f=[IO.File]::Open($path,'CreateNew','Write','Read');try{$f.Write($bytes,0,$bytes.Length);$f.Flush($true)}finally{$f.Dispose()}}
$directory=Get-Item -LiteralPath $root -Force;$acl=Get-Acl -LiteralPath $root
if(!$directory.PSIsContainer-or($directory.Attributes-band[IO.FileAttributes]::ReparsePoint)-or$acl.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Original protected bootstrap directory'}
foreach($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){if($rule.AccessControlType-ne'Allow'-or$rule.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Original private directory ACL'}}
if((Test-Path -LiteralPath $case)-or(H $config)-cne$expectedConfig-or(H (Join-Path $root 'Bootstrap-DevAccess.ps1'))-cne$expectedBootstrap){throw 'Only untouched original expired bootstrap; existing recovery means readback only'}
$cfg=Get-Content -LiteralPath $config -Raw|ConvertFrom-Json
if((($cfg.PSObject.Properties.Name|Sort-Object)-join',')-cne'expires_at,notebook_public_key,schema_version,server,server_host_key'-or$cfg.schema_version-ne1-or$cfg.server-cne'discovery.ease-technologies.de'-or$cfg.expires_at-cne'2026-11-14T12:55:31.254999+00:00'){throw 'Exact original public config and old expiry'}
$expiry=[DateTimeOffset]::Parse($newExpiry);if($expiry-le[DateTimeOffset]::UtcNow-or$expiry-gt[DateTimeOffset]::UtcNow.AddHours(24)){throw 'Bounded reviewed new UTC expiry'}
$tunnelPublic=((Get-Content -LiteralPath (Join-Path $root 'tunnel_ed25519.pub') -Raw).Trim()-split'\s+')[0..1]-join' '
$windowsHostPublic=((Get-Content -LiteralPath 'C:\ProgramData\ssh\ssh_host_ed25519_key.pub' -Raw).Trim()-split'\s+')[0..1]-join' '
if($tunnelPublic-cne$expectedTunnel-or$windowsHostPublic-cne$expectedWindowsHost-or(Get-Content -LiteralPath (Join-Path $root 'known_hosts') -Raw)-cne('discovery.ease-technologies.de '+$cfg.server_host_key+"`n")-or(Get-Content -LiteralPath 'C:\ProgramData\ssh\administrators_authorized_keys' -Raw)-cne($cfg.notebook_public_key+"`n")){throw 'Original tunnel/server/Windows/notebook public pins'}
$account=Get-LocalUser -Name 'rmm-dev';if(!$account.Enabled-or!$account.AccountExpires-or$account.AccountExpires.ToUniversalTime().ToFileTimeUtc().ToString()-cne'134391345310000000'){throw 'Existing original expired account only'}
$task=Get-ScheduledTask -TaskName $taskName;$actions=@($task.Actions)
if($task.State-cne'Ready'-or$actions.Count-ne1-or$actions[0].Execute-ine'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'-or$actions[0].Arguments-cne'-NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -File "C:\ProgramData\RmmDevAccess\Bootstrap-DevAccess.ps1" -MaintainTunnel'-or$task.Principal.UserId-notin@('SYSTEM','S-1-5-18')-or$task.Principal.LogonType-cne'ServiceAccount'-or$task.Principal.RunLevel-cne'Highest'){throw 'Unchanged original SYSTEM task must be Ready'}
$active=@(Get-CimInstance Win32_Process -Filter "Name='powershell.exe' OR Name='ssh.exe'" -OperationTimeoutSec 10|Where-Object{$_.CommandLine-like'*Bootstrap-DevAccess.ps1* -MaintainTunnel*'-or$_.CommandLine-like'*C:\ProgramData\RmmDevAccess\tunnel_ed25519*'})
if($active.Count){throw 'Old maintainer/tunnel must exit naturally; no kill or duplicate start'}
$taskXml=Export-ScheduledTask -TaskName $taskName;$fixed=[ordered]@{}
foreach($path in @((Join-Path $root 'known_hosts'),(Join-Path $root 'Bootstrap-DevAccess.ps1'),(Join-Path $root 'tunnel_ed25519.pub'),'C:\ProgramData\ssh\ssh_host_ed25519_key.pub','C:\ProgramData\ssh\sshd_config','C:\ProgramData\ssh\administrators_authorized_keys')){$item=Get-Item -LiteralPath $path -Force;if($item.PSIsContainer-or($item.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'No reparse public/bootstrap file'};$fixed[$path]=@{sha256=(H $path);sddl=(Get-Acl -LiteralPath $path).Sddl}}
$private=[ordered]@{};foreach($path in @((Join-Path $root 'tunnel_ed25519'),'C:\ProgramData\ssh\ssh_host_ed25519_key','C:\ProgramData\ssh\ssh_host_rsa_key','C:\ProgramData\ssh\ssh_host_ecdsa_key')){if(Test-Path -LiteralPath $path){$item=Get-Item -LiteralPath $path -Force;if($item.PSIsContainer-or($item.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'No reparse private key'};$private[$path]=@{bytes=$item.Length;created=$item.CreationTimeUtc.Ticks.ToString();written=$item.LastWriteTimeUtc.Ticks.ToString();sddl=(Get-Acl -LiteralPath $path).Sddl}}}
New-Item -ItemType Directory -Path $case|Out-Null
NewReceipt (Join-Path $case 'intent.json') @{id=$recoveryId;new_expiry=$newExpiry;original_config_sha256=$expectedConfig;account_sid=$account.SID.Value;task_xml_sha256=(B $taskXml);fixed=$fixed;private_metadata=$private;private_keys_read=$false;no_new_authority=$true}
$backup=Join-Path $case 'bootstrap-public.original';[IO.File]::Copy($config,$backup,$false)
$cfg.expires_at=$newExpiry;$candidate=Join-Path $case 'bootstrap-public.next';NewReceipt $candidate $cfg;$nativeBackup=Join-Path $case 'bootstrap-public.native-original'
NewReceipt (Join-Path $case 'config-replace-intent.json') @{old_sha256=$expectedConfig;new_expiry=$newExpiry;native_backup=$nativeBackup}
if((H $config)-cne$expectedConfig-or(Test-Path -LiteralPath $nativeBackup)){throw 'Immediate original config CAS'};$originalAcl=Get-Acl -LiteralPath $config
[IO.File]::Replace($candidate,$config,$nativeBackup);Set-Acl -LiteralPath $config -AclObject $originalAcl
NewReceipt (Join-Path $case 'account-expiry-intent.json') @{existing_sid=$account.SID.Value;new_expiry=$newExpiry}
if((Get-LocalUser -Name 'rmm-dev').SID.Value-cne$account.SID.Value){throw 'Original account changed'}
Set-LocalUser -Name 'rmm-dev' -AccountExpires $expiry.LocalDateTime
if((Get-LocalUser -Name 'rmm-dev').AccountExpires.ToUniversalTime().ToFileTimeUtc().ToString()-cne'@@FILETIME@@'){throw 'Exact renewed account expiry'}
foreach($path in $fixed.Keys){if((H $path)-cne$fixed[$path].sha256-or(Get-Acl -LiteralPath $path).Sddl-cne$fixed[$path].sddl){throw 'Original fixed bootstrap/key bytes or ACL changed'}}
foreach($path in $private.Keys){$item=Get-Item -LiteralPath $path -Force;$meta=@{bytes=$item.Length;created=$item.CreationTimeUtc.Ticks.ToString();written=$item.LastWriteTimeUtc.Ticks.ToString();sddl=(Get-Acl -LiteralPath $path).Sddl};foreach($field in @('bytes','created','written','sddl')){if($meta[$field]-cne$private[$path][$field]){throw 'Private key metadata changed'}}}
if((Export-ScheduledTask -TaskName $taskName)-cne$taskXml-or(Get-ScheduledTask -TaskName $taskName).State-cne'Ready'){throw 'Original task changed; no start'}
NewReceipt (Join-Path $case 'original-task-start-intent.json') @{start_once=$true;task_xml_sha256=(B $taskXml)}
Start-ScheduledTask -TaskName $taskName
NewReceipt (Join-Path $case 'console-completed.json') @{completed=$true;new_expiry=$newExpiry;original_task_start_requested_once=$true;private_keys_read=$false;no_keys_ports_policy_acl_install_reboot_or_rmm_change=$true}
Write-Host ('Bestehender SSH-Zugang erneuert bis '+$newExpiry+'. Originaltunnel einmal gestartet. Bitte diese Zeile zurueckmelden; keine Schluessel senden.')
'''
class ServerAccess:
def __init__(self,root):self.root=Path(root).absolute();require(self.root==self.root.resolve() and self.root!=cb.ROOT,'separate protected Main access root')
def rpc(self,payload):
cloud=pair.u.transport.cloud;cfg=cloud.bootstrap.access.load_config(self.root/'credentials/server.conf')
ssh=['ssh','-F','/dev/null','-T','-p',cfg.get('port','22'),'-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','IdentitiesOnly=yes','-o','ForwardAgent=no','-i',str(Path(cfg['ssh_key_path']).expanduser()),cfg['username']+'@'+cfg['address'],'python3 -']
code='import os,json,subprocess,base64,hashlib,uuid,pwd\nfrom pathlib import Path\n'+inspect.getsource(cloud.bootstrap.require)+'\n'+inspect.getsource(recover_server)+'\ntry:\n print(json.dumps(recover_server('+repr(payload)+')))\nexcept Exception as e:\n print(json.dumps(dict(error=type(e).__name__)))\n'
result=subprocess.run(ssh,input=code.encode(),capture_output=True,timeout=60);require(result.returncode==0,'fixed server-only recovery RPC')
value=json.loads(result.stdout,object_pairs_hook=cb.contract.strict_object);require('error' not in value,'server-only recovery incomplete; readback only');return value
def prepare(access):
require(cb.contract.now()>dt.datetime.fromisoformat(OLD_EXPIRY),'original lease actually expired')
ident=str(uuid.uuid4());folder=STATE/ident;folder.mkdir(mode=0o700,parents=True)
expiry=(cb.contract.now()+dt.timedelta(hours=24)).replace(microsecond=0)
console=cb.contract.protected_json(access.root/'devstate/windows-bootstrap/console-registration.json')
with zipfile.ZipFile(access.root/'devstate/windows-bootstrap/windows-dev-access.zip') as bundle:
original=bundle.read('bootstrap-public.json')
public=json.loads(original,object_pairs_hook=cb.contract.strict_object)
require(public['expires_at']==OLD_EXPIRY and public['server']=='discovery.ease-technologies.de','original public-only bundle')
payload=dict(id=ident,phase='state',old_expiry=OLD_EXPIRY,new_expiry=expiry.isoformat(),tunnel_public_key=console['tunnel_public_key'])
save(folder/'prepare-intent.json',dict(id=ident,source_sha256=sha(__file__),new_expiry=payload['new_expiry'],no_windows_access=True))
baseline=access.rpc(payload);require(baseline['expiry']==dt.datetime.fromisoformat(OLD_EXPIRY).strftime('%Y%m%d%H%M%SZ'),'only original expired key')
payload['server_before']=baseline
script=CONSOLE
for key,value in {'ID':ident,'EXPIRY':payload['new_expiry'],'CONFIG':hashlib.sha256(original).hexdigest(),'BOOTSTRAP':sha(cb.ROOT/'deploy/windows/Bootstrap-DevAccess.ps1'),'TUNNEL':console['tunnel_public_key'],'HOST':console['windows_host_public_key'],'FILETIME':str((int(expiry.timestamp())+11644473600)*10000000)}.items():
token='@@'+key+'@@';require(script.count(token)==1,'exact fixed public console field');script=script.replace(token,value)
require('@@' not in script,'complete fixed public instructions')
pair.write_bytes(folder/'Recover-ExistingDevAccess.ps1',script.encode())
save(folder/'public-recovery.json',dict(id=ident,new_expiry=payload['new_expiry'],script_sha256=pair.raw_sha(script.encode()),no_private_keys=True))
readme=('Bestehenden Windows-Entwicklungszugang wiederherstellen\r\n\r\n'
'Nur in dieser Windows-Test-VM ausfuehren, in einer als Administrator gestarteten PowerShell.\r\n'
'Der Cloudserver muss zuvor durch den Entwickler fuer diese feste Frist erneuert worden sein.\r\n'
'Neue UTC-Frist: '+payload['new_expiry']+'\r\n'
'ZIP-SHA256 mit dem unabhaengig mitgeteilten Downloadhash vergleichen; dann hier entpacken.\r\n'
'Folgende Befehle im entpackten Verzeichnis ausfuehren:\r\n\r\n'
"$recoveryScript = Join-Path (Get-Location) 'Recover-ExistingDevAccess.ps1'\r\n"
"if ((Get-FileHash -LiteralPath $recoveryScript -Algorithm SHA256).Hash.ToLowerInvariant() -cne '"+pair.raw_sha(script.encode())+"') { throw 'Falsche Recoverydatei' }\r\n"
'Unblock-File -LiteralPath $recoveryScript\r\n'
'powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File $recoveryScript\r\n\r\n'
'Unblock-File betrifft nur diese exakt gepruefte heruntergeladene Datei; RemoteSigned nur diesen Bootstrapprozess.\r\n'
'Keine globale Policy/GPO aendern. Falls eine Richtlinie oder Pruefung verweigert: stoppen, Fehlermeldung melden, nicht erneut ausfuehren.\r\n'
'Das Skript behaelt Schluessel, Pins, SSH-Profil und Taskdefinition bei, erneuert nur die Ablaufzeit und startet den Originaltunnel einmal.\r\n'
'Keine Installation, ACL-Reparatur, RMM-Aktion, Reboot oder Update. Private Schluessel werden nicht gelesen/ausgegeben.\r\n'
'Nach Erfolg bitte nur die Abschlusszeile melden, keine Schluessel oder Zugangsdaten. Bei Fehler den Zustand fuer lesende Kontrolle behalten.\r\n')
pair.write_bytes(folder/'README.txt',readme.encode('utf-8'))
bundle=folder/'windows-dev-access-recovery.zip'
with zipfile.ZipFile(bundle,'x',compression=zipfile.ZIP_DEFLATED) as archive:
for name in ('Recover-ExistingDevAccess.ps1','public-recovery.json','README.txt'):
archive.write(folder/name,name)
bundle.chmod(0o600)
intent=dict(id=ident,source_sha256=sha(__file__),access_root=str(access.root),payload=payload,console_sha256=pair.raw_sha(script.encode()),bundle_sha256=sha(bundle),readme_sha256=sha(folder/'README.txt'),public_json_sha256=sha(folder/'public-recovery.json'))
save(folder/'intent.json',intent)
print(json.dumps(dict(id=ident,review_sha256=sha(folder/'intent.json'),console_source=str((folder/'Recover-ExistingDevAccess.ps1').resolve()),console_sha256=intent['console_sha256'],bundle=str(bundle.resolve()),bundle_sha256=sha(bundle),new_expiry=payload['new_expiry'],windows_not_accessed=True)))
def run(access,ident,phase,review_sha):
require(str(uuid.UUID(ident))==ident,'canonical original recovery');folder=STATE/ident;intent=cb.contract.protected_json(folder/'intent.json')
require(intent['source_sha256']==sha(__file__) and intent['access_root']==str(access.root) and sha(folder/'Recover-ExistingDevAccess.ps1')==intent['console_sha256'] and sha(folder/'windows-dev-access-recovery.zip')==intent['bundle_sha256'] and sha(folder/'README.txt')==intent['readme_sha256'] and sha(folder/'public-recovery.json')==intent['public_json_sha256'],'same immutable console recovery source/public package')
if phase=='server-enter':
require(review_sha==sha(folder/'intent.json'),'explicit reviewed server-only CAS');save(folder/'server-enter-intent.json',dict(once=True))
payload=dict(intent['payload'],phase='enter' if phase=='server-enter' else 'readback')
result=access.rpc(payload);save(folder/('server-entered.json' if phase=='server-enter' else 'readback-'+str(uuid.uuid4())+'.json'),result)
print(json.dumps(dict(id=ident,result=result,windows_not_accessed=True,console_handoff_allowed=result.get('completed') is True)))
def main():
os.umask(0o077);parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('phase',choices=('prepare','server-enter','readback'));parser.add_argument('--access-root',required=True,type=Path);parser.add_argument('--id');parser.add_argument('--review-sha256');args=parser.parse_args();access=ServerAccess(args.access_root)
if args.phase=='prepare':require(not(args.id or args.review_sha256),'fresh server-only preparation');prepare(access)
else:require(args.id and ((args.phase=='server-enter')==bool(args.review_sha256)),'same case, reviewed CAS once');run(access,args.id,args.phase,args.review_sha256)
if __name__=='__main__':
try:main()
except Exception as error:print('CONSOLE_ACCESS_RECOVERY_INCOMPLETE:'+type(error).__name__);raise SystemExit(2) from None
+238
View File
@@ -0,0 +1,238 @@
#!/usr/bin/env python3
"""One 24h renewal of the existing restricted development SSH transport.
No new key, port, shell, RMM setting, download lease, stop/kill or reboot.
The unchanged tunnel expires naturally; one SYSTEM worker starts its original
scheduled task at original expiry+60s. This deliberately permits a short gap.
Lost mutation replies allow readback only. Main config publication is Root work.
"""
import argparse
import base64
import datetime as dt
import inspect
import json
import os
from pathlib import Path
import subprocess
import uuid
import client_bootstrap as cb
import system_pipe_upgrade as pair
require, sha, canonical, save = pair.require, pair.sha, pair.canonical, pair.save
STATE = cb.EVIDENCE / 'dev-access-renewal'
OLD_EXPIRY = '2026-11-14T12:55:31.254999+00:00'
OLD_UTC = dt.datetime.fromisoformat(OLD_EXPIRY)
NEW_UTC = OLD_UTC.replace(microsecond=0) + dt.timedelta(hours=24)
START_UTC = OLD_UTC.replace(microsecond=0) + dt.timedelta(seconds=60)
def server(payload):
import datetime as dt
import re
import stat
root=Path('/opt/rust-discovery/devstate/windows-bootstrap')
authorized=Path('/var/lib/rmm-win-tunnel/.ssh/authorized_keys')
profile=Path('/etc/ssh/sshd_config.d/80-rmm-windows-tunnel.conf')
ident=str(uuid.UUID(payload['id']));case=root/('renew-'+ident)
require(payload['phase'] in ('state','enter','readback'),'fixed renewal phase')
def check(path,mode):
s=path.lstat();require(not path.is_symlink() and stat.S_ISREG(s.st_mode) and s.st_uid==0 and stat.S_IMODE(s.st_mode)==mode and s.st_size<65536,'protected original transport file')
def digest(path):return hashlib.sha256(path.read_bytes()).hexdigest()
check(authorized,0o644);check(profile,0o644)
account=pwd.getpwnam('rmm-win-tunnel');require(account.pw_dir=='/var/lib/rmm-win-tunnel' and account.pw_shell=='/usr/sbin/nologin','existing forwarding-only account')
public=' '.join(Path('/etc/ssh/ssh_host_ed25519_key.pub').read_text().split()[:2])
fingerprint=subprocess.run(['ssh-keygen','-lf','/etc/ssh/ssh_host_ed25519_key.pub'],capture_output=True,check=True,timeout=10).stdout.decode().split()[1]
require(fingerprint=='SHA256:+NEin4XJc3CbhjQi7/ZpMIgxOrXn8AT2tlpTaXW5quw','confirmed original server host key')
raw=authorized.read_text();match=re.fullmatch(r'restrict,port-forwarding,permitlisten="127\.0\.0\.1:22240",expiry-time="(\d{14}Z)" (ssh-ed25519 [A-Za-z0-9+/=]{68})\n',raw)
require(match is not None and match[2]==payload['tunnel_public_key'],'exact unchanged forwarding key/options')
effective=subprocess.run(['/usr/sbin/sshd','-T','-C','user=rmm-win-tunnel,host=localhost,addr=127.0.0.1'],capture_output=True,check=True,timeout=10).stdout
for line in (b'allowtcpforwarding remote\n',b'permitlisten 127.0.0.1:22240\n',b'permitopen none\n',b'gatewayports no\n',b'maxsessions 0\n',b'passwordauthentication no\n'):require(line in effective,'same restricted forwarding-only profile')
def state():return dict(read_only=True,authorized_sha256=digest(authorized),profile_sha256=digest(profile),effective_sha256=hashlib.sha256(effective).hexdigest(),server_host_key_sha256=hashlib.sha256(public.encode()).hexdigest(),tunnel_public_key_sha256=hashlib.sha256(match[2].encode()).hexdigest(),expiry=match[1],uid=account.pw_uid,gid=account.pw_gid,home=account.pw_dir,shell=account.pw_shell)
if payload['phase']=='state':return state()
if payload['phase']=='readback':
value=state();value['case_exists']=case.exists();value['replace_intent']=case.exists() and (case/'replace-intent.json').exists();value['completed']=case.exists() and (case/'completed.json').exists();return value
old=dt.datetime.fromisoformat(payload['old_expiry']).astimezone(dt.timezone.utc);new=dt.datetime.fromisoformat(payload['new_expiry']).astimezone(dt.timezone.utc)
require(old.isoformat()=='2026-11-14T12:55:31.254999+00:00' and new==old.replace(microsecond=0)+dt.timedelta(hours=24) and dt.datetime.now(dt.timezone.utc)<old and state()==payload['server_before'],'exact original server expiry/CAS and single 24h extension')
require(not case.exists(),'existing server renewal: readback only');case.mkdir(mode=0o700)
def write(path,data,mode=0o600):
fd=os.open(path,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,mode)
with os.fdopen(fd,'wb') as out:out.write(data);out.flush();os.fsync(out.fileno());os.fchmod(out.fileno(),mode)
write(case/'intent.json',json.dumps(payload).encode());write(case/'authorized_keys.original',raw.encode())
replacement=raw.replace('expiry-time="'+old.strftime('%Y%m%d%H%M%SZ')+'"','expiry-time="'+new.strftime('%Y%m%d%H%M%SZ')+'"')
require(replacement!=raw and replacement.replace(new.strftime('%Y%m%d%H%M%SZ'),old.strftime('%Y%m%d%H%M%SZ'))==raw,'expiry only, key/options unchanged')
candidate=authorized.parent/('renew-'+ident+'.next');write(candidate,replacement.encode(),0o644)
write(case/'replace-intent.json',json.dumps(dict(old_sha256=digest(authorized),new_sha256=hashlib.sha256(replacement.encode()).hexdigest())).encode())
require(digest(authorized)==payload['server_before']['authorized_sha256'] and digest(profile)==payload['server_before']['profile_sha256'],'immediate original server CAS')
os.replace(candidate,authorized);directory=os.open(authorized.parent,os.O_RDONLY);os.fsync(directory);os.close(directory)
require(authorized.read_text()==replacement,'actual exact renewed authorization');write(case/'completed.json',json.dumps(dict(completed=True,new_expiry=payload['new_expiry'],download_lease_changed=False)).encode())
return dict(completed=True,authorized_sha256=digest(authorized),expiry=new.strftime('%Y%m%d%H%M%SZ'),no_new_authority=True,download_lease_changed=False)
COMMON = r'''
$ErrorActionPreference='Stop';$p=$global:RmmRenewalPayload
if(!$p-or[guid]::ParseExact($p.id,'D').ToString()-cne$p.id-or$p.phase-notin@('state','enter','readback','worker')){throw 'Fixed access renewal'}
$root='C:\ProgramData\RmmDevAccess';$case=Join-Path $root ('renew-'+$p.id);$config=Join-Path $root 'bootstrap-public.json';$taskName='RmmDevReverseTunnel';$workerName='RmmDevAccessRenew-'+$p.id
$sys='S-1-5-18';$admin='S-1-5-32-544'
function Safe($path,$directory){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$directory-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Original regular transport path'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@($sys,$admin)){throw 'Transport owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty transport ACL'};foreach($r in $rules){if($r.AccessControlType-ne'Allow'-or$r.IdentityReference.Value-notin@($sys,$admin)){throw 'Private transport ACL'}}}
function SafePublic($path){
if($path-notin@((Join-Path $root 'tunnel_ed25519.pub'),'C:\ProgramData\ssh\ssh_host_ed25519_key.pub')){throw 'Only two fixed public key files'}
$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)-or$i.Length-gt4096){throw 'Bounded regular public key'};Safe $i.Directory.FullName $true
$ancestor=$i.Directory;while($null-ne$ancestor){if($ancestor.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'Public key reparse ancestor'};$ancestor=$ancestor.Parent}
$builtin=@(Get-LocalUser|Where-Object{$_.SID.Value-like'*-500'});if($builtin.Count-ne1){throw 'Actual builtin Administrator SID'};$builtinSid=$builtin[0].SID.Value
if(@(Get-LocalGroupMember -SID $admin|Where-Object{$_.SID.Value-ceq$builtinSid}).Count-ne1){throw 'Builtin Administrator membership'}
$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@($sys,$admin,$builtinSid)){throw 'Public key trusted owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty public DACL'}
foreach($r in $rules){if($r.AccessControlType-ne'Allow'){throw 'Public key DACL shape'};if($r.IdentityReference.Value-notin@($sys,$admin,$builtinSid)-and([int64]$r.FileSystemRights-band(-bnot[int64]0x1200a9))-ne0){throw 'No public file writer beyond SYSTEM/Admin/builtin Administrator'}}
}
function HashPublic($path){SafePublic $path;return(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()}
function HashBytes([byte[]]$b){$h=[Security.Cryptography.SHA256]::Create();try{return([BitConverter]::ToString($h.ComputeHash($b))).Replace('-','').ToLowerInvariant()}finally{$h.Dispose()}}
function Hash($path){Safe $path $false;return(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()}
function Acl($path){return HashBytes ([Text.Encoding]::UTF8.GetBytes((Get-Acl -LiteralPath $path).Sddl))}
function WriteBytes($path,[byte[]]$b){$f=[IO.File]::Open($path,'CreateNew','Write','Read');try{$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}}
function WriteNew($path,$value){WriteBytes $path ([Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 16 -Compress)))}
function Equal($a,$b){return(($a|ConvertTo-Json -Depth 16 -Compress)-ceq($b|ConvertTo-Json -Depth 16 -Compress))}
function ProcessRecord($process){
if(!$process){return $null};$owner=(Invoke-CimMethod -InputObject $process -MethodName GetOwnerSid -OperationTimeoutSec 10).Sid;if($owner-cne$sys){throw 'Actual own SYSTEM task process'};$native=[Diagnostics.Process]::GetProcessById([int]$process.ProcessId)
try{if($native.HasExited){throw 'Own process exited while pinning'};$birth=$native.StartTime.ToUniversalTime().ToFileTimeUtc().ToString()}finally{$native.Dispose()}
return @{pid=[uint32]$process.ProcessId;parent_pid=[uint32]$process.ParentProcessId;creation_filetime=$birth;owner_sid=$owner;image=$process.ExecutablePath;image_sha256=(Get-FileHash -LiteralPath $process.ExecutablePath -Algorithm SHA256).Hash.ToLowerInvariant();command_sha256=(HashBytes ([Text.Encoding]::UTF8.GetBytes($process.CommandLine)))}
}
function OriginalTask{
$task=Get-ScheduledTask -TaskName $taskName;$action=@($task.Actions);$expected='-NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -File "C:\ProgramData\RmmDevAccess\Bootstrap-DevAccess.ps1" -MaintainTunnel'
if($action.Count-ne1-or$action[0].Execute-ine'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'-or$action[0].Arguments-cne$expected-or$task.Principal.UserId-notin@('SYSTEM',$sys)-or$task.Principal.LogonType-cne'ServiceAccount'-or$task.Principal.RunLevel-cne'Highest'-or$task.Settings.MultipleInstances-cne'IgnoreNew'){throw 'Original task definition/authority'}
return @{xml_sha256=(HashBytes ([Text.Encoding]::UTF8.GetBytes((Export-ScheduledTask -TaskName $taskName))));action_execute=$action[0].Execute;action_arguments_sha256=(HashBytes ([Text.Encoding]::UTF8.GetBytes($action[0].Arguments)));principal=$task.Principal.UserId;logon_type=[string]$task.Principal.LogonType;run_level=[string]$task.Principal.RunLevel;state=[string]$task.State}
}
function State{
Safe $root $true;Safe $config $false;$cfg=Get-Content -LiteralPath $config -Raw|ConvertFrom-Json
if((($cfg.PSObject.Properties.Name|Sort-Object)-join',')-cne'expires_at,notebook_public_key,schema_version,server,server_host_key'-or$cfg.schema_version-ne1-or$cfg.server-cne'discovery.ease-technologies.de'){throw 'Original public transport schema'}
$user=Get-LocalUser -Name 'rmm-dev';if(!$user.Enabled-or!$user.AccountExpires){throw 'Original enabled temporary access account'}
$files=[ordered]@{};foreach($entry in @(@('bootstrap',(Join-Path $root 'Bootstrap-DevAccess.ps1')),@('known_hosts',(Join-Path $root 'known_hosts')),@('public_key',(Join-Path $root 'tunnel_ed25519.pub')),@('sshd_config','C:\ProgramData\ssh\sshd_config'),@('authorized','C:\ProgramData\ssh\administrators_authorized_keys'),@('host_public','C:\ProgramData\ssh\ssh_host_ed25519_key.pub'))){$digest=$null;if($entry[0]-in@('public_key','host_public')){$digest=HashPublic $entry[1]}else{$digest=Hash $entry[1]};$files[$entry[0]]=@{sha256=$digest;acl_sha256=(Acl $entry[1])}}
$key=Join-Path $root 'tunnel_ed25519';Safe $key $false;$k=Get-Item -LiteralPath $key -Force
$known=[IO.File]::ReadAllText((Join-Path $root 'known_hosts'));if($known-cne('discovery.ease-technologies.de '+$cfg.server_host_key+"`n")){throw 'Original strict server host pin'}
$public=((Get-Content -LiteralPath (Join-Path $root 'tunnel_ed25519.pub') -Raw).Trim()-split'\s+')[0..1]-join' ';if($public-cne$p.tunnel_public_key){throw 'Original VM tunnel public key'}
$hostPublic=((Get-Content -LiteralPath 'C:\ProgramData\ssh\ssh_host_ed25519_key.pub' -Raw).Trim()-split'\s+')[0..1]-join' ';if($hostPublic-cne$p.windows_host_public_key){throw 'Console-confirmed original VM host pin'}
if((Get-Content -LiteralPath 'C:\ProgramData\ssh\administrators_authorized_keys' -Raw)-cne($cfg.notebook_public_key+"`n")){throw 'Original only notebook public key'}
$t=OriginalTask;$all=@(Get-CimInstance Win32_Process -Filter "Name='powershell.exe'" -OperationTimeoutSec 10|Where-Object{$_.CommandLine-like'*Bootstrap-DevAccess.ps1* -MaintainTunnel*'});if($all.Count-gt1){throw 'Only original maintainer instance'};$maintainer=$null;$child=$null
if($all.Count-eq1){if($all[0].ExecutablePath-ine$t.action_execute){throw 'Original maintainer image'};$maintainer=ProcessRecord $all[0];$children=@(Get-CimInstance Win32_Process -Filter ('ParentProcessId='+$maintainer.pid) -OperationTimeoutSec 10|Where-Object{$_.Name-ceq'ssh.exe'});if($children.Count-gt1){throw 'Only original SSH child'};if($children.Count-eq1){if($children[0].ExecutablePath-ine'C:\Windows\System32\OpenSSH\ssh.exe'-or$children[0].CommandLine-notlike'*-R*127.0.0.1:22240:127.0.0.1:22222*rmm-win-tunnel@discovery.ease-technologies.de*'){throw 'Original restricted SSH child'};$child=ProcessRecord $children[0]}}
$listeners=@(Get-NetTCPConnection -State Listen -LocalPort 22222 -ErrorAction SilentlyContinue);if(!$listeners.Count-or@($listeners|Where-Object{$_.LocalAddress-cne'127.0.0.1'}).Count){throw 'Existing SSH loopback-only listener'}
return @{config_sha256=(Hash $config);config_acl_sha256=(Acl $config);expires_at=$cfg.expires_at;account_sid=$user.SID.Value;account_expires_filetime=$user.AccountExpires.ToUniversalTime().ToFileTimeUtc().ToString();files=$files;private_key_metadata=@{bytes=$k.Length;created=$k.CreationTimeUtc.Ticks.ToString();written=$k.LastWriteTimeUtc.Ticks.ToString();acl_sha256=(Acl $key);private_key_read=$false};server_host_key_sha256=(HashBytes ([Text.Encoding]::UTF8.GetBytes($cfg.server_host_key)));task=$t;maintainer=$maintainer;ssh_child=$child}
}
function ReadIntent{Safe $case $true;Safe (Join-Path $case 'intent.json') $false;$i=Get-Content -LiteralPath (Join-Path $case 'intent.json') -Raw|ConvertFrom-Json;foreach($field in $p.PSObject.Properties.Name){if($field-cne'phase'-and!(Equal $i.$field $p.$field)){throw 'Same exact original renewal intent'}};return $i}
'''
WORKER = COMMON + r'''
$p=Get-Content -LiteralPath (Join-Path $PSScriptRoot 'intent.json') -Raw|ConvertFrom-Json;$p.phase='worker';$null=ReadIntent
if((Hash $PSCommandPath)-cne$p.worker_sha256-or$PSCommandPath-cne(Join-Path $case 'Renew-Transport.ps1')){throw 'Actual fixed own worker source'}
WriteNew (Join-Path $case 'worker-started.json') @{once=$true;utc=[DateTimeOffset]::UtcNow.ToString('o')}
$registration=Get-Content -LiteralPath (Join-Path $case 'worker-registered.json') -Raw|ConvertFrom-Json;if((HashBytes ([Text.Encoding]::UTF8.GetBytes((Export-ScheduledTask -TaskName $workerName))))-cne$registration.worker_xml_sha256){throw 'Exact own worker task definition'}
$now=[DateTimeOffset]::UtcNow;if($p.start_at-cne'2026-11-14T12:56:31+00:00'-or$now-lt[DateTimeOffset]::Parse($p.start_at)-or$now-gt[DateTimeOffset]::Parse($p.start_at).AddMinutes(5)){throw 'Only narrow original expiry+60s worker window'}
$state=State;if($state.expires_at-cne$p.new_expiry-or$state.account_expires_filetime-cne$p.new_account_filetime-or$state.task.state-cne'Ready'-or$null-ne$state.maintainer-or$null-ne$state.ssh_child){throw 'Old task/child must have naturally exited; never kill or repeat'}
foreach($field in @('files','private_key_metadata','account_sid','config_acl_sha256','server_host_key_sha256')){if(!(Equal $p.before.$field $state.$field)){throw 'Original transport identity/ACL changed'}}
if($state.task.xml_sha256-cne$p.before.task.xml_sha256){throw 'Original task XML unchanged'}
foreach($record in @($p.before.maintainer,$p.before.ssh_child)){$current=Get-Process -Id $record.pid -ErrorAction SilentlyContinue;if($current){try{if($current.StartTime.ToUniversalTime().ToFileTimeUtc().ToString()-ceq$record.creation_filetime-and!$current.HasExited){throw 'Original pinned process still alive'}}finally{$current.Dispose()}}}
WriteNew (Join-Path $case 'original-task-start-attempt.json') @{once=$true;original_task=$taskName;original_xml_sha256=$state.task.xml_sha256}
Start-ScheduledTask -TaskName $taskName
$deadline=[DateTimeOffset]::UtcNow.AddSeconds(30);do{Start-Sleep -Seconds 1;$after=State;if($after.task.state-ceq'Running'-and$null-ne$after.maintainer-and$null-ne$after.ssh_child){break}}while([DateTimeOffset]::UtcNow-lt$deadline)
if($after.task.state-cne'Running'-or$null-eq$after.maintainer-or$null-eq$after.ssh_child-or$after.task.xml_sha256-cne$p.before.task.xml_sha256){throw 'One fresh original tunnel task start not verified'}
WriteNew (Join-Path $case 'completed.json') @{completed=$true;new_expiry=$p.new_expiry;new_state=$after;no_kill=$true;no_new_authority=$true;download_lease_changed=$false}
Disable-ScheduledTask -TaskName $workerName|Out-Null
WriteNew (Join-Path $case 'worker-disabled.json') @{disabled=$true;retained=$true}
'''
SCRIPT = COMMON + r'''
if($p.phase-ceq'state'){State|ConvertTo-Json -Depth 16 -Compress;exit 0}
if($p.phase-ceq'readback'){$value=@{read_only=$true;state=(State);case_exists=(Test-Path -LiteralPath $case)};if($value.case_exists){$null=ReadIntent;$value['phases']=@{};foreach($name in @('config-replace-attempt','config-replaced','account-expiry-attempt','account-expiry-set','worker-register-attempt','worker-registered','worker-started','original-task-start-attempt','completed','worker-disabled')){$value.phases[$name]=Test-Path -LiteralPath (Join-Path $case ($name+'.json'))}};$value|ConvertTo-Json -Depth 16 -Compress;exit 0}
if($p.phase-cne'enter'-or(Test-Path -LiteralPath $case)-or(Get-ScheduledTask -TaskName $workerName -ErrorAction SilentlyContinue)){throw 'Single new renewal admission; readback only'}
if($p.old_expiry-cne'2026-11-14T12:55:31.254999+00:00'-or[DateTimeOffset]::Parse($p.new_expiry)-ne[DateTimeOffset]::Parse($p.old_expiry).AddHours(24).AddTicks(-2549990)-or[DateTimeOffset]::UtcNow-ge[DateTimeOffset]::Parse($p.old_expiry)){throw 'Exact original window and 24h renewal'}
$before=State;if(!(Equal $before $p.before)-or$before.task.state-cne'Running'-or$null-eq$before.maintainer-or$null-eq$before.ssh_child){throw 'Concrete original live transport CAS'}
New-Item -ItemType Directory -Path $case|Out-Null;Safe $case $true;WriteNew (Join-Path $case 'intent.json') $p
$original=Join-Path $case 'bootstrap-public.original';[IO.File]::Copy($config,$original,$false);Safe $original $false
$cfg=Get-Content -LiteralPath $config -Raw|ConvertFrom-Json;$cfg.expires_at=$p.new_expiry;$candidate=Join-Path $case 'bootstrap-public.next';WriteNew $candidate $cfg;$nativeBackup=Join-Path $case 'bootstrap-public.native-original'
WriteNew (Join-Path $case 'config-replace-attempt.json') @{original_sha256=$before.config_sha256;native_backup=$nativeBackup}
if((Hash $config)-cne$before.config_sha256-or(Test-Path -LiteralPath $nativeBackup)){throw 'Immediate original config CAS'};$sddl=(Get-Acl -LiteralPath $config).Sddl;[IO.File]::Replace($candidate,$config,$nativeBackup);$acl=New-Object Security.AccessControl.FileSecurity;$acl.SetSecurityDescriptorSddlForm($sddl);Set-Acl -LiteralPath $config -AclObject $acl
WriteNew (Join-Path $case 'config-replaced.json') @{sha256=(Hash $config);native_backup_sha256=(Hash $nativeBackup)}
WriteNew (Join-Path $case 'account-expiry-attempt.json') @{account='rmm-dev';old_filetime=$before.account_expires_filetime;new_filetime=$p.new_account_filetime}
$currentUser=Get-LocalUser -Name 'rmm-dev';if($currentUser.SID.Value-cne$before.account_sid-or$currentUser.AccountExpires.ToUniversalTime().ToFileTimeUtc().ToString()-cne$before.account_expires_filetime){throw 'Immediate original account SID/expiry CAS'}
Set-LocalUser -Name 'rmm-dev' -AccountExpires ([DateTimeOffset]::Parse($p.new_expiry).LocalDateTime)
if((Get-LocalUser -Name 'rmm-dev').AccountExpires.ToUniversalTime().ToFileTimeUtc().ToString()-cne$p.new_account_filetime){throw 'Actual exact account expiry'};WriteNew (Join-Path $case 'account-expiry-set.json') @{new_filetime=$p.new_account_filetime}
$worker=Join-Path $case 'Renew-Transport.ps1';$bytes=[Convert]::FromBase64String($p.worker_base64);if((HashBytes $bytes)-cne$p.worker_sha256){throw 'Exact reviewed renewal worker'};WriteBytes $worker $bytes;Safe $worker $false
$action=New-ScheduledTaskAction -Execute 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe' -Argument ('-NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -File "'+$worker+'"')
$principal=New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest
$settings=New-ScheduledTaskSettingsSet -MultipleInstances IgnoreNew -ExecutionTimeLimit ([TimeSpan]::FromMinutes(2)) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
$trigger=New-ScheduledTaskTrigger -Once -At ([DateTimeOffset]::Parse($p.start_at).LocalDateTime)
WriteNew (Join-Path $case 'worker-register-attempt.json') @{name=$workerName;source_sha256=$p.worker_sha256;once=$true;start_at=$p.start_at}
Register-ScheduledTask -TaskName $workerName -Action $action -Trigger $trigger -Settings $settings -Principal $principal|Out-Null
WriteNew (Join-Path $case 'worker-registered.json') @{registered=$true;original_task_unmodified=$true;worker_xml_sha256=(HashBytes ([Text.Encoding]::UTF8.GetBytes((Export-ScheduledTask -TaskName $workerName))))}
@{entered=$true;planned_gap=$true;start_at=$p.start_at;new_expiry=$p.new_expiry;original_task_restarted_now=$false;download_lease_changed=$false}|ConvertTo-Json -Compress
'''
# Worker sets its own fixed payload before COMMON examines it.
WORKER = "$global:RmmRenewalPayload=Get-Content -LiteralPath (Join-Path $PSScriptRoot 'intent.json') -Raw|ConvertFrom-Json;$global:RmmRenewalPayload.phase='worker'\n" + WORKER
class Access(pair.Access):
def stage_controller(self,path):
name='DevAccessRenewal.ps1';digest=sha(path)
prepare=pair.u.transport.PREPARE_SCRIPT.replace('TransportAcceptance.ps1',name)
observed=self.powershell(prepare,dict(sha256=digest))
if not observed['already_uploaded']:
access=cb.contract.protected_json(self.root/'credentials/windows-dev-access.json');prefix=access['ssh_prefix']
args=['sftp']+[p for p in prefix[1:-1] if p!='-T']+['-b','-',prefix[-1]]
target='/C:/ProgramData/RustDiscoveryBootstrap/'+digest+'/'+name
result=subprocess.run(args,input=('put '+json.dumps(str(path.resolve()))+' '+json.dumps(target)+'\n').encode(),capture_output=True,timeout=60)
require(result.returncode==0,'single exact renewal source transfer; no retry')
require(self.powershell(prepare,dict(sha256=digest))['already_uploaded'] is True,'exact staged controller')
def rpc(self, payload):
cloud=pair.u.transport.cloud;cfg=cloud.bootstrap.access.load_config(self.root/'credentials/server.conf')
ssh=['ssh','-F','/dev/null','-T','-p',cfg.get('port','22'),'-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','IdentitiesOnly=yes','-o','ForwardAgent=no','-i',str(Path(cfg['ssh_key_path']).expanduser()),cfg['username']+'@'+cfg['address'],'python3 -']
code='import os,json,subprocess,base64,hashlib,uuid,pwd\nfrom pathlib import Path\n'+inspect.getsource(cloud.bootstrap.require)+'\n'+inspect.getsource(server)+'\ntry:\n print(json.dumps(server('+repr(payload)+')))\nexcept Exception as e:\n print(json.dumps(dict(error=type(e).__name__)))\n'
result=subprocess.run(ssh,input=code.encode(),capture_output=True,timeout=60);require(result.returncode==0,'fixed renewal server RPC')
value=json.loads(result.stdout,object_pairs_hook=cb.contract.strict_object);require('error' not in value,'server renewal incomplete; readback only');return value
def windows(self,payload):
# Existing fixed access bridge; no credentials copy or Main writes.
launch=pair.LAUNCH.replace('SystemPipeUpgrade.ps1','DevAccessRenewal.ps1').replace('RmmPipeUpgradePayload','RmmRenewalPayload')
return self.powershell(launch,dict(sha256=pair.raw_sha(SCRIPT.encode()),payload=payload),timeout=150)
def load(access,ident):
require(str(uuid.UUID(ident))==ident,'canonical case');folder=STATE/ident;intent=cb.contract.protected_json(folder/'intent.json')
require(intent['runner_sha256']==sha(__file__) and intent['worker_sha256']==pair.raw_sha(WORKER.encode()) and intent['access_root']==str(access.root),'original immutable renewal source/accessroot')
return folder,intent
def prepare(access):
ident=str(uuid.uuid4());folder=STATE/ident;folder.mkdir(mode=0o700,parents=True)
console=cb.contract.protected_json(access.root/'devstate/windows-bootstrap/console-registration.json')
payload=dict(id=ident,phase='state',tunnel_public_key=console['tunnel_public_key'],windows_host_public_key=console['windows_host_public_key'],old_expiry=OLD_EXPIRY,new_expiry=NEW_UTC.isoformat(),start_at=START_UTC.isoformat(),new_account_filetime=str((int(NEW_UTC.timestamp())+11644473600)*10000000),worker_sha256=pair.raw_sha(WORKER.encode()),worker_base64=base64.b64encode(WORKER.encode()).decode())
require(cb.contract.now()<OLD_UTC,'original lease still active')
save(folder/'prepare-intent.json',dict(id=ident,runner_sha256=sha(__file__),no_new_authority=True))
source=folder/'DevAccessRenewal.ps1';pair.write_bytes(source,SCRIPT.encode());access.stage_controller(source)
before=access.windows(payload);server_before=access.rpc(payload)
require(before['files']['bootstrap']['sha256']==sha(cb.ROOT/'deploy/windows/Bootstrap-DevAccess.ps1'),'original fixed maintainer source')
require(before['expires_at']==OLD_EXPIRY and before['server_host_key_sha256']==server_before['server_host_key_sha256'] and server_before['expiry']==OLD_UTC.strftime('%Y%m%d%H%M%SZ'),'same original windows/server expiry/host pin')
payload.update(before=before,server_before=server_before)
intent=dict(id=ident,runner_sha256=sha(__file__),worker_sha256=payload['worker_sha256'],access_root=str(access.root),payload=payload)
save(folder/'intent.json',intent)
print(json.dumps(dict(id=ident,prepared=True,review_sha256=sha(folder/'intent.json'),new_expiry=payload['new_expiry'],start_at=payload['start_at'],planned_short_gap=True)))
def run(access,ident,phase,review_sha=None):
folder,intent=load(access,ident);payload=dict(intent['payload'],phase='readback' if phase=='readback' else 'enter')
if phase=='enter':
require(review_sha==sha(folder/'intent.json'),'explicit reviewed renewal intent SHA')
save(folder/'server-enter-attempt.json',dict(once=True))
server_result=access.rpc(payload);require(server_result.get('completed') is True,'server expiry CAS first');save(folder/'server-entered.json',server_result)
save(folder/'windows-enter-attempt.json',dict(once=True))
observed=access.windows(payload);save(folder/'windows-entered.json',observed)
else:
server_result=access.rpc(payload);observed=access.windows(payload);save(folder/('readback-'+str(uuid.uuid4())+'.json'),dict(server=server_result,windows=observed))
print(json.dumps(dict(id=ident,phase=phase,server_expiry=server_result.get('expiry'),windows=observed,main_config_updated=False)))
def main():
os.umask(0o077);parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('phase',choices=('prepare','enter','readback'));parser.add_argument('--access-root',required=True,type=Path);parser.add_argument('--id');parser.add_argument('--review-sha256');args=parser.parse_args();access=Access(args.access_root)
if args.phase=='prepare':require(not(args.id or args.review_sha256),'new readonly renewal baseline');prepare(access)
else:require(args.id and ((args.phase=='enter')==bool(args.review_sha256)),'same case and reviewed intent for enter');run(access,args.id,args.phase,args.review_sha256)
if __name__=='__main__':
try:main()
except Exception as error:print('DEV_ACCESS_RENEWAL_INCOMPLETE:'+type(error).__name__);raise SystemExit(2) from None
+564
View File
@@ -0,0 +1,564 @@
#!/usr/bin/env python3
"""One preserving passive pipe-v2 pair upgrade; no target actions by default.
prepare stages immutable bootstrap artifacts and captures a read-only baseline.
enter needs that exact separately reviewed baseline hash and runs once. A lost
reply permits readback/finish only. Main access-root is read-only, including the
current indices: Root publishes those separately after reviewing this result.
"""
import argparse
import base64
import hashlib
import inspect
import json
import os
from pathlib import Path
import re
import subprocess
import sys
import time
import uuid
import client_bootstrap as cb
import system_delegation_upgrade as u
require = cb.contract.require
ROOT = cb.ROOT
STATE = cb.EVIDENCE / 'system-pipe-upgrade'
ORIGINAL_RUNNER = 'f8dc1c8fbc064e253b1fbe130fb628afef58cf45c2bafb6837d6716125b42d38'
OLD_AGENT = '89004ad3475af3fb8a03bdb1e63c3ef1f2a08d31d0d97193e02fe770a1d7f676'
OLD_HELPER = 'e6aacbdd691c8c56612a2ba205c48396defe70e7d527e031aa3a76a8ae5a3662'
OLD_POLICY = '007adf5f4932dcf68fa4c0c3ba601ec1996b350e7e3e1d14e89a31dd712e5703'
OLD_PIN = '126670bc6ed71aad76438ec588b739d3bc02d36ae305ce8f8b5613e4a9e11a15'
OLD_CASE = '6d2df065-0877-41c4-983c-2c9fdb6e5437'
OLD_RESULT_SHA = 'ac00411fe1e109b18b28fd9c020245f462c179bb3ac99a37b69c7cff39c38460'
PIPE_VERIFIER_SHA = '2ac6bd55e608e7dbb0f0cf65cf37e7bbccc42b862d09c50b37e9162f29f4bbdf'
sha, raw_sha, canonical, save = u.sha, u.raw_sha, u.canonical, u.save
def replace_once(text, old, new):
require(text.count(old) == 1, 'exact reviewed bootstrap splice')
return text.replace(old, new, 1)
def write_bytes(path, data):
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, 'wb') as output:
output.write(data); output.flush(); os.fsync(output.fileno())
# Reuse read-only witnesses only, bound to the historical runner hash below.
# None of its original hard-PID stop, File.Replace(NULL), start, or case logic
# is included. Every new mutation is visible in this file.
PREFIX = u.SCRIPT.split('\nfunction ReadIntent', 1)[0]
PREFIX = replace_once(PREFIX, 'RmmDelegationUpgradePayload', 'RmmPipeUpgradePayload')
PREFIX = replace_once(PREFIX, "@('state','enter','finish','readback')", "@('baseline','enter','finish','readback')")
PREFIX = replace_once(PREFIX, "('system-delegation-'+$p.id)", "('system-pipe-'+$p.id)")
PREFIX = replace_once(PREFIX, "'system-delegation-active-intent.json'", "'system-pipe-active-intent.json'")
for old, new in ((u.OLD_AGENT, OLD_AGENT), (u.OLD_HELPER, OLD_HELPER), (u.OLD_POLICY, OLD_POLICY), (u.OLD_PIN, OLD_PIN)):
PREFIX = replace_once(PREFIX, old, new)
NATIVE = r'''
Add-Type -TypeDefinition @'
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using Microsoft.Win32.SafeHandles;
public static class RmmPipeNative {
public sealed class Held : SafeHandleZeroOrMinusOneIsInvalid {
public Held(IntPtr h):base(true){SetHandle(h);}
protected override bool ReleaseHandle(){return CloseHandle(handle);}
}
[StructLayout(LayoutKind.Sequential)] public struct FileId {
public ulong Volume;
[MarshalAs(UnmanagedType.ByValArray,SizeConst=16)] public byte[] Id;
}
[StructLayout(LayoutKind.Sequential)] struct SidAndAttributes {public IntPtr Sid;public uint Attributes;}
[StructLayout(LayoutKind.Sequential)] struct Groups {public uint Count;public SidAndAttributes First;}
[DllImport("kernel32.dll",SetLastError=true)] static extern IntPtr OpenProcess(uint access,bool inherit,int pid);
[DllImport("kernel32.dll",SetLastError=true)] static extern bool CloseHandle(IntPtr h);
[DllImport("kernel32.dll",SetLastError=true)] static extern bool GetProcessTimes(Held h,out long creation,out long exit,out long kernel,out long user);
[DllImport("kernel32.dll",SetLastError=true,CharSet=CharSet.Unicode)] static extern bool QueryFullProcessImageName(Held h,uint flags,StringBuilder image,ref uint size);
[DllImport("kernel32.dll",SetLastError=true)] static extern uint WaitForSingleObject(Held h,uint millis);
[DllImport("advapi32.dll",SetLastError=true)] static extern bool OpenProcessToken(Held process,uint access,out IntPtr token);
[DllImport("advapi32.dll",SetLastError=true)] static extern bool GetTokenInformation(IntPtr token,int kind,IntPtr data,int bytes,out int needed);
[DllImport("kernel32.dll",SetLastError=true)] public static extern bool GetFileInformationByHandleEx(SafeFileHandle h,int kind,out FileId id,uint size);
[DllImport("kernel32.dll",SetLastError=true,CharSet=CharSet.Unicode)] public static extern SafeFileHandle CreateFile(string path,uint access,uint share,IntPtr security,uint creation,uint flags,IntPtr template);
public static Held Open(int pid){IntPtr h=OpenProcess(0x101000,false,pid);if(h==IntPtr.Zero)throw new Win32Exception();return new Held(h);}
public static bool Alive(Held h){return WaitForSingleObject(h,0)==258;}
public static bool Exited(Held h,uint timeout){return WaitForSingleObject(h,timeout)==0;}
static IntPtr Info(IntPtr token,int kind,out int bytes){
int needed;GetTokenInformation(token,kind,IntPtr.Zero,0,out needed);
if(needed<=0||needed>65536)throw new InvalidOperationException("Token size");
IntPtr p=Marshal.AllocHGlobal(needed);if(!GetTokenInformation(token,kind,p,needed,out bytes)){Marshal.FreeHGlobal(p);throw new Win32Exception();}return p;
}
public static Dictionary<string,object> Proof(Held h,int pid,string owner,string serviceSid,string image){
if(!Alive(h))throw new InvalidOperationException("Process not alive");
long creation,exit,kernel,user;if(!GetProcessTimes(h,out creation,out exit,out kernel,out user))throw new Win32Exception();
StringBuilder path=new StringBuilder(32768);uint length=32768;if(!QueryFullProcessImageName(h,0,path,ref length)||!String.Equals(path.ToString(),image,StringComparison.OrdinalIgnoreCase))throw new InvalidOperationException("Process image");
IntPtr token;if(!OpenProcessToken(h,8,out token))throw new Win32Exception();
try {
int bytes;IntPtr info=Info(token,1,out bytes);string actual;
try {actual=new SecurityIdentifier(Marshal.ReadIntPtr(info)).Value;}finally{Marshal.FreeHGlobal(info);}
if(actual!=owner)throw new InvalidOperationException("Process owner");
info=Info(token,2,out bytes);bool found=false;
try {int count=Marshal.ReadInt32(info);int offset=(int)Marshal.OffsetOf(typeof(Groups),"First");int stride=Marshal.SizeOf(typeof(SidAndAttributes));
if(count<0||count>1024||offset+(long)count*stride>bytes)throw new InvalidOperationException("Groups size");
for(int n=0;n<count;n++){SidAndAttributes g=(SidAndAttributes)Marshal.PtrToStructure(IntPtr.Add(info,offset+n*stride),typeof(SidAndAttributes));if(new SecurityIdentifier(g.Sid).Value==serviceSid&&(g.Attributes&4)!=0&&(g.Attributes&16)==0)found=true;}
}finally{Marshal.FreeHGlobal(info);}
if(!found||!Alive(h))throw new InvalidOperationException("Enabled service SID/process liveness");
return new Dictionary<string,object>{{"pid",pid},{"creation_filetime",creation.ToString(System.Globalization.CultureInfo.InvariantCulture)},{"owner_sid",actual},{"service_sid",serviceSid},{"service_sid_enabled",true},{"image",path.ToString()},{"kernel_handle_bound",true}};
}finally{CloseHandle(token);}
}
}
'@
function FileIdentity($path,[bool]$actor=$false){
Check $path $false $actor;$file=[IO.File]::Open($path,[IO.FileMode]::Open,[IO.FileAccess]::Read,[IO.FileShare]::Read)
try{$id=New-Object RmmPipeNative+FileId;$size=[Runtime.InteropServices.Marshal]::SizeOf([type][RmmPipeNative+FileId]);if($size-ne24-or![RmmPipeNative]::GetFileInformationByHandleEx($file.SafeFileHandle,18,[ref]$id,[uint32]$size)){throw 'Native file identity'}
return [ordered]@{volume_serial=$id.Volume.ToString([Globalization.CultureInfo]::InvariantCulture);file_id=([BitConverter]::ToString($id.Id)).Replace('-','').ToLowerInvariant();bytes=$file.Length;acl_sha256=(AclHash $path);sha256=(Hash $path $actor)}
}finally{$file.Dispose()}
}
function Kernel($role,$record,$held){
$owner='S-1-5-19';$sid=$agentSid;$image=$agentBinary;if($role-ceq'helper'){$owner=$sys;$sid=$helperSid;$image=$helperBinary}
$proof=[RmmPipeNative]::Proof($held,[int]$record.pid,$owner,$sid,$image)
if($proof.creation_filetime-cne$record.creation_filetime-or$proof.owner_sid-cne$record.owner_sid){throw 'SCM/kernel process identity mismatch'};return $proof
}
function ActualState([bool]$new){
$value=State $new
$value['files']=[ordered]@{agent=(FileIdentity $agentBinary);helper=(FileIdentity $helperBinary);settings=(FileIdentity $settings);pin=(FileIdentity $pin);config=(FileIdentity $config);ca=(FileIdentity (Join-Path $agentRoot 'server-ca.pem') $true);identity=(FileIdentity (Join-Path $agentState 'identity.json') $true);certificate=(FileIdentity (Join-Path $agentState 'device.pem') $true);private_key=(FileIdentityMetadata (Join-Path $agentState 'device.key'))}
foreach($role in @('agent','helper')){$record=$value.service;if($role-ceq'helper'){$record=$value.helper_service}
$proof=$null;if($record.state-ceq'Running'){$held=[RmmPipeNative]::Open([int]$record.pid);try{$proof=Kernel $role $record $held;if(!(JsonEqual $record (Service $role))-or![RmmPipeNative]::Alive($held)){throw 'SCM/kernel generation changed during proof'}}finally{$held.Dispose()}}
$value[$role+'_kernel']=$proof
};return $value
}
# FILE_READ_ATTRIBUTES only: no key content read/hash/export. This also binds
# the private key's actual native FileID, not merely a timestamp/name.
function FileIdentityMetadata($path){
Check $path $false $true;$i=Get-Item -LiteralPath $path -Force;$h=[RmmPipeNative]::CreateFile($path,0x80,7,[IntPtr]::Zero,3,0,[IntPtr]::Zero)
try{if($h.IsInvalid){throw 'Private metadata-only handle'};$id=New-Object RmmPipeNative+FileId;if(![RmmPipeNative]::GetFileInformationByHandleEx($h,18,[ref]$id,24)){throw 'Private metadata-only native FileID'};return @{volume_serial=$id.Volume.ToString([Globalization.CultureInfo]::InvariantCulture);file_id=([BitConverter]::ToString($id.Id)).Replace('-','').ToLowerInvariant();bytes=$i.Length;creation_ticks=$i.CreationTimeUtc.Ticks.ToString();last_write_ticks=$i.LastWriteTimeUtc.Ticks.ToString();acl_sha256=(AclHash $path);private_key_read=$false}}finally{$h.Dispose()}
}
function SameOriginal($before,$after){
Preserved $before $after $false
if(!(JsonEqual $before.files $after.files)){throw 'Original four files/config/private metadata CAS'}
foreach($role in @('service','helper_service','agent_kernel','helper_kernel')){if(!(JsonEqual $before.$role $after.$role)){throw 'Fresh original kernel/SCM generation changed; new reviewed baseline required'}}
}
function PreserveImmutableFiles($before,$after,[bool]$frozen){
Preserved $before $after $frozen
foreach($label in @('config','ca','identity','certificate','private_key')){if(!(JsonEqual $before.files.$label $after.files.$label)){throw 'Original immutable PKI/config native FileID/metadata changed'}}
}
'''
# The original fixed-role SCM configuration checks are reused exactly. Unlike
# Service(), this readback projection makes no running-process proof claim and
# honestly exposes pending/raw State/PID without changing a service.
READBACK_SERVICE = "\nfunction ReadbackService($role){" + u.SCRIPT.split('function Service($role){', 1)[1].split(' $processId=', 1)[0] + r'''
$state=[string]$service.State;if(!$state-or$state.Length-gt64){throw 'Bounded raw SCM state'}
return [ordered]@{state=$state;pid=[uint32]$service.ProcessId;start_name=$service.StartName;start_mode=$service.StartMode;path=$service.PathName;service_type=$service.ServiceType;sid_type=$sidType;service_acl_sha256=(BytesHash ([Text.Encoding]::UTF8.GetBytes($text)));process_identity_verified=$false;read_only=$true}
}
'''
PHASES = r'''
CheckControl $boot $true
if($p.script_sha256-notmatch'^[a-f0-9]{64}$'-or$PSCommandPath-cne(Join-Path (Join-Path $boot $p.script_sha256) 'SystemPipeUpgrade.ps1')-or(Hash $PSCommandPath)-cne$p.script_sha256){throw 'Actual executing pipe-upgrade source'}
if($p.action-ceq'baseline'){$before=ActualState $false;if($before.service.state-cne'Running'-or$before.helper_service.state-notin@('Running','Stopped')-or$before.journal.pending_inventory_events-ne0){throw 'Settled original passive baseline'};$before|ConvertTo-Json -Depth 40 -Compress;exit 0}
function ReadCase{
CheckControl $folder $true;CheckControl (Join-Path $folder 'intent.json') $false;CheckControl $active $false
$i=Get-Content -LiteralPath (Join-Path $folder 'intent.json') -Raw|ConvertFrom-Json;$a=Get-Content -LiteralPath $active -Raw|ConvertFrom-Json
if((($i.payload.PSObject.Properties.Name|Sort-Object)-join',')-cne(($p.PSObject.Properties.Name|Sort-Object)-join',')){throw 'Original exact pipe payload shape'}
foreach($field in $p.PSObject.Properties.Name){if($field-cne'action'-and!(JsonEqual $i.payload.$field $p.$field)){throw 'Original exact pipe intent'}}
if($a.id-cne$p.id-or$a.script_sha256-cne$p.script_sha256-or$a.baseline_sha256-cne$p.baseline_sha256){throw 'Original active pipe intent'};return $i
}
if($p.action-ceq'readback'){
function MaybeHash($path){if(!(Test-Path -LiteralPath $path)){return $null};return Hash $path}
$i=ReadCase;$phases=[ordered]@{};foreach($label in @('agent-stop-attempt','agent-stopped','helper-stop-attempt','helper-stopped','helper-already-stopped','frozen','agent-backup','helper-backup','settings-backup','pin-backup','agent-replace-attempt','agent-replaced','helper-replace-attempt','helper-replaced','settings-replace-attempt','settings-replaced','pin-replace-attempt','pin-replaced','swapped','helper-start-attempt','helper-started','agent-start-attempt','agent-started','entered')){$phases[$label]=Test-Path -LiteralPath (Join-Path $folder ($label+'.json'))}
@{read_only=$true;id=$p.id;phase_receipts=$phases;service=(ReadbackService 'agent');helper_service=(ReadbackService 'helper');hashes=@{agent=(MaybeHash $agentBinary);helper=(MaybeHash $helperBinary);settings=(MaybeHash $settings);pin=(MaybeHash $pin)}}|ConvertTo-Json -Depth 40 -Compress;exit 0
}
if($p.action-ceq'finish'){
$i=ReadCase;$after=ActualState $true;PreserveImmutableFiles $i.before $after $false
CheckControl (Join-Path $folder 'frozen.json') $false;$frozen=Get-Content -LiteralPath (Join-Path $folder 'frozen.json') -Raw|ConvertFrom-Json;PreserveImmutableFiles $frozen $after $false
foreach($role in @('agent','helper')){CheckControl (Join-Path $folder ($role+'-started.json')) $false;$started=Get-Content -LiteralPath (Join-Path $folder ($role+'-started.json')) -Raw|ConvertFrom-Json;$live=$after.service;if($role-ceq'helper'){$live=$after.helper_service};if($live.state-cne'Running'-or!(JsonEqual $started.service $live)-or!(JsonEqual $started.kernel $after.($role+'_kernel'))){throw 'Same single-start actual component instance required'}}
@{read_only=$true;completed=$true;id=$p.id;native=$after;original=$i.before;frozen=$frozen}|ConvertTo-Json -Depth 40 -Compress;exit 0
}
if((Test-Path -LiteralPath $folder)-or(Test-Path -LiteralPath $active)){throw 'Existing pipe intent: readback only'}
$baselineBytes=[Convert]::FromBase64String($p.baseline_base64);if((BytesHash $baselineBytes)-cne$p.baseline_sha256){throw 'Exact separately reviewed baseline bytes'};$baseline=[Text.Encoding]::UTF8.GetString($baselineBytes)|ConvertFrom-Json
$before=ActualState $false;SameOriginal $baseline $before
if($before.journal.pending_inventory_events-ne0-or$before.service.state-cne'Running'){throw 'Original ACK and running agent required'}
$heldAgent=[RmmPipeNative]::Open([int]$before.service.pid);$heldHelper=$null
try{
$null=Kernel 'agent' $before.service $heldAgent
if($before.helper_service.state-ceq'Running'){$heldHelper=[RmmPipeNative]::Open([int]$before.helper_service.pid);$null=Kernel 'helper' $before.helper_service $heldHelper}
New-Item -ItemType Directory -Path $folder|Out-Null;CheckControl $folder $true
WriteNew (Join-Path $folder 'intent.json') @{payload=$p;before=$before};WriteNew $active @{id=$p.id;script_sha256=$p.script_sha256;baseline_sha256=$p.baseline_sha256;no_jobs=$true}
function StopHeld($role,$record,$held){
$live=Service $role;if(!(JsonEqual $record $live)){throw 'SCM identity changed before own stop'};$null=Kernel $role $record $held
$name=$agentName;if($role-ceq'helper'){$name=$helperName};WriteNew (Join-Path $folder ($role+'-stop-attempt.json')) @{stop_once=$true;service=$record}
Stop-Service -Name $name;(Get-Service -Name $name).WaitForStatus([ServiceProcess.ServiceControllerStatus]::Stopped,[TimeSpan]::FromSeconds(20));if(![RmmPipeNative]::Exited($held,20000)){throw 'Pinned original process not exited'}
WriteNew (Join-Path $folder ($role+'-stopped.json')) @{original=$record;kernel_process_exited=$true}
}
StopHeld 'agent' $before.service $heldAgent
if($null-ne$heldHelper){StopHeld 'helper' $before.helper_service $heldHelper}else{if((Service 'helper').state-cne'Stopped'){throw 'Manual helper changed since reviewed stopped baseline'};WriteNew (Join-Path $folder 'helper-already-stopped.json') @{observed_stopped=$true;stop_called=$false;start_called=$false}}
$frozen=ActualState $false;Preserved $before $frozen $false;if($frozen.service.state-cne'Stopped'-or$frozen.helper_service.state-cne'Stopped'-or$frozen.journal.pending_inventory_events-ne0-or!(JsonEqual $before.files $frozen.files)){throw 'Stopped original complete pair/file identities'};WriteNew (Join-Path $folder 'frozen.json') $frozen
function Backup($label,$path,$expected){
$identity=FileIdentity $path;if(!(JsonEqual $identity $before.files.$label)-or$identity.sha256-cne$expected){throw 'Original backup file identity/hash/ACL'}
$backup=Join-Path $folder ($label+'-original');[IO.File]::Copy($path,$backup,$false);PrivateBackupAcl $backup;FlushCopy $backup
if((Hash $backup)-cne$expected){throw 'Exact private backup bytes'};WriteNew (Join-Path $folder ($label+'-backup.json')) @{original=$identity;backup=(FileIdentity $backup);original_sddl=(Get-Acl -LiteralPath $path).Sddl}
}
Backup 'agent' $agentBinary $p.old_agent;Backup 'helper' $helperBinary $p.old_helper;Backup 'settings' $settings $p.old_policy;Backup 'pin' $pin $p.old_pin
$settingBytes=[Convert]::FromBase64String($p.settings_base64);$pinBytes=[Convert]::FromBase64String($p.pin_base64);if((BytesHash $settingBytes)-cne$p.new_policy-or(BytesHash $pinBytes)-cne$p.new_pin){throw 'Deterministic closed reciprocal settings'}
WriteBytes (Join-Path $folder 'new-helper.json') $settingBytes;WriteBytes (Join-Path $folder 'new-agent-pin.json') $pinBytes
function Swap($label,$destination,$source,$oldHash,$newHash){
if((Service 'agent').state-cne'Stopped'-or(Service 'helper').state-cne'Stopped'){throw 'Both stopped for all four file replacements'}
foreach($other in @('agent','helper','settings','pin')){CheckControl (Join-Path $folder ($other+'-backup.json')) $false;if(!(Test-Path -LiteralPath (Join-Path $folder ($other+'-original')))){throw 'All four private backups precede first replacement'}}
$old=FileIdentity $destination;$sddl=(Get-Acl -LiteralPath $destination).Sddl;$nativeBackup=Join-Path $folder ($label+'-native-original');$candidate=Join-Path $folder ($label+'-candidate')
if(!(JsonEqual $old $before.files.$label)-or$old.sha256-cne$oldHash-or(Hash $source)-cne$newHash-or(Hash (Join-Path $folder ($label+'-original')))-cne$oldHash-or(Test-Path -LiteralPath $nativeBackup)){throw 'Fresh destination/source/backup CAS'}
[IO.File]::Copy($source,$candidate,$false);FlushCopy $candidate;$candidateId=FileIdentity $candidate;if($candidateId.sha256-cne$newHash){throw 'Complete staged replacement'}
WriteNew (Join-Path $folder ($label+'-replace-attempt.json')) @{old=$old;candidate=$candidateId;native_backup=$nativeBackup;source_sha256=$p.script_sha256}
if(!(JsonEqual (FileIdentity $destination) $old)-or!(JsonEqual (FileIdentity $candidate) $candidateId)-or(Test-Path -LiteralPath $nativeBackup)){throw 'Immediate file-ID/hash/ACL CAS'}
[IO.File]::Replace($candidate,$destination,$nativeBackup)
PrivateBackupAcl $nativeBackup;$acl=New-Object Security.AccessControl.FileSecurity;$acl.SetSecurityDescriptorSddlForm($sddl);Set-Acl -LiteralPath $destination -AclObject $acl;FlushCopy $destination
if((Hash $destination)-cne$newHash-or(Hash $nativeBackup)-cne$oldHash-or(AclHash $destination)-cne$old.acl_sha256){throw 'Exact actual replacement/explicit native backup/ACL'}
WriteNew (Join-Path $folder ($label+'-replaced.json')) @{original=$old;current=(FileIdentity $destination);native_backup=(FileIdentity $nativeBackup);original_backup=(FileIdentity (Join-Path $folder ($label+'-original')))}
}
Swap 'agent' $agentBinary (Join-Path (Join-Path $boot $p.new_agent) 'rmm-agent-windows.exe') $p.old_agent $p.new_agent
Swap 'helper' $helperBinary (Join-Path (Join-Path $boot $p.new_helper) 'rmm-helper-windows.exe') $p.old_helper $p.new_helper
Swap 'settings' $settings (Join-Path $folder 'new-helper.json') $p.old_policy $p.new_policy
Swap 'pin' $pin (Join-Path $folder 'new-agent-pin.json') $p.old_pin $p.new_pin
$swapped=ActualState $true;PreserveImmutableFiles $frozen $swapped $true;if($swapped.service.state-cne'Stopped'-or$swapped.helper_service.state-cne'Stopped'){throw 'All four new files while both stopped'};WriteNew (Join-Path $folder 'swapped.json') $swapped
function StartOnce($role){
$checked=ActualState $true;PreserveImmutableFiles $frozen $checked $false;if((Service $role).state-cne'Stopped'){throw 'First exact selected start only'};$name=$helperName;if($role-ceq'agent'){$name=$agentName}
WriteNew (Join-Path $folder ($role+'-start-attempt.json')) @{start_once=$true;all_four_files_verified=$true}
Start-Service -Name $name;(Get-Service -Name $name).WaitForStatus([ServiceProcess.ServiceControllerStatus]::Running,[TimeSpan]::FromSeconds(20))
$s=Service $role;$held=[RmmPipeNative]::Open([int]$s.pid);try{$kernel=Kernel $role $s $held;WriteNew (Join-Path $folder ($role+'-started.json')) @{service=$s;kernel=$kernel}}finally{$held.Dispose()}
}
StartOnce 'helper';StartOnce 'agent';$after=ActualState $true;PreserveImmutableFiles $before $after $false;WriteNew (Join-Path $folder 'entered.json') $after
@{entered=$true;id=$p.id;no_jobs=$true;no_reboot=$true;no_clock_change=$true}|ConvertTo-Json -Compress
}finally{$heldAgent.Dispose();if($null-ne$heldHelper){$heldHelper.Dispose()}}
'''
SCRIPT = PREFIX + '\n' + NATIVE + READBACK_SERVICE + '\n' + PHASES
PREPARE = u.transport.PREPARE_SCRIPT.replace('TransportAcceptance.ps1', 'SystemPipeUpgrade.ps1')
LAUNCH = u.transport.LAUNCH_SCRIPT.replace('TransportAcceptance.ps1', 'SystemPipeUpgrade.ps1').replace('RmmTransportPayload', 'RmmPipeUpgradePayload')
class Access:
"""Explicit read-only access roots; never redirects source/manifest globals."""
def __init__(self, root):
self.root = Path(root).absolute()
require(self.root == self.root.resolve() and self.root != ROOT.resolve(), 'separate real access root, no symlink/copy')
self.evidence = self.root / 'devstate/windows-client'
def powershell(self, source, payload, timeout=180):
access = cb.contract.protected_json(self.root / 'credentials/windows-dev-access.json')
wrapped = "try {\n" + source + "\n} catch {[pscustomobject]@{bootstrap_error=$true;error_id=$_.FullyQualifiedErrorId;line=$_.InvocationInfo.ScriptLineNumber}|ConvertTo-Json -Compress;exit 1}"
command = 'powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -EncodedCommand ' + base64.b64encode(wrapped.encode('utf-16le')).decode()
result = subprocess.run(access['ssh_prefix'] + [command], input=canonical(payload) + b'\n', capture_output=True, timeout=timeout)
if result.returncode:
# Fixed error identifiers/line only; never raw stderr/payload/commands.
safe = dict(returncode=result.returncode, stdout_bytes=len(result.stdout), stderr_bytes=len(result.stderr))
try:
error = json.loads(result.stdout.decode('utf-8-sig'), object_pairs_hook=cb.contract.strict_object)
if error.get('bootstrap_error') is True:
safe.update(error_id=error.get('error_id'), line=error.get('line'))
except (ValueError, AttributeError):
pass
save(STATE / ('remote-error-' + str(uuid.uuid4()) + '.json'), safe)
raise RuntimeError('fixed pipe upgrade bootstrap incomplete; readback only')
return json.loads(result.stdout.decode('utf-8-sig'), object_pairs_hook=cb.contract.strict_object)
def stage(self, path, name):
require(name in ('rmm-agent-windows.exe', 'rmm-helper-windows.exe', 'RuntimeStateProbe.exe', 'SystemStateProbe.exe', 'SystemPipeUpgrade.ps1'), 'fixed stage names')
path = Path(path)
digest = sha(path)
prepare = u.transport.PREPARE_SCRIPT.replace('TransportAcceptance.ps1', name)
observed = self.powershell(prepare, dict(sha256=digest))
if not observed['already_uploaded']:
access = cb.contract.protected_json(self.root / 'credentials/windows-dev-access.json')
prefix = access['ssh_prefix']
args = ['sftp'] + [p for p in prefix[1:-1] if p != '-T'] + ['-b', '-', prefix[-1]]
target = '/C:/ProgramData/RustDiscoveryBootstrap/' + digest + '/' + name
result = subprocess.run(args, input=('put ' + json.dumps(str(path.resolve())) + ' ' + json.dumps(target) + '\n').encode(), capture_output=True, timeout=60)
require(result.returncode == 0, 'immutable exact bootstrap transfer; no retry')
observed = self.powershell(prepare, dict(sha256=digest))
require(observed['already_uploaded'] is True and observed['sha256'] == digest, 'same exact existing-or-new stage')
def server(self, function, payload):
cloud = u.transport.cloud
require(function in (cloud.server, u.auto.server_state, u.transport.server_transport.server_evidence), 'fixed read-only server witnesses')
# The inherited parser is strict data parsing, not source/eval. Its ROOT
# only checks the source .gitignore; its supplied path remains Main.
cfg = cloud.bootstrap.access.load_config(self.root / 'credentials/server.conf')
ssh = ['ssh', '-F', '/dev/null', '-T', '-p', cfg.get('port', '22'), '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes', '-o', 'IdentitiesOnly=yes', '-o', 'ForwardAgent=no', '-o', 'ConnectTimeout=10', '-i', str(Path(cfg['ssh_key_path']).expanduser()), cfg['username'] + '@' + cfg['address'], 'python3 -']
code = ('import os,json,subprocess,base64,hashlib,ssl,http.client,socket,uuid,pwd\nfrom pathlib import Path\n' + inspect.getsource(cloud.bootstrap.require) + '\n' + inspect.getsource(function) + '\ntry:\n print(json.dumps(' + function.__name__ + '(' + repr(payload) + ')))\nexcept Exception as error:\n print(json.dumps(dict(error="READONLY_WITNESS_INCOMPLETE",kind=type(error).__name__)))\n')
result = subprocess.run(ssh, input=code.encode(), capture_output=True, timeout=60)
require(result.returncode == 0 and len(result.stdout) <= 1024 * 1024, 'bounded readonly server witness')
value = json.loads(result.stdout, object_pairs_hook=cb.contract.strict_object)
require('error' not in value, 'readonly server witness incomplete')
return value
def server_state(self):
cloud = u.transport.cloud
linux = cb.contract.protected_json(self.root / 'devstate/cloud-mvp-final-closeout.json')
require(linux['verified'] is True, 'accepted Linux target only')
counts = {name: self.server(cloud.server, dict(kind='gate', tenant_id=tenant, agent_id=agent)) for name, tenant, agent in (
('windows', cloud.TENANT, u.transport.AGENT), ('linux', linux['target']['tenant_id'], linux['target']['agent_id']))}
flags = self.server(u.auto.server_state, {})
require(u.auto.flags_disabled(flags) and counts['windows'] == dict(jobs=0, outbox=0, permits=0, unresolved=0), 'closed hooks and Windows zero-job gate')
return dict(counts=counts, flags=flags)
def observe(self, ident):
return self.server(u.transport.server_transport.server_evidence, dict(tenant_id=u.transport.cloud.TENANT, agent_id=u.transport.AGENT, fault_id=ident))
def device_and_denials(self):
bridge = self
class ReadBackend(u.transport.cloud.Backend):
def request(self, body):
if body['method'] == 'tools/call':
require(body['params']['name'] == 'inventory.get_device', 'only stored inventory reads')
else:
require(body['method'] in ('initialize', 'notifications/initialized'), 'only MCP read session')
return bridge.server(u.transport.cloud.server, dict(kind='http', path='/mcp', method='POST', headers=self.headers, body=body, principal=self.principal))
device = ReadBackend().call('inventory.get_device', dict(tenant_id=u.transport.cloud.TENANT, asset_id=u.transport.ASSET))
require(device['agent_id'] == u.transport.AGENT and device['source_id'] == 'windows.base' and set(device['capabilities']) == {'windows.base/1', 'heartbeat/1'} and device['presence'] == 'online', 'honest unchanged passive inventory')
denied = []
backend = ReadBackend('b')
for tenant in (u.transport.cloud.TENANT, '22222222-2222-4222-8222-222222222222'):
backend.sequence += 1
response = backend.request(dict(jsonrpc='2.0', id=backend.sequence, method='tools/call', params=dict(name='inventory.get_device', arguments=dict(tenant_id=tenant, asset_id=u.transport.ASSET))))
data = response.get('data', {})
require('error' in data or data.get('result', {}).get('isError'), 'foreign tenant denied')
denied.append(dict(tenant_id=tenant, denied=True))
return device, denied
def dependencies():
modules = [cb, cb.contract, u, u.transport, u.auto, u.transport.cloud, u.transport.cloud.bootstrap, u.transport.cloud.bootstrap.access, u.transport.server_transport, u.qualification, u.qualification.feature, u.qualification.previous, u.original_helper]
return {str(Path(m.__file__).resolve().relative_to(ROOT)): sha(m.__file__) for m in modules}
def guards():
require(sha(u.__file__) == ORIGINAL_RUNNER, 'immutable original read-only witness source')
require('function PinProcess' not in PREFIX and 'function Swap' not in PREFIX and 'function StopPinned' not in PREFIX and 'function StartOnce' not in PREFIX, 'historical mutations excluded')
require('[IO.File]::Replace($candidate,$destination,$nativeBackup)' in SCRIPT and '[IO.File]::Replace($candidate,$destination,$null)' not in SCRIPT, 'explicit additional absent native backup')
ordered = [SCRIPT.index(token) for token in (" StopHeld 'agent'", " Backup 'agent'", "Backup 'pin'", " Swap 'agent'", "Swap 'pin'", '$swapped=ActualState $true', " StartOnce 'helper'", "StartOnce 'agent'")]
require(ordered == sorted(ordered), 'all backups before any replacement; all replacements before helper/agent starts')
require(SCRIPT.count('Start-Service -Name $name') == SCRIPT.count('Stop-Service -Name $name') == 1, 'single fixed-role control primitives')
require(all(word not in SCRIPT + LAUNCH for word in ('Restart-Service', 'Restart-Computer', 'Stop-Computer', 'Set-Service', 'New-Service', 'Remove-Item', 'Invoke-Expression', 'Bypass')), 'no install/reconfigure/cleanup/reboot/automatic rollback')
# Fresh isolated interpreter: the Pipe pack deliberately imports its transport
# modules from Main. Reusing its module in this interpreter would accidentally
# reuse our cached worktree client_bootstrap and corrupt the source/access split.
# This code calls verification/read-only proof parsing ONLY, never native().
VERIFY_PACK = r'''
import hashlib,importlib.util,json,re,sys,uuid
from pathlib import Path
path=Path(sys.argv[1]);spec=importlib.util.spec_from_file_location('fixed_pipe_pack',path)
pack=importlib.util.module_from_spec(spec);spec.loader.exec_module(pack)
manifest_path=Path(sys.argv[2]).resolve();proof_path=Path(sys.argv[3]).resolve()
manifest=pack.verified(manifest_path) # full current code/access hashes + Linux80/Windows58 Core proofs
proof=pack.cb.contract.protected_json(pack.private_file(proof_path));require=pack.require
case=proof['case_id'];require(str(uuid.UUID(case))==case and proof_path==pack.NATIVE/case/'passed.json','exact native pipe case namespace')
require(proof['verified'] is True and proof['manifest_path']==str(manifest_path) and proof['manifest_sha256']==pack.sha(manifest_path) and proof['no_jobs'] is True and proof['clock_adapter_qualified'] is False and proof['local_service_proof'] is False and proof['native_pipe_proof'] is False,'actual same pipe manifest units, no runtime capability')
intent=pack.cb.contract.protected_json(proof_path.parent/'intent.json')
require(intent['id']==case and intent['manifest_path']==str(manifest_path) and intent['manifest_sha256']==pack.sha(manifest_path) and intent['runner_sha256']==pack.sha(path) and intent['script_sha256']==hashlib.sha256(pack.SCRIPT.encode()).hexdigest(),'exact executed native unit source/manifest')
require(pack.cb.contract.protected_json(proof_path.parent/'started-local.json')['start_once'] is True,'original create-once native execution intent')
before=pack.cb.contract.protected_json(proof_path.parent/'server-before.json')
require(pack.auto.flags_disabled(before['flags']) and before['counts']['windows']==dict(jobs=0,outbox=0,permits=0,unresolved=0),'original closed native zero-job scope')
actual=proof['native']
require(actual['completed'] is True and actual['manifest_sha256']==pack.sha(manifest_path) and set(actual['reports'])==set(pack.COUNTS) and actual['both_lists_verified_before_any_test'] is True and actual['bootstrap_administrator_units'] is True and actual['local_service_proof'] is False and actual['native_pipe_proof'] is False and actual['rmm_jobs'] is False and actual['product_state_writes'] is False,'actual completed narrow units only')
for kind,count in pack.COUNTS.items():
report=actual['reports'][kind];listed=report['listed'];run=report['result']
names=re.findall(r'^(.+): test\r?$',listed['stdout'],re.M)
require(report['sha256']==manifest['artifacts'][kind]['sha256'] and names==report['names']==pack.TESTS[kind] and len(set(names))==count and type(listed['exit_code']) is int and listed['exit_code']==0 and type(run['exit_code']) is int and run['exit_code']==0 and listed['timed_out'] is False and run['timed_out'] is False and re.search(r'test result: ok\. '+str(count)+r' passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;',run['stdout']),'all exact 23/7 native cases, no ignored/filtered/timeout')
print(json.dumps(manifest))
'''
def qualified(manifest_path, proof_path):
verifier = ROOT / 'deploy/windows/system_pipe_acceptance.py'
require(sha(verifier) == PIPE_VERIFIER_SHA, 'exact independently reviewed Pipe-v2 pack verifier')
result = subprocess.run([sys.executable, '-I', '-c', VERIFY_PACK, str(verifier), str(manifest_path), str(proof_path)], capture_output=True, timeout=60)
require(result.returncode == 0 and len(result.stdout) <= 1024 * 1024, 'fresh isolated read-only Pipe verifier/native proof; details withheld')
value = json.loads(result.stdout, object_pairs_hook=cb.contract.strict_object)
require(value['type'] == 'rmm.windows.pipe-v2-build' and value['transport_version'] == 2 and value['native_counts_expected'] == dict(lib=23, bin=7), 'Pipe-v2 manifest, never historical delegation relabeling')
return value
def prior(access):
runtime_path = access.evidence / 'current-runtime.json'
components_path = access.evidence / 'current-components.json'
runtime = cb.contract.protected_json(runtime_path)
components = cb.contract.protected_json(components_path)
result_path = access.evidence / ('system-delegation-upgrade/' + OLD_CASE + '/result.json')
require(sha(result_path) == OLD_RESULT_SHA, 'independently accepted original joint result')
result = cb.contract.protected_json(result_path)
require(result['verified'] is True and result['completed'] is True and result['no_jobs'] is True and result['windows_jobs_enabled'] is False and result['clock_adapter_qualified'] is False, 'accepted closed passive generation')
evidence = dict(path=str(result_path.resolve()), sha256=OLD_RESULT_SHA)
require(runtime['case_id'] == components['case_id'] == OLD_CASE and runtime['evidence'] == components['evidence'] == evidence and runtime['binary_sha256'] == components['agent_sha256'] == OLD_AGENT and components['helper_sha256'] == OLD_HELPER and components['policy_sha256'] == OLD_POLICY and components['pin_sha256'] == OLD_PIN and runtime['transport'] == 'auto' and runtime['windows_jobs_enabled'] is False and runtime['clock_adapter_qualified'] is False and runtime['system_helper_client_feature'] is True and components['windows_jobs_enabled'] is False and components['clock_adapter_qualified'] is False and components['helper_effects_enabled'] is False, 'current accepted four-file indices, no adoption of readback')
recovery = access.evidence / 'system-delegation-recovery/595dd1da-0d7f-4364-9040-a75e16c6da83/acceptance.json'
require(sha(recovery) == '5ad5925c8928f49cd0f9d48a64f81018281b5b6e3704c799bae64a42898322bb' and cb.contract.protected_json(recovery)['verified'] is True, 'accepted original explicit-backup recovery preserved')
original = cb.contract.protected_json(result_path.parent / 'intent.json')
settings = base64.b64decode(original['payload']['settings_base64'], validate=True)
require(raw_sha(settings) == OLD_POLICY and raw_sha(base64.b64decode(original['payload']['pin_base64'], validate=True)) == OLD_PIN, 'exact original reciprocal public settings')
return dict(runtime=runtime, components=components, runtime_sha256=sha(runtime_path), components_sha256=sha(components_path), result_sha256=OLD_RESULT_SHA), result, json.loads(settings, object_pairs_hook=cb.contract.strict_object)
def passive_settings(old, agent, helper):
require(set(old) == {'schema_version', 'binding', 'agent', 'helper', 'allowed_services', 'max_runtime_seconds', 'enable_effects', 'allow_reboot'} and type(old['schema_version']) is int and old['schema_version'] == 1 and old['allowed_services'] == [] and old['enable_effects'] is False and old['allow_reboot'] is False and type(old['max_runtime_seconds']) is int and old['max_runtime_seconds'] == 30 and old['agent']['binary_sha256'] == OLD_AGENT and old['helper']['binary_sha256'] == OLD_HELPER, 'exact original closed public settings')
require(all(isinstance(h, str) and len(h) == 64 and all(c in '0123456789abcdef' for c in h) for h in (agent, helper)), 'qualified new image hashes')
new = json.loads(canonical(old)); new['agent']['binary_sha256'] = agent; new['helper']['binary_sha256'] = helper
settings = canonical(new); policy = raw_sha(settings)
pin = canonical(dict(schema_version=1, binding=new['binding'], policy_sha256=policy, agent=new['agent'], helper=new['helper']))
return settings, pin, policy
def leaves(access):
path = access.evidence / 'system-intent-bootstrap/f322a4d2-c537-4842-bf04-658ad8f814b0/acceptance.json'
require(sha(path) == u.INTENT_PREPARATION_SHA, 'accepted original empty-leaf preparation')
proof = cb.contract.protected_json(path)
require(proof['verified'] is True and proof['sqlite_initialized'] is False, 'not a store/SQLite qualification')
created_path = path.parent / 'created.json'
require(sha(created_path) == proof['native_created_sha256'], 'original native empty-leaf receipt')
created = cb.contract.protected_json(created_path)
items = {v['name']: v for v in created['leaves']}
require(set(items) == {'system-intents.sqlite', 'system-intents.sqlite-journal'} and all(v['length'] == 0 for v in items.values()), 'exact two original zero-byte leaves')
return {label: dict(name=name, acl_sha256=raw_sha(items[name]['sddl'].encode())) for label, name in [('database', 'system-intents.sqlite'), ('journal', 'system-intents.sqlite-journal')]}
def remote(access, intent, action):
require(intent['script_sha256'] == raw_sha(SCRIPT.encode()), 'immutable new pipe bootstrap source')
return access.powershell(LAUNCH, dict(sha256=intent['script_sha256'], payload=dict(intent['payload'], action=action)))
def load(ident, access):
require(str(uuid.UUID(ident)) == ident, 'canonical original case UUID')
folder = STATE / ident
intent = cb.contract.protected_json(folder / 'intent.json')
require(intent['id'] == ident and intent['runner_sha256'] == sha(__file__) and intent['script_sha256'] == raw_sha(SCRIPT.encode()) and intent['dependencies'] == dependencies() and intent['access_root'] == str(access.root), 'same source/dependencies/access root case')
manifest = qualified(Path(intent['manifest_path']), Path(intent['qualification_path']))
require(sha(intent['manifest_path']) == intent['payload']['manifest_sha256'] and sha(intent['qualification_path']) == intent['payload']['qualification_sha256'] and manifest['artifacts']['agent']['sha256'] == intent['payload']['new_agent'] and manifest['artifacts']['helper']['sha256'] == intent['payload']['new_helper'], 'same actually native-qualified new pair')
return folder, intent
def prepare(access, manifest_path, proof_path):
guards()
manifest = qualified(manifest_path, proof_path)
indices, accepted, old = prior(access)
settings, pin, policy = passive_settings(old, manifest['artifacts']['agent']['sha256'], manifest['artifacts']['helper']['sha256'])
require(manifest['artifacts']['agent']['sha256'] != OLD_AGENT and manifest['artifacts']['helper']['sha256'] != OLD_HELPER, 'new coordinated pipe pair, no old source round')
ident = str(uuid.uuid4()); folder = STATE / ident; folder.mkdir(mode=0o700, parents=True)
script_sha = raw_sha(SCRIPT.encode())
payload = dict(id=ident, old_agent=OLD_AGENT, old_helper=OLD_HELPER, old_policy=OLD_POLICY, old_pin=OLD_PIN, new_agent=manifest['artifacts']['agent']['sha256'], new_helper=manifest['artifacts']['helper']['sha256'], new_policy=policy, new_pin=raw_sha(pin), config_sha256=accepted['native']['config_sha256'], probe_sha256=manifest['artifacts']['probe']['sha256'], system_probe_sha256=manifest['artifacts']['system_probe']['sha256'], manifest_sha256=sha(manifest_path), qualification_sha256=sha(proof_path), script_sha256=script_sha, settings_base64=base64.b64encode(settings).decode(), pin_base64=base64.b64encode(pin).decode(), intent_leaves=leaves(access))
draft = dict(id=ident, started_at=cb.contract.now().isoformat(), access_root=str(access.root), runner_sha256=sha(__file__), script_sha256=script_sha, manifest_path=str(manifest_path.resolve()), qualification_path=str(proof_path.resolve()), dependencies=dependencies(), original_indices=indices, payload=payload, no_jobs=True)
save(folder / 'prepare-intent.json', draft)
for name, data in [('runner.py', Path(__file__).read_bytes()), ('SystemPipeUpgrade.ps1', SCRIPT.encode())]:
write_bytes(folder / name, data)
for kind in ('agent', 'helper', 'probe', 'system_probe'):
item = manifest['artifacts'][kind]
require(sha(item['path']) == item['sha256'], 'qualified staged artifact bytes')
access.stage(item['path'], item['name'])
access.stage(folder / 'SystemPipeUpgrade.ps1', 'SystemPipeUpgrade.ps1')
before = remote(access, draft, 'baseline')
expected = accepted['native']
for field in ('agent_id', 'asset_id', 'binary_sha256', 'helper_sha256', 'policy_sha256', 'pin_sha256', 'config_sha256', 'config_acl_sha256', 'binary_acl_sha256', 'helper_binary_acl_sha256', 'settings_acl_sha256', 'pin_acl_sha256', 'public_hashes', 'identity_acls', 'private_key_metadata'):
require(before[field] == expected[field], 'accepted original identity/PKI/config/four-file ACLs; no private key read')
for field in ('database_file_id', 'database_creation', 'identity_sha256', 'schema'):
require(before['journal'][field] == expected['journal'][field], 'same actual original telemetry database identity')
for field in ('helper_ledger', 'executor_lock', 'intent_store'):
require(before['helper_witness'][field] == expected['helper_witness'][field], 'same actual helper DB/lock/FileIDs/zero-byte leaves')
for role in ('service', 'helper_service'):
for field in ('start_name', 'start_mode', 'path', 'service_type', 'sid_type', 'service_acl_sha256'):
require(before[role][field] == expected[role][field], 'original exact SCM account/config/ACL')
baseline = canonical(before)
write_bytes(folder / 'baseline.json', baseline)
payload.update(baseline_base64=base64.b64encode(baseline).decode(), baseline_sha256=raw_sha(baseline))
draft['payload'] = payload
save(folder / 'intent.json', draft)
save(folder / 'server-before.json', access.server_state())
central = access.observe(ident)['device']; require(central and central['agent_id'] == u.transport.AGENT, 'original stored authenticated device')
save(folder / 'central-before.json', central)
print(json.dumps(dict(id=ident, prepared=True, no_component_mutation=True, baseline_sha256=raw_sha(baseline), needs_explicit_review_before_enter=True)))
def enter(access, ident, baseline_sha):
folder, intent = load(ident, access)
require(sha(folder / 'baseline.json') == intent['payload']['baseline_sha256'] == baseline_sha, 'explicit reviewed exact baseline required')
indices, _, _ = prior(access)
require(indices == intent['original_indices'] and access.server_state() == cb.contract.protected_json(folder / 'server-before.json'), 'both original current indices and server gates unchanged')
save(folder / 'enter-attempt.json', dict(enter_once=True, baseline_sha256=baseline_sha, lost_reply_readback_only=True))
result = remote(access, intent, 'enter')
require(result.get('entered') is True and result['id'] == ident, 'actual same single transition reply')
save(folder / 'entered.json', result)
print(json.dumps(dict(id=ident, entered=True, continuation='finish/readback only; never repeat enter')))
def finish(access, ident, read_only=False):
folder, intent = load(ident, access)
action = 'readback' if read_only else 'finish'
observed = remote(access, intent, action)
save(folder / ('readback-' + str(uuid.uuid4()) + '.json'), observed)
require(observed['read_only'] is True and observed['id'] == ident, 'only existing case readback')
if read_only:
print(json.dumps(dict(id=ident, read_only=True, phase_receipts=observed['phase_receipts']))); return
require(observed['completed'] is True, 'actual complete pair preservation')
result_path = folder / 'result.json'
if result_path.exists():
previous = cb.contract.protected_json(result_path)
require(previous['verified'] is True and all(previous['native'][role] == observed['native'][role] for role in ('service', 'helper_service')), 'same completed current instances; no republication or mutation')
print(json.dumps(dict(id=ident, verified=True, retained_original_result=True, main_indices_published=False))); return
# Two genuinely new server heartbeats after both single starts, not cached
# contacts from baseline, and no new network-agent jobs/capabilities.
after = cb.contract.timestamp(intent['started_at']); baseline = cb.contract.protected_json(folder / 'central-before.json')
watermark = access.observe(ident)['device']
require(watermark and watermark['agent_id'] == u.transport.AGENT and watermark['last_contact_at'], 'post-finish server heartbeat watermark')
deadline = time.monotonic() + 150; first = None
while True:
evidence = access.observe(ident); device = evidence['device']
if device and device['transport'] == 'wss' and device['last_contact_at'] and cb.contract.timestamp(device['last_contact_at']) > cb.contract.timestamp(watermark['last_contact_at']):
require(all(device[k] == baseline[k] for k in ('agent_id', 'asset_id', 'enrollment_generation', 'assignment_version', 'certificate_sha256')), 'same original mTLS identity')
if first is None: first = evidence
elif device['last_contact_at'] != first['device']['last_contact_at']: break
require(time.monotonic() < deadline, 'two native post-upgrade heartbeats missing')
time.sleep(2)
final = remote(access, intent, 'finish'); native = final['native']
original = json.loads(base64.b64decode(intent['payload']['baseline_base64']), object_pairs_hook=cb.contract.strict_object)
require(native['journal']['pending_inventory_events'] == 0 and native['journal']['sequence'] > original['journal']['sequence'], 'fresh telemetry sequence and concrete inventory ACK')
device, denied = access.device_and_denials()
require(cb.contract.timestamp(device['observed_at']) >= after, 'fresh original stored inventory')
require(access.server_state() == cb.contract.protected_json(folder / 'server-before.json'), 'both target counts/policies/hooks unchanged')
indices, _, _ = prior(access)
require(indices == intent['original_indices'], 'Main current indices still original; Root owns later CAS publication')
pipe = u.actual_pipe_proof(native, intent)
result = dict(verified=True, completed=True, id=ident, original=final['original'], frozen=final['frozen'], native=native, online=dict(watermark=watermark, first=first, second=evidence), stored_inventory=device, foreign_denied=denied, native_pipe_peer_test=pipe, pipe_framing_version=2, no_jobs=True, windows_jobs_enabled=False, clock_adapter_qualified=False, system_helper_client_feature=True, helper_effects_enabled=False, no_reboot=True, no_clock_change=True, private_key_read=False, original_indices=intent['original_indices'], main_indices_published=False, manifest_path=intent['manifest_path'], manifest_sha256=intent['payload']['manifest_sha256'], qualification_sha256=intent['payload']['qualification_sha256'], runner_sha256=intent['runner_sha256'], script_sha256=intent['script_sha256'])
save(result_path, result)
print(json.dumps(dict(id=ident, verified=True, passive_preservation=True, native_pipe_peer_test=pipe, main_indices_published=False)))
def main():
os.umask(0o077)
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('phase', choices=('prepare', 'enter', 'finish', 'readback', 'guards'))
parser.add_argument('--access-root', type=Path); parser.add_argument('--manifest', type=Path); parser.add_argument('--qualification', type=Path); parser.add_argument('--id'); parser.add_argument('--baseline-sha256')
args = parser.parse_args(); guards()
if args.phase == 'guards':
require(not any((args.access_root, args.manifest, args.qualification, args.id, args.baseline_sha256)), 'local source guards only'); print('PASS: local source guards; no VM action'); return
require(args.access_root, 'explicit separate read-only Main access root')
access = Access(args.access_root)
if args.phase == 'prepare':
require(args.manifest and args.qualification and not (args.id or args.baseline_sha256), 'qualified new pair and read-only baseline preparation')
prepare(access, args.manifest, args.qualification)
elif args.phase == 'enter':
require(args.id and args.baseline_sha256 and not (args.manifest or args.qualification), 'same prepared case and reviewed baseline hash')
enter(access, args.id, args.baseline_sha256)
else:
require(args.id and not (args.manifest or args.qualification or args.baseline_sha256), 'same original case readback/finish')
finish(access, args.id, args.phase == 'readback')
if __name__ == '__main__':
try: main()
except Exception as error:
print('WINDOWS_PIPE_UPGRADE_INCOMPLETE:' + type(error).__name__)
raise SystemExit(2) from None
@@ -0,0 +1,70 @@
"""Four local orchestration guards; no credentials/VM/Windows API calls."""
import contextlib
import copy
import io
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import Mock, patch
import system_pipe_upgrade as p
def settings():
return dict(schema_version=1, binding={'public_fixture': True}, agent=dict(binary_sha256=p.OLD_AGENT), helper=dict(binary_sha256=p.OLD_HELPER), allowed_services=[], max_runtime_seconds=30, enable_effects=False, allow_reboot=False)
class PipeUpgradeGuards(unittest.TestCase):
def test_closed_reciprocal_settings_only_change_two_image_pins(self):
original = settings(); preserved = copy.deepcopy(original)
raw, pin, policy = p.passive_settings(original, 'a' * 64, 'b' * 64)
changed = json.loads(raw); changed['agent']['binary_sha256'] = p.OLD_AGENT; changed['helper']['binary_sha256'] = p.OLD_HELPER
self.assertEqual(changed, preserved); self.assertEqual(original, preserved)
self.assertEqual(p.raw_sha(raw), policy); self.assertEqual(json.loads(pin)['policy_sha256'], policy)
for field, value in [('enable_effects', True), ('allow_reboot', True), ('allowed_services', ['foreign']), ('max_runtime_seconds', 120), ('schema_version', True)]:
bad = settings(); bad[field] = value
with self.subTest(field=field), self.assertRaises(RuntimeError): p.passive_settings(bad, 'a' * 64, 'b' * 64)
def test_historical_mutation_helpers_excluded_and_explicit_backups_ordered(self):
p.guards()
self.assertNotIn('function PinProcess', p.PREFIX)
self.assertNotIn('[IO.File]::Replace($candidate,$destination,$null)', p.SCRIPT)
self.assertIn('[RmmPipeNative]::Open([int]$before.service.pid)', p.SCRIPT)
self.assertNotIn('$expected=5140', p.SCRIPT)
self.assertIn("'helper-already-stopped.json'", p.SCRIPT)
self.assertIn('stop_called=$false;start_called=$false', p.SCRIPT)
self.assertIn("@('config','ca','identity','certificate','private_key')", p.SCRIPT)
self.assertEqual(p.SCRIPT.count('PreserveImmutableFiles '), 5)
readback = p.PHASES.split("if($p.action-ceq'readback'){", 1)[1].split("if($p.action-ceq'finish'){", 1)[0]
self.assertIn("(ReadbackService 'agent')", readback)
self.assertNotIn('(Service ', readback)
self.assertIn('process_identity_verified=$false', p.READBACK_SERVICE)
self.assertIn('pack.verified(manifest_path)', p.VERIFY_PACK)
self.assertIn("names==report['names']==pack.TESTS[kind]", p.VERIFY_PACK)
with patch.object(p.subprocess, 'run', return_value=Mock(returncode=0, stdout=b'{"type":"rmm.windows.system-delegation-build"}')):
with self.assertRaises(RuntimeError): p.qualified(Path('unused-fixture'), Path('unused-proof'))
def test_lost_enter_reply_cannot_repeat_target_mutation(self):
with tempfile.TemporaryDirectory() as temporary:
folder = Path(temporary); p.write_bytes(folder / 'baseline.json', b'{}')
digest = p.sha(folder / 'baseline.json'); indices = {'unit_fixture': True}
intent = dict(payload=dict(baseline_sha256=digest), original_indices=indices)
p.save(folder / 'server-before.json', {'unit_counts': 0})
access = Mock(); access.server_state.return_value = {'unit_counts': 0}
with patch.object(p, 'load', return_value=(folder, intent)), patch.object(p, 'prior', return_value=(indices, {}, {})), patch.object(p, 'remote', side_effect=TimeoutError('unit fixture lost reply')) as remote:
with self.assertRaises(TimeoutError): p.enter(access, 'fixture', digest)
self.assertTrue((folder / 'enter-attempt.json').exists())
with self.assertRaises(FileExistsError): p.enter(access, 'fixture', digest)
self.assertEqual(remote.call_count, 1)
def test_readback_never_queries_server_starts_or_publishes_main_indices(self):
with tempfile.TemporaryDirectory() as temporary:
access = Mock(); access.server_state.side_effect = AssertionError('server unavailable in readback')
with patch.object(p, 'load', return_value=(Path(temporary), {})), patch.object(p, 'remote', return_value=dict(read_only=True, id='fixture', phase_receipts={})) as remote, contextlib.redirect_stdout(io.StringIO()):
p.finish(access, 'fixture', read_only=True)
remote.assert_called_once_with(access, {}, 'readback')
self.assertFalse(access.server_state.called)
if __name__ == '__main__': unittest.main()