diff --git a/deploy/browser/cloud_apt_diagnostic.cjs b/deploy/browser/cloud_apt_diagnostic.cjs index 8da59d3..b1e0f63 100644 --- a/deploy/browser/cloud_apt_diagnostic.cjs +++ b/deploy/browser/cloud_apt_diagnostic.cjs @@ -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')); diff --git a/deploy/cloud_apt_followup.py b/deploy/cloud_apt_followup.py index c6141c1..7997681 100644 --- a/deploy/cloud_apt_followup.py +++ b/deploy/cloud_apt_followup.py @@ -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 diff --git a/deploy/linux/apt-hook-diagnostic.py b/deploy/linux/apt-hook-diagnostic.py new file mode 100644 index 0000000..a481935 --- /dev/null +++ b/deploy/linux/apt-hook-diagnostic.py @@ -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() diff --git a/deploy/linux/apt-local-file-hook-diagnostic.py b/deploy/linux/apt-local-file-hook-diagnostic.py new file mode 100644 index 0000000..a4be124 --- /dev/null +++ b/deploy/linux/apt-local-file-hook-diagnostic.py @@ -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() diff --git a/deploy/windows/Bootstrap-DevAccess.ps1 b/deploy/windows/Bootstrap-DevAccess.ps1 index 910bbbe..4803c92 100644 --- a/deploy/windows/Bootstrap-DevAccess.ps1 +++ b/deploy/windows/Bootstrap-DevAccess.ps1 @@ -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) diff --git a/deploy/windows/README.md b/deploy/windows/README.md index d8a429b..2c117f2 100644 --- a/deploy/windows/README.md +++ b/deploy/windows/README.md @@ -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: diff --git a/deploy/windows/Repair-DevAccess.ps1 b/deploy/windows/Repair-DevAccess.ps1 new file mode 100644 index 0000000..c66377d --- /dev/null +++ b/deploy/windows/Repair-DevAccess.ps1 @@ -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 diff --git a/deploy/windows/download_service.py b/deploy/windows/download_service.py index a2009d7..74ef222 100644 --- a/deploy/windows/download_service.py +++ b/deploy/windows/download_service.py @@ -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(): diff --git a/deploy/windows/prepare_dev_access.py b/deploy/windows/prepare_dev_access.py index 5e7eedb..058ba3e 100644 --- a/deploy/windows/prepare_dev_access.py +++ b/deploy/windows/prepare_dev_access.py @@ -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)