fix: verify cloud APT sandbox isolation and prepare Windows SSH bootstrap
Rust development slice / linux (push) Failing after 6s

This commit is contained in:
2026-11-13 14:01:25 +01:00
parent fbef0e4e2f
commit f3cc5b7cbf
5 changed files with 472 additions and 0 deletions
+142
View File
@@ -0,0 +1,142 @@
#!/usr/bin/env python3
"""One versioned sandbox upgrade; preserves consumed attempts and failed handoff.
No package retry, receipt creation, enrollment or marker reset. The new native
probe runs only under the exact dedicated service profile, on a copied dpkg DB.
APT endpoint remains absent from the agent configuration and is stopped after
the probe. General helper resumes with the existing binding/shared ledger.
"""
import base64
import hashlib
import json
import os
import uuid
import cloud_apt_followup as followup
cloud=followup.cloud
require=cloud.require
def upgrade(payload):
import ast
import fcntl
import sqlite3
import time
import traceback
os.umask(0o077)
base=Path('/var/lib/rmm-apt-transaction');ledger=Path('/var/lib/rmm-helper/consumption.sqlite')
state=Path('/var/lib/rmm-agent-remote');binary=Path('/usr/local/libexec/rmm-privileged-helper')
provider=Path('/usr/lib/rmm-apt-transaction/apt_transaction.py');config=Path('/etc/rmm/apt-helper.json')
proof=Path('/etc/rmm-remote/apt-helper-proof.json');metadata=base/'install-metadata.json'
def run(args,**kw):return subprocess.run(args,capture_output=True,check=True,timeout=90,**kw).stdout
def sha(data):return hashlib.sha256(data).hexdigest()
def create(path,data,mode=0o600,gid=0):
fd=os.open(path,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,mode)
with os.fdopen(fd,'wb') as f:f.write(data);f.flush();os.fsync(f.fileno());os.fchown(f.fileno(),0,gid);os.fchmod(f.fileno(),mode)
def manifest(path):
result={}
for p in path.rglob('*'):
require(not p.is_symlink(),'preserved state symlink')
if p.is_file():result[str(p.relative_to(path))]=sha(p.read_bytes())
return result
def ledger_guard():
with sqlite3.connect(ledger.as_uri()+'?mode=ro',uri=True) as db:
require(db.execute('PRAGMA integrity_check').fetchone()[0]=='ok','ledger integrity')
require(db.execute('SELECT count(*) FROM consumed').fetchone()[0]==5 and
db.execute('SELECT count(*) FROM consumed WHERE result IS NULL').fetchone()[0]==0 and
db.execute('SELECT count(*) FROM helper_sync_meta WHERE fault IS NOT NULL').fetchone()[0]==0,'five known closed root attempts required')
ledger_guard()
require(json.loads((state/'identity.json').read_text())['agent_id']==payload['agent_id'],'cloud identity drift')
with sqlite3.connect((state/'journal.sqlite').as_uri()+'?mode=ro',uri=True) as db:
require(db.execute("SELECT count(*) FROM job_attempts WHERE state NOT IN ('succeeded','failed','cancelled','expired')").fetchone()[0]==0,'unresolved native job')
require(run(['systemctl','show','rmm-apt-helper.service','-p','ActiveState','--value']).strip()==b'inactive','APT helper must be stopped')
require(not list(base.glob('acceptance-*.json')) and not (base/'active/hook-armed.json').exists(),'existing acceptance/effect needs reconciliation')
markers=list(base.glob('bootstrap-attempt-*.json'));require(len(markers)==1 and markers[0].name=='bootstrap-attempt-rmm-apt-fixture-install-1.0.json','preserve original failed attempt')
for name,pin in payload['old_files'].items():
p=Path(name);require(not p.is_symlink() and p.stat().st_uid==0 and p.stat().st_mode&0o022==0 and sha(p.read_bytes())==pin,'installed file drift')
require(Path('/etc/systemd/system/rmm-apt-helper.service').read_text()==payload['unit'],'reviewed exact APT profile required')
raw=base64.b64decode(payload['binary'],validate=True);code=base64.b64decode(payload['provider'],validate=True)
require(sha(raw)==payload['helper_sha256'] and raw[:6]==b'\x7fELF\x02\x01' and raw[18:20]==b'\x3e\x00','reviewed x64 binary required')
require(sha(code)==payload['provider_sha256'],'reviewed provider required');ast.parse(code)
old_meta=json.loads(metadata.read_text());require(old_meta['schema_version']==2 and old_meta['provider_sha256']==sha(provider.read_bytes()) and
old_meta['hook_sha256']==sha(Path('/usr/lib/rmm-apt-transaction/hook').read_bytes()) and old_meta['unit_sha256']==sha(payload['unit'].encode()),'metadata drift')
backup=Path('/var/lib/rmm-bootstrap-history')/('cloud-sandbox-'+payload['id']);backup.mkdir(mode=0o700)
report=dict(stage='validated',completed=False,package_transactions=False,backups={})
def save():
p=backup/'.next.json';create(p,json.dumps(report,indent=2).encode());os.replace(p,backup/'report.json')
def retain(p):
target=backup/str(p).lstrip('/').replace('/','__')
require(not p.is_symlink() and p.stat().st_dev==backup.stat().st_dev and not target.exists(),'exclusive same-filesystem backup')
os.rename(p,target);report['backups'][str(p)]=str(target);save()
stopped=False;lockfd=None
try:
save();staged=backup/'helper-next';create(staged,raw,0o755)
run(['/lib64/ld-linux-x86-64.so.2','--list',str(staged)])
run(['systemctl','stop','rmm-agent-remote.service','rmm-helper-cloud.service']);stopped=True
lockfd=os.open(ledger.parent/'executor.lock',os.O_RDWR|os.O_NOFOLLOW);fcntl.flock(lockfd,fcntl.LOCK_EX|fcntl.LOCK_NB)
ledger_guard();inode=(ledger.stat().st_dev,ledger.stat().st_ino)
preserved={str(p):manifest(p) for p in (state,Path('/var/lib/rmm-agent'),ledger.parent,
base/'active',base/'archives',base/'baselines',base/'history',base/'log',base/'state')}
marker=markers[0].read_bytes();old_general=json.loads(Path('/etc/rmm-remote/general-helper-proof.json').read_text())
old_config=json.loads(config.read_text())
for p in (binary,provider,config,metadata,proof,base/'native-readiness.json'):retain(p)
os.rename(staged,binary);create(provider,code,0o755)
create(metadata,json.dumps(dict(old_meta,provider_sha256=sha(code))).encode())
cmd=['/usr/bin/python3','-I',str(provider)]
runtime=json.loads(run(cmd+['inspect-runtime']));runtime_sha=sha(json.dumps(runtime,sort_keys=True,separators=(',',':'),ensure_ascii=True).encode())
old_config['apt_provider']['runtime_sha256']=runtime_sha
require(old_config['apt_provider']['apt_config_sha256']==sha(run(cmd+['print-config'])),'unchanged APT config required')
create(config,json.dumps(old_config).encode())
pin=json.loads(run([str(binary),'--inspect-apt-profile'],env=dict(os.environ,RMM_HELPER_CONFIG=str(config))))
require(pin['identity']==old_general['identity'],'helper identity changed')
create(proof,json.dumps(pin).encode(),0o640,984)
general=json.loads(run([str(binary),'--inspect-general-profile'],env=dict(os.environ,RMM_HELPER_CONFIG='/etc/rmm-remote/helper-general.json')))
require(general==old_general,'general policy changed')
require(all(manifest(Path(p))==v for p,v in preserved.items()) and markers[0].read_bytes()==marker and
(ledger.stat().st_dev,ledger.stat().st_ino)==inode,'preserved identity/attempt/ledger changed')
report.update(stage='installed_preserved',preserved_state=True,runtime_sha256=runtime_sha,apt_pin=pin,general_pin=general);save()
fcntl.flock(lockfd,fcntl.LOCK_UN);os.close(lockfd);lockfd=None
run(['systemd-analyze','verify','/etc/systemd/system/rmm-apt-helper.service'])
run(['systemctl','daemon-reload'])
run(['systemctl','start','rmm-helper-cloud.service','rmm-apt-helper.service'])
for _ in range(10):
for name in ('rmm-helper-cloud.service','rmm-apt-helper.service'):
status=run(['systemctl','show',name,'-p','ActiveState','-p','SubState','-p','NRestarts']).decode()
require('ActiveState=active\n' in status and 'SubState=running\n' in status and 'NRestarts=0\n' in status,'stable helper start required')
time.sleep(1)
readiness=json.loads((base/'native-readiness.json').read_text())
require(readiness['runtime']==runtime and readiness['readiness_only'] is True and readiness['native_acceptance'] is False,'actual new native probe required')
ledger_guard();require(markers[0].read_bytes()==marker and manifest(base/'active')==preserved[str(base/'active')],'failed attempt changed during probe')
require(not Path('/usr/share/rmm-mvp-test/version').exists(),'unexpected fixture payload')
report.update(stage='native_sandbox_probe_passed',completed=True,readiness_only=True,native_acceptance=False,
readiness_sha256=sha((base/'native-readiness.json').read_bytes()),probe_id=readiness['probe_id']);save()
except Exception as error:
report.update(error_class=type(error).__name__,frames=[dict(function=f.name,line=f.lineno) for f in traceback.extract_tb(error.__traceback__)]);save()
finally:
if lockfd is not None:os.close(lockfd)
subprocess.run(['systemctl','stop','rmm-apt-helper.service'],capture_output=True,timeout=30)
if stopped:
run(['systemctl','start','rmm-helper-cloud.service','rmm-agent-remote.service'])
return dict(report,backup=str(backup))
def main():
os.umask(0o077);m=cloud.contract
require(followup.evidence('gate')['unresolved']==0,'unresolved central job')
diagnosis=m.protected_json(followup.STATE/'diagnosis/checkpoint.json');require(diagnosis.get('verified') is True,'diagnostic evidence required')
preflights=list(followup.STATE.glob('preflight-*.json'));require(len(preflights)==1,'one reviewed installed baseline')
old=m.protected_json(preflights[0]);artifact=(followup.STATE/'helper-sandbox-fixed').read_bytes()
code=(cloud.ROOT/'tools/apt-transaction/apt_transaction.py').read_bytes()
payload=dict(id=str(uuid.uuid4()),agent_id=followup.identity()['agent_id'],old_files=old['files'],
binary=base64.b64encode(artifact).decode(),helper_sha256=hashlib.sha256(artifact).hexdigest(),
provider=base64.b64encode(code).decode(),provider_sha256=hashlib.sha256(code).hexdigest(),unit=(cloud.ROOT/'deploy/linux/rmm-apt-helper.service').read_text())
result=cloud.bootstrap.rpc('linux-vm.conf',upgrade,payload)
m.write_private(followup.STATE/('sandbox-'+payload['id']+'.json'),result)
print({k:result.get(k) for k in ('completed','stage','error_class','frames','preserved_state','runtime_sha256','readiness_only')})
require(result['completed'],'native probe incomplete; preserve reports, never repeat installation')
if __name__=='__main__':
try:main()
except Exception as error:
print('APT_SANDBOX_UPGRADE_INCOMPLETE:'+type(error).__name__);raise SystemExit(2) from None
+145
View File
@@ -0,0 +1,145 @@
#requires -Version 5.1
#requires -RunAsAdministrator
[CmdletBinding()]
param([switch]$MaintainTunnel)
$ErrorActionPreference = 'Stop'
$statePath = Join-Path $env:ProgramData 'RmmDevAccess'
function Protect-AdminFile([string]$Path) {
$directory = (Get-Item -LiteralPath $Path).PSIsContainer
if ($directory) { $acl = New-Object Security.AccessControl.DirectorySecurity }
else { $acl = New-Object Security.AccessControl.FileSecurity }
$acl.SetAccessRuleProtection($true, $false)
$admins = New-Object Security.Principal.SecurityIdentifier 'S-1-5-32-544'
$system = New-Object Security.Principal.SecurityIdentifier 'S-1-5-18'
$acl.SetOwner($admins)
foreach ($sid in @($admins, $system)) {
if ($directory) {
$rule = New-Object Security.AccessControl.FileSystemAccessRule($sid, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')
} else { $rule = New-Object Security.AccessControl.FileSystemAccessRule($sid, 'FullControl', 'Allow') }
[void]$acl.AddAccessRule($rule)
}
Set-Acl -LiteralPath $Path -AclObject $acl
}
function Write-Utf8([string]$Path, [string]$Text) {
[IO.File]::WriteAllText($Path, $Text, (New-Object Text.UTF8Encoding($false)))
}
if ($MaintainTunnel) {
$config = Get-Content -LiteralPath (Join-Path $statePath 'bootstrap-public.json') -Raw | ConvertFrom-Json
$expires = [DateTimeOffset]::Parse($config.expires_at)
$sshPath = Join-Path $env:WINDIR 'System32\OpenSSH\ssh.exe'
$sshArguments = @('-N', '-T', '-i', (Join-Path $statePath 'tunnel_ed25519'),
'-o', 'BatchMode=yes', '-o', 'IdentitiesOnly=yes', '-o', 'ForwardAgent=no',
'-o', 'StrictHostKeyChecking=yes', '-o', ('UserKnownHostsFile=' + (Join-Path $statePath 'known_hosts')),
'-o', 'GlobalKnownHostsFile=NUL', '-o', 'ExitOnForwardFailure=yes',
'-o', 'ServerAliveInterval=30', '-o', 'ServerAliveCountMax=3', '-o', 'ConnectTimeout=10',
'-R', '127.0.0.1:22240:127.0.0.1:22222', 'rmm-win-tunnel@discovery.ease-technologies.de')
while ([DateTimeOffset]::UtcNow -lt $expires) {
$start = New-Object Diagnostics.ProcessStartInfo
$start.FileName = $sshPath
# Fixed arguments contain neither quotes nor a final backslash. Quoting
# every argument preserves ProgramData paths containing spaces on PS5.1.
foreach ($argument in $sshArguments) { if ($argument.Contains('"') -or $argument.EndsWith('\')) { throw 'Unsafe SSH argument' } }
$start.Arguments = ($sshArguments | ForEach-Object { '"' + $_ + '"' }) -join ' '
$start.UseShellExecute = $false; $start.CreateNoWindow = $true
$start.RedirectStandardOutput = $true; $start.RedirectStandardError = $true
$tunnelProcess = New-Object Diagnostics.Process
$tunnelProcess.StartInfo = $start
try {
[void]$tunnelProcess.Start()
$stdoutTask = $tunnelProcess.StandardOutput.ReadToEndAsync()
$stderrTask = $tunnelProcess.StandardError.ReadToEndAsync()
while (-not $tunnelProcess.WaitForExit(15000)) {
if ([DateTimeOffset]::UtcNow -ge $expires) { $tunnelProcess.Kill(); break }
}
} finally { $tunnelProcess.Dispose() }
if ([DateTimeOffset]::UtcNow -lt $expires) { Start-Sleep -Seconds 30 }
}
exit 0
}
if ($env:OS -ne 'Windows_NT' -or $env:PROCESSOR_ARCHITECTURE -ne 'AMD64') { throw 'Windows x64 and elevated 64-bit PowerShell required' }
$publicPath = Join-Path $PSScriptRoot 'bootstrap-public.json'
$config = Get-Content -LiteralPath $publicPath -Raw | ConvertFrom-Json
if ($config.schema_version -ne 1 -or $config.server -ne 'discovery.ease-technologies.de') { throw 'Invalid bootstrap configuration' }
$expires = [DateTimeOffset]::Parse($config.expires_at)
if ($expires -le [DateTimeOffset]::UtcNow -or $expires -gt [DateTimeOffset]::UtcNow.AddHours(25)) { throw 'Bootstrap window expired or invalid' }
if ($config.notebook_public_key -notmatch '^ssh-(ed25519|rsa) [A-Za-z0-9+/=]+$') { throw 'Invalid notebook public key' }
if ($config.server_host_key -notmatch '^ssh-ed25519 [A-Za-z0-9+/=]+$') { throw 'Invalid pinned server host key' }
if ((Test-Path -LiteralPath $statePath) -or (Get-LocalUser -Name 'rmm-dev' -ErrorAction SilentlyContinue)) { throw 'Existing RMM bootstrap retained; do not overwrite or reset it' }
$existingSsh = Get-Service -Name sshd -ErrorAction SilentlyContinue
if ($existingSsh -and $existingSsh.Status -eq 'Running') { throw 'Existing running SSH service requires separate review' }
if (Get-ScheduledTask -TaskName 'RmmDevReverseTunnel' -ErrorAction SilentlyContinue) { throw 'Existing tunnel task retained' }
# Installs only the Windows optional OpenSSH capabilities. Never reboot or run
# an OS/package update. RestartNeeded stops before account/service provisioning.
foreach ($capability in @('OpenSSH.Client~~~~0.0.1.0', 'OpenSSH.Server~~~~0.0.1.0')) {
if ((Get-WindowsCapability -Online -Name $capability).State -ne 'Installed') {
$installed = Add-WindowsCapability -Online -Name $capability
if ($installed.RestartNeeded) { throw 'OpenSSH reports RestartNeeded; no reboot was initiated. Review before continuing.' }
}
}
[void](New-Item -ItemType Directory -Path $statePath); Protect-AdminFile $statePath
Copy-Item -LiteralPath $PSCommandPath -Destination (Join-Path $statePath 'Bootstrap-DevAccess.ps1')
Copy-Item -LiteralPath $publicPath -Destination (Join-Path $statePath 'bootstrap-public.json')
Write-Utf8 (Join-Path $statePath 'known_hosts') ('discovery.ease-technologies.de ' + $config.server_host_key + "`n")
$sshDirectory = Join-Path $env:WINDIR 'System32\OpenSSH'
$keygen = Join-Path $sshDirectory 'ssh-keygen.exe'
$keyPath = Join-Path $statePath 'tunnel_ed25519'
$keyStart = New-Object Diagnostics.ProcessStartInfo
$keyStart.FileName = $keygen; $keyStart.Arguments = '-q -t ed25519 -N "" -f "' + $keyPath + '"'
$keyStart.UseShellExecute = $false; $keyStart.CreateNoWindow = $true
$keyProcess = [Diagnostics.Process]::Start($keyStart)
$keyProcess.WaitForExit()
if ($keyProcess.ExitCode -ne 0) { throw 'Tunnel key generation failed; retained bootstrap requires inspection' }
$keyProcess.Dispose(); Protect-AdminFile $keyPath
# Dedicated temporary local administrator; password stays in VM memory, SSH is
# public-key only. Notebook private key and cloud root credentials are not used.
$random = New-Object byte[] 48
$rng = [Security.Cryptography.RandomNumberGenerator]::Create(); $rng.GetBytes($random); $rng.Dispose()
$password = ConvertTo-SecureString ('Rmm!7' + [Convert]::ToBase64String($random)) -AsPlainText -Force
$account = New-LocalUser -Name 'rmm-dev' -Password $password -AccountExpires $expires.LocalDateTime -Description 'Temporary RMM development SSH access'
$password.Dispose(); [Array]::Clear($random, 0, $random.Length)
$adminGroup = Get-LocalGroup -SID 'S-1-5-32-544'
Add-LocalGroupMember -Group $adminGroup -Member $account
$sshData = Join-Path $env:ProgramData 'ssh'
[void](New-Item -ItemType Directory -Path $sshData -Force)
$sshdConfig = Join-Path $sshData 'sshd_config'
if (Test-Path -LiteralPath $sshdConfig) { Copy-Item -LiteralPath $sshdConfig -Destination (Join-Path $statePath 'sshd_config.before') }
$authorized = Join-Path $sshData 'administrators_authorized_keys'
if (Test-Path -LiteralPath $authorized) { Copy-Item -LiteralPath $authorized -Destination (Join-Path $statePath 'administrators_authorized_keys.before') }
Write-Utf8 $authorized ($config.notebook_public_key + "`n"); Protect-AdminFile $authorized
$serverConfig = @('Port 22222', 'ListenAddress 127.0.0.1', 'PubkeyAuthentication yes',
'PasswordAuthentication no', 'AuthenticationMethods publickey', 'AllowUsers rmm-dev',
'AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys',
'AllowTcpForwarding no', 'AllowAgentForwarding no', 'PermitTTY yes',
'Subsystem sftp sftp-server.exe') -join "`n"
Write-Utf8 $sshdConfig ($serverConfig + "`n"); Protect-AdminFile $sshdConfig
& $keygen -A | Out-Null
if ($LASTEXITCODE -ne 0) { throw 'SSH host key generation failed' }
& (Join-Path $sshDirectory 'sshd.exe') -t
if ($LASTEXITCODE -ne 0) { throw 'SSH configuration rejected; retained files require inspection' }
[void](New-Item -Path 'HKLM:\SOFTWARE\OpenSSH' -Force)
New-ItemProperty -Path 'HKLM:\SOFTWARE\OpenSSH' -Name DefaultShell -Value (Join-Path $env:WINDIR 'System32\WindowsPowerShell\v1.0\powershell.exe') -PropertyType String -Force | Out-Null
Set-Service -Name sshd -StartupType Automatic; Start-Service -Name sshd
Get-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -ErrorAction SilentlyContinue | Disable-NetFirewallRule
$taskScript = Join-Path $statePath 'Bootstrap-DevAccess.ps1'
$action = New-ScheduledTaskAction -Execute (Join-Path $env:WINDIR 'System32\WindowsPowerShell\v1.0\powershell.exe') -Argument ('-NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -File "' + $taskScript + '" -MaintainTunnel')
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -MultipleInstances IgnoreNew -ExecutionTimeLimit ([TimeSpan]::Zero) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
$principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest
$task = New-ScheduledTask -Action $action -Trigger (New-ScheduledTaskTrigger -AtStartup) -Settings $settings -Principal $principal
Register-ScheduledTask -TaskName 'RmmDevReverseTunnel' -InputObject $task | Out-Null
Start-ScheduledTask -TaskName 'RmmDevReverseTunnel'
$hostKeyPath = Join-Path $sshData 'ssh_host_ed25519_key.pub'
$hostPublic = ((Get-Content -LiteralPath $hostKeyPath -Raw).Trim() -split '\s+')[0..1] -join ' '
$tunnelPublic = ((Get-Content -LiteralPath ($keyPath + '.pub') -Raw).Trim() -split '\s+')[0..1] -join ' '
Write-Host 'Bitte nur diese oeffentliche Ausgabe zurueckgeben; der Tunnel verbindet nach Hinterlegung des Public Keys automatisch:'
[ordered]@{ windows_user='rmm-dev'; tunnel_public_key=$tunnelPublic; windows_host_public_key=$hostPublic;
expires_at=$config.expires_at; windows_architecture=$env:PROCESSOR_ARCHITECTURE } | ConvertTo-Json
& $keygen -lf $hostKeyPath
+81
View File
@@ -0,0 +1,81 @@
# Windows-11-Entwicklungszugang
Userentscheidung 2026-11-13 / Spezifikation 1.8: Windows darf parallel zur noch
offenen Linux-MVP-Abnahme entwickelt werden. Notebook-Host bleibt ohne Agent.
Dieser Bootstrap schafft SSH-Zugang zum Windows-Gast, keine RMM-Installation
und keine Ausnahme von der späteren WebUI-Jobgenehmigung.
## Vorbereitet und tatsächlich geprüft
`python3 deploy/windows/prepare_dev_access.py` hat auf dem endgültigen Server
das separate Systemkonto `rmm-win-tunnel` und dessen SSH-Matchprofil angelegt.
`sshd -t` und effektive Benutzerkonfiguration bestanden; Root-SSH-Konfiguration
vor/nach identisch. Nur Remote-TCP-Forwarding auf `127.0.0.1:22240`, keine
Shell/SFTP/Sitzungen (`MaxSessions 0`), keine Local-/Streamlocal-/Agentforwards,
keine Passwortanmeldung. Noch kein Windows-Key hinterlegt, kein Windows-
Tunnel/Administrationszugang nachgewiesen. Keine neue öffentliche Portfreigabe.
Public-only Paket lokal unter `devstate/windows-bootstrap/windows-dev-access.zip`:
dieses Skript und `bootstrap-public.json` mit Notebook-Public-Key, bereits
unabhängig geprüftem Server-ED25519-Hostkey und 24-Stunden-Frist. Kein privater
Schlüssel und kein Cloud-Rootzugang werden verteilt. Der neue Tunnelschlüssel
wird ausschließlich auf der Windows-VM erzeugt und verlässt sie nicht.
PowerShell-Parserprüfung mit offiziellem PowerShell 7.7.0 auf dem Notebook:
bestanden. **Kein nativer Windows-Ausführungs-/OpenSSH-/ACL-/Tasknachweis.**
Das Skript verwendet PowerShell-5.1-Syntax; die Ausführung auf Windows 11 muss
noch durch den User erfolgen. Vorhandene laufende SSH-Installation, gleichnamiger
Account/Task oder Teilbootstrap werden verweigert statt überschrieben.
## In der Windows-Test-VM ausführen (geplant, noch nicht nachgewiesen)
Paket auf die VM kopieren und entpacken. Erhöhte **64-Bit-PowerShell** im
entpackten Verzeichnis öffnen, Skript prüfen und dann:
```powershell
Unblock-File -LiteralPath .\Bootstrap-DevAccess.ps1
powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File .\Bootstrap-DevAccess.ps1
```
`RemoteSigned` gilt ausschließlich für den gestarteten Prozess; keine Änderung
der systemweiten Ausführungsrichtlinie und kein Umgehen einer Gruppenrichtlinie.
Es installiert nötigenfalls ausschließlich die optionalen OpenSSH-Funktionen.
`RestartNeeded` stoppt die Vorbereitung; kein automatischer Neustart/OS-Update.
Es erstellt den bis zur Paketfrist gültigen lokalen Administrator `rmm-dev`
mit zufälligem, ausschließlich VM-internem Passwort und Public-Key-only-SSH.
Authorized-Keys und Bootstrapstate sind nur für SYSTEM/Administratoren zugänglich
(SIDs statt sprachabhängiger Namen). Windows-SSH lauscht ausschließlich auf
`127.0.0.1:22222`; Standard-OpenSSH-Firewallregel wird deaktiviert. Konfigurations-
und Keydateien einer vorhandenen gestoppten Installation werden gesichert.
Ein SYSTEM-Task verbindet ausgehend zum bekannten Server und prüft dessen
Hostkey strikt. Reverse-Listener dort nur Loopback. Wiederverbindung alle 30s
ist ausschließlich Bootstraptransport, kein RMM-Job-Retry. Task beendet seinen
eigenen SSH-Prozess nach Frist; kein Reboot. Bestehende RMM-Policies bleiben.
Das Skript druckt ausschließlich öffentliche Registrierungsdaten:
`windows_user`, `tunnel_public_key`, `windows_host_public_key`, `expires_at`,
`windows_architecture` sowie Hostkeyfingerprint. Diese Ausgabe von der tatsächlichen
VM-Konsole zurückgeben; keine privaten Schlüssel/Passwörter übertragen.
Nach Hinterlegung des Tunnel-Public-Keys und Prüfung/Pinnen des Windows-Hostkeys
kann der Entwicklungsrechner über den Cloudserver mit seinem vorhandenen Key
auf den Windows-Administrator zugreifen. Native Nachweise folgen erst dann.
Grundlagen: [Microsoft OpenSSH-Installation](https://learn.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse),
[Windows-Konfiguration und Administrator-Key-ACL](https://learn.microsoft.com/en-us/windows-server/administration/openssh/openssh-server-configuration).
## Zugang bei Bedarf stoppen
Auf der Windows-VM als Administrator, ausschließlich eigene Bootstrapressourcen:
```powershell
Stop-ScheduledTask -TaskName RmmDevReverseTunnel
Unregister-ScheduledTask -TaskName RmmDevReverseTunnel -Confirm:$false
Disable-LocalUser -Name rmm-dev
Stop-Service -Name sshd
```
Backups/Hostkeys und Zustandsdateien erhalten. Cloud-Tunnelkey separat sperren;
keine pauschale Änderung anderer SSH-Zugänge. Vollständige Entfernung einer
vorherigen SSH-Konfiguration ist ein eigener kontrollierter Vorgang.
+74
View File
@@ -0,0 +1,74 @@
#!/usr/bin/env python3
"""Prepare public-only Win11 bootstrap bundle and a forwarding-only cloud user.
Windows generates its own tunnel key; no private key is distributed. Activation
requires the VM-console public key and host key, not a password in chat.
"""
import datetime as dt
import json
import os
from pathlib import Path
import sys
import uuid
import zipfile
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
import remote_client_bootstrap as transport
import cloud_mvp_acceptance as cloud
def provision(payload):
root=Path('/opt/rust-discovery/devstate/windows-bootstrap');require(not root.exists(),'existing Windows bootstrap must be reviewed')
require(subprocess.run(['getent','passwd','rmm-win-tunnel'],capture_output=True).returncode!=0,'existing tunnel account')
path=Path('/etc/ssh/sshd_config.d/80-rmm-windows-tunnel.conf');require(not path.exists(),'existing SSH profile')
def run(args,**kw):return subprocess.run(args,capture_output=True,check=True,timeout=30,**kw).stdout
def config(user):return run(['/usr/sbin/sshd','-T','-C','user='+user+',host=localhost,addr=127.0.0.1'])
before=config('root');root.mkdir(mode=0o700)
host=Path('/etc/ssh/ssh_host_ed25519_key.pub').read_text().split();public=' '.join(host[:2])
fingerprint=run(['ssh-keygen','-lf','/etc/ssh/ssh_host_ed25519_key.pub']).decode().split()[1]
require(fingerprint=='SHA256:+NEin4XJc3CbhjQi7/ZpMIgxOrXn8AT2tlpTaXW5quw','confirmed server host key drift')
run(['useradd','--system','--user-group','--create-home','--home-dir','/var/lib/rmm-win-tunnel','--shell','/usr/sbin/nologin','rmm-win-tunnel'])
home=Path('/var/lib/rmm-win-tunnel');os.chown(home,0,0);home.chmod(0o755)
ssh=home/'.ssh';ssh.mkdir(mode=0o755)
fd=os.open(ssh/'authorized_keys',os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o644);os.close(fd)
profile=('Match User rmm-win-tunnel\n AuthenticationMethods publickey\n PasswordAuthentication no\n'
' KbdInteractiveAuthentication no\n AllowTcpForwarding remote\n AllowStreamLocalForwarding no\n'
' PermitListen 127.0.0.1:22240\n PermitOpen none\n GatewayPorts no\n MaxSessions 0\n'
' PermitTTY no\n AllowAgentForwarding no\n X11Forwarding no\n PermitTunnel no\n PermitUserRC no\nMatch all\n')
fd=os.open(path,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o644)
with os.fdopen(fd,'w') as f:f.write(profile);f.flush();os.fsync(f.fileno())
run(['/usr/sbin/sshd','-t'])
require(config('root')==before,'root SSH profile changed')
effective=config('rmm-win-tunnel').decode()
for option in ('allowtcpforwarding remote','allowstreamlocalforwarding no','permitlisten 127.0.0.1:22240',
'permitopen none','gatewayports no','maxsessions 0','passwordauthentication no'):
require(option+'\n' in effective,'restricted SSH profile not effective')
run(['systemctl','reload','ssh'])
report=dict(account='rmm-win-tunnel',listener='127.0.0.1:22240',profile_valid=True,root_profile_unchanged=True,
pending_public_key=True,server_host_key=public,server_fingerprint=fingerprint,expires_at=payload['expires_at'])
p=root/'prepared.json';p.write_text(json.dumps(report));p.chmod(0o600)
return report
def main():
os.umask(0o077)
folder=cloud.ROOT/'devstate/windows-bootstrap';folder.mkdir(mode=0o700,exist_ok=False)
expires=(dt.datetime.now(dt.timezone.utc)+dt.timedelta(hours=24)).isoformat()
result=transport.rpc('server.conf',provision,dict(expires_at=expires))
# Derive only the public part for the explicitly requested Windows access.
cfg=transport.access.load_config(cloud.ROOT/'credentials/server.conf')
public=transport.execute(['ssh-keygen','-y','-f',str(Path(cfg['ssh_key_path']).expanduser())]).decode().split()
public=' '.join(public[:2])
data=dict(schema_version=1,server=transport.DOMAIN,server_host_key=result['server_host_key'],notebook_public_key=public,expires_at=expires)
bundle=folder/'windows-dev-access.zip'
with zipfile.ZipFile(bundle,'x',compression=zipfile.ZIP_DEFLATED) as archive:
archive.write(cloud.ROOT/'deploy/windows/Bootstrap-DevAccess.ps1','Bootstrap-DevAccess.ps1')
archive.writestr('bootstrap-public.json',json.dumps(data,indent=2))
cloud.contract.write_private(folder/'prepared.json',dict(result,bundle=str(bundle)))
print('Public-only Windows bootstrap bundle prepared; cloud profile verified; awaiting VM-console public keys')
require=transport.require
if __name__=='__main__':
try:main()
except Exception as error:
print('WINDOWS_BOOTSTRAP_INCOMPLETE:'+type(error).__name__);raise SystemExit(2) from None
+30
View File
@@ -1,5 +1,35 @@
# Tatsächlicher Implementierungsstand
## Sandbox-Fix nativ auf Cloud-VM geprüft — 2026-11-13
`deploy/cloud_apt_sandbox_upgrade.py` tatsächlich erfolgreich ausgeführt. Neuer
Helper und eingebetteter Provider kontrolliert installiert, alte Dateien/Proofs
versioniert gesichert. Beide Agentidentitäten/-journale, gemeinsames Ledger samt
Inode, fünf bekannte abgeschlossene Rootversuche, gesamtes `active/`, Archive,
Baselines und ursprünglicher Create-once-Marker vor/nach Installation identisch.
Keine neue Enrollmentgeneration, kein Reset, kein Paketversuch.
Tatsächlicher Readonly-Probe unter exakt gehärteter `rmm-apt-helper.service`
bestanden. Neuer Provider prüft im echten Worker, dass auch `/etc/rmm-remote`
und `/var/lib/rmm-agent-remote` verborgen/leer sind; Host-dpkg-Status nur kopiert.
Beide Helper danach zehnmal aktiv/running ohne Restart. Neue Runtime
`8d03b28975a90904bb4f5a0de43923ef23e27e97a3b6f1ce0251c1f00a21ddd2`;
neue Native-Readiness, ausdrücklich **keine** Paket-Acceptance. APT-Daemon nach
Probe wieder gestoppt, kein APT-Endpoint im Agentdrop-in aktiviert.
Cloud-Agent und allgemeiner Helper laufen mit unveränderter Gerätebindung weiter.
Private Reports: `devstate/cloud-apt-followup/sandbox-*.json`, VM-Backups unter
`/var/lib/rmm-bootstrap-history/cloud-sandbox-*`.
Der vorangegangene Dry-Run-Diagnoseschritt ist als `fbef0e4` auf Gitea gepusht.
Die konkrete APT-100-Ursache bleibt nach bestandenem Solver-Dry-Run weiter offen;
als Nächstes sichere Diagnose der Acquisitionphase ohne dpkg-Ausführung.
Windows parallel ausdrücklich erlaubt (Spezifikation 1.8): Public-only Bootstrap-
Paket vorbereitet, Cloud-Tunnelprofil validiert und Root-SSH unverändert geprüft.
PowerShell-AST-Parse bestanden. **Windows-Skript noch nicht auf VM ausgeführt**,
Warten auf öffentliche VM-Konsolenausgabe; keine Windows-Abnahme behauptet.
Details: [Windows-Entwicklungszugang](../deploy/windows/README.md).
## APT-Diagnose, erster Folgeschritt — 2026-11-13
Tatsächlicher neuer Root-Diagnosejob auf bestehender Cloud-VM, Server weiterhin