Files
rust-discovery/deploy/updater_server_signing_bootstrap.py
T
2026-11-16 15:25:46 +01:00

121 lines
13 KiB
Python

#!/usr/bin/env python3
"""Explicit server-only release/baseline signing bootstrap; never installs policy.
Private release and Health keys remain on the server. No job/time key reuse,
service restart, catalog mutation, grant or approval is performed by this tool.
Prepared source: mutation phases require coordination by the owning Root task.
"""
import argparse
import base64
import json
from pathlib import Path
import linux_updater_compatible_apply as bootstrap
def server(payload):
import base64,datetime,hashlib,json,os,stat,subprocess,uuid
from pathlib import Path
require(os.geteuid()==0 and os.uname().machine=='aarch64','fixed Root ARM64 server')
root=Path('/opt/rust-discovery/devstate');platform=payload.get('platform','linux');require(platform in('linux','windows'),'closed release key platform');release_dir=root/('agent-update-release-'+platform+'-v1');health_dir=root/'agent-update-health-v1'
release_key=release_dir/'release.pem';health_key=health_dir/'health.pem';trust_dir=root/('agent-update-public-'+platform+'-v1')
ident=str(uuid.UUID(payload['case_id']));case=root/('updater-signing-'+ident)
def digest(raw):return hashlib.sha256(raw).hexdigest()
def encode(value):return json.dumps(value,separators=(',',':'),ensure_ascii=False).encode()
def run(args):return subprocess.check_output(args,stderr=subprocess.DEVNULL,timeout=10)
def syncdir(path):
fd=os.open(path,os.O_RDONLY|os.O_DIRECTORY)
try:os.fsync(fd)
finally:os.close(fd)
def metadata(path):
m=path.lstat();require(stat.S_ISREG(m.st_mode)and m.st_nlink==1 and stat.S_IMODE(m.st_mode)==0o600,'single protected key file');return [m.st_dev,m.st_ino,m.st_uid,m.st_gid,m.st_mode,m.st_nlink,m.st_size,m.st_mtime_ns,m.st_ctime_ns]
def public(key):
raw=run(['openssl','pkey','-in',str(key),'-pubout','-outform','DER']);require(len(raw)==44 and raw[:12]==bytes.fromhex('302a300506032b6570032100'),'Ed25519 public DER');return raw[12:]
def store(name,value):
path=case/name
with path.open('xb')as stream:stream.write(encode(value));stream.flush();os.fsync(stream.fileno())
syncdir(case)
def b64(raw):return base64.urlsafe_b64encode(raw).rstrip(b'=').decode()
def decode(text):
raw=base64.urlsafe_b64decode(text+'='*((-len(text))%4));require(b64(raw)==text,'canonical Base64url');return raw
if payload['action']=='public-separation':
pin=Path('/etc/rmm-time-source/time-public-key.json');before=metadata(pin);require(before[2]==0 and before[6]<=8192,'original Root public time pin');raw=pin.read_bytes();require(metadata(pin)==before,'public time pin unchanged')
time_key=json.loads(raw)['public_key_hex'];job_key=payload['job_public_key_hex'];require(all(len(v)==64 and set(v)<=set('0123456789abcdef')for v in(time_key,job_key))and time_key!=job_key,'independent actual Job/time public keys')
return {'operation':'updater_signer_public_separation_v1','forbidden_public_key_sha256':sorted([digest(bytes.fromhex(v))for v in(time_key,job_key)]),'time_public_pin_sha256':digest(raw),'private_key_read':False,'services_changed':False,'job_authority':False}
if payload['action']=='provision':
forbidden=payload['forbidden_public_key_sha256'];require(len(forbidden)>=2 and len(forbidden)<=16 and len(set(forbidden))==len(forbidden)and all(len(v)==64 and set(v)<=set('0123456789abcdef')for v in forbidden),'independent Job/time public-key SHA256 values required, never role aliases')
require(not release_dir.exists()and not trust_dir.exists()and not case.exists(),'create-only independent release signer namespace')
owner=(root/'jobs/ed25519.pem').lstat().st_uid;require(owner==10001,'actual existing signer owner contract')
case.mkdir(mode=0o700);store('provision-intent.json',{'release_dir':str(release_dir),'health_dir':str(health_dir),'forbidden_public_key_sha256':forbidden,'job_authority':False})
health_origin=health_dir/'public-origin.json'
reuse_health=health_dir.exists()
if reuse_health:
directory=health_dir.lstat();origin_meta=health_origin.lstat();require(stat.S_ISDIR(directory.st_mode)and directory.st_uid==owner and stat.S_IMODE(directory.st_mode)==0o700 and stat.S_ISREG(origin_meta.st_mode)and origin_meta.st_uid==0 and origin_meta.st_nlink==1 and stat.S_IMODE(origin_meta.st_mode)==0o600 and origin_meta.st_size<=4096,'original protected shared Health provenance')
origin=json.loads(health_origin.read_text());require(origin['profile']=='shared_agent_update_health_v1'and metadata(health_key)==origin['private_metadata']and public(health_key).hex()==origin['public_key_hex'],'exact original shared Health key')
for directory,key,uid in [(release_dir,release_key,0)]+([]if reuse_health else[(health_dir,health_key,owner)]):
directory.mkdir(mode=0o700);fd=os.open(key,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600);os.close(fd)
run(['openssl','genpkey','-algorithm','Ed25519','-out',str(key)]);os.chmod(key,0o600);os.chown(key,uid,uid);os.chown(directory,uid,uid)
fd=os.open(key,os.O_RDONLY|os.O_NOFOLLOW)
try:os.fsync(fd)
finally:os.close(fd)
syncdir(directory);syncdir(root)
release=public(release_key);health=public(health_key);require(release!=health and digest(release)not in forbidden and digest(health)not in forbidden,'independent key domains')
if not reuse_health:
with health_origin.open('x')as stream:json.dump({'profile':'shared_agent_update_health_v1','public_key_hex':health.hex(),'private_metadata':metadata(health_key)},stream,sort_keys=True);stream.flush();os.fsync(stream.fileno())
health_origin.chmod(0o600)
syncdir(health_dir)
other=root/('agent-update-release-'+('windows'if platform=='linux'else'linux')+'-v1/release-public.json')
if other.exists():
other_meta=other.lstat();require(stat.S_ISREG(other_meta.st_mode)and other_meta.st_uid==0 and stat.S_IMODE(other_meta.st_mode)==0o600 and other_meta.st_nlink==1 and other_meta.st_size<=4096,'other platform original public provenance');require(json.loads(other.read_text())['public_key_hex']!=release.hex(),'distinct platform release keys')
with(release_dir/'release-public.json').open('x')as stream:json.dump({'platform':platform,'public_key_hex':release.hex(),'key_id':digest(release)},stream,sort_keys=True);stream.flush();os.fsync(stream.fileno())
os.chmod(release_dir/'release-public.json',0o600)
syncdir(release_dir)
keyring=encode({'schema_version':1,'generation':1,'keys':[{'public_key_hex':release.hex(),'platform':'x86_64-unknown-linux-gnu'if platform=='linux'else'x86_64-pc-windows-msvc','first_sequence':1,'last_sequence':2,'revoked':False}]})
trust_dir.mkdir(mode=0o700);os.chown(trust_dir,owner,owner)
fd=os.open(trust_dir/'keyring.json',os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600)
with os.fdopen(fd,'wb')as stream:os.fchown(stream.fileno(),owner,owner);stream.write(keyring);stream.flush();os.fsync(stream.fileno())
syncdir(trust_dir);syncdir(root)
result={'schema_version':1,'profile':'agent_updater_separate_signers_v1','platform':platform,'shared_health_key_reused':reuse_health,'case_id':ident,'release_key_id':digest(release),'release_public_key_hex':release.hex(),'keyring_base64url':b64(keyring),'keyring_sha256':digest(keyring),'public_keyring_host_path':str(trust_dir/'keyring.json'),'public_keyring_metadata':metadata(trust_dir/'keyring.json'),'keyring_recipient_roles':['api','gateway'],'health_pin':{'schema_version':1,'key_id':digest(health),'public_key_hex':health.hex()},'release_private_metadata':metadata(release_key),'health_private_metadata':metadata(health_key),'health_recipient_role':'gateway','health_recipient_uid':owner,'gateway_mount_pending':True,'services_changed':False,'job_authority':False}
store('provision-result.json',result);return result
require(case.is_dir(),'existing explicit signer case')
provision=json.loads((case/'provision-result.json').read_text());require(provision['case_id']==ident and provision['platform']==platform and public(release_key).hex()==provision['release_public_key_hex']and public(health_key).hex()==provision['health_pin']['public_key_hex'],'original independent keys')
require(metadata(release_key)==provision['release_private_metadata']and metadata(health_key)==provision['health_private_metadata'],'protected private key metadata unchanged')
require(metadata(trust_dir/'keyring.json')==provision['public_keyring_metadata']and digest((trust_dir/'keyring.json').read_bytes())==provision['keyring_sha256'],'original protected public keyring')
if payload['action']=='readback':return provision
require(payload['action']in('sign-release','sign-baseline'),'fixed signing purpose only')
require(platform=='linux','Windows signing awaits a separately qualified actual MSVC source pair; never relabel GNU')
raw=decode(payload['canonical_payload_base64url']);require(len(raw)<=32768 and digest(raw)==payload['payload_sha256'],'exact typed public payload')
doc=json.loads(raw)
artifacts={1:[('7fef8d0f1e2bcf5cd6c373e567a0c17bfb08d8c780cd4d1925b6c1355e572547',16275360),('8fdc6ded02278eb18e64003d0bc7bf45d452cd48ded0450e6e900ca66e44d449',13325104)],2:[('4d212066bef226af3fa679ffe95f69c43a9668cbef7e665d53328f4e41aa3799',16273896),('89b28db3afe870c667297dff97ad7a042c550ccce1f712d69108e8de672ad450',13322944)]}
if payload['action']=='sign-release':
sequence=doc['release_sequence'];require(sequence in(1,2)and doc['schema_version']==1 and doc['version']==('0.1.0'if sequence==1 else'0.1.1')and doc['platform']=='x86_64-unknown-linux-gnu'and doc['protocol_major']==1 and doc['state_schema']==1 and doc['minimum_updater_version']==1,'exact compatible release profile')
require(str(uuid.UUID(doc['release_id']))==doc['release_id']and doc['release_id']!='00000000-0000-0000-0000-000000000000','release identity')
require(abs(int(datetime.datetime.now(datetime.timezone.utc).timestamp())-doc['published_at'])<300 and doc['expires_at']-doc['published_at']==604800,'bounded initial release dates')
require(len(doc['artifacts'])==2 and [a['role']for a in doc['artifacts']]==['agent','helper']and [(a['sha256'],a['bytes'])for a in doc['artifacts']]==artifacts[sequence],'exact frozen source artifact hashes')
ids=[str(uuid.UUID(a['artifact_id']))for a in doc['artifacts']];require(len(set(ids))==2 and all(v!='00000000-0000-0000-0000-000000000000'for v in ids),'distinct artifact identities')
prefix=b'rmm.agent-release.v1\0';name='release-'+str(sequence)
else:
require(doc['schema_version']==1 and doc['profile']=='decoder_compatible_handoff_v1'and doc['platform']=='x86_64-unknown-linux-gnu'and doc['activation_floor']==1 and doc['previous_record_sha256']is None and doc['rolled_back']is False,'initial compatible baseline only')
prior=json.loads((case/'release-1-result.json').read_text());require(doc['release_envelope']==prior['envelope']and doc['manifest_sha256']==prior['payload_sha256'],'exact original signed baseline release')
qualification=decode(payload['qualification_base64url']);q=json.loads(qualification)
require(q['profile']=='linux_compatible_baseline_qualification_v1'and q['normal_signed_sync_observed']and q['ready']is False and q['helper_ready']is False and q['unlock']is False and q['job_authority']is False,'independent actual compatible qualification, never a lease')
require([s['service']for s in q['services']]==['agent','general','full']and [s['process']['image_sha256']for s in q['services']]==[artifacts[1][0][0],artifacts[1][1][0],artifacts[1][1][0]],'actual compatible initial code pair')
require(doc['activation_evidence']=={'kind':'bootstrap','qualification_receipt_sha256':digest(qualification)},'exact public qualification hash')
observed=datetime.datetime.fromisoformat(q['observed_at'].replace('Z','+00:00'));require(observed.tzinfo is not None and int(observed.timestamp())==doc['activated_at'],'actual baseline activation time')
prefix=b'rmm.agent-update-baseline.v1\0';name='baseline'
require(not(case/(name+'-intent.json')).exists(),'existing signing intent means readback only')
store(name+'-intent.json',{'payload_sha256':digest(raw),'purpose':payload['action'],'job_authority':False})
message=case/(name+'.message');signature=case/(name+'.signature')
with message.open('xb')as stream:stream.write(prefix+raw);stream.flush();os.fsync(stream.fileno())
run(['openssl','pkeyutl','-sign','-rawin','-inkey',str(release_key),'-in',str(message),'-out',str(signature)])
signed=signature.read_bytes();require(len(signed)==64,'Ed25519 signature')
public_der=case/(name+'.public.der')
with public_der.open('xb')as stream:stream.write(bytes.fromhex('302a300506032b6570032100')+bytes.fromhex(provision['release_public_key_hex']));stream.flush();os.fsync(stream.fileno())
run(['openssl','pkeyutl','-verify','-rawin','-pubin','-keyform','DER','-inkey',str(public_der),'-in',str(message),'-sigfile',str(signature)])
result={'schema_version':1,'key_id':provision['release_key_id'],'payload_sha256':digest(raw),'envelope':{'schema_version':1,'key_id':provision['release_key_id'],'payload_bytes':b64(raw),'signature':b64(signed)},'job_authority':False}
store(name+'-result.json',result);return result
def main():
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=('public-separation','provision','readback','sign-release','sign-baseline'));parser.add_argument('--input',type=Path,required=True);args=parser.parse_args()
p=json.loads(args.input.read_text());p['action']=args.action
print(json.dumps(bootstrap.native_rpc(server,p,config='server.conf')))
if __name__=='__main__':main()