fix: identify APT local-file handoff failure and verify Windows admin tunnel
Rust development slice / linux (push) Failing after 6s
Rust development slice / linux (push) Failing after 6s
This commit is contained in:
@@ -5,14 +5,14 @@ param([switch]$MaintainTunnel)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$statePath = Join-Path $env:ProgramData 'RmmDevAccess'
|
||||
|
||||
function Protect-AdminFile([string]$Path) {
|
||||
function Protect-AdminFile([string]$Path, [switch]$SystemOwner) {
|
||||
$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)
|
||||
if ($SystemOwner) { $acl.SetOwner($system) } else { $acl.SetOwner($admins) }
|
||||
foreach ($sid in @($admins, $system)) {
|
||||
if ($directory) {
|
||||
$rule = New-Object Security.AccessControl.FileSystemAccessRule($sid, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')
|
||||
@@ -109,19 +109,24 @@ Add-LocalGroupMember -Group $adminGroup -Member $account
|
||||
|
||||
$sshData = Join-Path $env:ProgramData 'ssh'
|
||||
[void](New-Item -ItemType Directory -Path $sshData -Force)
|
||||
Protect-AdminFile $sshData -SystemOwner
|
||||
$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
|
||||
Write-Utf8 $authorized ($config.notebook_public_key + "`n"); Protect-AdminFile $authorized -SystemOwner
|
||||
$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
|
||||
Write-Utf8 $sshdConfig ($serverConfig + "`n"); Protect-AdminFile $sshdConfig -SystemOwner
|
||||
& $keygen -A | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { throw 'SSH host key generation failed' }
|
||||
foreach ($name in @('ssh_host_rsa_key', 'ssh_host_ecdsa_key', 'ssh_host_ed25519_key')) {
|
||||
$hostPrivatePath = Join-Path $sshData $name
|
||||
if (Test-Path -LiteralPath $hostPrivatePath) { Protect-AdminFile $hostPrivatePath -SystemOwner }
|
||||
}
|
||||
& (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)
|
||||
|
||||
@@ -93,6 +93,31 @@ systemd-Timer stoppt den eigenen Downloadservice und schließt dessen Firewallpo
|
||||
Bootstrapwartung auf dem Server, kein autorisierender RMM-Job oder VM-Reboot.
|
||||
Windows-Ausführung weiterhin nicht nachgewiesen.
|
||||
|
||||
## Tatsächlich hergestellter Zugang / Reparaturen
|
||||
|
||||
Der User führte das erste Paket auf Windows aus. Dienst zunächst Exit 1067,
|
||||
Vordergrundstart dagegen erfolgreich. `Repair-DevAccess.ps1` prüft die bestehenden
|
||||
Skripte/Config gegen die ursprünglichen Hashes, sichert ACLs, setzt SYSTEM als
|
||||
Eigentümer und SYSTEM/Administratoren als einzige Zugriffsberechtigte für
|
||||
SSH-Verzeichnis, Config und Hostprivatekeys. Keine Schlüssel-/Kontoneuerzeugung.
|
||||
Danach Dienst tatsächlich `Running`, Hostkey unverändert. Erstbootstrap-Quelle
|
||||
für neue Pakete entsprechend korrigiert; historisches Public-ZIP unverändert,
|
||||
separates Repair-ZIP mit eigener expliziter Downloadroute veröffentlicht.
|
||||
|
||||
Cloud-Public-Key registriert; anfänglich ungültige Option `permitopen="none"`
|
||||
aus `authorized_keys` entfernt. Sie ist ausschließlich im sshd-Matchprofil gültig
|
||||
und dort unverändert aktiv. Zusätzlich öffentliche `.ssh`-Directorymodi explizit
|
||||
gesetzt, statt sie einer umask zu überlassen. Remote-only/PermitListen/MaxSessions
|
||||
bleiben erhalten. Private Keys wurden nicht übertragen.
|
||||
|
||||
Windows-Tunnel anschließend automatisch durch den Hintergrundtask aufgebaut.
|
||||
Notebook-SSH über Cloud-Loopback mit unabhängig aus der VM-Konsole bestätigtem
|
||||
Hostkey und vorhandenem Notebook-Key erfolgreich. Echt beobachtet: **Windows 11
|
||||
Pro, Build 26300, 64 Bit, Administrator=true**. Zugangsdaten nur unter
|
||||
`credentials/windows-dev-access.json`, Belege unter `devstate/windows-bootstrap/`.
|
||||
**Noch kein RMM-Windows-Client installiert/enrolled/abgenommen.** Keine Änderung
|
||||
am Notebook-Host als reinem Entwicklungsrechner.
|
||||
|
||||
## Zugang bei Bedarf stoppen
|
||||
|
||||
Auf der Windows-VM als Administrator, ausschließlich eigene Bootstrapressourcen:
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
#requires -Version 5.1
|
||||
#requires -RunAsAdministrator
|
||||
[CmdletBinding()]
|
||||
param()
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$statePath = Join-Path $env:ProgramData 'RmmDevAccess'
|
||||
$sshData = Join-Path $env:ProgramData 'ssh'
|
||||
$repairConfig = Get-Content -LiteralPath (Join-Path $PSScriptRoot 'repair-public.json') -Raw | ConvertFrom-Json
|
||||
$bootstrapScript = Join-Path $statePath 'Bootstrap-DevAccess.ps1'
|
||||
if ((Get-FileHash -LiteralPath $bootstrapScript -Algorithm SHA256).Hash.ToLowerInvariant() -ne $repairConfig.previous_bootstrap_sha256) { throw 'Existing bootstrap differs; no overwrite performed' }
|
||||
$config = Get-Content -LiteralPath (Join-Path $statePath 'bootstrap-public.json') -Raw | ConvertFrom-Json
|
||||
if ($config.server -ne 'discovery.ease-technologies.de' -or [DateTimeOffset]::Parse($config.expires_at) -le [DateTimeOffset]::UtcNow) { throw 'Existing bootstrap expired or invalid' }
|
||||
if (-not (Get-LocalUser -Name 'rmm-dev' -ErrorAction SilentlyContinue)) { throw 'Expected existing development account missing' }
|
||||
$sshdConfig = Join-Path $sshData 'sshd_config'
|
||||
if ((Get-FileHash -LiteralPath $sshdConfig -Algorithm SHA256).Hash.ToLowerInvariant() -ne $repairConfig.previous_sshd_config_sha256) { throw 'SSH configuration changed; retained for inspection' }
|
||||
$backupPath = Join-Path $statePath ('service-repair-' + [Guid]::NewGuid().ToString('N'))
|
||||
[void](New-Item -ItemType Directory -Path $backupPath)
|
||||
|
||||
function Protect-SystemPath([string]$Path) {
|
||||
$item = Get-Item -LiteralPath $Path
|
||||
if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'Reparse point refused' }
|
||||
if ($item.PSIsContainer) { $acl = New-Object Security.AccessControl.DirectorySecurity }
|
||||
else { $acl = New-Object Security.AccessControl.FileSecurity }
|
||||
$acl.SetAccessRuleProtection($true, $false)
|
||||
$system = New-Object Security.Principal.SecurityIdentifier 'S-1-5-18'
|
||||
$admins = New-Object Security.Principal.SecurityIdentifier 'S-1-5-32-544'
|
||||
$acl.SetOwner($system)
|
||||
foreach ($sid in @($system, $admins)) {
|
||||
if ($item.PSIsContainer) { $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
|
||||
}
|
||||
|
||||
$paths = @($sshData, $sshdConfig, (Join-Path $sshData 'administrators_authorized_keys'))
|
||||
foreach ($name in @('ssh_host_rsa_key', 'ssh_host_ecdsa_key', 'ssh_host_ed25519_key')) {
|
||||
$candidate = Join-Path $sshData $name
|
||||
if (Test-Path -LiteralPath $candidate) { $paths += $candidate }
|
||||
}
|
||||
$acls = @()
|
||||
foreach ($path in $paths) { $acls += [ordered]@{ path=$path; sddl=(Get-Acl -LiteralPath $path).Sddl } }
|
||||
$acls | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath (Join-Path $backupPath 'acls-before.json') -Encoding UTF8
|
||||
Copy-Item -LiteralPath $sshdConfig -Destination (Join-Path $backupPath 'sshd_config.before')
|
||||
foreach ($path in $paths) { Protect-SystemPath $path }
|
||||
Write-Host 'SSH directory, configuration and host-key ACLs set for SYSTEM and Administrators; keys preserved.'
|
||||
$sshd = Join-Path $env:WINDIR 'System32\OpenSSH\sshd.exe'
|
||||
& $sshd -t
|
||||
if ($LASTEXITCODE -ne 0) { throw 'SSH configuration rejected; no key/account reset performed' }
|
||||
try { Start-Service -Name sshd -ErrorAction Stop }
|
||||
catch {
|
||||
# Keep the original config/ACLs. Enable private startup logging for the
|
||||
# service context; do not reinstall/regenerate identities or loosen access.
|
||||
$logPath = Join-Path $sshData 'logs'
|
||||
[void](New-Item -ItemType Directory -Path $logPath -Force); Protect-SystemPath $logPath
|
||||
[IO.File]::AppendAllText($sshdConfig, "SyslogFacility LOCAL0`nLogLevel DEBUG3`n", (New-Object Text.UTF8Encoding($false)))
|
||||
try { Start-Service -Name sshd -ErrorAction Stop } catch { Write-Host 'Service still fails; private service-context log follows.' }
|
||||
Get-Content -LiteralPath (Join-Path $logPath 'sshd.log') -Tail 35 -ErrorAction SilentlyContinue
|
||||
if ((Get-Service -Name sshd).Status -ne 'Running') { throw 'SSH service still stopped; retain repair evidence and report the startup log' }
|
||||
}
|
||||
Set-Service -Name sshd -StartupType Automatic
|
||||
Get-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -ErrorAction SilentlyContinue | Disable-NetFirewallRule
|
||||
if (-not (Get-NetTCPConnection -State Listen -LocalAddress 127.0.0.1 -LocalPort 22222 -ErrorAction SilentlyContinue)) { throw 'Expected loopback SSH listener absent' }
|
||||
if (Get-ScheduledTask -TaskName 'RmmDevReverseTunnel' -ErrorAction SilentlyContinue) { throw 'Existing tunnel task retained; inspect instead of replacing' }
|
||||
$action = New-ScheduledTaskAction -Execute (Join-Path $env:WINDIR 'System32\WindowsPowerShell\v1.0\powershell.exe') -Argument ('-NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -File "' + $bootstrapScript + '" -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 (Join-Path $statePath 'tunnel_ed25519.pub') -Raw).Trim() -split '\s+')[0..1] -join ' '
|
||||
[ordered]@{ windows_user='rmm-dev'; tunnel_public_key=$tunnelPublic; windows_host_public_key=$hostPublic;
|
||||
expires_at=$config.expires_at; windows_architecture=$env:PROCESSOR_ARCHITECTURE; ssh_service='Running' } | ConvertTo-Json
|
||||
& (Join-Path $env:WINDIR 'System32\OpenSSH\ssh-keygen.exe') -lf $hostKeyPath
|
||||
@@ -14,9 +14,11 @@ def select_file(mode, request_path, config, now):
|
||||
if mode == 'acme':
|
||||
match = re.fullmatch(r'/\.well-known/acme-challenge/([A-Za-z0-9_-]{20,128})', request_path)
|
||||
return Path('/srv/rmm-bootstrap-acme') / match[1] if match else None
|
||||
if now >= dt.datetime.fromisoformat(config['expires_at']) or request_path != config['url_path']:
|
||||
if now >= dt.datetime.fromisoformat(config['expires_at']):
|
||||
return None
|
||||
return Path('/srv/rmm-bootstrap-download/windows-dev-access.zip')
|
||||
filename=config.get('public_files',{config['url_path']:'windows-dev-access.zip'}).get(request_path)
|
||||
if filename not in ('windows-dev-access.zip','windows-dev-repair.zip'):return None
|
||||
return Path('/srv/rmm-bootstrap-download')/filename
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
@@ -5,10 +5,14 @@ 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 argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import subprocess
|
||||
import shlex
|
||||
import time
|
||||
import uuid
|
||||
import zipfile
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
|
||||
@@ -28,7 +32,7 @@ def provision(payload):
|
||||
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)
|
||||
ssh=home/'.ssh';ssh.mkdir(mode=0o755);ssh.chmod(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'
|
||||
@@ -50,6 +54,11 @@ def provision(payload):
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--register-console');parser.add_argument('--probe-registered',action='store_true');args=parser.parse_args()
|
||||
if args.probe_registered:
|
||||
probe_registered(cloud.contract.protected_json(cloud.ROOT/'devstate/windows-bootstrap/console-registration.json'));return
|
||||
if args.register_console:
|
||||
register_console(Path(args.register_console));return
|
||||
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()
|
||||
@@ -67,6 +76,71 @@ def main():
|
||||
print('Public-only Windows bootstrap bundle prepared; cloud profile verified; awaiting VM-console public keys')
|
||||
|
||||
|
||||
def register_key(payload):
|
||||
import datetime as dt
|
||||
import re
|
||||
root=Path('/opt/rust-discovery/devstate/windows-bootstrap')
|
||||
prepared=json.loads((root/'prepared.json').read_text())
|
||||
require(prepared['pending_public_key'] is True and prepared['profile_valid'] is True,'known pending tunnel')
|
||||
require(payload['expires_at']==prepared['expires_at'],'VM/bootstrap expiry differs')
|
||||
expires=dt.datetime.fromisoformat(prepared['expires_at']).astimezone(dt.timezone.utc)
|
||||
require(dt.datetime.now(dt.timezone.utc)<expires,'tunnel enrollment window expired')
|
||||
require(re.fullmatch(r'ssh-ed25519 [A-Za-z0-9+/=]{68}',payload['public_key']) is not None,'canonical ED25519 public key required')
|
||||
p=Path('/var/lib/rmm-win-tunnel/.ssh/authorized_keys')
|
||||
require(not p.is_symlink() and p.stat().st_uid==0 and p.read_bytes()==b'','initial empty authorized keys required')
|
||||
# PermitOpen none belongs in sshd_config; authorized_keys only accepts a
|
||||
# host:port pair for permitopen. Match already denies all local forwarding.
|
||||
options='restrict,port-forwarding,permitlisten="127.0.0.1:22240",expiry-time="'+expires.strftime('%Y%m%d%H%M%SZ')+'" '
|
||||
next_path=p.with_suffix('.enroll-next')
|
||||
fd=os.open(next_path,os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_NOFOLLOW,0o644)
|
||||
with os.fdopen(fd,'w') as f:f.write(options+payload['public_key']+'\n');f.flush();os.fsync(f.fileno());os.fchmod(f.fileno(),0o644)
|
||||
os.replace(next_path,p)
|
||||
receipt=dict(public_key_registered=True,expires_at=prepared['expires_at'],listener='127.0.0.1:22240',shell_allowed=False)
|
||||
p=root/'registered.json';p.write_text(json.dumps(receipt));p.chmod(0o600)
|
||||
return receipt
|
||||
|
||||
|
||||
def register_console(file):
|
||||
import re
|
||||
import base64
|
||||
os.umask(0o077);data=cloud.contract.protected_json(file)
|
||||
require(data['windows_user']=='rmm-dev' and data['windows_architecture']=='AMD64' and data['ssh_service']=='Running','actual Windows console report required')
|
||||
for field in ('tunnel_public_key','windows_host_public_key'):
|
||||
require(re.fullmatch(r'ssh-ed25519 [A-Za-z0-9+/=]{68}',data[field]) is not None,'canonical public key required')
|
||||
folder=cloud.ROOT/'devstate/windows-bootstrap'
|
||||
pin=folder/'windows-host-key.pub';cloud.contract.write_private(folder/'console-registration.json',data)
|
||||
pin.write_text(data['windows_host_public_key']+'\n');pin.chmod(0o600)
|
||||
fingerprint=transport.execute(['ssh-keygen','-lf',str(pin)]).decode().split()[1]
|
||||
require(fingerprint=='SHA256:E663MwfdBF/ZS0/JZgk5Jctxzh2dfc9p/yECHw3AN+c','VM-console-confirmed host key differs')
|
||||
result=transport.rpc('server.conf',register_key,dict(public_key=data['tunnel_public_key'],expires_at=data['expires_at']))
|
||||
cloud.contract.write_private(folder/'tunnel-registered.json',result)
|
||||
known=cloud.ROOT/'credentials/windows-dev.known_hosts';require(not known.exists(),'existing Windows pin retained')
|
||||
known.write_text('rmm-windows-dev '+data['windows_host_public_key']+'\n');known.chmod(0o600)
|
||||
probe_registered(data)
|
||||
|
||||
|
||||
def probe_registered(data):
|
||||
import base64
|
||||
folder=cloud.ROOT/'devstate/windows-bootstrap';known=cloud.ROOT/'credentials/windows-dev.known_hosts'
|
||||
cfg=transport.access.load_config(cloud.ROOT/'credentials/server.conf');key=str(Path(cfg['ssh_key_path']).expanduser())
|
||||
jump=['ssh','-F','/dev/null','-T','-p',cfg.get('port','22'),'-i',key,'-o','StrictHostKeyChecking=yes','-o','BatchMode=yes',
|
||||
'-o','ForwardAgent=no','-o','IdentitiesOnly=yes','-W','127.0.0.1:22240',cfg['username']+'@'+cfg['address']]
|
||||
cmd=['ssh','-F','/dev/null','-T','-i',key,'-o','ProxyCommand='+shlex.join(jump),'-o','HostKeyAlias=rmm-windows-dev',
|
||||
'-o','UserKnownHostsFile='+str(known),'-o','GlobalKnownHostsFile=/dev/null','-o','StrictHostKeyChecking=yes',
|
||||
'-o','BatchMode=yes','-o','IdentitiesOnly=yes','-o','ForwardAgent=no','-o','ConnectTimeout=10','rmm-dev@127.0.0.1']
|
||||
script="$p=[Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent();$o=Get-CimInstance Win32_OperatingSystem;@{admin=$p.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator);os=$o.Caption;build=$o.BuildNumber;architecture=$o.OSArchitecture}|ConvertTo-Json -Compress"
|
||||
encoded=base64.b64encode(script.encode('utf-16le')).decode()
|
||||
end=time.monotonic()+90
|
||||
while True:
|
||||
process=subprocess.run(cmd+['powershell.exe -NoProfile -NonInteractive -EncodedCommand '+encoded],capture_output=True,timeout=20)
|
||||
if process.returncode==0:break
|
||||
require(time.monotonic()<end,'tunnel/Windows access not ready; retain keys and registration, no reinstall');time.sleep(5)
|
||||
observed=json.loads(process.stdout.decode('utf-8-sig').strip());require(observed['admin'] is True,'Windows administrator token required')
|
||||
cloud.contract.write_private(folder/'windows-access-verified.json',dict(observed,host_key_verified=True,private_keys_transferred=False,rmm_client_installed=False))
|
||||
cloud.contract.write_private(cloud.ROOT/'credentials/windows-dev-access.json',dict(ssh_prefix=cmd,expires_at=data['expires_at']))
|
||||
print(dict(windows_access_verified=True,**observed))
|
||||
|
||||
|
||||
require=transport.require
|
||||
if __name__=='__main__':
|
||||
try:main()
|
||||
|
||||
@@ -111,8 +111,29 @@ def add_expiry_cleanup(payload):
|
||||
return dict(expiry_cleanup_armed=True,expires_at=config['expires_at'])
|
||||
|
||||
|
||||
def add_repair(payload):
|
||||
script=Path('/usr/local/libexec/rmm-bootstrap-public.py');config_path=Path('/etc/rmm-bootstrap-download.json')
|
||||
require(not script.is_symlink() and script.stat().st_uid==0 and hashlib.sha256(script.read_bytes()).hexdigest()==payload['previous_code_sha256'],'public server code drift')
|
||||
config=json.loads(config_path.read_text());require('public_files' not in config,'existing additional publication retained')
|
||||
raw=base64.b64decode(payload['bundle'],validate=True)
|
||||
require(len(raw)<262144 and hashlib.sha256(raw).hexdigest()==payload['sha256'],'repair bundle mismatch')
|
||||
root=Path('/opt/rmm-bootstrap-download')
|
||||
def create(p,data,mode):
|
||||
fd=os.open(p,os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_NOFOLLOW,mode)
|
||||
with os.fdopen(fd,'wb') as f:f.write(data);f.flush();os.fsync(f.fileno());os.fchmod(f.fileno(),mode)
|
||||
create(root/'public-server-before-repair.py',script.read_bytes(),0o600)
|
||||
create(root/'public-config-before-repair.json',config_path.read_bytes(),0o600)
|
||||
create(Path('/srv/rmm-bootstrap-download/windows-dev-repair.zip'),raw,0o644)
|
||||
url_path=config['url_path'].rsplit('/',1)[0]+'/windows-dev-repair.zip'
|
||||
config['public_files']={config['url_path']:'windows-dev-access.zip',url_path:'windows-dev-repair.zip'}
|
||||
next_config=config_path.with_suffix('.repair-next');create(next_config,json.dumps(config).encode(),0o644);os.replace(next_config,config_path)
|
||||
next_script=script.with_suffix('.repair-next');create(next_script,base64.b64decode(payload['code'],validate=True),0o755);os.replace(next_script,script)
|
||||
subprocess.run(['systemctl','restart','rmm-bootstrap-download.service'],capture_output=True,check=True)
|
||||
return dict(url='https://discovery.ease-technologies.de:8443'+url_path,sha256=payload['sha256'],expires_at=config['expires_at'])
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser();parser.add_argument('action',choices=('install','status','finish','cleanup-timer'));args=parser.parse_args();os.umask(0o077)
|
||||
parser=argparse.ArgumentParser();parser.add_argument('action',choices=('install','status','finish','cleanup-timer','repair'));args=parser.parse_args();os.umask(0o077)
|
||||
if args.action=='install':
|
||||
with __import__('zipfile').ZipFile(STATE/'windows-dev-access.zip') as archive:
|
||||
config=json.loads(archive.read('bootstrap-public.json'))
|
||||
@@ -126,6 +147,14 @@ def main():
|
||||
elif args.action=='cleanup-timer':
|
||||
result=cloud.bootstrap.rpc('server.conf',add_expiry_cleanup,{})
|
||||
cloud.contract.write_private(STATE/'publication-expiry.json',result);print(result)
|
||||
elif args.action=='repair':
|
||||
bundle=(STATE/'windows-dev-repair.zip').read_bytes()
|
||||
result=cloud.bootstrap.rpc('server.conf',add_repair,dict(bundle=base64.b64encode(bundle).decode(),sha256=hashlib.sha256(bundle).hexdigest(),
|
||||
previous_code_sha256=(STATE/'download-service-before-repair.sha256').read_text(),
|
||||
code=base64.b64encode((cloud.ROOT/'deploy/windows/download_service.py').read_bytes()).decode()))
|
||||
with urllib.request.urlopen(result['url'],context=ssl.create_default_context(),timeout=15) as response:raw=response.read(262145)
|
||||
require(hashlib.sha256(raw).hexdigest()==result['sha256'],'downloaded repair mismatch')
|
||||
cloud.contract.write_private(STATE/'repair-published.json',result);print(result)
|
||||
else:
|
||||
r=cloud.bootstrap.rpc('server.conf',finish,{})
|
||||
published=cloud.contract.protected_json(STATE/'publication.json')
|
||||
|
||||
Reference in New Issue
Block a user