142 lines
9.9 KiB
Python
142 lines
9.9 KiB
Python
#!/usr/bin/env python3
|
|
"""Replace the withdrawn public recovery ZIP; preserve all previous evidence.
|
|
|
|
Same existing TLS bootstrap service and port, one new URL and 45 minute limit.
|
|
No SSH, RMM, certificate, key, account or Windows changes in this publisher.
|
|
"""
|
|
import argparse
|
|
import base64
|
|
import datetime as dt
|
|
import hashlib
|
|
import inspect
|
|
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
|
|
|
|
STATE = transport.ROOT / 'devstate/windows-precision-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')
|
|
archive = Path('/srv/rmm-bootstrap-download/windows-dev-access-recovery.zip')
|
|
old_timer = 'rmm-recovery-download-close-7f549bc4-cf12-4292-aae6-377ac9ecb2d4'
|
|
history = Path('/opt/rmm-bootstrap-download') / ('precision-' + 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(), 'protected existing download file')
|
|
safe(cfg, 0o644); safe(code, 0o755); safe(archive, 0o644)
|
|
def snapshot():
|
|
return dict(config_sha256=digest(cfg), code_sha256=digest(code), archive_sha256=digest(archive),
|
|
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()
|
|
require(before == dict(config_sha256='1aa119f0355754e2ba054e6e1c4276f484c1287750cb853dd73bffe552ef8f93',
|
|
code_sha256='b4f85778dd356377b95e04d6736b3fb6f4e272a276a9466f28efeaccd6ef1b7d',
|
|
archive_sha256='7bf4f7bb8336fb50852f72eec2f3e370e96cb7009b14ee15aa7232c025a38ed7',
|
|
service_state='inactive'), 'only exact withdrawn original publication')
|
|
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'
|
|
original_timer = '[Unit]\nDescription=Expire public recovery download\n[Timer]\nOnCalendar=2026-11-14 13:53:24 UTC\nPersistent=true\nUnit=' + old_timer + '.service\n[Install]\nWantedBy=timers.target\n'
|
|
for suffix, expected in (('.service', service), ('.timer', original_timer)):
|
|
path = Path('/etc/systemd/system') / (old_timer + suffix)
|
|
safe(path, 0o644); require(path.read_text() == expected, 'only original download close timer may be superseded')
|
|
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'])
|
|
if p['action'] == 'prepare': return before
|
|
require(p['action'] == 'publish' and before == p['before'], 'same independently reviewed original 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), 'new download limited to 45 minutes')
|
|
require(not history.exists(), 'existing precision publication: readback only')
|
|
raw = base64.b64decode(p['bundle'], validate=True)
|
|
require(len(raw) < 262144 and hashlib.sha256(raw).hexdigest() == p['bundle_sha256'], 'exact corrected public archive')
|
|
history.mkdir(mode=0o700)
|
|
def write(path, data, mode=0o600):
|
|
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())
|
|
write(history / 'original-config.json', cfg.read_bytes())
|
|
write(history / 'original-recovery.zip', archive.read_bytes())
|
|
next_cfg = cfg.parent / ('rmm-precision-' + p['id'] + '.next')
|
|
next_zip = archive.parent / ('rmm-precision-' + 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_zip, raw, 0o644)
|
|
name = 'rmm-precision-download-close-' + p['id']
|
|
timer = '[Unit]\nDescription=Expire corrected 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 config/code/archive CAS while download is stopped')
|
|
write(history / 'replace-intent.json', b'{"once":true}')
|
|
os.replace(next_zip, archive); os.replace(next_cfg, cfg)
|
|
require(digest(archive) == p['bundle_sha256'] and digest(code) == before['code_sha256'], 'corrected ZIP and unchanged server code')
|
|
run(['systemctl', 'daemon-reload'])
|
|
run(['systemctl', 'enable', '--now', name + '.timer'])
|
|
write(history / 'supersede-old-timer-intent.json', json.dumps(dict(timer=old_timer + '.timer')).encode())
|
|
run(['systemctl', 'disable', '--now', old_timer + '.timer'])
|
|
write(history / 'start-intent.json', b'{"once":true}')
|
|
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', old_timer_superseded=old_timer + '.timer', rmm_deployment_changed=False, ssh_expiry_changed=False, private_keys_read=False)
|
|
write(history / 'completed.json', json.dumps(result).encode())
|
|
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 corrected public package')
|
|
with zipfile.ZipFile(args.bundle) as z:
|
|
transport.require(len(z.namelist()) == 3 and 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 corrected public script')
|
|
ident = str(uuid.uuid4()); folder = STATE / ident; folder.mkdir(parents=True, mode=0o700)
|
|
p = dict(id=ident, 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(p, action='prepare'))
|
|
save(folder / 'intent.json', dict(source_sha256=sha(__file__), bundle_path=str(args.bundle.resolve()), payload=dict(p, 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 precision 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 corrected package')
|
|
if args.action == 'publish':
|
|
transport.require(args.review_sha256 == sha(folder / 'intent.json'), 'reviewed 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, 'corrected 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 normal TLS and exact corrected ZIP')
|
|
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()
|