149 lines
10 KiB
Python
149 lines
10 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 argparse
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import sys
|
|
import subprocess
|
|
import shlex
|
|
import time
|
|
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);ssh.chmod(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():
|
|
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--register-console');parser.add_argument('--probe-registered',action='store_true');args=parser.parse_args()
|
|
if args.probe_registered:
|
|
probe_registered(cloud.contract.protected_json(cloud.ROOT/'devstate/windows-bootstrap/console-registration.json'));return
|
|
if args.register_console:
|
|
register_console(Path(args.register_console));return
|
|
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')
|
|
|
|
|
|
def register_key(payload):
|
|
import datetime as dt
|
|
import re
|
|
root=Path('/opt/rust-discovery/devstate/windows-bootstrap')
|
|
prepared=json.loads((root/'prepared.json').read_text())
|
|
require(prepared['pending_public_key'] is True and prepared['profile_valid'] is True,'known pending tunnel')
|
|
require(payload['expires_at']==prepared['expires_at'],'VM/bootstrap expiry differs')
|
|
expires=dt.datetime.fromisoformat(prepared['expires_at']).astimezone(dt.timezone.utc)
|
|
require(dt.datetime.now(dt.timezone.utc)<expires,'tunnel enrollment window expired')
|
|
require(re.fullmatch(r'ssh-ed25519 [A-Za-z0-9+/=]{68}',payload['public_key']) is not None,'canonical ED25519 public key required')
|
|
p=Path('/var/lib/rmm-win-tunnel/.ssh/authorized_keys')
|
|
require(not p.is_symlink() and p.stat().st_uid==0 and p.read_bytes()==b'','initial empty authorized keys required')
|
|
# PermitOpen none belongs in sshd_config; authorized_keys only accepts a
|
|
# host:port pair for permitopen. Match already denies all local forwarding.
|
|
options='restrict,port-forwarding,permitlisten="127.0.0.1:22240",expiry-time="'+expires.strftime('%Y%m%d%H%M%SZ')+'" '
|
|
next_path=p.with_suffix('.enroll-next')
|
|
fd=os.open(next_path,os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_NOFOLLOW,0o644)
|
|
with os.fdopen(fd,'w') as f:f.write(options+payload['public_key']+'\n');f.flush();os.fsync(f.fileno());os.fchmod(f.fileno(),0o644)
|
|
os.replace(next_path,p)
|
|
receipt=dict(public_key_registered=True,expires_at=prepared['expires_at'],listener='127.0.0.1:22240',shell_allowed=False)
|
|
p=root/'registered.json';p.write_text(json.dumps(receipt));p.chmod(0o600)
|
|
return receipt
|
|
|
|
|
|
def register_console(file):
|
|
import re
|
|
import base64
|
|
os.umask(0o077);data=cloud.contract.protected_json(file)
|
|
require(data['windows_user']=='rmm-dev' and data['windows_architecture']=='AMD64' and data['ssh_service']=='Running','actual Windows console report required')
|
|
for field in ('tunnel_public_key','windows_host_public_key'):
|
|
require(re.fullmatch(r'ssh-ed25519 [A-Za-z0-9+/=]{68}',data[field]) is not None,'canonical public key required')
|
|
folder=cloud.ROOT/'devstate/windows-bootstrap'
|
|
pin=folder/'windows-host-key.pub';cloud.contract.write_private(folder/'console-registration.json',data)
|
|
pin.write_text(data['windows_host_public_key']+'\n');pin.chmod(0o600)
|
|
fingerprint=transport.execute(['ssh-keygen','-lf',str(pin)]).decode().split()[1]
|
|
require(fingerprint=='SHA256:E663MwfdBF/ZS0/JZgk5Jctxzh2dfc9p/yECHw3AN+c','VM-console-confirmed host key differs')
|
|
result=transport.rpc('server.conf',register_key,dict(public_key=data['tunnel_public_key'],expires_at=data['expires_at']))
|
|
cloud.contract.write_private(folder/'tunnel-registered.json',result)
|
|
known=cloud.ROOT/'credentials/windows-dev.known_hosts';require(not known.exists(),'existing Windows pin retained')
|
|
known.write_text('rmm-windows-dev '+data['windows_host_public_key']+'\n');known.chmod(0o600)
|
|
probe_registered(data)
|
|
|
|
|
|
def probe_registered(data):
|
|
import base64
|
|
folder=cloud.ROOT/'devstate/windows-bootstrap';known=cloud.ROOT/'credentials/windows-dev.known_hosts'
|
|
cfg=transport.access.load_config(cloud.ROOT/'credentials/server.conf');key=str(Path(cfg['ssh_key_path']).expanduser())
|
|
jump=['ssh','-F','/dev/null','-T','-p',cfg.get('port','22'),'-i',key,'-o','StrictHostKeyChecking=yes','-o','BatchMode=yes',
|
|
'-o','ForwardAgent=no','-o','IdentitiesOnly=yes','-W','127.0.0.1:22240',cfg['username']+'@'+cfg['address']]
|
|
cmd=['ssh','-F','/dev/null','-T','-i',key,'-o','ProxyCommand='+shlex.join(jump),'-o','HostKeyAlias=rmm-windows-dev',
|
|
'-o','UserKnownHostsFile='+str(known),'-o','GlobalKnownHostsFile=/dev/null','-o','StrictHostKeyChecking=yes',
|
|
'-o','BatchMode=yes','-o','IdentitiesOnly=yes','-o','ForwardAgent=no','-o','ConnectTimeout=10','rmm-dev@127.0.0.1']
|
|
script="$p=[Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent();$o=Get-CimInstance Win32_OperatingSystem;@{admin=$p.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator);os=$o.Caption;build=$o.BuildNumber;architecture=$o.OSArchitecture}|ConvertTo-Json -Compress"
|
|
encoded=base64.b64encode(script.encode('utf-16le')).decode()
|
|
end=time.monotonic()+90
|
|
while True:
|
|
process=subprocess.run(cmd+['powershell.exe -NoProfile -NonInteractive -EncodedCommand '+encoded],capture_output=True,timeout=20)
|
|
if process.returncode==0:break
|
|
require(time.monotonic()<end,'tunnel/Windows access not ready; retain keys and registration, no reinstall');time.sleep(5)
|
|
observed=json.loads(process.stdout.decode('utf-8-sig').strip());require(observed['admin'] is True,'Windows administrator token required')
|
|
cloud.contract.write_private(folder/'windows-access-verified.json',dict(observed,host_key_verified=True,private_keys_transferred=False,rmm_client_installed=False))
|
|
cloud.contract.write_private(cloud.ROOT/'credentials/windows-dev-access.json',dict(ssh_prefix=cmd,expires_at=data['expires_at']))
|
|
print(dict(windows_access_verified=True,**observed))
|
|
|
|
|
|
require=transport.require
|
|
if __name__=='__main__':
|
|
try:main()
|
|
except Exception as error:
|
|
print('WINDOWS_BOOTSTRAP_INCOMPLETE:'+type(error).__name__);raise SystemExit(2) from None
|