Run approved FreeBSD root jobs through independently pinned and synchronized local helper
Rust development slice / linux (push) Failing after 11s
Rust development slice / linux (push) Failing after 11s
This commit is contained in:
@@ -0,0 +1,132 @@
|
||||
"""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()<end
|
||||
time.sleep(.05)
|
||||
invoke('Probe',True,uid=65534)
|
||||
assert invoke('Probe')=='Pins'
|
||||
snap=invoke({'Snapshot':1})['Snapshot']; q=pb.SyncRequest(request_id=new(),journal_id=new(),checkpoint=1,
|
||||
helper_journal_id=snap['journal_id'],helper_checkpoint=snap['checkpoint'],assignment_version=1,journal_complete=True)
|
||||
raw=q.SerializeToString();t=now()
|
||||
dec=pack(dict(**b,domain='rmm.reconciliation-decision',schema_version=1,decision_id=new(),request_id=q.request_id,
|
||||
request_hash=sha(raw),connection_generation=1,boot_id=snap['boot_id'],journal_id=q.journal_id,checkpoint=1,
|
||||
helper_journal_id=q.helper_journal_id,helper_checkpoint=q.helper_checkpoint,issued_at=t.isoformat(),
|
||||
valid_until=(t+datetime.timedelta(seconds=59)).isoformat(),ready=True,helper_ready=True,reason='CONSISTENT',
|
||||
attempts=[],acknowledged_message_ids=[],key_id=sha(public)))
|
||||
invoke({'Apply':[list(raw),dict(decision_bytes=list(dec),signature=signed(dec))]})
|
||||
t=now();job=dict(**b,schema_version=1,job_id=new(),attempt_id=new(),execution_identity='root',
|
||||
not_before=(t-datetime.timedelta(minutes=2)).isoformat(),start_before=(t+datetime.timedelta(minutes=2)).isoformat(),
|
||||
max_runtime_seconds=10,max_output_bytes=1024,action=dict(action='run_script',interpreter='posix_sh',
|
||||
script_utf8='id -u\n',arguments=[],expected_stdout='0\n',privileged_script_profile='full_maintenance_v1'))
|
||||
body=pack(job);aid=new();ph=sha(b'isolated plan')
|
||||
permit=pack(dict(**b,domain='rmm.execution-permit',schema_version=1,grant_id=new(),authorization_id=aid,
|
||||
job_id=job['job_id'],attempt_id=job['attempt_id'],plan_hash=ph,job_payload_hash=sha(body),action='run_script',
|
||||
execution_identity='root',not_before=(t-datetime.timedelta(seconds=6)).isoformat(),
|
||||
start_before=(t+datetime.timedelta(seconds=50)).isoformat(),max_runtime_seconds=10,key_id=sha(public)))
|
||||
req=dict(job_bytes=list(body),permit_bytes=list(permit),signature=signed(permit),plan_hash=ph,authorization_id=aid)
|
||||
invoke({'Execute':[1,dict(req,signature=[0]*64)]},True)
|
||||
invoke({'Execute':[2,req]},True)
|
||||
invoke({'Execute':[1,dict(req,job_bytes=list(body.replace(b'id -u',b'id -g')))]},True)
|
||||
db=sqlite3.connect('file:'+str(inside(STATE+'/consumption.sqlite'))+'?mode=ro',uri=True)
|
||||
assert db.execute('SELECT count(*) FROM consumed').fetchone()==(0,)
|
||||
out=invoke({'Execute':[1,req]})['Outcome']
|
||||
assert out['state']=='succeeded' and out['exit_code']==0 and bytes(out['stdout'])==b'0\n'
|
||||
assert out['evidence']['execution_uid']==0 and out['evidence']['script_sha256']==sha(b'id -u\n')
|
||||
assert invoke({'Execute':[1,req]})['Outcome']==out
|
||||
assert db.execute('SELECT count(*) FROM consumed JOIN execution_evidence USING(grant_id) WHERE result IS NOT NULL AND start IS NOT NULL').fetchone()==(1,)
|
||||
db.close()
|
||||
result.update(native_chroot_root_uid=0,replay_consumptions=1,foreign_peer_denied=True,
|
||||
bad_signature_denied=True,altered_script_denied=True,stale_channel_denied=True)
|
||||
finally:
|
||||
helper.terminate();helper.wait(timeout=8)
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
if not sys.platform.startswith('freebsd') or os.getuid()!=0:sys.exit('requires FreeBSD test guest as root')
|
||||
sys.path.insert(0,'/usr/local/libexec/discovery-agent/agent.pyz')
|
||||
with tempfile.TemporaryDirectory(prefix='discovery-helper-fixture-') as name:
|
||||
folder=Path(name);jail=folder/'root';jail.mkdir();result={};check(jail,folder,result);print(json.dumps(result))
|
||||
Reference in New Issue
Block a user