Run approved FreeBSD root jobs through independently pinned and synchronized local helper
Rust development slice / linux (push) Failing after 11s

This commit is contained in:
2026-11-20 08:27:13 +01:00
parent 2e3916b84b
commit 0b0790de71
17 changed files with 1037 additions and 61 deletions
+3 -1
View File
@@ -17,6 +17,8 @@ Der OPNsense-eigene Python-Interpreter führt zwei Zipapps aus. Der lokale Colle
**Firewall:** aktiver PF-Hauptregelsatz in Kernelreihenfolge, einschließlich automatisch erzeugter Regeln. Kein Editor und kein rekursives Auslesen der Anchor-Regelsätze.
**Profile:** Ohne Worker und Signaturbindung bleibt das Gerät passiv. Mit dem FreeBSD-Worker unterstützt `0.1.0-opnsense.5` genau die feste Kernelabfrage (`uname -s\n`, `posix_sh`, erwartete Ausgabe `FreeBSD\n`, keine Argumente, Dienstkonto, 10 s, 1024 Byte). Unter **Geräte → OPNsense-Kernelabfrage** lässt sie sich für diese Installation einreichen. Die persönliche WebUI-Genehmigung und der signierte Startgrant sind erforderlich. Root, beliebige Shell-/Bibliotheksskripte und signierte OPNsense-Releases bleiben offen. Das Gerät ist kein Linuxziel.
**Skripte:** Unter **Aufträge → Neuer Auftrag** die OPNsense-Zielgeräte wählen. Unter **Aus der Bibliothek** eine feste POSIX-Shell-Revision wählen, alternativ ein **Einmaliges Skript** eingeben. **Ausführen als** unterstützt Dienstkonto und bei entsprechender Berechtigung `root`. **Zusammenfassung ansehen** bindet das Skript samt Zielen und Grenzen; **Zur Genehmigung einreichen** legt den Antrag an. Die persönliche Freigabe erfolgt unter **Genehmigungen**, die Ausgabe erscheint im Auftrag. OPNsense kann POSIX-Shellskripte ausführen; Linux-spezifische Programme und Optionen werden nicht übersetzt. Zwei [Startrevisionen aus dem Repository](../../migrations/0047_opnsense_library.sql) zeigen Version/Ausführungskonto bzw. aktive Firewallregeln. Im Gerätedetail stehen Inventar und Verweise auf vorhandene Aufträge.
**Probe bereitstellen:** Im Gast steht die gepinnte Toolchain unter `/opt/discovery-rust`. `cargo build --locked -p rmm-opnsense-jobs` nativ bauen und `rmm-opnsense-jobs` root-eigen (0555) neben den Zipapps installieren. Auf der bereits aufgenommenen Testinstallation `python3 -I pin-probe.py TENANT ASSET AGENT ENROLLMENT_GENERATION ASSIGNMENT_VERSION` mit den bestätigten Kennungen aufrufen. Das Skript bezieht den öffentlichen Jobschlüssel über das bestehende Gerätezertifikat und überschreibt keine andere Bindung. Den Agentendienst anschließend neu starten. Der Worker nutzt bestehende Nachrichtenfolgen, den signierten Abgleich und getrennte dauerhafte Start-/Ergebnisjournale. Er läuft ohne Netzwerklistener als `discovery`. Der [native Integrationstest](../../crates/agent-opnsense-jobs/src/native/tests.rs) prüft mit eigener Testidentität und eigenem Schlüssel die Ablehnung einer defekten Signatur, erwartete Ausgabe, einen Verbrauch und keine zweite Ausführung bei Wiederzustellung. Das ist ein separater Beleg vom persönlich genehmigten Geräteauftrag.
**Root-Helper (ab `0.1.0-opnsense.6`):** Native Binärdatei zusätzlich in den privaten Stagingordner kopieren. Auf dem Gast `python3 -I enable-root.py /absoluter/Stagingpfad/rmm-opnsense-jobs` und `sh install-dev.sh /absoluter/Stagingpfad` ausführen. Die lokale Policy bindet Worker-Hash, Gerätebindung, Dienst-UID und Gruppe. Der zusätzliche `rc.d`-Prozess läuft als root, hört ausschließlich auf einem geschützten Unix-Socket und prüft den Peer über `getpeereid`. Den vom Helper bestätigten Binär- und Policyhash mit `tools/dev_opnsense_root_scope.py --help` für die genaue Kopplung und den berechtigten lokalen Principal registrieren. Es gibt keine automatische Freigabe oder automatische Pinrotation. Root akzeptiert `posix_sh` mit `full_maintenance_v1` (bis 300 Sekunden und 65536 Ausgabebyte), verifiziert selbst Sync, Grant, Skriptbytes, Boot und Uhr, und führt ein eigenes Verbrauchsjournal in `/var/db/discovery-root-jobs`. Ohne Startbeleg gibt es kein positives Ergebnis. Bei `unknown` zuerst die bestehenden Journale abgleichen. Der [isolierte native Helper-Test](test_root_helper.py) benutzt nur eine Wegwerfidentität und separate Journale.
+18 -5
View File
@@ -1,4 +1,4 @@
"""Unprivileged OPNsense telemetry channel. Input never selects a local command."""
"""Unprivileged OPNsense telemetry and signed job transport."""
import hashlib
import contextlib
import fcntl
@@ -20,7 +20,7 @@ STATE = Path('/var/db/discovery-agent')
CA = '/usr/local/etc/discovery-agent/ca.pem'
HOST = 'discovery.ease-technologies.de'
MEDIA = 'application/x-protobuf'
VERSION = '0.1.0-opnsense.5'
VERSION = '0.1.0-opnsense.6'
WORKER = Path('/usr/local/libexec/discovery-agent/rmm-opnsense-jobs')
BINDING = Path('/usr/local/etc/discovery-agent/job-binding.json')
@@ -225,11 +225,19 @@ def run_channel(db, identity, boot, instance, stack):
ctx = context()
ctx.load_cert_chain(STATE/'device.pem', STATE/'device.key')
caps = ['heartbeat/1','opnsense.base/1']
root_caps=[]
if enabled:
caps.extend(['rmm.sync.v1','run_script','opnsense.uname/1'])
caps.extend(['rmm.sync.v1','run_script','opnsense.uname/1','opnsense.posix/1'])
if Path('/usr/local/etc/discovery-agent/root-policy.json').is_file():
probe=subprocess.run([WORKER,'--root-capabilities'],capture_output=True,timeout=15)
if probe.returncode==0:
root_caps=json.loads(probe.stdout)
caps.extend(root_caps)
generation = send('client_hello',pb.ClientHello(agent_version=VERSION, capabilities=caps))
if enabled:
p = subprocess.Popen([WORKER,identity['agent_id'],identity['asset_id'],boot,str(generation)],
env=os.environ.copy();env.pop('DISCOVERY_ROOT_SESSION',None)
if root_caps:env['DISCOVERY_ROOT_SESSION']='1'
p = subprocess.Popen([WORKER,identity['agent_id'],identity['asset_id'],boot,str(generation)],env=env,
stdin=subprocess.PIPE,stdout=subprocess.PIPE,close_fds=True)
def close():
p.stdin.close()
@@ -271,8 +279,13 @@ def run_channel(db, identity, boot, instance, stack):
scope='opnsense.base',schema_version=1,chunk_count=1,data=raw,
sha256=hashlib.sha256(raw).digest(),completeness='partial'),stamp//1_000_000)
last = stamp
if jobs:
if jobs and (root_caps or not Path('/usr/local/etc/discovery-agent/root-policy.json').is_file()):
jobs.pump(ctx,identity['agent_id'],boot,generation)
elif jobs:
# Preserve the established helper journal chain across a helper
# restart. Keep telemetry flowing, then renegotiate capabilities.
if subprocess.run([WORKER,'--root-capabilities'],capture_output=True,timeout=15).returncode==0:
return
time.sleep(20)
+10 -1
View File
@@ -11,6 +11,15 @@ start_cmd=discovery_start
stop_cmd=discovery_stop
discovery_start() {
if [ -f /usr/local/etc/discovery-agent/root-policy.json ]; then
install -d -o root -g wheel -m 0700 /var/db/discovery-root-jobs || return 1
install -d -o root -g discovery -m 0750 /var/run/discovery-root-jobs || return 1
pid=/var/run/discovery-root-jobs.pid
if [ -z "$(check_pidfile "$pid" /usr/sbin/daemon)" ]; then
/usr/sbin/daemon -f -r -R 5 -P "$pid" -S -T discovery-root-jobs \
/usr/local/libexec/discovery-agent/rmm-opnsense-jobs --root-helper || return 1
fi
fi
for part in collect agent; do
pid=/var/run/discovery-$part.pid
[ -z "$(check_pidfile "$pid" /usr/sbin/daemon)" ] || continue
@@ -21,7 +30,7 @@ discovery_start() {
done
}
discovery_stop() {
for part in agent collect; do
for part in agent collect root-jobs; do
pid=$(check_pidfile "/var/run/discovery-$part.pid" /usr/sbin/daemon)
[ -z "$pid" ] || kill -TERM "$pid"
done
+38
View File
@@ -0,0 +1,38 @@
"""In the guest, bind a staged native helper to the existing signed job identity.
Print only the hashes used by the central operator. Never replace another policy.
"""
import hashlib
import json
import os
from pathlib import Path
import pwd
import stat
import sys
def main():
if os.getuid()!=0 or os.geteuid()!=0 or len(sys.argv)!=2:
raise SystemExit('Run as root: enable-root.py /absolute/staging/rmm-opnsense-jobs')
app=Path(sys.argv[1]).resolve(strict=True)
conf=Path('/usr/local/etc/discovery-agent')
binding=conf/'job-binding.json'
for path in (app,*app.parents,binding,*binding.parents):
info=path.lstat()
if info.st_uid!=0 or info.st_mode & 0o022 or stat.S_ISLNK(info.st_mode):
raise ValueError('untrusted provisioning path')
user=pwd.getpwnam('discovery')
if not user.pw_uid or not user.pw_gid: raise ValueError('invalid agent identity')
image=hashlib.file_digest(app.open('rb'),'sha256').hexdigest()
policy=dict(schema_version=1,profile='full_maintenance_v1',agent_uid=user.pw_uid,agent_gid=user.pw_gid,
binding_sha256=hashlib.sha256(binding.read_bytes()).hexdigest(),helper_binary_sha256=image)
raw=(json.dumps(policy,separators=(',',':'))+'\n').encode()
path=conf/'root-policy.json'
if path.exists():
if path.is_symlink() or path.read_bytes()!=raw: raise ValueError('existing policy differs')
else:
with path.open('xb') as f:
os.fchmod(f.fileno(),0o444); f.write(raw);f.flush();os.fsync(f.fileno())
print(json.dumps(dict(helper_binary_sha256=image,helper_policy_sha256=hashlib.sha256(raw).hexdigest())))
if __name__=='__main__':main()
+11 -2
View File
@@ -24,13 +24,22 @@ done
if [ -x "$rc" ]; then
"$rc" onestop
for _ in 1 2 3 4 5; do
[ -f /var/run/discovery-agent.pid ] || [ -f /var/run/discovery-collect.pid ] || break
[ -f /var/run/discovery-agent.pid ] || [ -f /var/run/discovery-collect.pid ] || [ -f /var/run/discovery-root-jobs.pid ] || break
sleep 1
done
if [ -f /var/run/discovery-agent.pid ] || [ -f /var/run/discovery-collect.pid ]; then
if [ -f /var/run/discovery-agent.pid ] || [ -f /var/run/discovery-collect.pid ] || [ -f /var/run/discovery-root-jobs.pid ]; then
echo 'Existing service still running' >&2; exit 1
fi
fi
if [ -f "$src/rmm-opnsense-jobs" ]; then
install -o root -g wheel -m 0555 "$src/rmm-opnsense-jobs" "$app/jobs.next"
if [ -f "$conf/root-policy.json" ] && ! /usr/local/bin/python3 -I -c \
'import hashlib,json,sys;sys.exit(hashlib.file_digest(open(sys.argv[1],"rb"),"sha256").hexdigest()!=json.load(open(sys.argv[2]))["helper_binary_sha256"])' \
"$app/jobs.next" "$conf/root-policy.json"; then
echo 'Native helper differs from the local policy pin' >&2; "$rc" start; exit 1
fi
mv -f "$app/jobs.next" "$app/rmm-opnsense-jobs"
fi
for part in collect agent; do mv -f "$app/$part.next" "$app/$part.pyz"; done
install -o root -g wheel -m 0444 "$src/ca.pem" "$conf/ca.pem"
install -o root -g wheel -m 0555 "$src/discovery_agent" "$rc"
+132
View File
@@ -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))