171 lines
12 KiB
Python
171 lines
12 KiB
Python
#!/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 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','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'))
|
|
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)
|
|
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')
|
|
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
|