Files
rust-discovery/deploy/windows/client_bootstrap.py
T
2026-11-14 07:43:36 +01:00

199 lines
13 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
import time
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|rmm-helper-windows|windows-tests-(lib|bin|acl)|windows-core-(contracts|reconcile|helper-reconcile))\.exe|(Install-PassiveClient|Build-MsiFixture|Build-NativeMsvc|Install-NativeBuildTools)\.ps1|PassiveStateProbe\.exe|WindowsTlsProbe\.exe|RuntimeStateProbe\.exe|SystemStateProbe\.exe)$') {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|rmm-helper-windows|windows-tests-(lib|bin|acl)|windows-core-(contracts|reconcile|helper-reconcile))\.exe|(Install-PassiveClient|Build-MsiFixture|Build-NativeMsvc|Install-NativeBuildTools)\.ps1|PassiveStateProbe\.exe|WindowsTlsProbe\.exe|RuntimeStateProbe\.exe|SystemStateProbe\.exe)$') {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
'''
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-acl-tests','upload-installer','upload-state-probe','install','install-after-nonstart','passive-acceptance','probe','test-lib','test-bin','test-acl'])
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-acl-tests':'windows-tests-acl.exe','upload-installer':'Install-PassiveClient.ps1','upload-state-probe':'PassiveStateProbe.exe'}[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=='passive-acceptance':
import cloud_mvp_acceptance as cloud
import remote_client_bootstrap as bootstrap
identity=contract.protected_json(EVIDENCE/'service-initial-state.json')['identity']
backend=cloud.Backend()
first=backend.call('inventory.get_device',{'tenant_id':cloud.TENANT,'asset_id':identity['asset_id']})
contract.require(first['presence']=='online' and first['source_id']=='windows.base' and first['inventory'] is not None,'native_windows_inventory_required')
contract.require(set(first['capabilities'])=={'windows.base/1','heartbeat/1'} and first['inventory']['root_available_inodes'] is None,'honest_passive_capabilities')
deadline=time.monotonic()+75
while True:
current=backend.call('inventory.get_device',{'tenant_id':cloud.TENANT,'asset_id':identity['asset_id']})
if current['last_contact_at']!=first['last_contact_at']:break
contract.require(time.monotonic()<deadline,'second_fresh_heartbeat_missing')
time.sleep(2)
contract.require(current['agent_id']==identity['agent_id'] and current['presence']=='online' and current['observed_at']==first['observed_at'],'same_persisted_identity_and_inventory')
foreign=cloud.Backend('b')
denied=[]
for tenant in (cloud.TENANT,'22222222-2222-4222-8222-222222222222'):
foreign.sequence+=1
response=foreign.request({'jsonrpc':'2.0','id':foreign.sequence,'method':'tools/call','params':{'name':'inventory.get_device','arguments':{'tenant_id':tenant,'asset_id':identity['asset_id']}}})
data=response.get('data',{})
result=data.get('result',{})
contract.require('error' in data or result.get('isError'),'foreign_windows_inventory_must_be_denied')
denied.append({'tenant':tenant,'denied':True})
gate=bootstrap.rpc('server.conf',cloud.server,{'kind':'gate','tenant_id':cloud.TENANT,'agent_id':identity['agent_id']})
contract.require(gate=={'jobs':0,'outbox':0,'permits':0,'unresolved':0},'passive_agent_zero_jobs_required')
report={'first':first,'second':current,'foreign_denied':denied,'gate':gate,'native_windows':True,'server':'discovery.ease-technologies.de','no_jobs_or_approvals':True}
record('passive-acceptance.json',report)
print(json.dumps({'native_windows':True,'source_id':current['source_id'],'two_fresh_heartbeats':True,'foreign_denied':len(denied),'gate':gate,'same_identity':True}))
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'))
access=contract.protected_json(ROOT/'credentials/windows-dev-access.json')
command=REMOTE+'\\'+artifact['sha256']+'\\windows-tests-'+kind+'.exe --test-threads=1'
native=subprocess.run(access['ssh_prefix']+[command],capture_output=True,timeout=60)
summary=[line for line in native.stdout.decode('utf-8',errors='replace').splitlines() if line.startswith('test result: ')]
contract.require(len(summary)==1,'native_test_summary_required')
result={'exit_code':native.returncode,'native_execution':True,'artifact_sha256':artifact['sha256'],'summary':summary[0]}
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)