fix: identify APT local-file handoff failure and verify Windows admin tunnel
Rust development slice / linux (push) Failing after 6s

This commit is contained in:
2026-11-13 14:42:44 +01:00
parent a707d80e40
commit e18fae0e8a
12 changed files with 483 additions and 17 deletions
+2 -2
View File
@@ -13,8 +13,8 @@ function readPrivate(file) {
}
(async () => {
const file = path.resolve(process.argv[2]); const expected = readPrivate(file);
assert(expected.profile === 'dev/test' && ['apt_diagnostic_v1', 'apt_acquisition_v1'].includes(expected.case) && expected.expected_principal === 'simulated-testprincipal-a');
const sourceFile = expected.case === 'apt_diagnostic_v1' ? 'apt-diagnostic.py' : 'apt-acquisition-diagnostic.py';
assert(expected.profile === 'dev/test' && ['apt_diagnostic_v1', 'apt_acquisition_v1', 'apt_hook_v1', 'apt_local_hook_v1'].includes(expected.case) && expected.expected_principal === 'simulated-testprincipal-a');
const sourceFile = { apt_diagnostic_v1: 'apt-diagnostic.py', apt_acquisition_v1: 'apt-acquisition-diagnostic.py', apt_hook_v1: 'apt-hook-diagnostic.py', apt_local_hook_v1: 'apt-local-file-hook-diagnostic.py' }[expected.case];
const source = fs.readFileSync(path.join(root, 'deploy/linux', sourceFile), 'utf8');
const script = "exec /usr/bin/python3 -I - <<'RMM_APT_DIAGNOSTIC'\n" + source + '\nRMM_APT_DIAGNOSTIC\n';
const login = readPrivate(path.join(root, 'credentials/server-browser-login.json'));
+12 -7
View File
@@ -64,15 +64,18 @@ def diagnose(case='apt_diagnostic_v1'):
m=cloud.contract;settings=identity();require(evidence('gate')['unresolved']==0,'unresolved central job')
backend=cloud.Backend();device=backend.call('inventory.get_device',{k:settings[k] for k in ('tenant_id','asset_id')})
require(device['presence']=='online' and {'root:run_script','rmm.sync.v1','helper.root.v1'}<=set(device['capabilities']),'online root helper required')
require(case in ('apt_diagnostic_v1','apt_acquisition_v1'),'fixed diagnostic case')
source=(ROOT/'deploy/linux'/('apt-diagnostic.py' if case=='apt_diagnostic_v1' else 'apt-acquisition-diagnostic.py')).read_text()
require(case in ('apt_diagnostic_v1','apt_acquisition_v1','apt_hook_v1','apt_local_hook_v1'),'fixed diagnostic case')
sources=dict(apt_diagnostic_v1='apt-diagnostic.py',apt_acquisition_v1='apt-acquisition-diagnostic.py',apt_hook_v1='apt-hook-diagnostic.py',apt_local_hook_v1='apt-local-file-hook-diagnostic.py')
source=(ROOT/'deploy/linux'/sources[case]).read_text()
script="exec /usr/bin/python3 -I - <<'RMM_APT_DIAGNOSTIC'\n"+source+'\nRMM_APT_DIAGNOSTIC\n'
request=m.case_input('service_setup',settings)
request['parameters'].update(variants=[dict(os_family='linux',interpreter='posix_sh',encoding='utf-8',script_utf8=script)],
timeout_seconds=90,max_output_bytes=16384,expected_stdout=None)
request['reason']=('APT Exit 100 diagnosis: two dry-run solver checks; no package transaction; preserve failed attempt' if case=='apt_diagnostic_v1'
else 'APT Exit 100 acquisition diagnosis: download-only, copied dpkg DB, private scratch; no package transaction; preserve failed attempt')
folder=STATE/('diagnosis' if case=='apt_diagnostic_v1' else 'diagnosis-acquisition');folder.mkdir(mode=0o700,exist_ok=False)
if case=='apt_hook_v1':request['reason']='APT real hook protocol diagnosis: copied DB, hook always vetoes, independent dpkg effect guard; no transaction or native acceptance'
if case=='apt_local_hook_v1':request['reason']='APT local file acquisition hook comparison: copied DB, hook always vetoes, dpkg effect guard, IP sockets denied; no transaction or native acceptance'
folder=STATE/dict(apt_diagnostic_v1='diagnosis',apt_acquisition_v1='diagnosis-acquisition',apt_hook_v1='diagnosis-hook',apt_local_hook_v1='diagnosis-local-hook')[case];folder.mkdir(mode=0o700,exist_ok=False)
prepare=folder/'prepare.json';output=folder/'prepared.json'
common=dict(profile='dev/test',case=case,expected_principal='simulated-testprincipal-a',**settings)
m.write_private(prepare,dict(common,phase='prepare',request=request,output_file=str(output)))
@@ -98,8 +101,8 @@ def diagnose(case='apt_diagnostic_v1'):
def finish_diagnosis(case='apt_diagnostic_v1'):
"""Read/audit the existing fixed job only; never prepare or approve again."""
require(case in ('apt_diagnostic_v1','apt_acquisition_v1'),'fixed existing diagnostic case')
m=cloud.contract;settings=identity();folder=STATE/('diagnosis' if case=='apt_diagnostic_v1' else 'diagnosis-acquisition');path=folder/'checkpoint.json'
require(case in ('apt_diagnostic_v1','apt_acquisition_v1','apt_hook_v1','apt_local_hook_v1'),'fixed existing diagnostic case')
m=cloud.contract;settings=identity();folder=STATE/dict(apt_diagnostic_v1='diagnosis',apt_acquisition_v1='diagnosis-acquisition',apt_hook_v1='diagnosis-hook',apt_local_hook_v1='diagnosis-local-hook')[case];path=folder/'checkpoint.json'
checkpoint=m.protected_json(path);plan=checkpoint['plan'];job=plan['jobs'][0]
require(all(checkpoint[k]==settings[k] for k in settings),'diagnostic target changed')
operation=dict(operation_id=checkpoint['operation_id']);common=checkpoint;backend=cloud.Backend()
@@ -127,10 +130,12 @@ def close():
if __name__=='__main__':
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=('activate','diagnose','finish','diagnose-acquisition','finish-acquisition','close'));args=parser.parse_args()
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=('activate','diagnose','finish','diagnose-acquisition','finish-acquisition','diagnose-hook','finish-hook','diagnose-local-hook','finish-local-hook','close'));args=parser.parse_args()
try:
os.umask(0o077);STATE.mkdir(mode=0o700,exist_ok=True)
dict(activate=activate,diagnose=diagnose,finish=finish_diagnosis,close=close,
**{'diagnose-acquisition':lambda:diagnose('apt_acquisition_v1'),'finish-acquisition':lambda:finish_diagnosis('apt_acquisition_v1')})[args.action]()
**{'diagnose-acquisition':lambda:diagnose('apt_acquisition_v1'),'finish-acquisition':lambda:finish_diagnosis('apt_acquisition_v1'),
'diagnose-hook':lambda:diagnose('apt_hook_v1'),'finish-hook':lambda:finish_diagnosis('apt_hook_v1'),
'diagnose-local-hook':lambda:diagnose('apt_local_hook_v1'),'finish-local-hook':lambda:finish_diagnosis('apt_local_hook_v1')})[args.action]()
except Exception as error:
print('APT_FOLLOWUP_INCOMPLETE:'+type(error).__name__);raise SystemExit(2) from None
+82
View File
@@ -0,0 +1,82 @@
"""Capture a real APT v3 hook, always veto, and run pure validators only.
Copied dpkg database/private scratch; a second guard forbids every dpkg effect.
Never calls the provider hook/execute/native-acceptance or writes its handoff.
"""
import dataclasses
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
def sha(data):return hashlib.sha256(data).hexdigest()
def preserved():
base=Path('/var/lib/rmm-apt-transaction')
paths=[Path('/var/lib/dpkg/status'),base/'bootstrap-attempt-rmm-apt-fixture-install-1.0.json']
paths.extend(p for p in (base/'active').rglob('*') if p.is_file())
return {str(p):sha(p.read_bytes()) for p in paths}
def main():
os.umask(0o077)
base=Path('/var/lib/rmm-apt-transaction');before=preserved()
spec=importlib.util.spec_from_file_location('rmm_apt_hook_diagnostic','/usr/lib/rmm-apt-transaction/apt_transaction.py')
provider=importlib.util.module_from_spec(spec);sys.modules[spec.name]=provider;spec.loader.exec_module(provider)
transaction=provider.ResolvedAptTransaction.parse(json.loads((base/'active/expectation.json').read_text()))
assert transaction.recipe_id=='rmm-apt-fixture-install-1.0'
package=transaction.packages[0];assert sha(Path(package.archive_path).read_bytes())==package.sha256
result=dict(schema_version=1,diagnostic_only=True,transaction_executed=False,hook_always_veto=True,dpkg_effect_guard=True)
with tempfile.TemporaryDirectory(prefix='rmm-apt-hook-') as temp:
work=Path(temp)
for name in ('empty','lists','cache','log','state','dpkg'):(work/name).mkdir(mode=0o700)
(work/'dpkg/status').write_bytes(Path('/var/lib/dpkg/status').read_bytes())
collector=work/'collector';guard=work/'dpkg-guard'
collector.write_text('#!/usr/bin/python3 -I\nimport os,sys,json\nfrom pathlib import Path\ntry:\n'
' data=sys.stdin.buffer.read(1048577)\n Path('+repr(str(work/'protocol'))+').write_bytes(data)\n'
' Path('+repr(str(work/'hook-env.json'))+').write_text(json.dumps({k:os.environ.get(k) for k in ("APT_HOOK_INFO_FD","DPKG_FRONTEND_LOCKED")}))\n'
'finally:\n os._exit(73)\n');collector.chmod(0o700)
guard.write_text('#!/usr/bin/python3 -I\nimport os,re,sys\nfrom pathlib import Path\n'
'if len(sys.argv)==2 and (sys.argv[1] in ("--version","--print-architecture","--print-foreign-architectures") or re.fullmatch(r"--assert-[a-z0-9-]+",sys.argv[1])):\n'
' os.execve("/usr/bin/dpkg",["/usr/bin/dpkg",sys.argv[1]],dict(os.environ))\n'
'Path('+repr(str(work/'dpkg-effect-denied'))+').touch()\nsys.exit(75)\n');guard.chmod(0o700)
original=(base/'active/apt.conf').read_text()
text='\n'.join(line for line in original.splitlines() if not line.startswith(('DPkg::Pre-Install-Pkgs','DPkg::Tools::Options')))+'\n'
text=text.replace(str(base/'active'),str(work)).replace(str(base/'log'),str(work/'log')).replace(str(base/'state'),str(work/'state'))
text=text.replace('/var/lib/dpkg/status',str(work/'dpkg/status')).replace('Dir::Bin::dpkg "/usr/bin/dpkg";','Dir::Bin::dpkg "'+str(guard)+'";')
text+='DPkg::Pre-Install-Pkgs { "'+str(collector)+'"; };\nDPkg::Tools::Options::'+str(collector)+'::Version "3";\nDPkg::Tools::Options::'+str(collector)+'::InfoFD "0";\n'
(work/'apt.conf').write_text(text)
env=dict(PATH='/usr/sbin:/usr/bin:/sbin:/bin',LC_ALL='C',HOME='/root',DEBIAN_FRONTEND='noninteractive',APT_CONFIG=str(work/'apt.conf'))
with tempfile.TemporaryFile() as out,tempfile.TemporaryFile() as err:
process=subprocess.run(['/usr/bin/apt-get','--yes','--no-remove','--no-install-recommends','--no-download','install','--',package.archive_path],
env=env,stdin=subprocess.DEVNULL,stdout=out,stderr=err,timeout=25)
result['apt_exit_code']=process.returncode
result['dpkg_effect_requested']=(work/'dpkg-effect-denied').exists()
result['hook_reached']=(work/'protocol').exists()
if result['hook_reached']:
raw=(work/'protocol').read_bytes();result['hook_env']=json.loads((work/'hook-env.json').read_text())
try:
config,actions=provider.parse_protocol3(raw);result['protocol_parse']='passed'
result['actions']=[dataclasses.asdict(a) for a in actions]
normalized=[]
for key,value in config:
key=key.replace(str(collector),provider.HOOK)
value=value.replace(str(collector),provider.HOOK).replace(str(guard),'/usr/bin/dpkg')
value=value.replace(str(work/'dpkg/status'),'/var/lib/dpkg/status')
normalized.append((key,value))
for name,function in (('config_validate',lambda:provider.check_hook_config(normalized)),('action_validate',lambda:provider.validate_actions(transaction,actions))):
try:function();result[name]='passed'
except provider.Veto as error:result[name]=str(error)
except provider.Veto as error:result['protocol_parse']=str(error)
assert process.returncode!=0 and not result['dpkg_effect_requested']
assert preserved()==before and not Path('/usr/share/rmm-mvp-test/version').exists()
result['preserved_state']=True;print(json.dumps(result))
if __name__=='__main__':main()
@@ -0,0 +1,92 @@
"""Capture a real APT v3 hook, always veto, and run pure validators only.
Copied dpkg database/private scratch; a second guard forbids every dpkg effect.
Never calls the provider hook/execute/native-acceptance or writes its handoff.
"""
import dataclasses
import socket
import errno
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
def sha(data):return hashlib.sha256(data).hexdigest()
def preserved():
base=Path('/var/lib/rmm-apt-transaction')
paths=[Path('/var/lib/dpkg/status'),base/'bootstrap-attempt-rmm-apt-fixture-install-1.0.json']
paths.extend(p for p in (base/'active').rglob('*') if p.is_file())
return {str(p):sha(p.read_bytes()) for p in paths}
def main():
os.umask(0o077)
# Permit local file acquisition only in this always-vetoing diagnostic.
# Kernel AF restrictions still deny both IP families; never install.
for family in (socket.AF_INET, socket.AF_INET6):
try:
connection=socket.socket(family,socket.SOCK_STREAM);connection.close()
except OSError as error:
assert error.errno in (errno.EAFNOSUPPORT,errno.EPERM,errno.EACCES)
else:raise AssertionError("IP socket unexpectedly permitted")
base=Path('/var/lib/rmm-apt-transaction');before=preserved()
spec=importlib.util.spec_from_file_location('rmm_apt_hook_diagnostic','/usr/lib/rmm-apt-transaction/apt_transaction.py')
provider=importlib.util.module_from_spec(spec);sys.modules[spec.name]=provider;spec.loader.exec_module(provider)
transaction=provider.ResolvedAptTransaction.parse(json.loads((base/'active/expectation.json').read_text()))
assert transaction.recipe_id=='rmm-apt-fixture-install-1.0'
package=transaction.packages[0];assert sha(Path(package.archive_path).read_bytes())==package.sha256
result=dict(schema_version=1,diagnostic_only=True,transaction_executed=False,hook_always_veto=True,dpkg_effect_guard=True,ip_families_denied=True,local_file_acquisition=True)
with tempfile.TemporaryDirectory(prefix='rmm-apt-hook-') as temp:
work=Path(temp)
for name in ('empty','lists','cache','log','state','dpkg'):(work/name).mkdir(mode=0o700)
(work/'dpkg/status').write_bytes(Path('/var/lib/dpkg/status').read_bytes())
collector=work/'collector';guard=work/'dpkg-guard'
collector.write_text('#!/usr/bin/python3 -I\nimport os,sys,json\nfrom pathlib import Path\ntry:\n'
' data=sys.stdin.buffer.read(1048577)\n Path('+repr(str(work/'protocol'))+').write_bytes(data)\n'
' Path('+repr(str(work/'hook-env.json'))+').write_text(json.dumps({k:os.environ.get(k) for k in ("APT_HOOK_INFO_FD","DPKG_FRONTEND_LOCKED")}))\n'
'finally:\n os._exit(73)\n');collector.chmod(0o700)
guard.write_text('#!/usr/bin/python3 -I\nimport os,re,sys\nfrom pathlib import Path\n'
'if len(sys.argv)==2 and (sys.argv[1] in ("--version","--print-architecture","--print-foreign-architectures") or re.fullmatch(r"--assert-[a-z0-9-]+",sys.argv[1])):\n'
' os.execve("/usr/bin/dpkg",["/usr/bin/dpkg",sys.argv[1]],dict(os.environ))\n'
'Path('+repr(str(work/'dpkg-effect-denied'))+').touch()\nsys.exit(75)\n');guard.chmod(0o700)
original=(base/'active/apt.conf').read_text()
text='\n'.join(line for line in original.splitlines() if not line.startswith(('DPkg::Pre-Install-Pkgs','DPkg::Tools::Options')))+'\n'
text=text.replace(str(base/'active'),str(work)).replace(str(base/'log'),str(work/'log')).replace(str(base/'state'),str(work/'state'))
text=text.replace('/var/lib/dpkg/status',str(work/'dpkg/status')).replace('Dir::Bin::dpkg "/usr/bin/dpkg";','Dir::Bin::dpkg "'+str(guard)+'";')
text+='DPkg::Pre-Install-Pkgs { "'+str(collector)+'"; };\nDPkg::Tools::Options::'+str(collector)+'::Version "3";\nDPkg::Tools::Options::'+str(collector)+'::InfoFD "0";\n'
(work/'apt.conf').write_text(text)
env=dict(PATH='/usr/sbin:/usr/bin:/sbin:/bin',LC_ALL='C',HOME='/root',DEBIAN_FRONTEND='noninteractive',APT_CONFIG=str(work/'apt.conf'))
with tempfile.TemporaryFile() as out,tempfile.TemporaryFile() as err:
process=subprocess.run(['/usr/bin/apt-get','--yes','--no-remove','--no-install-recommends','install','--',package.archive_path],
env=env,stdin=subprocess.DEVNULL,stdout=out,stderr=err,timeout=25)
result['apt_exit_code']=process.returncode
result['dpkg_effect_requested']=(work/'dpkg-effect-denied').exists()
result['hook_reached']=(work/'protocol').exists()
if result['hook_reached']:
raw=(work/'protocol').read_bytes();result['hook_env']=json.loads((work/'hook-env.json').read_text())
try:
config,actions=provider.parse_protocol3(raw);result['protocol_parse']='passed'
result['actions']=[dataclasses.asdict(a) for a in actions]
normalized=[]
for key,value in config:
key=key.replace(str(collector),provider.HOOK)
value=value.replace(str(collector),provider.HOOK).replace(str(guard),'/usr/bin/dpkg')
value=value.replace(str(work/'dpkg/status'),'/var/lib/dpkg/status')
normalized.append((key,value))
for name,function in (('config_validate',lambda:provider.check_hook_config(normalized)),('action_validate',lambda:provider.validate_actions(transaction,actions))):
try:function();result[name]='passed'
except provider.Veto as error:result[name]=str(error)
except provider.Veto as error:result['protocol_parse']=str(error)
assert process.returncode!=0 and not result['dpkg_effect_requested']
assert preserved()==before and not Path('/usr/share/rmm-mvp-test/version').exists()
result['preserved_state']=True;print(json.dumps(result))
if __name__=='__main__':main()
+9 -4
View File
@@ -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)
+25
View File
@@ -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:
+76
View File
@@ -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
+4 -2
View File
@@ -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():
+75 -1
View File
@@ -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()
+30 -1
View File
@@ -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')