feat: verify native Windows client probe and preserve unknown APT outcome
Rust development slice / linux (push) Failing after 7s
Rust development slice / linux (push) Failing after 7s
This commit is contained in:
@@ -5,7 +5,7 @@ const crypto = require('node:crypto');
|
||||
const { isDeepStrictEqual: equal } = require('node:util');
|
||||
const { chromium } = require('../../web/node_modules/playwright');
|
||||
const root = path.resolve(__dirname, '../..');
|
||||
const assert = v => { if (!v) throw new Error('APT UI contract mismatch'); };
|
||||
const assert = v => { if (!v) { const error = new Error('APT UI contract mismatch'); Error.captureStackTrace(error, assert); throw error; } };
|
||||
function readPrivate(file) {
|
||||
const s = fs.lstatSync(file);
|
||||
assert(s.isFile() && !s.isSymbolicLink() && s.uid === process.getuid() && (s.mode & 0o777) === 0o600 && s.size < 1048576);
|
||||
@@ -80,7 +80,12 @@ function checkAction(p, expected) {
|
||||
assert(pending.approval_state === 'pending_approval' && pending.job_count === 0 && pending.execution_state === null);
|
||||
await op.getByRole('button', { name: 'Unveränderlichen Plan zur Prüfung öffnen' }).click();
|
||||
const plan = JSON.parse(await detail.locator('pre').innerText());
|
||||
assert(equal(plan, expected.plan) && plan.jobs.length === 1 && plan.resolved_targets.length === 1);
|
||||
// Submission changes request metadata, never the fixed plan bytes/jobs.
|
||||
// Require the new pending state explicitly and compare EVERY other field.
|
||||
const { approval_state: currentState, ...currentPlan } = plan;
|
||||
const { approval_state: preparedState, ...preparedPlan } = expected.plan;
|
||||
assert(currentState === 'pending_approval' && preparedState === null);
|
||||
assert(equal(currentPlan, preparedPlan) && plan.jobs.length === 1 && plan.resolved_targets.length === 1);
|
||||
assert(crypto.createHash('sha256').update(Buffer.from(plan.plan_payload_bytes)).digest('hex') === plan.plan_hash);
|
||||
const p = plan.jobs[0].payload; checkAction(p, expected);
|
||||
assert(p.agent_id === expected.agent_id && p.asset_id === expected.asset_id && p.tenant_id === expected.tenant_id && Date.parse(p.start_before) > Date.now());
|
||||
|
||||
@@ -58,6 +58,40 @@ def upgrade_agent(payload):
|
||||
return dict(binary_sha256=payload['sha256'], state_preserved_before_start=True, package_effects=False, backup=str(backup))
|
||||
|
||||
|
||||
def stored_attempt_evidence(payload):
|
||||
"""Read only already persisted evidence; no live collector/package command."""
|
||||
import sqlite3
|
||||
import re
|
||||
base = Path('/var/lib/rmm-apt-transaction'); active = base/'active'
|
||||
context = json.loads((active/'context.json').read_text())
|
||||
require(context['job_id'] == payload['job_id'] and context['attempt_id'] == payload['attempt_id'], 'exact stored attempt required')
|
||||
result = dict(files={}, records={}, context=context)
|
||||
for name in ('hook-armed.json','native-prechecks.json','sandbox-ready.json','sandbox-result.json','launch.json'):
|
||||
path = active/name
|
||||
result['files'][name] = dict(exists=path.exists(), symlink=path.is_symlink())
|
||||
if path.is_file() and not path.is_symlink(): result['records'][name] = json.loads(path.read_text())
|
||||
for name in ('bootstrap-attempt-rmm-apt-fixture-install-1.0.json','bootstrap-retry-rmm-apt-fixture-install-1.0.json',
|
||||
'acceptance-rmm-apt-fixture-install-1.0.json','pending-acceptance-rmm-apt-fixture-install-1.0.json'):
|
||||
path = base/name
|
||||
result['files'][name] = dict(exists=path.exists(), symlink=path.is_symlink(), sha256=hashlib.sha256(path.read_bytes()).hexdigest() if path.is_file() else None)
|
||||
with sqlite3.connect('file:/var/lib/rmm-helper/consumption.sqlite?mode=ro', uri=True) as db:
|
||||
row = db.execute('SELECT c.result,e.outcome FROM consumed c JOIN execution_evidence e USING(grant_id) WHERE c.grant_id=?', (context['grant_id'],)).fetchone()
|
||||
result['ledger'] = dict(result=json.loads(row[0]) if row[0] else None, outcome=json.loads(row[1]) if row[1] else None,
|
||||
consumed=db.execute('SELECT count(*) FROM consumed').fetchone()[0], unresolved=db.execute('SELECT count(*) FROM consumed WHERE result IS NULL').fetchone()[0])
|
||||
result['logs'] = {}
|
||||
for name in ('dpkg.log','term.log','history.log'):
|
||||
path = base/'log'/name
|
||||
if path.is_file() and not path.is_symlink():
|
||||
raw = path.read_bytes(); require(len(raw) <= 1024*1024, 'bounded stored log')
|
||||
text = raw.decode('utf-8', errors='replace')
|
||||
result['logs'][name] = dict(sha256=hashlib.sha256(raw).hexdigest(), size=len(raw),
|
||||
fixture_states=re.findall(r'\bstatus (not-installed|half-installed|unpacked|half-configured|installed|triggers-pending|triggers-awaited) rmm-mvp-test(?::all)? (1\.[01])\b', text),
|
||||
configure_record=bool(re.search(r'\bconfigure rmm-mvp-test(?::all)?\b', text)),
|
||||
setup_message='Setting up rmm-mvp-test (1.0)' in text,
|
||||
dpkg_error='dpkg: error' in text)
|
||||
return result
|
||||
|
||||
|
||||
def switch_endpoint(payload):
|
||||
import sqlite3
|
||||
os.umask(0o077)
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
# Windows-Client: erster nativer Entwicklungsstand
|
||||
|
||||
Stand 2026-11-13, Spezifikation 1.9. Windows-11-Gast und Notebook-Host sind
|
||||
verschiedene Geräte. Auf dem Notebook laufen ausschließlich Entwicklungstools;
|
||||
der Client verwendet den endgültigen Cloudserver `discovery.ease-technologies.de`.
|
||||
|
||||
## Tatsächlich nachgewiesen
|
||||
|
||||
`rmm-agent-windows` als eigene Plattform-Crate mit gemeinsamen Domain-/Protobuf-
|
||||
Verträgen und direkt wiederverwendeten WSS-/HTTPS-/TLS-Modulen des Linux-Agenten.
|
||||
Isolierter Docker-Crossbuild mit Rust 1.99.1 für `x86_64-pc-windows-gnu`:
|
||||
Debug und Release erfolgreich; Windows-target Clippy über alle Targets mit
|
||||
`-D warnings` erfolgreich. Zwei gezielte Domain-Tests prüfen die unveränderte
|
||||
Linux-Validierung, Windows ohne erfundene Inodes und abgewiesene Plattformmischung.
|
||||
Das sind ergänzende lokale Prüfungen, keine nativen Windows-Dienstnachweise.
|
||||
|
||||
Releaseartefakt SHA256
|
||||
`31e360e50b177b4d5729d24e436d4f25aeed7b1a7bd35f2a129841ba1abffd37`
|
||||
auf der tatsächlichen Windows-11-Pro-VM (Version 10.0.26300, x64) gestartet:
|
||||
`--native-probe` erfolgreich. Hostname und Systemvolume tatsächlich über Win32
|
||||
lesbar; Bootkennung aus `Win32_OperatingSystem.LastBootUpTime` abgeleitet statt
|
||||
bei jedem Agentstart neu erzeugt. Inodes ausdrücklich `null`/nicht anwendbar.
|
||||
Keine Schlüssel oder realen Hostnamen in der veröffentlichten Probeausgabe.
|
||||
|
||||
Binärtransfer über bestehendes, hostkeygeprüftes SFTP mit SHA256-Nachprüfung.
|
||||
Große PowerShell-Console-JSON-Eingaben waren als Bootstraptransport ungeeignet
|
||||
(Timeout/Console-Reader-Ausnahme); deshalb nur kleine zeilenbegrenzte Metadaten
|
||||
über stdin. SSH-/Hostkeyprüfung und Reverse-Portgrenzen bleiben unverändert.
|
||||
Artefaktverzeichnisse werden nach Hash neu angelegt, keine vorhandene Identität
|
||||
oder Historie gelöscht. Private Evidenz: `devstate/windows-client/`.
|
||||
|
||||
## Implementiert, Dienst-/Online-Abnahme noch offen
|
||||
|
||||
- Nativer SCM-Dienstlebenszyklus, vorgesehen als `LocalService` mit eigenem
|
||||
Service-SID-Zugriff auf Zustand und ausschließlich lesbarem Programm/Config.
|
||||
- Windows prüft Owner/DACL und verweigert Reparse-Points/breite ACLs. Geräteschlüssel
|
||||
werden nur auf Windows erzeugt; Enrollment über CA- und namensgeprüftes TLS,
|
||||
danach mTLS. Ein verlorener Enrollmentnachweis löst keinen Identitätsreset aus.
|
||||
- SQLite mit FULL-Synchronisierung, Prozesssperre, monotoner persistenter Sequenz,
|
||||
konkretem ACK und begrenzter Telemetriequeue. Kein Löschen für Platzgewinn.
|
||||
- Separate `windows.base`-Beobachtungen mit Erhebungszeit/Quelle/Qualität; Server
|
||||
bindet den Scope an die authentisierte Verbindung und deren Capability.
|
||||
Geräte-API zeigt die gespeicherte Quelle statt eines festen Linuxlabels.
|
||||
- Ausschließlich `windows.base/1` und `heartbeat/1` werden angeboten.
|
||||
**Kein Jobexecutor, keine PowerShell-Jobfähigkeit, kein privilegierter Helper.**
|
||||
Angebote/Startgrants werden verweigert. Es gibt keine Genehmigungsabkürzung.
|
||||
|
||||
Dieser erste Entwicklungsbuild ist **unsigniert**. Kein produktiver signierter
|
||||
Installer/MSVC-Supportnachweis, keine Zertifikatsrotations-/Widerrufs-/Proxy- oder
|
||||
Windows-Paket-/Dienstaktionsabnahme. Native Testprogramme sowie die tatsächliche
|
||||
SCM-/Enrollment-/mTLS-/Inventarstrecke sind zum Zeitpunkt dieses Abschnitts noch
|
||||
offen. Ein erfolgreicher Crossbuild bzw. `--native-probe` ersetzt sie nicht.
|
||||
|
||||
## Ausgeführte und geplante Befehle
|
||||
|
||||
Tatsächlich ausgeführt: Docker-Build und gezielte Rust-Prüfungen oben sowie
|
||||
`python3 deploy/windows/client_bootstrap.py upload-agent --artifact <Release-EXE>`
|
||||
und `python3 deploy/windows/client_bootstrap.py probe` gegen ausschließlich den
|
||||
Windows-Gast. Keine RMM-Jobs oder Genehmigungen wurden dabei erzeugt.
|
||||
|
||||
Geplant, noch nicht als bestanden behauptet: native Testprogramme und
|
||||
`Install-PassiveClient.ps1` über `client_bootstrap.py install`, anschließend
|
||||
zwei frische Heartbeats, korrekt zugeordnetes Inventar und Tenant-B-Verweigerung.
|
||||
Installation ist create-only; bei Teilfehlern Zustand inspizieren und erhalten,
|
||||
nicht blind neu enrollen oder den Bootstrap wiederholen.
|
||||
@@ -0,0 +1,83 @@
|
||||
# Development bootstrap only. No RMM jobs, privileged helper or execution bypass.
|
||||
# Run through the pinned SSH transport as the bootstrap administrator.
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$p = $global:RmmBootstrapPayload
|
||||
if ($null -eq $p) { throw 'Bootstrap payload required through the pinned launcher' }
|
||||
if ($p.sha256 -notmatch '^[0-9a-f]{64}$' -or $p.token -notmatch '^[0-9a-f]{64}$') { throw 'Invalid bootstrap metadata' }
|
||||
$serviceName = 'RmmDiscoveryWindows'
|
||||
$application = 'C:\Program Files\RustDiscovery'
|
||||
$root = 'C:\ProgramData\RustDiscovery'
|
||||
$state = Join-Path $root 'state'
|
||||
$source = 'C:\ProgramData\RustDiscoveryBootstrap\' + $p.sha256 + '\rmm-agent-windows.exe'
|
||||
if (Get-Service -Name $serviceName -ErrorAction SilentlyContinue) { throw 'Service already exists: preserve identity and inspect instead of reinstalling' }
|
||||
if ((Test-Path -LiteralPath $application) -or (Test-Path -LiteralPath $root)) { throw 'Existing client state must be preserved' }
|
||||
if ((Get-FileHash -LiteralPath $source -Algorithm SHA256).Hash.ToLowerInvariant() -cne $p.sha256) { throw 'Artifact hash mismatch' }
|
||||
$ca = [Convert]::FromBase64String($p.ca)
|
||||
if ($ca.Length -lt 100 -or $ca.Length -gt 32768) { throw 'CA size' }
|
||||
$administrators = New-Object Security.Principal.SecurityIdentifier('S-1-5-32-544')
|
||||
$system = New-Object Security.Principal.SecurityIdentifier('S-1-5-18')
|
||||
function Protect-Directory([string]$Path, $ServiceSid, [string]$Rights) {
|
||||
$acl = New-Object Security.AccessControl.DirectorySecurity
|
||||
$acl.SetAccessRuleProtection($true, $false)
|
||||
$acl.SetOwner($administrators)
|
||||
foreach ($sid in @($administrators, $system)) {
|
||||
$acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule($sid, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')))
|
||||
}
|
||||
if ($null -ne $ServiceSid) {
|
||||
$acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule($ServiceSid, $Rights, 'ContainerInherit,ObjectInherit', 'None', 'Allow')))
|
||||
}
|
||||
Set-Acl -LiteralPath $Path -AclObject $acl
|
||||
}
|
||||
function Protect-ReadFile([string]$Path, $ServiceSid) {
|
||||
$acl = New-Object Security.AccessControl.FileSecurity
|
||||
$acl.SetAccessRuleProtection($true, $false)
|
||||
$acl.SetOwner($administrators)
|
||||
foreach ($sid in @($administrators, $system)) {
|
||||
$acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule($sid, 'FullControl', 'Allow')))
|
||||
}
|
||||
$acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule($ServiceSid, 'ReadAndExecute', 'Allow')))
|
||||
Set-Acl -LiteralPath $Path -AclObject $acl
|
||||
}
|
||||
New-Item -ItemType Directory -Path $application | Out-Null
|
||||
New-Item -ItemType Directory -Path $root | Out-Null
|
||||
Protect-Directory $application $null 'ReadAndExecute'
|
||||
Protect-Directory $root $null 'ReadAndExecute'
|
||||
Copy-Item -LiteralPath $source -Destination (Join-Path $application 'rmm-agent-windows.exe')
|
||||
$binary = '"C:\Program Files\RustDiscovery\rmm-agent-windows.exe" --service --config "C:\ProgramData\RustDiscovery\config.json"'
|
||||
$sc = Join-Path $env:WINDIR 'System32\sc.exe'
|
||||
# New-Service passes the quoted image path directly to SCM, avoiding native
|
||||
# PowerShell 5.1 command-line quoting of a path containing spaces. Keep it manual
|
||||
# until the account has been narrowed; it is never started as LocalSystem.
|
||||
New-Service -Name $serviceName -BinaryPathName $binary -StartupType Manual | Out-Null
|
||||
& $sc config $serviceName start= auto obj= 'NT AUTHORITY\LocalService' | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { throw 'SCM service identity configuration failed' }
|
||||
& $sc sidtype $serviceName unrestricted | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { throw 'SCM service SID configuration failed' }
|
||||
$serviceSid = (New-Object Security.Principal.NTAccount('NT SERVICE', $serviceName)).Translate([Security.Principal.SecurityIdentifier])
|
||||
Protect-Directory $application $serviceSid 'ReadAndExecute'
|
||||
Protect-Directory $root $serviceSid 'ReadAndExecute'
|
||||
New-Item -ItemType Directory -Path $state | Out-Null
|
||||
Protect-Directory $state $serviceSid 'Modify'
|
||||
$caPath = Join-Path $root 'server-ca.pem'
|
||||
[IO.File]::WriteAllBytes($caPath, $ca)
|
||||
Protect-ReadFile $caPath $serviceSid
|
||||
# Only this one-use token is writable by the service so it can remove the copy.
|
||||
$tokenPath = Join-Path $state 'enrollment.token'
|
||||
[IO.File]::WriteAllText($tokenPath, $p.token, (New-Object Text.UTF8Encoding($false)))
|
||||
$address = @([Net.Dns]::GetHostAddresses('discovery.ease-technologies.de') | Where-Object {$_.AddressFamily -eq [Net.Sockets.AddressFamily]::InterNetwork})[0]
|
||||
if ($null -eq $address) { throw 'Server DNS has no IPv4 address' }
|
||||
$config = [ordered]@{
|
||||
server_name = 'discovery.ease-technologies.de'
|
||||
connect_address = $address.ToString() + ':443'
|
||||
ca_file = $caPath
|
||||
state_directory = $state
|
||||
enrollment_token_file = $tokenPath
|
||||
transport = 'wss'
|
||||
}
|
||||
$configPath = Join-Path $root 'config.json'
|
||||
[IO.File]::WriteAllText($configPath, ($config | ConvertTo-Json -Compress), (New-Object Text.UTF8Encoding($false)))
|
||||
Protect-ReadFile $configPath $serviceSid
|
||||
& $sc description $serviceName 'Rust Discovery development passive agent; no job executor' | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Service description failed' }
|
||||
Start-Service -Name $serviceName
|
||||
[pscustomobject]@{installed=$true;service_name=$serviceName;service_identity='LocalService';service_sid=$serviceSid.Value;artifact_sha256=$p.sha256;no_job_executor=$true;no_reboot=$true} | ConvertTo-Json -Compress
|
||||
@@ -0,0 +1,174 @@
|
||||
#!/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)
|
||||
Reference in New Issue
Block a user