"""Native development integration: private chroot, disposable signer and identities. Runs the installed FreeBSD helper binary and a child with the discovery uid in an empty root; the installed device's socket, config, keys and journals are not used. """ import datetime import hashlib import json import os from pathlib import Path import pwd import re import shutil import socket import sqlite3 import struct import subprocess import sys import tempfile import time import uuid APP='/usr/local/libexec/discovery-agent/rmm-opnsense-jobs' CONF='/usr/local/etc/discovery-agent' SOCK='/var/run/discovery-root-jobs/control.sock' STATE='/var/db/discovery-root-jobs' pack=lambda v:json.dumps(v,separators=(',',':')).encode() sha=lambda b:hashlib.sha256(b).hexdigest() new=lambda:str(uuid.uuid4()) now=lambda:datetime.datetime.now(datetime.timezone.utc) def check(jail, folder, result): import agent_pb2 as pb u=pwd.getpwnam('discovery') def inside(path):return jail/path.lstrip('/') def copy(path): dst=inside(path);dst.parent.mkdir(exist_ok=True,parents=True);shutil.copyfile(path,dst);dst.chmod(0o555) copy('/libexec/ld-elf.so.1') for path in [APP,'/bin/sh','/usr/bin/id','/sbin/sysctl']: copy(path) for lib in re.findall(r'=> (/\S+)',subprocess.check_output(['ldd',path],text=True)):copy(lib) for path in [CONF,STATE,str(Path(SOCK).parent),'/tmp','/dev']:inside(path).mkdir(exist_ok=True,parents=True) inside(STATE).chmod(0o700);inside('/tmp').chmod(0o1777);inside('/dev/null').touch() key=folder/'fixture.key' subprocess.run(['openssl','genpkey','-algorithm','Ed25519','-out',key],check=True) public=subprocess.check_output(['openssl','pkey','-in',key,'-pubout','-outform','DER'])[-32:] def signed(data): f=folder/'message';f.write_bytes(data) return list(subprocess.check_output(['openssl','pkeyutl','-sign','-rawin','-inkey',key,'-in',f])) b=dict(tenant_id=new(),asset_id=new(),agent_id=new(),assignment_version=1,enrollment_generation=1) binding=pack(dict(**b,public_key_hex=public.hex()));inside(CONF+'/job-binding.json').write_bytes(binding) image=sha(inside(APP).read_bytes()) policy=pack(dict(schema_version=1,profile='full_maintenance_v1',agent_uid=u.pw_uid,agent_gid=u.pw_gid, helper_binary_sha256=image,binding_sha256=sha(binding))) inside(CONF+'/root-policy.json').write_bytes(policy) helper=subprocess.Popen([APP,'--root-helper'],preexec_fn=lambda:(os.chroot(jail),os.chdir('/')), stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL) def invoke(op,deny=False,uid=u.pw_uid): # Socket comes from the isolated chroot. The peer uid seen by getpeereid # must be a real kernel credential, not a field in the test frame. a,z=socket.socketpair();pid=os.fork() if pid==0: a.close() try: os.chroot(jail);os.chdir('/');os.setgroups([]);os.setgid(u.pw_gid);os.setuid(uid) with socket.socket(socket.AF_UNIX) as s: s.settimeout(12);s.connect(SOCK) nonce=new();raw=pack(dict(nonce=nonce,policy=sha(policy),image=image,op=op)) s.sendall(struct.pack('>I',len(raw))+raw) with s.makefile('rb') as f: hdr=f.read(4) if not hdr:os._exit(0 if deny else 1) n=struct.unpack('>I',hdr)[0];assert n<=8*1024*1024 r=json.loads(f.read(n));assert not deny and r['nonce']==nonce z.sendall(pack(r['data'])) os._exit(0) except (ConnectionResetError,BrokenPipeError): os._exit(0 if deny else 1) except BaseException:os._exit(1) z.close() with a,a.makefile('rb') as f:data=f.read() assert os.waitpid(pid,0)[1]==0, 'unexpected response from helper' return json.loads(data) if data else None try: end=time.monotonic()+8 while not inside(SOCK).is_socket(): assert helper.poll() is None and time.monotonic()