Files
rust-discovery/deploy/windows/prepare_dev_access.py
T
2026-11-13 14:01:25 +01:00

75 lines
4.6 KiB
Python

#!/usr/bin/env python3
"""Prepare public-only Win11 bootstrap bundle and a forwarding-only cloud user.
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 json
import os
from pathlib import Path
import sys
import uuid
import zipfile
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
import remote_client_bootstrap as transport
import cloud_mvp_acceptance as cloud
def provision(payload):
root=Path('/opt/rust-discovery/devstate/windows-bootstrap');require(not root.exists(),'existing Windows bootstrap must be reviewed')
require(subprocess.run(['getent','passwd','rmm-win-tunnel'],capture_output=True).returncode!=0,'existing tunnel account')
path=Path('/etc/ssh/sshd_config.d/80-rmm-windows-tunnel.conf');require(not path.exists(),'existing SSH profile')
def run(args,**kw):return subprocess.run(args,capture_output=True,check=True,timeout=30,**kw).stdout
def config(user):return run(['/usr/sbin/sshd','-T','-C','user='+user+',host=localhost,addr=127.0.0.1'])
before=config('root');root.mkdir(mode=0o700)
host=Path('/etc/ssh/ssh_host_ed25519_key.pub').read_text().split();public=' '.join(host[:2])
fingerprint=run(['ssh-keygen','-lf','/etc/ssh/ssh_host_ed25519_key.pub']).decode().split()[1]
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)
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'
' PermitListen 127.0.0.1:22240\n PermitOpen none\n GatewayPorts no\n MaxSessions 0\n'
' PermitTTY no\n AllowAgentForwarding no\n X11Forwarding no\n PermitTunnel no\n PermitUserRC no\nMatch all\n')
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(profile);f.flush();os.fsync(f.fileno())
run(['/usr/sbin/sshd','-t'])
require(config('root')==before,'root SSH profile changed')
effective=config('rmm-win-tunnel').decode()
for option in ('allowtcpforwarding remote','allowstreamlocalforwarding no','permitlisten 127.0.0.1:22240',
'permitopen none','gatewayports no','maxsessions 0','passwordauthentication no'):
require(option+'\n' in effective,'restricted SSH profile not effective')
run(['systemctl','reload','ssh'])
report=dict(account='rmm-win-tunnel',listener='127.0.0.1:22240',profile_valid=True,root_profile_unchanged=True,
pending_public_key=True,server_host_key=public,server_fingerprint=fingerprint,expires_at=payload['expires_at'])
p=root/'prepared.json';p.write_text(json.dumps(report));p.chmod(0o600)
return report
def main():
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()
result=transport.rpc('server.conf',provision,dict(expires_at=expires))
# Derive only the public part for the explicitly requested Windows access.
cfg=transport.access.load_config(cloud.ROOT/'credentials/server.conf')
public=transport.execute(['ssh-keygen','-y','-f',str(Path(cfg['ssh_key_path']).expanduser())]).decode().split()
public=' '.join(public[:2])
data=dict(schema_version=1,server=transport.DOMAIN,server_host_key=result['server_host_key'],notebook_public_key=public,expires_at=expires)
bundle=folder/'windows-dev-access.zip'
with zipfile.ZipFile(bundle,'x',compression=zipfile.ZIP_DEFLATED) as archive:
archive.write(cloud.ROOT/'deploy/windows/Bootstrap-DevAccess.ps1','Bootstrap-DevAccess.ps1')
archive.writestr('bootstrap-public.json',json.dumps(data,indent=2))
cloud.contract.write_private(folder/'prepared.json',dict(result,bundle=str(bundle)))
print('Public-only Windows bootstrap bundle prepared; cloud profile verified; awaiting VM-console public keys')
require=transport.require
if __name__=='__main__':
try:main()
except Exception as error:
print('WINDOWS_BOOTSTRAP_INCOMPLETE:'+type(error).__name__);raise SystemExit(2) from None