239 lines
28 KiB
Python
239 lines
28 KiB
Python
#!/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
|