190 lines
22 KiB
Python
190 lines
22 KiB
Python
#!/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
|