#!/usr/bin/env python3 """Republish one public recovery ZIP for 45 minutes using existing bootstrap TLS. The expired original downloads remain unavailable. No ACME, port80, RMM deployment, SSH key or production TLS change. Lost replies use readback only. """ import argparse import base64 import datetime as dt import hashlib import json import os from pathlib import Path import ssl import sys import urllib.request import uuid import zipfile sys.path.insert(0, str(Path(__file__).resolve().parents[1])) import remote_client_bootstrap as transport ROOT = transport.ROOT STATE = ROOT / 'devstate/windows-recovery-publication' def server(p): import datetime as dt import stat cfg = Path('/etc/rmm-bootstrap-download.json') code = Path('/usr/local/libexec/rmm-bootstrap-public.py') history = Path('/opt/rmm-bootstrap-download') / ('recovery-' + str(uuid.UUID(p['id']))) def digest(path): return hashlib.sha256(path.read_bytes()).hexdigest() def run(args): return subprocess.run(args, capture_output=True, check=True, timeout=30).stdout def safe(path, mode): s = path.lstat() require(stat.S_ISREG(s.st_mode) and s.st_uid == 0 and stat.S_IMODE(s.st_mode) == mode and not path.is_symlink(), 'existing protected download file') safe(cfg, 0o644); safe(code, 0o755) def snapshot(): return dict(config_sha256=digest(cfg), code_sha256=digest(code), service_state=run(['systemctl', 'show', 'rmm-bootstrap-download.service', '-p', 'ActiveState', '--value']).decode().strip()) if p['action'] == 'readback': return dict(snapshot=snapshot(), history_present=history.exists(), completed=(history / 'completed.json').exists()) before = snapshot() if p['action'] == 'prepare': require(before['service_state'] == 'inactive', 'expired original download must be inactive') require(dt.datetime.fromisoformat(json.loads(cfg.read_text())['expires_at']) < dt.datetime.now(dt.timezone.utc), 'original download expired') require(before['code_sha256'] == p['old_code_sha256'], 'known reviewed original download server') run(['openssl', 'x509', '-in', '/opt/rmm-bootstrap-download/chain.pem', '-noout', '-checkhost', 'discovery.ease-technologies.de', '-checkend', '3600']) run(['openssl', 'verify', '-CAfile', '/etc/ssl/certs/ca-certificates.crt', '-untrusted', '/opt/rmm-bootstrap-download/chain.pem', '/opt/rmm-bootstrap-download/chain.pem']) return before require(p['action'] == 'publish' and before == p['before'] and before['service_state'] == 'inactive', 'same reviewed inactive download generation') expiry = dt.datetime.fromisoformat(p['expires_at']) require(dt.datetime.now(dt.timezone.utc) < expiry <= dt.datetime.now(dt.timezone.utc) + dt.timedelta(minutes=45), 'bounded new 45 minute download') require(not history.exists(), 'existing publication: readback only') raw = base64.b64decode(p['bundle'], validate=True) require(len(raw) < 262144 and hashlib.sha256(raw).hexdigest() == p['bundle_sha256'], 'exact public recovery archive') old_code = code.read_bytes() old = b"('windows-dev-access.zip','windows-dev-repair.zip')" new = b"('windows-dev-access.zip','windows-dev-repair.zip','windows-dev-access-recovery.zip')" require(old_code.count(old) == 1 and digest(code) == p['old_code_sha256'], 'one additional fixed recovery filename only') history.mkdir(mode=0o700) def write(path, data, mode): fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, mode) with os.fdopen(fd, 'wb') as out: out.write(data); out.flush(); os.fsync(out.fileno()); os.fchmod(out.fileno(), mode) write(history / 'intent.json', json.dumps({k: v for k, v in p.items() if k != 'bundle'}).encode(), 0o600) write(history / 'original-server.py', old_code, 0o600) write(history / 'original-config.json', cfg.read_bytes(), 0o600) archive = Path('/srv/rmm-bootstrap-download/windows-dev-access-recovery.zip') write(archive, raw, 0o644) next_cfg = cfg.parent / ('rmm-bootstrap-recovery-' + p['id'] + '.next') next_code = code.parent / ('rmm-bootstrap-recovery-' + p['id'] + '.next') write(next_cfg, json.dumps(dict(url_path=p['url_path'], expires_at=p['expires_at'], public_files={p['url_path']: archive.name})).encode(), 0o644) write(next_code, old_code.replace(old, new), 0o755) name = 'rmm-recovery-download-close-' + p['id'] service = '[Unit]\nDescription=Close temporary public recovery download\n[Service]\nType=oneshot\nExecStart=/usr/bin/systemctl stop rmm-bootstrap-download.service\nExecStart=/usr/sbin/ufw delete allow proto tcp from 0.0.0.0/0 to any port 8443\nNoNewPrivileges=true\n' timer = '[Unit]\nDescription=Expire public recovery download\n[Timer]\nOnCalendar=' + expiry.strftime('%Y-%m-%d %H:%M:%S UTC') + '\nPersistent=true\nUnit=' + name + '.service\n[Install]\nWantedBy=timers.target\n' for suffix, data in (('.service', service), ('.timer', timer)): unit = Path('/etc/systemd/system') / (name + suffix) write(unit, data.encode(), 0o644); run(['systemd-analyze', 'verify', str(unit)]) require(snapshot() == before, 'immediate original config/code CAS') write(history / 'replace-intent.json', b'{"once":true}', 0o600) os.replace(next_cfg, cfg); os.replace(next_code, code) run(['systemctl', 'daemon-reload']) run(['systemctl', 'enable', '--now', name + '.timer']) write(history / 'start-intent.json', b'{"once":true}', 0o600) run(['ufw', 'allow', 'proto', 'tcp', 'from', '0.0.0.0/0', 'to', 'any', 'port', '8443']) run(['systemctl', 'start', 'rmm-bootstrap-download.service']) result = dict(published=True, expires_at=p['expires_at'], bundle_sha256=digest(archive), snapshot=snapshot(), close_timer=name + '.timer', rmm_deployment_changed=False, private_keys_read=False) write(history / 'completed.json', json.dumps(result).encode(), 0o600) return result def sha(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() def save(path, value): with path.open('x') as out: json.dump(value, out, indent=2); out.flush(); os.fsync(out.fileno()) def main(): os.umask(0o077) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('action', choices=('prepare', 'publish', 'readback')) parser.add_argument('--bundle', type=Path); parser.add_argument('--id'); parser.add_argument('--review-sha256') args = parser.parse_args() if args.action == 'prepare': transport.require(args.bundle and not args.id and not args.review_sha256, 'new public bundle preparation') with zipfile.ZipFile(args.bundle) as z: transport.require(set(z.namelist()) == {'Recover-ExistingDevAccess.ps1', 'public-recovery.json', 'README.txt'} and all(i.file_size < 65536 for i in z.infolist()), 'only three public recovery files') public = json.loads(z.read('public-recovery.json')) transport.require(public['no_private_keys'] is True and hashlib.sha256(z.read('Recover-ExistingDevAccess.ps1')).hexdigest() == public['script_sha256'], 'bound public script') ident = str(uuid.uuid4()); folder = STATE / ident; folder.mkdir(parents=True, mode=0o700) payload = dict(id=ident, old_code_sha256=sha(ROOT / 'deploy/windows/download_service.py'), expires_at=(dt.datetime.now(dt.timezone.utc) + dt.timedelta(minutes=45)).replace(microsecond=0).isoformat(), url_path='/windows/' + uuid.uuid4().hex + '/windows-dev-access-recovery.zip', bundle_sha256=sha(args.bundle), bundle=base64.b64encode(args.bundle.read_bytes()).decode()) before = transport.rpc('server.conf', server, dict(payload, action='prepare')) save(folder / 'intent.json', dict(source_sha256=sha(__file__), bundle_path=str(args.bundle.resolve()), payload=dict(payload, before=before))) print(json.dumps(dict(id=ident, prepared=True, review_sha256=sha(folder / 'intent.json')))); return transport.require(args.id and str(uuid.UUID(args.id)) == args.id, 'same canonical publication case') folder = STATE / args.id; intent = json.loads((folder / 'intent.json').read_text()); p = intent['payload'] transport.require(intent['source_sha256'] == sha(__file__) and sha(intent['bundle_path']) == p['bundle_sha256'], 'same reviewed source and bundle') if args.action == 'publish': transport.require(args.review_sha256 == sha(folder / 'intent.json'), 'reviewed exact publication intent') save(folder / 'publish-attempt.json', dict(once=True, lost_reply_readback_only=True)) result = transport.rpc('server.conf', server, dict(p, action=args.action)) save(folder / (args.action + '-' + str(uuid.uuid4()) + '.json'), result) if args.action == 'publish': transport.require(result.get('published') is True, 'publication completed') url = 'https://discovery.ease-technologies.de:8443' + p['url_path'] with urllib.request.urlopen(url, context=ssl.create_default_context(), timeout=15) as response: raw = response.read(262145) transport.require(hashlib.sha256(raw).hexdigest() == p['bundle_sha256'], 'external TLS verified exact download') save(folder / 'external-verified.json', dict(url=url, sha256=p['bundle_sha256'], expires_at=p['expires_at'], ordinary_tls_verified=True)) print(json.dumps(dict(url=url, sha256=p['bundle_sha256'], expires_at=p['expires_at'], ordinary_tls_verified=True))); return print(json.dumps(result)) if __name__ == '__main__': main()