175 lines
10 KiB
Python
175 lines
10 KiB
Python
#!/usr/bin/env python3
|
|
"""Narrow SSH bootstrap for the Windows development guest. No RMM execution.
|
|
|
|
Reads credentials only as protected JSON; all remote code is fixed here.
|
|
Private keys are generated by the Windows agent and never downloaded.
|
|
"""
|
|
import argparse
|
|
import base64
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import sys
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
sys.path.insert(0, str(ROOT / 'deploy'))
|
|
import vm_mvp_acceptance as contract
|
|
|
|
EVIDENCE = ROOT / 'devstate/windows-client'
|
|
REMOTE = r'C:\ProgramData\RustDiscoveryBootstrap'
|
|
|
|
|
|
def powershell(script, payload=None, timeout=60, remote_signed=False):
|
|
access = contract.protected_json(ROOT / 'credentials/windows-dev-access.json')
|
|
script = "try {\n"+script+"\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 ' if remote_signed else '') + '-EncodedCommand ' + base64.b64encode(script.encode('utf-16le')).decode('ascii')
|
|
result = subprocess.run(access['ssh_prefix'] + [command], input=(json.dumps(payload or {})+'\n').encode(), capture_output=True, timeout=timeout)
|
|
if result.returncode:
|
|
print(json.dumps({'bootstrap_returncode':result.returncode,'stdout_bytes':len(result.stdout),'stderr_bytes':len(result.stderr)}))
|
|
failure=EVIDENCE/'bootstrap-private-last-error.json'
|
|
fd=os.open(failure,os.O_CREAT|os.O_TRUNC|os.O_WRONLY,0o600)
|
|
with os.fdopen(fd,'w') as out:json.dump({'stdout':result.stdout.decode('utf-8',errors='replace'),'stderr':result.stderr.decode('utf-8',errors='replace')},out)
|
|
# Exact stderr can contain private paths, command arguments and tokens.
|
|
try:
|
|
report=json.loads(result.stdout.decode('utf-8-sig'))
|
|
if report.get('bootstrap_error'):
|
|
print(json.dumps({'bootstrap_error':True,'error_id':report.get('error_id'),'line':report.get('line')}))
|
|
except (ValueError,AttributeError):pass
|
|
raise RuntimeError('WINDOWS_BOOTSTRAP_FAILED_' + str(result.returncode))
|
|
return json.loads(result.stdout.decode('utf-8-sig'))
|
|
|
|
|
|
UPLOAD = r'''
|
|
$ErrorActionPreference='Stop'
|
|
$p=([Console]::In.ReadLine() | ConvertFrom-Json)
|
|
if ($p.name -notmatch '^((rmm-agent-windows|windows-tests-(lib|bin))\.exe|Install-PassiveClient\.ps1)$') {throw 'Artifact allowlist'}
|
|
$root='C:\ProgramData\RustDiscoveryBootstrap'
|
|
if (!(Test-Path -LiteralPath $root)) {
|
|
New-Item -ItemType Directory -Path $root | Out-Null
|
|
$acl=New-Object Security.AccessControl.DirectorySecurity
|
|
$acl.SetAccessRuleProtection($true,$false)
|
|
foreach($sid in @('S-1-5-18','S-1-5-32-544')) {
|
|
$s=New-Object Security.Principal.SecurityIdentifier($sid)
|
|
$acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule($s,'FullControl','ContainerInherit,ObjectInherit','None','Allow')))
|
|
}
|
|
$acl.SetOwner((New-Object Security.Principal.SecurityIdentifier('S-1-5-32-544')))
|
|
Set-Acl -LiteralPath $root -AclObject $acl
|
|
}
|
|
if ($p.sha256 -notmatch '^[0-9a-f]{64}$') {throw 'Artifact hash format'}
|
|
$version=Join-Path $root $p.sha256
|
|
if (!(Test-Path -LiteralPath $version)) {New-Item -ItemType Directory -Path $version | Out-Null}
|
|
$path=Join-Path $version $p.name
|
|
if (Test-Path -LiteralPath $path) {throw 'Artifact already exists'}
|
|
[pscustomobject]@{prepared=$true;sha256=$p.sha256} | ConvertTo-Json -Compress
|
|
'''
|
|
VERIFY_UPLOAD = r'''
|
|
$ErrorActionPreference='Stop'
|
|
$p=([Console]::In.ReadLine() | ConvertFrom-Json)
|
|
if ($p.sha256 -notmatch '^[0-9a-f]{64}$' -or $p.name -notmatch '^((rmm-agent-windows|windows-tests-(lib|bin))\.exe|Install-PassiveClient\.ps1)$') {throw 'Artifact allowlist'}
|
|
$path='C:\ProgramData\RustDiscoveryBootstrap\'+$p.sha256+'\'+$p.name
|
|
$hash=(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()
|
|
if ($hash -cne $p.sha256) {throw 'Artifact hash'}
|
|
[pscustomobject]@{uploaded=$true;sha256=$hash;size=(Get-Item -LiteralPath $path).Length} | ConvertTo-Json -Compress
|
|
'''
|
|
PROBE = r'''
|
|
$ErrorActionPreference='Stop'
|
|
$p=([Console]::In.ReadLine() | ConvertFrom-Json)
|
|
if ($p.sha256 -notmatch '^[0-9a-f]{64}$') {throw 'Artifact hash format'}
|
|
$path='C:\ProgramData\RustDiscoveryBootstrap\'+$p.sha256+'\rmm-agent-windows.exe'
|
|
$raw=& $path --native-probe
|
|
if ($LASTEXITCODE -ne 0) {throw 'Native probe failed'}
|
|
$probe=$raw | ConvertFrom-Json
|
|
$os=Get-CimInstance Win32_OperatingSystem -Property Caption,Version,OSArchitecture
|
|
[pscustomobject]@{probe=$probe;os_caption=$os.Caption;os_version=$os.Version;architecture=$os.OSArchitecture;native_execution=$true} | ConvertTo-Json -Depth 8 -Compress
|
|
'''
|
|
TEST = r'''
|
|
$ErrorActionPreference='Stop'
|
|
$p=([Console]::In.ReadLine() | ConvertFrom-Json)
|
|
if ($p.kind -notin @('lib','bin')) {throw 'Test allowlist'}
|
|
if ($p.sha256 -notmatch '^[0-9a-f]{64}$') {throw 'Artifact hash format'}
|
|
$path='C:\ProgramData\RustDiscoveryBootstrap\'+$p.sha256+'\windows-tests-'+$p.kind+'.exe'
|
|
$out=& $path --test-threads=1 2>&1
|
|
$code=$LASTEXITCODE
|
|
$summary=@($out | Where-Object {"$_" -match '^test result: '})
|
|
if (!$summary) {throw 'No native test summary'}
|
|
[pscustomobject]@{exit_code=$code;native_execution=$true;summary=($summary -join ' ')} | ConvertTo-Json -Compress
|
|
'''
|
|
|
|
|
|
def record(name, evidence):
|
|
EVIDENCE.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
EVIDENCE.chmod(0o700)
|
|
path=EVIDENCE/name
|
|
fd=os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
|
|
with os.fdopen(fd,'w') as out:
|
|
json.dump(evidence,out,indent=2)
|
|
out.flush(); os.fsync(out.fileno())
|
|
return path
|
|
|
|
|
|
def upload(path, name):
|
|
data=Path(path).read_bytes()
|
|
digest=hashlib.sha256(data).hexdigest()
|
|
metadata=dict(name=name,sha256=digest)
|
|
powershell(UPLOAD,metadata,timeout=60)
|
|
access=contract.protected_json(ROOT/'credentials/windows-dev-access.json')
|
|
prefix=access['ssh_prefix']
|
|
args=['sftp']+[part for part in prefix[1:-1] if part!='-T']+['-b','-',prefix[-1]]
|
|
remote='/C:/ProgramData/RustDiscoveryBootstrap/'+digest+'/'+name
|
|
batch='put '+json.dumps(str(Path(path).resolve()))+' '+json.dumps(remote)+'\n'
|
|
transferred=subprocess.run(args,input=batch.encode(),capture_output=True,timeout=120)
|
|
if transferred.returncode:raise RuntimeError('WINDOWS_SFTP_UPLOAD_FAILED')
|
|
result=powershell(VERIFY_UPLOAD,metadata,timeout=60)
|
|
record(name+'.'+result['sha256']+'.uploaded.json',result)
|
|
pointer=EVIDENCE/(name+'.latest.json')
|
|
fd=os.open(pointer,os.O_CREAT|os.O_TRUNC|os.O_WRONLY,0o600)
|
|
with os.fdopen(fd,'w') as out:json.dump(result,out)
|
|
return result
|
|
|
|
|
|
def main():
|
|
parser=argparse.ArgumentParser()
|
|
parser.add_argument('action',choices=['upload-agent','upload-lib-tests','upload-bin-tests','upload-installer','install','install-after-nonstart','probe','test-lib','test-bin'])
|
|
parser.add_argument('--artifact',type=Path)
|
|
args=parser.parse_args()
|
|
if args.action.startswith('upload-'):
|
|
if args.artifact is None: parser.error('--artifact required')
|
|
name={'upload-agent':'rmm-agent-windows.exe','upload-lib-tests':'windows-tests-lib.exe','upload-bin-tests':'windows-tests-bin.exe','upload-installer':'Install-PassiveClient.ps1'}[args.action]
|
|
result=upload(args.artifact,name)
|
|
print(json.dumps(result))
|
|
elif args.action in ('install','install-after-nonstart'):
|
|
import remote_client_bootstrap as cloud
|
|
artifact=contract.protected_json(EVIDENCE/'rmm-agent-windows.exe.latest.json')
|
|
installer=contract.protected_json(EVIDENCE/'Install-PassiveClient.ps1.latest.json')
|
|
# A create-once local checkpoint prevents creating a second token after
|
|
# an ambiguous remote bootstrap. Inspect/preserve Windows state instead.
|
|
if args.action=='install-after-nonstart':
|
|
previous=contract.protected_json(EVIDENCE/'install-nonstart-after-policy.json')
|
|
contract.require(not any(previous[k] for k in ('client_root','application_root','service')) and previous['machine_policy']=='Undefined' and previous['user_policy']=='Undefined','verified_bootstrap_nonstart_required')
|
|
checkpoint='installation-started.json' if args.action=='install' else 'installation-after-nonstart-started.json'
|
|
record(checkpoint,{'artifact_sha256':artifact['sha256'],'installer_sha256':installer['sha256'],'new_windows_guest_only':True,'process_execution_policy':'RemoteSigned' if args.action=='install-after-nonstart' else 'unchanged'})
|
|
material=cloud.rpc('server.conf',cloud.server,{'action':'enroll'})
|
|
script="$p=([Console]::In.ReadLine() | ConvertFrom-Json);$path='C:\\ProgramData\\RustDiscoveryBootstrap\\"+installer['sha256']+"\\Install-PassiveClient.ps1'; if ((Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant() -cne '"+installer['sha256']+"') {throw 'Installer hash'}; $global:RmmBootstrapPayload=$p; & $path"
|
|
# Pass one small JSON line on stdin, never arguments/environment/logs.
|
|
record(checkpoint+'.enrollment-token-hash.json',{'token_sha256':hashlib.sha256(material['token'].encode()).hexdigest(),'one_use':True})
|
|
result=powershell(script,{'sha256':artifact['sha256'],'token':material['token'],'ca':material['ca']},timeout=90,remote_signed=args.action=='install-after-nonstart')
|
|
record('installed.json',result);print(json.dumps(result))
|
|
elif args.action=='probe':
|
|
artifact=contract.protected_json(EVIDENCE/'rmm-agent-windows.exe.latest.json')
|
|
result=powershell(PROBE,{'sha256':artifact['sha256']},timeout=60);record('native-probe-'+artifact['sha256']+'.json',result)
|
|
print(json.dumps({k:v for k,v in result.items() if k!='probe'}|{'jobs_supported':result['probe']['jobs_supported']}))
|
|
else:
|
|
kind=args.action.removeprefix('test-')
|
|
artifact=contract.protected_json(EVIDENCE/('windows-tests-'+kind+'.exe.latest.json'))
|
|
result=powershell(TEST,{'kind':kind,'sha256':artifact['sha256']},timeout=120)
|
|
record(args.action+'.json',result);print(json.dumps(result))
|
|
if result['exit_code']!=0:raise RuntimeError('NATIVE_WINDOWS_TEST_FAILED')
|
|
|
|
|
|
if __name__=='__main__':
|
|
try:main()
|
|
except Exception as error:
|
|
print(json.dumps({'error':type(error).__name__,'details_suppressed':True}));sys.exit(1)
|