fix: identify APT local-file handoff failure and verify Windows admin tunnel
Rust development slice / linux (push) Failing after 6s
Rust development slice / linux (push) Failing after 6s
This commit is contained in:
@@ -5,10 +5,14 @@ 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]))
|
||||
@@ -28,7 +32,7 @@ def provision(payload):
|
||||
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=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'
|
||||
@@ -50,6 +54,11 @@ def provision(payload):
|
||||
|
||||
|
||||
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()
|
||||
@@ -67,6 +76,71 @@ def main():
|
||||
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()
|
||||
|
||||
Reference in New Issue
Block a user