352 lines
27 KiB
Python
352 lines
27 KiB
Python
#!/usr/bin/env python3
|
|
"""Reviewable preserving Linux runtime installation; parent executes only.
|
|
|
|
All active shared-ledger readers become the same new generation. General rights
|
|
and controls remain byte-identical. APT stays already closed/unqualified. No RMM
|
|
job/approval or automatic install retry. This source never installs the notebook.
|
|
"""
|
|
import argparse
|
|
import base64
|
|
import hashlib
|
|
import inspect
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import uuid
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
PREFLIGHT_SHA = '0e210b857d3f25e0ff228bbbd4a6533dadd91c9d21dbcba5923b26c2fe72eec9'
|
|
if hashlib.sha256((ROOT / 'deploy/script_console_bootstrap.py').read_bytes()).hexdigest() != PREFLIGHT_SHA:
|
|
raise RuntimeError('Reviewed preflight source changed')
|
|
import script_console_bootstrap as pre
|
|
support = pre.support
|
|
STATE = ROOT / 'devstate/script-console-install'
|
|
REMOTE = '/var/lib/rmm-bootstrap-history/script-console-v1-'
|
|
|
|
|
|
def require(value, code):
|
|
if not value:
|
|
raise RuntimeError(code)
|
|
|
|
|
|
def server_gate(p):
|
|
import datetime as dt
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import subprocess
|
|
import uuid
|
|
tenant = str(uuid.UUID(p['target']['tenant_id'])); agent = str(uuid.UUID(p['target']['agent_id']))
|
|
require(tenant == p['target']['tenant_id'] and agent == p['target']['agent_id'], 'canonical exact target')
|
|
scope = "tenant_id='" + tenant + "' AND agent_id='" + agent + "'"
|
|
query = ("SELECT json_build_object('jobs',(SELECT count(*) FROM jobs WHERE " + scope + "),"
|
|
"'outbox',(SELECT count(*) FROM outbox o JOIN jobs j USING(tenant_id,job_id,attempt_id) WHERE " + scope.replace('tenant_id=', 'j.tenant_id=').replace('agent_id=', 'j.agent_id=') + "),"
|
|
"'permits',(SELECT count(*) FROM execution_permits e JOIN jobs j USING(tenant_id,job_id,attempt_id) WHERE " + scope.replace('tenant_id=', 'j.tenant_id=').replace('agent_id=', 'j.agent_id=') + "),"
|
|
"'unresolved',(SELECT count(*) FROM jobs WHERE " + scope + " AND state NOT IN ('succeeded','failed','cancelled','expired')));")
|
|
root = Path('/opt/rust-discovery')
|
|
cmd = ['docker','compose','--env-file',str(root/'devstate/.env'),'-f',str(root/'deploy/server.compose.yaml'),
|
|
'exec','-T','postgres','psql','-X','-qAt','-v','ON_ERROR_STOP=1','-U','postgres','-d','rmm']
|
|
value = json.loads(subprocess.run(cmd, input=query.encode(), capture_output=True, check=True, timeout=20).stdout)
|
|
require(value == dict(jobs=30,outbox=30,permits=26,unresolved=0), 'same central closed count')
|
|
path = root/'devstate/root-policy/policy.json'; raw=path.read_bytes(); meta=path.lstat()
|
|
require(not path.is_symlink() and meta.st_uid==10001 and meta.st_mode&0o777==0o600
|
|
and hashlib.sha256(raw).hexdigest()==p['central_policy_sha256'], 'unchanged protected central policy')
|
|
require(dt.datetime.fromisoformat(json.loads(raw)['expires_at']) <= dt.datetime.now(dt.timezone.utc), 'Root scope remains closed')
|
|
return dict(counts=value,policy_sha256=p['central_policy_sha256'],closed=True,observed_at=dt.datetime.now(dt.timezone.utc).isoformat(),jobs_created=False,approvals=False)
|
|
|
|
|
|
def vm(p):
|
|
import base64
|
|
import fcntl
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import sqlite3
|
|
import stat
|
|
import subprocess
|
|
import traceback
|
|
import uuid
|
|
import datetime as dt
|
|
os.umask(0o077)
|
|
ident=str(uuid.UUID(p['id'])); require(ident==p['id'] and os.geteuid()==0,'fixed root installation case')
|
|
require(p['action'] in ('prepare','install','read') and p['type']=='rmm.script-console.preserving-install-v1','fixed operation')
|
|
parent=Path('/var/lib/rmm-bootstrap-history'); case=parent/('script-console-v1-'+ident)
|
|
intent={k:v for k,v in p.items() if k not in ('action','fresh_server_gate')}
|
|
def encode(v):return json.dumps(v,sort_keys=True,separators=(',',':')).encode()
|
|
def sha(b):return hashlib.sha256(b).hexdigest()
|
|
def fsync_dir(path):
|
|
fd=os.open(path,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW)
|
|
try:os.fsync(fd)
|
|
finally:os.close(fd)
|
|
def create(path,raw,mode=0o600,gid=0):
|
|
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(raw);out.flush();os.fchmod(out.fileno(),mode);os.fchown(out.fileno(),0,gid);os.fsync(out.fileno())
|
|
fsync_dir(path.parent)
|
|
def safe(path,directory=False,owner=0):
|
|
m=path.lstat();require(not path.is_symlink() and m.st_uid==owner and not m.st_mode&0o022
|
|
and (stat.S_ISDIR(m.st_mode) if directory else stat.S_ISREG(m.st_mode) and m.st_nlink==1),'safe owned path')
|
|
return m
|
|
def run(args,**kwargs):return subprocess.run(args,capture_output=True,check=True,timeout=25,**kwargs).stdout
|
|
def svc(name):
|
|
return dict(line.split('=',1) for line in run(['systemctl','show',name,'-p','ActiveState','-p','MainPID','-p','UnitFileState']).decode().splitlines())
|
|
def marker(name, **fields):
|
|
create(case/(name+'.json'),encode(dict(id=ident,phase=name,**fields)))
|
|
def live_readback():
|
|
# This path never repairs, restarts, replaces or retries anything. A
|
|
# receipt is historical; only independently observed markers and native
|
|
# state describe what may have happened after an interrupted install.
|
|
started=dt.datetime.now(dt.timezone.utc).isoformat()
|
|
def observed_file(path, content=False):
|
|
if not os.path.lexists(path):return dict(present=False)
|
|
try:
|
|
m=path.lstat();value=dict(present=True,device=m.st_dev,inode=m.st_ino,
|
|
uid=m.st_uid,gid=m.st_gid,mode=stat.S_IMODE(m.st_mode),bytes=m.st_size,
|
|
symlink=stat.S_ISLNK(m.st_mode),regular=stat.S_ISREG(m.st_mode))
|
|
if not stat.S_ISREG(m.st_mode) or path.is_symlink() or m.st_size>256*1024*1024:
|
|
value['inspection_error']='unexpected_or_unbounded_file';return value
|
|
raw=path.read_bytes();value['sha256']=sha(raw)
|
|
if content:
|
|
require(m.st_uid==0 and not m.st_mode&0o022 and m.st_nlink==1
|
|
and m.st_size<8*1024*1024,'safe bounded historical receipt')
|
|
value['historical_content']=json.loads(raw)
|
|
return value
|
|
except Exception as e:return dict(present=True,inspection_error=type(e).__name__)
|
|
phase_names=('install-entered','stop-intent','stopped','agent-exchange-intent','agent-exchanged',
|
|
'helper-exchange-intent','helper-exchanged','full-files-installed','restart-intent',
|
|
'general-started','full-started','agent-started')
|
|
markers={name:observed_file(case/(name+'.json'),True) for name in phase_names}
|
|
services={}
|
|
for name in ('rmm-agent-remote.service','rmm-helper-cloud.service','rmm-full-maintenance-helper.service','rmm-apt-helper.service'):
|
|
try:
|
|
reply=subprocess.run(['systemctl','show',name,'-p','LoadState','-p','ActiveState',
|
|
'-p','SubState','-p','MainPID','-p','UnitFileState'],capture_output=True,timeout=25)
|
|
value=dict(exit_code=reply.returncode,properties=dict(line.split('=',1)
|
|
for line in reply.stdout.decode().splitlines() if '=' in line))
|
|
# A missing named Full unit is an observable partial state,
|
|
# not a reason to discard the other independent observations.
|
|
if reply.returncode!=0 and not (name=='rmm-full-maintenance-helper.service'
|
|
and reply.returncode==1 and value['properties'].get('LoadState')=='not-found'
|
|
and value['properties'].get('ActiveState')=='inactive'
|
|
and value['properties'].get('MainPID')=='0'):
|
|
value['inspection_error']='systemctl_show_failed'
|
|
pid=int(value['properties'].get('MainPID','0'))
|
|
if pid>0:
|
|
try:
|
|
proc=Path('/proc',str(pid));before=(proc/'stat').read_text()
|
|
status=(proc/'status').read_text().splitlines()
|
|
image=sha((proc/'exe').read_bytes())
|
|
require((proc/'stat').read_text().rsplit(')',1)[1].split()[19]
|
|
==before.rsplit(')',1)[1].split()[19],'same observed process start')
|
|
value['process']=dict(pid=pid,start_ticks=before.rsplit(')',1)[1].split()[19],sha256=image,
|
|
uids=next(x.split()[1:] for x in status if x.startswith('Uid:')),
|
|
gids=next(x.split()[1:] for x in status if x.startswith('Gid:')))
|
|
except Exception as e:value['process']=dict(pid=pid,inspection_error=type(e).__name__)
|
|
services[name]=value
|
|
except Exception as e:services[name]=dict(inspection_error=type(e).__name__)
|
|
files={}
|
|
for key,path in (('agent',Path('/usr/local/libexec/rmm-agent-remote')),('helper',Path('/usr/local/libexec/rmm-privileged-helper'))):
|
|
files[key+'_current']=observed_file(path)
|
|
for generation in ('previous','next'):files[key+'_'+generation]=observed_file(case/(key+'-'+generation))
|
|
historical=observed_file(case/'report.json',True)
|
|
return dict(id=ident,readback_only=True,observed_from=started,
|
|
observed_until=dt.datetime.now(dt.timezone.utc).isoformat(),install_entered=markers['install-entered']['present'],
|
|
services_may_have_changed=markers['stop-intent']['present'],
|
|
stop_confirmed=markers['stopped']['present'],markers=markers,services=services,files=files,
|
|
historical_report=historical,repair_attempted=False,retry_allowed=False,
|
|
product_state_writes=False,rmm_jobs=False,approvals=False)
|
|
def retained_files():
|
|
# Never open private device keys. Retain all file identities, sizes,
|
|
# modes and change timestamps; SQL content has its own full row witness.
|
|
value={}
|
|
for root in (Path('/var/lib/rmm-agent-remote'),Path('/var/lib/rmm-helper')):
|
|
for path in [root,*sorted(root.rglob('*'))]:
|
|
m=path.lstat();require(not path.is_symlink() and (stat.S_ISDIR(m.st_mode) or stat.S_ISREG(m.st_mode)),'no unexpected retained state object')
|
|
if str(path).endswith(('-journal','-wal','-shm')):raise RuntimeError('Settled journal required')
|
|
value[str(path)]=[m.st_dev,m.st_ino,m.st_uid,m.st_gid,m.st_mode,m.st_size,m.st_mtime_ns,m.st_ctime_ns]
|
|
return value
|
|
def sql_witness():
|
|
result={}
|
|
for name,identity in p['preflight']['database_inodes'].items():
|
|
path=Path(name);m=path.lstat();require([m.st_dev,m.st_ino]==identity and not path.is_symlink(),'preserved DB identity')
|
|
require(all(not os.path.lexists(str(path)+suffix) for suffix in ('-wal','-shm','-journal')),'no live SQLite sidecars')
|
|
db=sqlite3.connect(path.as_uri()+'?mode=ro',uri=True)
|
|
try:
|
|
db.execute('PRAGMA query_only=ON');db.execute('BEGIN')
|
|
require(db.execute('PRAGMA integrity_check').fetchone()[0]=='ok','retained SQL integrity')
|
|
tables=dict(db.execute("SELECT name,sql FROM sqlite_master WHERE type='table' ORDER BY name"))
|
|
rows={}
|
|
for table in tables:
|
|
require(table.replace('_','').isalnum(),'fixed SQLite identifier')
|
|
rows[table]=[sha(encode([dict(blob_sha256=sha(v),bytes=len(v)) if isinstance(v,bytes) else v for v in row]))
|
|
for row in db.execute('SELECT rowid,* FROM "'+table+'" ORDER BY rowid')]
|
|
result[name]=dict(schema=tables,rows=rows,identity=identity)
|
|
if path.name=='journal.sqlite':
|
|
require(db.execute("SELECT count(*) FROM job_attempts WHERE state NOT IN ('succeeded','failed','cancelled','expired')").fetchone()[0]==0,'no running job')
|
|
if path.parent.name=='rmm-helper':
|
|
current=db.execute('SELECT c.grant_id,c.agent,c.generation,c.job,c.attempt,c.result,e.start,e.outcome FROM consumed c LEFT JOIN execution_evidence e USING(grant_id) ORDER BY grant_id').fetchall()
|
|
exact={r[0]:sha(json.dumps([dict(sha256=sha(v),size=len(v)) if isinstance(v,bytes) else v for v in r],separators=(',',':')).encode()) for r in current}
|
|
require(exact==p['preflight']['root_rows'] and len(exact)==18 and all(r[5] is not None for r in current),'exact retained Root18')
|
|
finally:db.close()
|
|
return result
|
|
safe(parent,True)
|
|
if p['action']=='prepare':
|
|
before=snapshot_vm(p['preflight'])
|
|
require(before['controls']==p['baseline']['controls'] and before['processes']==p['baseline']['processes']
|
|
and before['databases']==p['baseline']['databases'],'fresh original preflight still exact')
|
|
case.mkdir(mode=0o700);create(case/'intent.json',encode(intent))
|
|
return dict(id=ident,prepared=True,services_changed=False,product_state_writes=False)
|
|
safe(case,True);safe(case/'intent.json')
|
|
require((case/'intent.json').read_bytes()==encode(intent),'original immutable install intent')
|
|
if p['action']=='read':
|
|
return live_readback()
|
|
require(not os.path.lexists(case/'install-entered.json'),'same case install must never repeat')
|
|
gate=p['fresh_server_gate']
|
|
require(gate['closed'] is True and gate['counts']==dict(jobs=30,outbox=30,permits=26,unresolved=0)
|
|
and gate['policy_sha256']==p['central_policy_sha256'],'fresh separate closed server gate')
|
|
before=snapshot_vm(p['preflight'])
|
|
require(before['controls']==p['baseline']['controls'] and before['processes']==p['baseline']['processes']
|
|
and before['databases']==p['baseline']['databases'],'exact pre-stop CAS including PIDs/startticks')
|
|
binaries={'agent':Path('/usr/local/libexec/rmm-agent-remote'),'helper':Path('/usr/local/libexec/rmm-privileged-helper')}
|
|
for key,path in binaries.items():
|
|
upload=case/(key+'-next');safe(upload)
|
|
require(sha(upload.read_bytes())==p['artifacts'][key]['sha256'] and upload.stat().st_size==p['artifacts'][key]['bytes'],'exact native-qualified upload')
|
|
marker('install-entered',install_once=True)
|
|
report=dict(id=ident,stage='entered',completed_preserving_bootstrap=False,signed_sync_verified=False,
|
|
services_changed=False,services_may_have_changed=False,root_consumed=18,root_unresolved=0,rmm_jobs=False,approvals=False,
|
|
package_effects=False,reboot_requested=False,apt_endpoint_enabled=False,apt_current_runtime_qualified=False,
|
|
full_job_accepted=False)
|
|
def save():
|
|
pending=case/'report-next';create(pending,encode(report));os.replace(pending,case/'report.json');fsync_dir(case)
|
|
locks=[]
|
|
try:
|
|
save();marker('stop-intent',services_may_have_changed=True)
|
|
report.update(stage='stop_requested',services_may_have_changed=True);save()
|
|
run(['systemctl','stop','rmm-agent-remote.service','rmm-helper-cloud.service'])
|
|
require(all(svc(n)['ActiveState']=='inactive' for n in ('rmm-agent-remote.service','rmm-helper-cloud.service')),'both old daemons stopped')
|
|
marker('stopped',confirmed=True);report['services_changed']=True;save()
|
|
for path in (Path('/var/lib/rmm-agent-remote/agent.lock'),Path('/var/lib/rmm-helper/executor.lock')):
|
|
fd=os.open(path,os.O_RDWR|os.O_NOFOLLOW);fcntl.flock(fd,fcntl.LOCK_EX|fcntl.LOCK_NB);locks.append(fd)
|
|
frozen_sql=sql_witness();frozen_files=retained_files()
|
|
create(case/'sql-before.json',encode(frozen_sql));create(case/'files-before.json',encode(frozen_files))
|
|
for key,path in binaries.items():
|
|
safe(path);require(sha(path.read_bytes())==p['preflight']['old_artifacts'][key],'unchanged old binary immediately before exchange')
|
|
require(path.stat().st_dev==case.stat().st_dev,'same-filesystem preserving exchange')
|
|
marker(key+'-exchange-intent',may_have_changed=True)
|
|
os.rename(path,case/(key+'-previous'));fsync_dir(path.parent);fsync_dir(case)
|
|
os.chmod(case/(key+'-next'),0o755);os.rename(case/(key+'-next'),path);fsync_dir(path.parent);fsync_dir(case)
|
|
marker(key+'-exchanged',confirmed=True)
|
|
report['stage']=key+'_exchanged';save()
|
|
helper=binaries['helper'];env={'PATH':'/usr/sbin:/usr/bin:/sbin:/bin','LANG':'C','LC_ALL':'C','RMM_HELPER_CONFIG':'/etc/rmm-remote/helper-general.json'}
|
|
general=json.loads(run([str(helper),'--inspect-general-profile'],env=env))
|
|
require(general==p['general_pin'],'new General generation retains identical public policy pin')
|
|
for path,expected in p['baseline']['controls'].items():
|
|
if path in [str(x) for x in binaries.values()]:continue
|
|
item=Path(path);m=item.lstat()
|
|
actual=dict(device=m.st_dev,inode=m.st_ino,mode=stat.S_IMODE(m.st_mode),uid=m.st_uid,gid=m.st_gid,bytes=m.st_size,sha256=sha(item.read_bytes()))
|
|
require(not item.is_symlink() and actual==expected,'General/APT/package control bytes/inodes/modes unchanged')
|
|
full=p['baseline']['full_config_candidate'];raw=base64.b64decode(full['bytes_b64'],validate=True)
|
|
require(sha(raw)==full['sha256'] and json.loads(raw)['helper_binary_sha256']==p['artifacts']['helper']['sha256'],'exact reviewed Fullconfig')
|
|
config=Path('/etc/rmm-remote/helper-full-maintenance.json');create(config,raw,0o600)
|
|
env['RMM_HELPER_CONFIG']=str(config)
|
|
pin=json.loads(run([str(helper),'--inspect-full-maintenance-profile'],env=env))
|
|
require(pin['schema_version']==2 and pin['profile']=='full_maintenance_v1' and pin['identity']==general['identity']
|
|
and pin['helper_binary_sha256']==p['artifacts']['helper']['sha256'],'actual new image/profile/identity proof')
|
|
pinpath=Path('/etc/rmm-remote/full-maintenance-helper-proof.json');create(pinpath,json.dumps(pin,separators=(',',':')).encode(),0o640,984)
|
|
unit=Path('/etc/systemd/system/rmm-full-maintenance-helper.service');create(unit,base64.b64decode(p['unit_bytes_b64'],validate=True),0o644)
|
|
dropin=Path('/etc/systemd/system/rmm-agent-remote.service.d/60-full-maintenance.conf')
|
|
safe(dropin.parent,True);create(dropin,b'[Service]\nEnvironment=RMM_FULL_MAINTENANCE_HELPER_SOCKET=/run/rmm-helper-maintenance/control.sock\nEnvironment=RMM_FULL_MAINTENANCE_POLICY_FILE=/etc/rmm-remote/full-maintenance-helper-proof.json\n',0o644)
|
|
require(sql_witness()==frozen_sql and retained_files()==frozen_files,'all preexisting SQL rows/bytes/inodes/keys unchanged before restart')
|
|
marker('full-files-installed',preserved_before_restart=True)
|
|
report.update(stage='installed_preserved',general_pin=general,full_pin=pin,preserved_before_restart=True);save()
|
|
for fd in reversed(locks):fcntl.flock(fd,fcntl.LOCK_UN);os.close(fd)
|
|
locks.clear();run(['systemctl','daemon-reload']);run(['systemd-analyze','verify',str(unit)])
|
|
names=('User','Group','NoNewPrivileges','PrivateNetwork','PrivateTmp','ProtectSystem','ProtectHome',
|
|
'ProtectKernelTunables','ProtectKernelModules','ProtectControlGroups','RestrictSUIDSGID',
|
|
'RestrictAddressFamilies','SystemCallFilter','RootDirectory','RootImage')
|
|
full_unit=dict(line.split('=',1) for line in run(['systemctl','show','rmm-full-maintenance-helper.service',
|
|
*[argument for name in names for argument in ('-p',name)]]).decode().splitlines())
|
|
require(full_unit['User']=='root' and full_unit['Group']=='rmm-agent'
|
|
and all(full_unit[name]=='no' for name in names[2:11])
|
|
and all(full_unit[name]=='' for name in names[11:]),'effective Full unit must not inherit General sandbox')
|
|
report['effective_full_unit']=full_unit;save()
|
|
marker('restart-intent',services_may_have_changed=True)
|
|
for name,label in (('rmm-helper-cloud.service','general'),('rmm-full-maintenance-helper.service','full'),('rmm-agent-remote.service','agent')):
|
|
run(['systemctl','start',name]);require(svc(name)['ActiveState']=='active','new exact service active')
|
|
marker(label+'-started',confirmed=True)
|
|
processes={}
|
|
for name,key,uid in (('rmm-helper-cloud.service','general',0),('rmm-full-maintenance-helper.service','full',0),('rmm-agent-remote.service','agent',993)):
|
|
pid=int(svc(name)['MainPID']);status=Path('/proc',str(pid),'status').read_text().splitlines()
|
|
uids=next(x.split()[1:] for x in status if x.startswith('Uid:'));gids=next(x.split()[1:] for x in status if x.startswith('Gid:'))
|
|
image=sha(Path('/proc',str(pid),'exe').read_bytes());expected=p['artifacts']['agent' if key=='agent' else 'helper']['sha256']
|
|
require(uids==[str(uid)]*4 and gids==['984']*4 and image==expected,'actual new service accounts/code generation')
|
|
processes[key]=dict(pid=pid,uids=uids,gids=gids,sha256=image)
|
|
require(svc('rmm-apt-helper.service')['ActiveState']=='inactive' and svc('rmm-apt-helper.service')['UnitFileState']=='disabled','APT remains already closed')
|
|
require(Path('/proc/sys/kernel/random/boot_id').read_text().strip()==p['preflight']['boot_id'],'no boot transition')
|
|
report.update(stage='new_generations_started',completed_preserving_bootstrap=True,processes=processes,boot_id=p['preflight']['boot_id']);save()
|
|
except Exception as e:
|
|
report.update(stage='incomplete_manual_review',error_class=type(e).__name__,frames=[dict(function=f.name,line=f.lineno) for f in traceback.extract_tb(e.__traceback__)]);save()
|
|
finally:
|
|
for fd in reversed(locks):fcntl.flock(fd,fcntl.LOCK_UN);os.close(fd)
|
|
return report
|
|
|
|
|
|
def rpc(prefix, function, payload, folder):
|
|
code=inspect.getsource(require)+'\n'+inspect.getsource(pre.snapshot_vm)+'\n'+inspect.getsource(function)
|
|
code+='\ntry:\n print(__import__("json").dumps('+function.__name__+'('+repr(payload)+')))\nexcept Exception as e:\n print(__import__("json").dumps(dict(bootstrap_error=True,error_class=type(e).__name__)))\n'
|
|
return support.transport(prefix,'python3 -',code.encode(),folder,timeout=230)
|
|
|
|
|
|
def server_prefix():
|
|
cfg=support.access.load_config(pre.ACCESS_ROOT/'credentials/server.conf')
|
|
require(cfg['address']=='88.99.80.202' and cfg['username']=='root' and cfg.get('port','22')=='22' and cfg.get('ssh_key_path'),'fixed server bootstrap transport')
|
|
return ['ssh','-F','/dev/null','-T','-p','22','-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','IdentitiesOnly=yes','-o','ForwardAgent=no','-o','ConnectTimeout=10','-i',str(Path(cfg['ssh_key_path']).expanduser()),'root@88.99.80.202']
|
|
|
|
|
|
if __name__=='__main__':
|
|
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('mode',choices=('prepare-local','stage','install','read'))
|
|
parser.add_argument('--snapshot',type=Path);parser.add_argument('--snapshot-sha');parser.add_argument('--case');args=parser.parse_args()
|
|
os.umask(0o077);STATE.mkdir(mode=0o700,parents=True,exist_ok=True);support.private(STATE,True)
|
|
if args.mode=='prepare-local':
|
|
require(args.case is None and args.snapshot is not None and args.snapshot_sha,'fresh reviewed snapshot required')
|
|
baseline=support.load(args.snapshot);require(support.sha(args.snapshot)==args.snapshot_sha and baseline['fresh_target_cas'] is True
|
|
and baseline['install_authorized'] is False and baseline['root_consumed']==18 and baseline['root_unresolved']==0,'exact fresh read-only snapshot')
|
|
prepath=args.snapshot.parent/'intent.json';previous=support.load(prepath)
|
|
require(previous['runner_sha256']==PREFLIGHT_SHA and previous['manifest_sha256']==pre.native.MANIFEST_SHA,'reviewed preflight generation')
|
|
case=str(uuid.uuid4());folder=STATE/case;folder.mkdir(mode=0o700)
|
|
manifest=support.load(pre.native.PACK/'manifest.json');old=support.load(pre.PRIOR)
|
|
require(support.sha(pre.native.PACK/'manifest.json')==pre.native.MANIFEST_SHA
|
|
and support.sha(pre.PRIOR)==pre.PRIOR_SHA and support.sha(pre.NATIVE)==pre.NATIVE_SHA
|
|
and all(support.sha(ROOT/n)==h for n,h in manifest['source_files'].items()),'actual frozen source/native provenance')
|
|
intent=dict(type='rmm.script-console.preserving-install-v1',id=case,runner_sha256=support.sha(__file__),preflight_source_sha256=PREFLIGHT_SHA,
|
|
manifest_sha256=pre.native.MANIFEST_SHA,snapshot_sha256=args.snapshot_sha,snapshot_path=str(args.snapshot.absolute()),preflight=previous,baseline=baseline,
|
|
target=previous['target'],central_policy_sha256=old['central_policy_sha256'],general_pin=old['general_pin'],
|
|
artifacts={k:{field:manifest['artifacts'][name][field] for field in ('sha256','bytes')} for k,name in (('agent','rmm-agent'),('helper','rmm-privileged-helper'))},
|
|
unit_bytes_b64=base64.b64encode((ROOT/'deploy/linux/rmm-full-maintenance-helper.service').read_bytes()).decode())
|
|
support.save(folder/'intent.json',intent)
|
|
else:
|
|
require(args.case is not None and args.snapshot is None and args.snapshot_sha is None,'original case only')
|
|
case=str(uuid.UUID(args.case));require(case==args.case,'canonical case');folder=STATE/case;intent=support.load(folder/'intent.json')
|
|
require(intent['runner_sha256']==support.sha(__file__) and intent['preflight_source_sha256']==PREFLIGHT_SHA,'original same-source intent')
|
|
require(support.sha(pre.native.PACK/'manifest.json')==pre.native.MANIFEST_SHA
|
|
and all(support.sha(ROOT/n)==h for n,h in support.load(pre.native.PACK/'manifest.json')['source_files'].items()),'frozen158 inputs remain exact')
|
|
prefix=support.access_settings(pre.ACCESS_ROOT,'linux')
|
|
if args.mode=='stage':
|
|
support.save(folder/'stage-entered-local.json',dict(stage_once=True))
|
|
result=rpc(prefix,vm,dict(intent,action='prepare'),folder);support.save(folder/'prepared-remote.json',result)
|
|
require(result['prepared'] is True,'new exact remote case')
|
|
for key,name in (('agent','rmm-agent'),('helper','rmm-privileged-helper')):
|
|
support.upload(prefix,dict(path=str(pre.native.PACK/name),**intent['artifacts'][key]),REMOTE+case+'/'+key+'-next',folder,key)
|
|
elif args.mode=='install':
|
|
support.load(folder/'prepared-remote.json');support.save(folder/'install-entered-local.json',dict(install_once=True,no_retry=True))
|
|
gate=rpc(server_prefix(),server_gate,intent,folder);support.save(folder/'fresh-server-gate.json',gate)
|
|
result=rpc(prefix,vm,dict(intent,action='install',fresh_server_gate=gate),folder);support.save(folder/'install-reply.json',result)
|
|
require(result.get('completed_preserving_bootstrap') is True and result.get('signed_sync_verified') is False
|
|
and result.get('full_job_accepted') is False and result.get('rmm_jobs') is False and result.get('approvals') is False,
|
|
'installation incomplete; same-case readback/manual review only')
|
|
else:
|
|
result=rpc(prefix,vm,dict(intent,action='read'),folder);support.save(folder/('readback-'+str(uuid.uuid4())+'.json'),result)
|
|
print(json.dumps(dict(case_id=case,intent=str(folder/'intent.json'),intent_sha256=support.sha(folder/'intent.json'),mode=args.mode,
|
|
target_called=args.mode!='prepare-local',rmm_jobs=False,approvals=False)))
|