#!/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 olddt.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