feat: publish expiring Windows bootstrap download over verified HTTPS
Rust development slice / linux (push) Failing after 7s

This commit is contained in:
2026-11-13 14:12:15 +01:00
parent f3cc5b7cbf
commit 548739ea45
5 changed files with 289 additions and 0 deletions
+28
View File
@@ -65,6 +65,34 @@ auf den Windows-Administrator zugreifen. Native Nachweise folgen erst dann.
Grundlagen: [Microsoft OpenSSH-Installation](https://learn.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse),
[Windows-Konfiguration und Administrator-Key-ACL](https://learn.microsoft.com/en-us/windows-server/administration/openssh/openssh-server-configuration).
## Öffentlicher Download auf dem Cloudserver — tatsächlich geprüft
Auf Userwunsch Public-only Paket separat auf HTTPS **8443**, ausschließlich ein
exakter Downloadpfad bis Paketablauf. Gültige öffentliche Let's-Encrypt-Kette
mit normalem externem Truststore geprüft; heruntergeladene Bytes SHA256-identisch.
RMM-TLS/mTLS auf 443, Verwaltungszugang und Client-Truststores unverändert.
Keine Secrets im Bundle. Link und Belege geschützt unter
`devstate/windows-bootstrap/{publication.json,published-verified.json}`.
`deploy/windows/publish_bootstrap.py`: ACME mit gepinntem, geprüftem
acme-tiny-Commit `dc2c102314a56580facafce2249b292cebcfc42b`; Account-/Domainkeys
bleiben auf dem Server in rootgeschütztem Verzeichnis. HTTP80 nur für ACME,
danach tatsächlich gestoppt und Firewallregel entfernt. Downloadserver mit
DynamicUser, readonly System, separaten systemd-Credentials für TLS-Key und
maximal 16 gleichzeitigen Verbindungen. Kein beliebiges Dateisystemhosting.
Ein späterer Verbindungsversuch traf zunächst auf eine blockierende TLS-Annahme.
Server korrigiert: Timeout/Handshake je begrenztem Worker, Listener blockiert
nicht mehr. Danach externer HTTPS-Download während gleichzeitig offener langsamer
TCP-Verbindung erfolgreich; `/`, `/etc/passwd`, `/auth/config` und codierter
Traversalpfad jeweils 404. Drei lokale Pfad-/Frist-/ACME-Guards bestanden.
Öffentliche Freigabe endet **2026-11-14 12:55:31 UTC**. Aktiver persistenter
systemd-Timer stoppt den eigenen Downloadservice und schließt dessen Firewallport
8443; auch die Anwendung verweigert nach Frist weitere Downloads. Dies ist
Bootstrapwartung auf dem Server, kein autorisierender RMM-Job oder VM-Reboot.
Windows-Ausführung weiterhin nicht nachgewiesen.
## Zugang bei Bedarf stoppen
Auf der Windows-VM als Administrator, ausschließlich eigene Bootstrapressourcen:
+69
View File
@@ -0,0 +1,69 @@
"""Temporary public-only bootstrap/challenge server; no arbitrary file serving."""
import argparse
import datetime as dt
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import os
from pathlib import Path
import re
import ssl
import threading
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']:
return None
return Path('/srv/rmm-bootstrap-download/windows-dev-access.zip')
def main():
parser=argparse.ArgumentParser();parser.add_argument('--mode',choices=('acme','download'),required=True);args=parser.parse_args()
config={} if args.mode=='acme' else json.loads(Path('/etc/rmm-bootstrap-download.json').read_text())
class Handler(BaseHTTPRequestHandler):
server_version='RMMBootstrap';sys_version=''
def setup(self):
self.request.settimeout(5)
if self.server.tls_context is not None:
self.request=self.server.tls_context.wrap_socket(self.request,server_side=True)
super().setup()
def log_message(self,*args):pass
def do_GET(self):self.send_file(False)
def do_HEAD(self):self.send_file(True)
def send_file(self,head):
path=select_file(args.mode,self.path,config,dt.datetime.now(dt.timezone.utc))
if path is None or path.is_symlink() or not path.is_file():self.send_error(404);return
size=path.stat().st_size
if size>262144:self.send_error(404);return
self.send_response(200)
self.send_header('Content-Length',str(size));self.send_header('Cache-Control','no-store')
self.send_header('X-Content-Type-Options','nosniff')
self.send_header('Content-Type','application/zip' if args.mode=='download' else 'text/plain')
if args.mode=='download':self.send_header('Content-Disposition','attachment; filename="windows-dev-access.zip"')
self.end_headers()
if not head:self.wfile.write(path.read_bytes())
class Server(ThreadingHTTPServer):
daemon_threads=True
request_queue_size=32
slots=threading.BoundedSemaphore(16)
tls_context=None
def process_request(self,request,address):
if not self.slots.acquire(blocking=False):self.shutdown_request(request);return
try:super().process_request(request,address)
except Exception:self.slots.release();raise
def process_request_thread(self,request,address):
try:super().process_request_thread(request,address)
finally:self.slots.release()
def handle_error(self,*args):pass
server=Server(('0.0.0.0',80 if args.mode=='acme' else 8443),Handler)
if args.mode=='download':
credentials=Path(os.environ['CREDENTIALS_DIRECTORY'])
context=ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER);context.minimum_version=ssl.TLSVersion.TLSv1_2
context.load_cert_chain(credentials/'chain.pem',credentials/'key.pem')
server.tls_context=context
server.serve_forever()
if __name__=='__main__':main()
+141
View File
@@ -0,0 +1,141 @@
#!/usr/bin/env python3
"""Serve only the public Windows bundle with trusted HTTPS, separate from RMM.
HTTP80 is temporary ACME challenge transport, closed after issuance. HTTPS8443
serves one exact path until bundle expiry. Project TLS/mTLS/ports are unchanged.
Private ACME/domain keys stay exclusively on the cloud server.
"""
import argparse
import base64
import hashlib
import json
import os
from pathlib import Path
import ssl
import sys
import urllib.request
import uuid
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
import cloud_mvp_acceptance as cloud
STATE=cloud.ROOT/'devstate/windows-bootstrap'
require=cloud.require
def install(payload):
root=Path('/opt/rmm-bootstrap-download');require(not root.exists(),'existing download installation retained')
for p in ('/srv/rmm-bootstrap-acme','/srv/rmm-bootstrap-download','/etc/rmm-bootstrap-download.json','/usr/local/libexec/rmm-bootstrap-public.py'):
require(not Path(p).exists(),'existing public download path')
raw=base64.b64decode(payload['bundle'],validate=True);code=base64.b64decode(payload['code'],validate=True);acme=base64.b64decode(payload['acme'],validate=True)
require(hashlib.sha256(raw).hexdigest()==payload['bundle_sha256'] and len(raw)<262144,'public bundle mismatch')
require(hashlib.sha256(acme).hexdigest()==payload['acme_sha256'],'reviewed ACME source mismatch')
root.mkdir(mode=0o700)
def create(p,data,mode=0o600):
fd=os.open(p,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,mode)
with os.fdopen(fd,'wb') as f:f.write(data);f.flush();os.fsync(f.fileno());os.fchmod(f.fileno(),mode)
def run(args):return subprocess.run(args,capture_output=True,check=True,timeout=30).stdout
for p in ('/srv/rmm-bootstrap-acme','/srv/rmm-bootstrap-download'):Path(p).mkdir(mode=0o755)
create(Path('/srv/rmm-bootstrap-download/windows-dev-access.zip'),raw,0o644)
create(Path('/usr/local/libexec/rmm-bootstrap-public.py'),code,0o755)
create(root/'acme_tiny.py',acme)
create(root/'source.json',json.dumps(dict(commit=payload['acme_commit'],sha256=payload['acme_sha256'])).encode())
create(Path('/etc/rmm-bootstrap-download.json'),json.dumps(dict(url_path=payload['url_path'],expires_at=payload['expires_at'])).encode(),0o644)
# Private keys are generated directly to files and never leave this host.
run(['openssl','genrsa','-out',str(root/'account.key'),'3072']);(root/'account.key').chmod(0o600)
run(['openssl','genpkey','-algorithm','EC','-pkeyopt','ec_paramgen_curve:P-256','-out',str(root/'domain.key')]);(root/'domain.key').chmod(0o600)
run(['openssl','req','-new','-sha256','-key',str(root/'domain.key'),'-subj','/CN=discovery.ease-technologies.de',
'-addext','subjectAltName=DNS:discovery.ease-technologies.de','-out',str(root/'domain.csr')])
common=('NoNewPrivileges=true\nPrivateTmp=true\nPrivateDevices=true\nProtectSystem=strict\nProtectHome=true\n'
'ProtectKernelTunables=true\nProtectKernelModules=true\nProtectControlGroups=true\nRestrictSUIDSGID=true\nUMask=0077\n')
units={
'rmm-bootstrap-acme.service':('[Unit]\nDescription=Temporary ACME challenge only\n[Service]\nDynamicUser=true\n'
'ExecStart=/usr/bin/python3 -I /usr/local/libexec/rmm-bootstrap-public.py --mode acme\n'
'AmbientCapabilities=CAP_NET_BIND_SERVICE\nCapabilityBoundingSet=CAP_NET_BIND_SERVICE\nRuntimeMaxSec=300s\n'+common),
'rmm-bootstrap-certificate.service':('[Unit]\nDescription=Issue bootstrap-only public TLS certificate\n[Service]\nType=oneshot\n'
'ExecStart=/usr/bin/python3 -I /opt/rmm-bootstrap-download/acme_tiny.py --account-key /opt/rmm-bootstrap-download/account.key '
'--csr /opt/rmm-bootstrap-download/domain.csr --acme-dir /srv/rmm-bootstrap-acme\n'
'StandardOutput=file:/opt/rmm-bootstrap-download/chain.pem\nStandardError=file:/opt/rmm-bootstrap-download/issue.log\n'
'TimeoutStartSec=180s\nCapabilityBoundingSet=\nReadWritePaths=/opt/rmm-bootstrap-download /srv/rmm-bootstrap-acme\n'+common+'UMask=0022\n'),
'rmm-bootstrap-download.service':('[Unit]\nDescription=Temporary public Windows bootstrap download only\n[Service]\nDynamicUser=true\n'
'ExecStart=/usr/bin/python3 -I /usr/local/libexec/rmm-bootstrap-public.py --mode download\n'
'LoadCredential=chain.pem:/opt/rmm-bootstrap-download/chain.pem\nLoadCredential=key.pem:/opt/rmm-bootstrap-download/domain.key\n'
'CapabilityBoundingSet=\nRuntimeMaxSec=24h\n'+common)
}
for name,unit in units.items():
p=Path('/etc/systemd/system')/name;create(p,unit.encode(),0o644);run(['systemd-analyze','verify',str(p)])
run(['systemctl','daemon-reload'])
run(['ufw','allow','proto','tcp','from','0.0.0.0/0','to','any','port','80'])
run(['systemctl','start','rmm-bootstrap-acme.service'])
run(['systemctl','start','--no-block','rmm-bootstrap-certificate.service'])
return dict(stage='issuing',url='https://discovery.ease-technologies.de:8443'+payload['url_path'],bundle_sha256=payload['bundle_sha256'],expires_at=payload['expires_at'])
def status(payload):
root=Path('/opt/rmm-bootstrap-download')
result=dict(status=subprocess.run(['systemctl','show','rmm-bootstrap-certificate.service','-p','ActiveState','-p','Result'],capture_output=True,text=True).stdout,
certificate_present=(root/'chain.pem').exists() and (root/'chain.pem').stat().st_size>0)
return result
def finish(payload):
root=Path('/opt/rmm-bootstrap-download')
def run(args):return subprocess.run(args,capture_output=True,check=True,timeout=30).stdout
run(['systemctl','stop','rmm-bootstrap-acme.service'])
run(['ufw','delete','allow','proto','tcp','from','0.0.0.0/0','to','any','port','80'])
run(['openssl','x509','-in',str(root/'chain.pem'),'-noout','-checkhost','discovery.ease-technologies.de'])
run(['openssl','verify','-CAfile','/etc/ssl/certs/ca-certificates.crt','-untrusted',str(root/'chain.pem'),str(root/'chain.pem')])
run(['ufw','allow','proto','tcp','from','0.0.0.0/0','to','any','port','8443'])
run(['systemctl','start','rmm-bootstrap-download.service'])
(root/'issue.log').chmod(0o600)
return dict(stage='download_started',http80_closed=True,certificate_verified=True,rmm_tls_unchanged=True)
def add_expiry_cleanup(payload):
import datetime as dt
config=json.loads(Path('/etc/rmm-bootstrap-download.json').read_text())
expires=dt.datetime.fromisoformat(config['expires_at']).astimezone(dt.timezone.utc)
require(dt.datetime.now(dt.timezone.utc)<expires<dt.datetime.now(dt.timezone.utc)+dt.timedelta(hours=25),'bounded future expiry required')
units={
'rmm-bootstrap-download-close.service':('[Unit]\nDescription=Close expired bootstrap download port\n[Service]\nType=oneshot\n'
'ExecStart=/usr/bin/systemctl stop rmm-bootstrap-download.service\n'
'ExecStart=/usr/sbin/ufw delete allow proto tcp from 0.0.0.0/0 to any port 8443\nNoNewPrivileges=true\n'),
'rmm-bootstrap-download-close.timer':('[Unit]\nDescription=Expire public bootstrap download\n[Timer]\nOnCalendar='+expires.strftime('%Y-%m-%d %H:%M:%S UTC')+
'\nPersistent=true\nUnit=rmm-bootstrap-download-close.service\n[Install]\nWantedBy=timers.target\n')
}
for name,unit in units.items():
path=Path('/etc/systemd/system')/name
fd=os.open(path,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o644)
with os.fdopen(fd,'w') as f:f.write(unit)
subprocess.run(['systemctl','daemon-reload'],capture_output=True,check=True)
subprocess.run(['systemctl','enable','--now','rmm-bootstrap-download-close.timer'],capture_output=True,check=True)
return dict(expiry_cleanup_armed=True,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)
if args.action=='install':
with __import__('zipfile').ZipFile(STATE/'windows-dev-access.zip') as archive:
config=json.loads(archive.read('bootstrap-public.json'))
acme=json.loads((STATE/'acme-source.json').read_text());bundle=(STATE/'windows-dev-access.zip').read_bytes()
payload=dict(bundle=base64.b64encode(bundle).decode(),bundle_sha256=hashlib.sha256(bundle).hexdigest(),
code=base64.b64encode((cloud.ROOT/'deploy/windows/download_service.py').read_bytes()).decode(),
acme=base64.b64encode((STATE/'acme_tiny.py').read_bytes()).decode(),acme_commit=acme['commit'],acme_sha256=acme['sha256'],
expires_at=config['expires_at'],url_path='/windows/'+uuid.uuid4().hex+'/windows-dev-access.zip')
r=cloud.bootstrap.rpc('server.conf',install,payload);cloud.contract.write_private(STATE/'publication.json',r);print(r)
elif args.action=='status':print(cloud.bootstrap.rpc('server.conf',status,{}))
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)
else:
r=cloud.bootstrap.rpc('server.conf',finish,{})
published=cloud.contract.protected_json(STATE/'publication.json')
raw=urllib.request.urlopen(published['url'],context=ssl.create_default_context(),timeout=15).read(262145)
require(hashlib.sha256(raw).hexdigest()==published['bundle_sha256'],'externally downloaded bundle differs')
cloud.contract.write_private(STATE/'published-verified.json',dict(r,**published,external_default_tls_verified=True))
print(dict(url=published['url'],external_default_tls_verified=True,sha256=published['bundle_sha256']))
require=cloud.require
if __name__=='__main__':
try:main()
except Exception as error:print('PUBLICATION_INCOMPLETE:'+type(error).__name__);raise SystemExit(2) from None
+17
View File
@@ -1,5 +1,22 @@
# Tatsächlicher Implementierungsstand
## Windows-Bootstrap zum HTTPS-Download bereitgestellt — 2026-11-13
Auf ausdrücklichen Userwunsch Public-only ZIP auf dem Cloudserver über einen
separaten, zeitlich begrenzten HTTPS-8443-Endpunkt bereitgestellt. Öffentlich
gültige Let's-Encrypt-Kette, extern mit unverändertem Systemtrust verifiziert;
heruntergeladener Bundlehash identisch. Root-ACME-/TLS-Schlüssel ausschließlich
auf dem Server, Downloadprozess als DynamicUser mit systemd-Credentials und
readonly System. Kein privater Schlüssel im ZIP, kein neuer RMM-/Verwaltungspfad.
RMM auf 443 unverändert. HTTP80 nach ACME tatsächlich wieder geschlossen.
Download bis 2026-11-14 12:55:31 UTC; persistenter Ablauf-Timer stoppt Service und
schließt Firewallport 8443. Blockierende erste TLS-Annahme korrigiert, anschließend
echter externer Download mit paralleler langsamer TCP-Verbindung erfolgreich.
Fremde Datei-/Administrations-/Traversalpfade 404; drei lokale Download-Guards
bestanden. Windows-Skript noch vom User auszuführen, keine native Windows-
Abnahme. Beschreibung: [Windows-Entwicklungszugang](../deploy/windows/README.md).
## Sandbox-Fix nativ auf Cloud-VM geprüft — 2026-11-13
`deploy/cloud_apt_sandbox_upgrade.py` tatsächlich erfolgreich ausgeführt. Neuer
+34
View File
@@ -0,0 +1,34 @@
"""Public bootstrap path/expiry regressions, without server/VM/network access."""
import datetime as dt
from pathlib import Path
import sys
import unittest
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'deploy/windows'))
from download_service import select_file
class DownloadGuards(unittest.TestCase):
def setUp(self):
self.now=dt.datetime(2026,11,13,12,tzinfo=dt.timezone.utc)
self.config=dict(url_path='/windows/fixed/windows-dev-access.zip',expires_at='2026-11-14T12:00:00+00:00')
def test_only_fixed_public_file_is_selected(self):
self.assertEqual(select_file('download',self.config['url_path'],self.config,self.now),
Path('/srv/rmm-bootstrap-download/windows-dev-access.zip'))
for path in ('/','/etc/passwd','/windows/../windows-dev-access.zip',self.config['url_path']+'?path=/etc/passwd',
'/windows/%2e%2e/windows-dev-access.zip','/windows/fixed/../../domain.key'):
with self.subTest(path=path):self.assertIsNone(select_file('download',path,self.config,self.now))
def test_expiry_has_no_grace_window(self):
for delta in (dt.timedelta(days=1),dt.timedelta(days=1,seconds=1)):
self.assertIsNone(select_file('download',self.config['url_path'],self.config,self.now+delta))
def test_acme_has_no_arbitrary_file_path(self):
token='a'*43
self.assertEqual(select_file('acme','/.well-known/acme-challenge/'+token,{},self.now),Path('/srv/rmm-bootstrap-acme')/token)
for path in ('/','/.well-known/acme-challenge/../../domain.key','/.well-known/acme-challenge/%2e%2e',
'/.well-known/acme-challenge/'+token+'?x=y'):
with self.subTest(path=path):self.assertIsNone(select_file('acme',path,{},self.now))
if __name__=='__main__':unittest.main()