Compare commits

..
Author SHA1 Message Date
kevin_janssen 131cc53de2 Document Windows drive-letter inventory and native multi-drive checks
Rust development slice / linux (push) Failing after 14s
2026-11-20 08:58:56 +01:00
kevin_janssen 04037c7acf Display Windows fixed volumes individually in both fleet views 2026-11-20 08:53:20 +01:00
kevin_janssen 9c61f8f2eb Collect capacity for every Windows fixed drive letter 2026-11-20 08:50:49 +01:00
kevin_janssen b5e96853c3 Show occupied disk and RAM capacity with matching used and free segments
Rust development slice / linux (push) Failing after 9s
2026-11-20 08:40:48 +01:00
kevin_janssen 957bf3cd58 Swap free and used colors on RAM and disk capacity bars
Rust development slice / linux (push) Failing after 10s
2026-11-20 08:37:18 +01:00
kevin_janssen 021fdfc1bc Use muted terracotta for occupied RAM and disk capacity
Rust development slice / linux (push) Failing after 10s
2026-11-20 08:35:50 +01:00
kevin_janssen 9057808d16 Show free disk capacity with the same bar and caption as RAM
Rust development slice / linux (push) Failing after 10s
2026-11-20 08:31:15 +01:00
kevin_janssen 0b0790de71 Run approved FreeBSD root jobs through independently pinned and synchronized local helper
Rust development slice / linux (push) Failing after 11s
2026-11-20 08:27:13 +01:00
kevin_janssen 2e3916b84b Seed versioned OPNsense scripts and label the shared POSIX interpreter 2026-11-20 08:22:59 +01:00
kevin_janssen 1f3cd5ea0c Route OPNsense library and custom jobs through the standard order composer 2026-11-20 08:15:07 +01:00
kevin_janssen 8a1ea58d86 Plan OPNsense POSIX root scripts with explicit device policy, profile and approval 2026-11-20 08:12:52 +01:00
kevin_janssen 47249644b9 Record approved OPNsense kernel probe and matching native start evidence
Rust development slice / linux (push) Failing after 6s
2026-11-20 08:06:32 +01:00
kevin_janssen 6792b0dd11 Verify signed OPNsense kernel probes on the service account and retain exactly-once evidence
Rust development slice / linux (push) Failing after 13s
2026-11-19 20:55:29 +01:00
kevin_janssen 2e060e9507 Plan an exact service-account OPNsense kernel probe through normal approval 2026-11-19 20:48:41 +01:00
kevin_janssen 71adc2adf6 Record live OPNsense enrollment, WireGuard handshakes and remaining job parity
Rust development slice / linux (push) Failing after 14s
2026-11-19 20:14:34 +01:00
kevin_janssen 8acbee6a60 Qualify FreeBSD kernel time and supervise bounded POSIX process groups natively 2026-11-19 20:14:34 +01:00
kevin_janssen 6bf6e2539c Exercise appliance secret projection, truncation and device-only UI states
Rust development slice / linux (push) Failing after 12s
2026-11-19 20:10:36 +01:00
46 changed files with 2308 additions and 112 deletions
Generated
+22
View File
@@ -2187,6 +2187,7 @@ dependencies = [
"chrono", "chrono",
"ed25519-dalek", "ed25519-dalek",
"hex", "hex",
"libc",
"openssl", "openssl",
"prost", "prost",
"reqwest", "reqwest",
@@ -2285,6 +2286,27 @@ dependencies = [
"zeroize", "zeroize",
] ]
[[package]]
name = "rmm-opnsense-jobs"
version = "0.1.0"
dependencies = [
"anyhow",
"chrono",
"ed25519-dalek",
"hex",
"libc",
"prost",
"rmm-agent-core",
"rmm-agent-linux",
"rmm-domain",
"rmm-protocol",
"rusqlite",
"serde",
"serde_json",
"sha1",
"uuid",
]
[[package]] [[package]]
name = "rmm-persistence" name = "rmm-persistence"
version = "0.1.0" version = "0.1.0"
+1 -1
View File
@@ -1,7 +1,7 @@
[workspace] [workspace]
resolver = "2" resolver = "2"
exclude = ["crates/oidc-auth"] exclude = ["crates/oidc-auth"]
members = ["crates/domain", "crates/protocol", "crates/persistence", "crates/server", "crates/agent-linux", "crates/agent-core", "crates/agent-windows", "crates/agent", "crates/privileged-helper", "crates/updater", "crates/updater-handoff", "crates/updater-linux", "crates/updater-worker", "crates/update-history", "crates/time-attestation", "crates/time-source-linux", "crates/time-broker-linux"] members = ["crates/domain", "crates/protocol", "crates/persistence", "crates/server", "crates/agent-linux", "crates/agent-core", "crates/agent-windows", "crates/agent", "crates/agent-opnsense-jobs", "crates/privileged-helper", "crates/updater", "crates/updater-handoff", "crates/updater-linux", "crates/updater-worker", "crates/update-history", "crates/time-attestation", "crates/time-source-linux", "crates/time-broker-linux"]
[workspace.package] [workspace.package]
version = "0.1.0" version = "0.1.0"
+5 -1
View File
@@ -12,7 +12,9 @@ Der Agent meldet den Gerätetyp mit dem passiven Hardwareinventar. `physical` be
Für aktuelle virtuelle Geräte kann die WebUI einen registrierten Hypervisor aus demselben Kundenbestand zuordnen. Die Geräteübersicht zeigt diese Verbindung unter dem Hostnamen der VM und verlinkt auf die Gerätedetails des Hypervisors. Die Zuordnung gilt, solange der verknüpfte Host im Bestand ist und sich als Hypervisor meldet. Eine VM mit gemeldetem Hersteller Hetzner erhält bei fehlendem konkreten Host den Anzeigeplatzhalter „Hetzner Cloud“. Der Platzhalter hat keine Kopplung und zählt nicht als registriertes Gerät. Für aktuelle virtuelle Geräte kann die WebUI einen registrierten Hypervisor aus demselben Kundenbestand zuordnen. Die Geräteübersicht zeigt diese Verbindung unter dem Hostnamen der VM und verlinkt auf die Gerätedetails des Hypervisors. Die Zuordnung gilt, solange der verknüpfte Host im Bestand ist und sich als Hypervisor meldet. Eine VM mit gemeldetem Hersteller Hetzner erhält bei fehlendem konkreten Host den Anzeigeplatzhalter „Hetzner Cloud“. Der Platzhalter hat keine Kopplung und zählt nicht als registriertes Gerät.
Die RAM-Spalte zeigt den für Anwendungen verfügbaren und den gesamten physischen Arbeitsspeicher in GiB. Im RAM-Balken ist der verfügbare Anteil (links) grün und der belegte Anteil grau. Die sichtbare Prozentangabe benennt den verfügbaren Anteil. Ohne gültiges Wertepaar erscheint kein Balken. Der Laufwerksbalken hebt weiterhin den belegten Anteil hervor. Die CPU-Spalte ergänzt die zuletzt gemessene Systemauslastung als Prozentwert. Die Agenten gewinnen sie aus den CPU-Zeitdifferenzen zwischen zwei Heartbeats im Abstand von ungefähr 30 Sekunden. Linux liefert systemweite Werte. Windows liefert den Wert, wenn alle logischen CPUs zu einer einzigen Prozessorgruppe gehören. Vor dem ersten aussagekräftigen Intervall bleibt die Auslastung offen. Die WebUI und MCP lesen dieselbe letzte Messung. Für Agenten ohne Ressourcenmeldung stammen verfügbare RAM-Werte aus dem vorhandenen Inventar. [Inventarprojektion](crates/server/src/devices.rs) Ab Windows-Client `0.1.27` zeigt die Spalte **Speicher belegt / gesamt** jedes lokale Festplattenvolume mit Laufwerksbuchstaben separat an, das Systemlaufwerk zuerst. Ein Laufwerk mit unbekannter Kapazität behält seinen Buchstaben ohne Belegungsbalken. Die Zuordnung erfolgt pro logischem Volume, nicht pro physischem Datenträger. Netzlaufwerke, optische Medien und Volumes ohne Laufwerksbuchstaben gehören nicht zu dieser Liste. Bei älteren Inventarmeldungen bleibt die vorhandene Systemlaufwerkskapazität sichtbar.
Geräteübersicht und Gerätedetails zeigen für Laufwerke und RAM „belegt / gesamt“ in GiB. Belegt ist die Gesamtkapazität abzüglich des freien Laufwerksplatzes bzw. des für Anwendungen verfügbaren Arbeitsspeichers. Die Balken in der Übersicht zeigen links den belegten Anteil in gedämpftem Rot und rechts den freien Anteil in Grün. Darunter steht der belegte Anteil in Prozent. Ohne gültiges Wertepaar erscheint kein Balken. Die CPU-Spalte ergänzt die zuletzt gemessene Systemauslastung als Prozentwert. Die Agenten gewinnen sie aus den CPU-Zeitdifferenzen zwischen zwei Heartbeats im Abstand von ungefähr 30 Sekunden. Linux liefert systemweite Werte. Windows liefert den Wert, wenn alle logischen CPUs zu einer einzigen Prozessorgruppe gehören. Vor dem ersten aussagekräftigen Intervall bleibt die Auslastung offen. Die WebUI und MCP lesen dieselbe letzte Messung. Für Agenten ohne Ressourcenmeldung stammen verfügbare RAM-Werte aus dem vorhandenen Inventar. [Inventarprojektion](crates/server/src/devices.rs)
Kunden lassen sich in der WebUI anlegen und umbenennen. Unter **Gerät verwalten → Kunden wechseln** wählt eine berechtigte Person den Zielkunden. Der Server prüft die Rechte zur Geräteverwaltung im bisherigen Kunden und zur Geräteaufnahme im Zielkunden. Der bereits installierte Agent empfängt den Wechsel über seine authentisierte Verbindung und erhält ein neues Zertifikat für eine neue Kopplung. Mit der ersten gültigen Inventarmeldung der authentisierten neuen Kopplung schließt der Server den Wechsel automatisch ab. Er sperrt die bisherige Geräteidentität und schaltet den Bestand in derselben Transaktion auf den Zielkunden um. Inventar und Auftragsergebnisse der bisherigen Kopplung bleiben beim bisherigen Kunden. Noch nicht abgeschlossene Aufträge, ungeklärte Versuche und gültige offene Genehmigungen müssen vor dem Wechsel abgeschlossen werden. Gerätegebundene erhöhte Rechte erfordern eine eigene Bindung für die neue Kopplung. Kunden lassen sich in der WebUI anlegen und umbenennen. Unter **Gerät verwalten → Kunden wechseln** wählt eine berechtigte Person den Zielkunden. Der Server prüft die Rechte zur Geräteverwaltung im bisherigen Kunden und zur Geräteaufnahme im Zielkunden. Der bereits installierte Agent empfängt den Wechsel über seine authentisierte Verbindung und erhält ein neues Zertifikat für eine neue Kopplung. Mit der ersten gültigen Inventarmeldung der authentisierten neuen Kopplung schließt der Server den Wechsel automatisch ab. Er sperrt die bisherige Geräteidentität und schaltet den Bestand in derselben Transaktion auf den Zielkunden um. Inventar und Auftragsergebnisse der bisherigen Kopplung bleiben beim bisherigen Kunden. Noch nicht abgeschlossene Aufträge, ungeklärte Versuche und gültige offene Genehmigungen müssen vor dem Wechsel abgeschlossen werden. Gerätegebundene erhöhte Rechte erfordern eine eigene Bindung für die neue Kopplung.
@@ -24,6 +26,8 @@ Die Spalte **Zweck** und das Gerätedetail zeigen optionalen Freitext. Unter **Z
## Vom Skript zum Ergebnis ## Vom Skript zum Ergebnis
**OPNsense:** Das Gerätegateway akzeptiert `opnsense.base/1` als eigene Inventarplattform. Im Gerätedetail erscheinen aktive PF-Filterregeln sowie getrennte Listen für konfigurierte VPNs und native Laufzeitbefunde. Fehlende Berechtigung bzw. ausgefallene Quellen sind kein Nachweis einer leeren Liste. Skriptaufträge gehören wie bei Linux und Windows unter **Aufträge**. Die WebUI bindet eine Bibliotheksrevision oder ein einmaliges POSIX-Skript an die ausgewählten OPNsense-Geräte. Für die Ausführung als `root` gelten zusätzlich zum normalen signierten Abgleich und persönlichen Freigabeverfahren `root:execute`, die zentrale Geräte- und Principalbindung sowie die unabhängige Prüfung durch den lokal provisionierten FreeBSD-Helper. [OPNsense-Betrieb](deploy/opnsense/README.md)
| Schritt | Verhalten | | Schritt | Verhalten |
| --- | --- | | --- | --- |
| Skript veröffentlichen | In der Bibliothek eines Kunden erhält ein Skript einen Namen, einen Interpreter, einen Standard-Ausführungskontext und eine unveränderliche Version. Eine Bearbeitung veröffentlicht eine weitere Version. | | Skript veröffentlichen | In der Bibliothek eines Kunden erhält ein Skript einen Namen, einen Interpreter, einen Standard-Ausführungskontext und eine unveränderliche Version. Eine Bearbeitung veröffentlicht eine weitere Version. |
+3
View File
@@ -31,3 +31,6 @@ openssl = { workspace = true, optional = true }
[target.'cfg(unix)'.dev-dependencies] [target.'cfg(unix)'.dev-dependencies]
openssl.workspace = true openssl.workspace = true
[target.'cfg(target_os = "freebsd")'.dependencies]
libc = "0.2"
+82
View File
@@ -0,0 +1,82 @@
//! Read-only FreeBSD kernel discipline for the signed reconciliation clock.
//! Never adjust the guest clock. No cached qualification across a failed read.
use crate::reconcile::{ClockReading, SyncClock};
use anyhow::{Context, Result, ensure};
use chrono::{DateTime, TimeDelta, Utc};
use std::{mem::MaybeUninit, time::Instant};
#[derive(Clone)]
pub struct NativeClock {
origin: DateTime<Utc>,
monotonic: Instant,
}
impl Default for NativeClock {
fn default() -> Self {
Self {
origin: Utc::now(),
monotonic: Instant::now(),
}
}
}
impl NativeClock {
fn observation(&self) -> Result<(DateTime<Utc>, TimeDelta)> {
let start = Instant::now();
let mut raw = MaybeUninit::<libc::ntptimeval>::zeroed();
// SAFETY: the read-only syscall writes the platform's ntptimeval.
let result = unsafe { libc::ntp_gettime(raw.as_mut_ptr()) };
ensure!(result == libc::TIME_OK, "FREEBSD_CLOCK_UNQUALIFIED");
let sample = unsafe { raw.assume_init() };
let wall =
DateTime::from_timestamp(sample.time.tv_sec, u32::try_from(sample.time.tv_nsec)?)
.context("FREEBSD_CLOCK_INVALID")?;
let duration = TimeDelta::from_std(start.elapsed())?;
ensure!(
sample.time_state == libc::TIME_OK
&& (0..=5_000_000).contains(&sample.maxerror)
&& (0..=sample.maxerror).contains(&sample.esterror)
&& sample.time.tv_nsec < 1_000_000_000
&& duration <= TimeDelta::milliseconds(100)
&& ((wall - self.origin) - TimeDelta::from_std(self.monotonic.elapsed())?)
.num_milliseconds()
.unsigned_abs()
<= 5000,
"FREEBSD_CLOCK_UNQUALIFIED"
);
Ok((wall, TimeDelta::microseconds(sample.maxerror) + duration))
}
}
impl SyncClock for NativeClock {
fn now(&self) -> Result<DateTime<Utc>> {
Ok(self.observation()?.0)
}
fn reading(&self) -> Result<ClockReading> {
let (wall, error) = self.observation()?;
Ok(ClockReading {
own_wall: wall,
upper: wall + error,
})
}
fn bounds(&self) -> Result<(DateTime<Utc>, DateTime<Utc>)> {
let (wall, error) = self.observation()?;
Ok((wall - error, wall + error))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore = "requires a FreeBSD guest synchronized by ntpd"]
fn native_bounds_and_monotonic_fence() -> Result<()> {
let mut clock = NativeClock::default();
let (low, high) = clock.bounds()?;
ensure!(low <= high && high - low <= TimeDelta::milliseconds(10200));
clock.origin += TimeDelta::minutes(1);
ensure!(clock.bounds().is_err());
Ok(())
}
}
+2
View File
@@ -5,6 +5,8 @@
pub mod auth; pub mod auth;
pub mod customer_transfer; pub mod customer_transfer;
pub mod crypto; pub mod crypto;
#[cfg(target_os = "freebsd")]
pub mod freebsd_clock;
pub mod helper_reconcile; pub mod helper_reconcile;
pub mod jobs; pub mod jobs;
pub mod ledger; pub mod ledger;
+44 -1
View File
@@ -114,7 +114,7 @@ pub(crate) fn run_controlled(
let state = unsafe { let state = unsafe {
libc::waitid( libc::waitid(
libc::P_PID, libc::P_PID,
child.id(), child.id() as libc::id_t,
info.as_mut_ptr(), info.as_mut_ptr(),
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT, libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
) )
@@ -232,6 +232,7 @@ fn drain(
} }
Ok(false) Ok(false)
} }
#[cfg(not(target_os = "freebsd"))]
fn group_has_no_live_members(pgid: u32) -> bool { fn group_has_no_live_members(pgid: u32) -> bool {
let Ok(entries) = std::fs::read_dir("/proc") else { let Ok(entries) = std::fs::read_dir("/proc") else {
return false; return false;
@@ -265,6 +266,48 @@ fn group_has_no_live_members(pgid: u32) -> bool {
true true
} }
#[cfg(target_os = "freebsd")]
fn group_has_no_live_members(pgid: u32) -> bool {
// FreeBSD has no Linux /proc/<pid>/stat. Ask the kernel for this
// process group while its original leader's PID is still reserved.
use std::{mem, ptr};
let mib = [
libc::CTL_KERN,
libc::KERN_PROC,
libc::KERN_PROC_PGRP,
pgid as i32,
];
let mut size = 0;
let query = |out, n: &mut usize| unsafe {
libc::sysctl(mib.as_ptr(), mib.len() as _, out, n, ptr::null(), 0)
};
let unit = mem::size_of::<libc::kinfo_proc>();
if query(ptr::null_mut(), &mut size) != 0 || size == 0 || size > 16 * 1024 * 1024 {
return false;
}
let mut rows = vec![mem::MaybeUninit::<libc::kinfo_proc>::zeroed(); size.div_ceil(unit) + 1];
size = rows.len() * unit;
if query(rows.as_mut_ptr().cast(), &mut size) != 0
|| !size.is_multiple_of(unit)
|| size / unit > rows.len()
{
return false;
}
let mut leader = false;
for row in &rows[..size / unit] {
// A successful MIB read returned this complete aligned record.
let row = unsafe { row.assume_init_ref() };
if row.ki_structsize as usize != unit
|| row.ki_pgid != pgid as i32
|| row.ki_stat != libc::SZOMB
{
return false;
}
leader |= row.ki_pid == pgid as i32;
}
leader
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
+24
View File
@@ -0,0 +1,24 @@
[package]
name = "rmm-opnsense-jobs"
version.workspace = true
edition.workspace = true
license.workspace = true
[target.'cfg(target_os = "freebsd")'.dependencies]
anyhow.workspace = true
chrono.workspace = true
hex.workspace = true
libc = "0.2"
prost.workspace = true
rmm-agent-core = { path = "../agent-core" }
rmm-agent-linux = { path = "../agent-linux" }
rmm-domain = { path = "../domain" }
rmm-protocol = { path = "../protocol" }
rusqlite.workspace = true
serde_json.workspace = true
serde.workspace = true
sha1 = "0.10"
uuid.workspace = true
[target.'cfg(target_os = "freebsd")'.dev-dependencies]
ed25519-dalek = "=2.2.0"
+20
View File
@@ -0,0 +1,20 @@
#[cfg(target_os = "freebsd")]
mod native;
#[cfg(target_os = "freebsd")]
mod root;
#[cfg(target_os = "freebsd")]
fn main() -> anyhow::Result<()> {
match std::env::args().nth(1).as_deref() {
Some("--root-helper") => root::serve(),
Some("--root-capabilities") => {
println!("{}", serde_json::to_string(&root::caps()?)?);
Ok(())
}
_ => native::main(),
}
}
#[cfg(not(target_os = "freebsd"))]
fn main() {
eprintln!("FreeBSD required");
std::process::exit(1);
}
+496
View File
@@ -0,0 +1,496 @@
//! One worker per authenticated Python HTTPS channel, never a network listener.
//! Executes approved service-account POSIX scripts or delegates approved root
//! scripts to the independently synchronized local helper.
use anyhow::{Context, Result, bail, ensure};
use chrono::Utc;
use prost::Message;
use rmm_agent_core::{
auth::{Binding, Outcome},
freebsd_clock::NativeClock,
jobs, ledger,
reconcile::{self, Channel, ClientSync, SyncClock},
};
use rmm_agent_linux::actions::{Interpreter, ScriptRequest, run_script_controlled};
use rmm_domain::jobs::{Action, JobPayload, hash};
use rmm_protocol::*;
use rusqlite::{Connection, params};
use std::{
env, fs,
io::{self, BufRead, Read, Write},
os::{
fd::AsRawFd,
unix::fs::{MetadataExt, OpenOptionsExt},
},
path::Path,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
thread::JoinHandle,
time::{Duration, Instant},
};
use uuid::Uuid;
#[cfg(test)]
mod tests;
fn supported(job: &JobPayload) -> bool {
job.execution_identity == "agent_service"
&& job.action.opnsense_service_script()
&& job
.action
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
}
struct Running {
offer: JobOffer,
grant: rmm_domain::jobs::ExecutionPermitPayload,
cancel: Arc<AtomicBool>,
task: JoinHandle<Outcome>,
}
struct Worker {
binding: Binding,
channel: Channel,
sync: ClientSync,
clock: NativeClock,
db: Connection,
ledger: Connection,
sync_due: Instant,
permit_after: Instant,
root_enabled: bool,
pending_sync: Option<SyncRequest>,
running: Option<Running>,
}
impl Drop for Worker {
fn drop(&mut self) {
if let Some(r) = self.running.take() {
r.cancel.store(true, Ordering::Release);
let _ = r.task.join();
}
}
}
impl Worker {
fn envelope(&self, payload: Payload) -> Result<Envelope> {
let seq = self.db.query_row(
"UPDATE counter SET seq=seq+1 WHERE id=1 RETURNING seq",
[],
|r| r.get(0),
)?;
Ok(Envelope {
protocol_major: 1,
message_id: Uuid::new_v4().to_string(),
agent_id: self.binding.agent_id.to_string(),
enrollment_generation: self.binding.enrollment_generation,
connection_generation: self.channel.connection_generation,
boot_id: self.channel.boot_id.to_string(),
sequence: seq,
observed_at: Utc::now().timestamp_millis(),
payload: Some(payload),
..Default::default()
})
}
fn result(&mut self, offer: &JobOffer, grant: &str, outcome: Outcome) -> Result<()> {
let mut e = self.envelope(Payload::JobResult(Default::default()))?;
let tx = self.db.transaction()?;
let rev = jobs::transition(&tx, offer, &outcome.state, grant)?;
e.payload = Some(Payload::JobResult(jobs::result(offer, rev, grant, outcome)));
jobs::event(&tx, &e)?;
tx.commit()?;
self.sync_due = Instant::now();
Ok(())
}
fn recover(&mut self) -> Result<()> {
for (offer, grant) in jobs::interrupted(&self.db, &self.ledger, &self.binding)? {
if grant.is_empty() {
jobs::interrupted_request(&self.db, &offer)?;
} else {
let saved =
jobs::recover_interrupted_outcome(&self.ledger, &self.binding, &offer, &grant)?;
self.result(
&offer,
&grant,
saved.unwrap_or_else(|| Outcome::unknown("AGENT_PROCESS_INTERRUPTED")),
)?;
}
}
Ok(())
}
fn next(&mut self) -> Result<Option<Envelope>> {
if self.running.as_ref().is_some_and(|r| r.task.is_finished()) {
let r = self.running.take().unwrap();
let o = r
.task
.join()
.unwrap_or_else(|_| Outcome::unknown("WORKER_INTERRUPTED"));
ledger::persist_outcome(&self.ledger, &r.grant, &o)?;
self.result(&r.offer, &r.grant.grant_id.to_string(), o.clone())?;
ledger::finish(&self.ledger, &r.grant, &o)?;
}
if let Some(mut e) = jobs::events(&self.db)?.into_iter().next() {
e.connection_generation = self.channel.connection_generation;
return Ok(Some(e));
}
// A refused or unqualified clock closes the effect gate, not telemetry.
if self.running.is_some() {
return Ok(None);
}
if Instant::now() >= self.sync_due {
self.sync_due = Instant::now() + Duration::from_secs(40);
if self.clock.now().is_err() {
self.sync.close();
return Ok(None);
}
let snapshot = if self.root_enabled {
Some(crate::root::snapshot(self.channel.connection_generation)?)
} else {
None
};
let p = self.sync.prepare(
&mut self.db,
&self.ledger,
self.channel.clone(),
snapshot.as_ref(),
&self.clock,
)?;
self.pending_sync = Some(p.request);
return Ok(Some(p.envelope));
}
if self.sync.can_start(&self.channel, false, &self.clock)
&& Instant::now() >= self.permit_after
&& let Some(offer) = jobs::next(&self.db)?
{
let job = self.binding.job(&offer.payload_bytes)?;
if self.clock.now()? >= job.start_before {
self.result(
&offer,
"",
jobs::no_start("expired", "START_DEADLINE_EXPIRED"),
)?;
return self.next();
}
let root = self.root_enabled && crate::root::supported(&job);
ensure!(supported(&job) || root, "UNSUPPORTED_JOB");
if !self.sync.can_start(&self.channel, root, &self.clock) {
self.sync_due = Instant::now();
return Ok(None);
}
jobs::reserve_request(&self.db, &offer)?;
return self
.envelope(Payload::ExecutionPermitRequest(ExecutionPermitRequest {
job_id: offer.job_id,
attempt_id: offer.attempt_id,
job_payload_hash: offer.job_payload_hash,
assignment_version: self.binding.assignment_version,
}))
.map(Some);
}
Ok(None)
}
fn receive(&mut self, e: Envelope) -> Result<()> {
ensure!(
valid_envelope(
&e,
&self.binding.agent_id.to_string(),
self.channel.connection_generation
) && e.enrollment_generation == self.binding.enrollment_generation,
"WRONG_CHANNEL"
);
match e.payload.context("EMPTY_REPLY")? {
Payload::Ack(a) => jobs::ack(&mut self.db, &a.message_id)?,
Payload::SyncResponse(s) => {
let q = self.pending_sync.take().context("UNEXPECTED_SYNC")?;
let applied = self.sync.apply(&mut self.db, &s, &self.clock)?;
self.sync.apply_consumption(&mut self.ledger, &self.clock)?;
if applied.helper_instruction.is_some() {
ensure!(self.root_enabled, "UNEXPECTED_HELPER");
let snapshot = crate::root::apply(&q, &s)?;
if self.sync.can_start(&self.channel, false, &self.clock) {
self.sync.confirm_helper(&snapshot)?;
}
}
}
Payload::JobOffer(o) => {
let receipt = self.envelope(Payload::JobAccepted(JobAccepted {
job_id: o.job_id.clone(),
attempt_id: o.attempt_id.clone(),
job_payload_hash: o.job_payload_hash.clone(),
journal_proof: hash(&o.encode_to_vec()),
}))?;
let tx = self.db.transaction()?;
let fresh = jobs::accept(&tx, &self.binding, &o, |j| {
supported(j) || (self.root_enabled && crate::root::supported(j))
})?;
jobs::event(&tx, &receipt)?;
tx.commit()?;
if fresh {
self.sync_due = Instant::now();
}
}
Payload::ExecutionPermit(p) => self.permit(p)?,
Payload::CancelRequest(c) => {
if let Some(r) = &self.running
&& r.offer.job_id == c.job_id
&& r.offer.attempt_id == c.attempt_id
{
r.cancel.store(true, Ordering::Release);
}
let offer:Option<Vec<u8>>=rusqlite::OptionalExtension::optional(self.db.query_row(
"UPDATE job_attempts SET cancel_requested=1 WHERE job=?1 AND attempt=?2 AND state='accepted' RETURNING offer",
params![c.job_id,c.attempt_id],|r|r.get(0)))?;
if let Some(bytes) = offer {
self.result(
&JobOffer::decode(bytes.as_slice())?,
"",
jobs::no_start("cancelled", "CANCELLED_BEFORE_START"),
)?;
}
}
_ => bail!("UNEXPECTED_JOB_MESSAGE"),
}
Ok(())
}
fn permit(&mut self, p: ExecutionPermit) -> Result<()> {
let offer = jobs::requesting(&self.db)?.context("UNSOLICITED_PERMIT")?;
if !p.denial_code.is_empty() {
jobs::denied_request(&self.db, &offer, &p)?;
self.sync.close();
self.sync_due = Instant::now();
self.permit_after = Instant::now() + Duration::from_secs(30);
return Ok(());
}
let req = jobs::permit_request(&offer, &p)?;
let root = self.binding.job(&offer.payload_bytes)?.execution_identity == "root";
let verify = || -> Result<_> {
ensure!(
self.sync.can_start(&self.channel, root, &self.clock),
"SYNC_REQUIRED"
);
let (low, high) = self.clock.bounds()?;
self.binding.verify(&req, high)?;
self.binding.verify(&req, low)
};
// The signed not_before is the reservation instant. Wait within the
// qualified uncertainty interval before checking both ends at start.
let began = Instant::now();
let (job, grant) = loop {
match verify() {
Ok(x) => break x,
Err(err)
if err.to_string() == "PERMIT_TIME"
&& began.elapsed() < Duration::from_secs(6) =>
{
std::thread::sleep(Duration::from_millis(50));
}
Err(e) => return Err(e),
}
};
ensure!(
supported(&job) || (self.root_enabled && crate::root::supported(&job)),
"UNSUPPORTED_JOB"
);
let Action::RunScript {
script_utf8,
arguments,
expected_stdout,
..
} = &job.action
else {
bail!("SCRIPT_REQUIRED")
};
let script = ScriptRequest::new(
script_utf8.as_bytes().to_vec(),
Interpreter::PosixSh,
arguments.clone(),
Duration::from_secs(job.max_runtime_seconds.into()),
job.max_output_bytes as usize,
)?;
ledger::begin_execution(
&mut self.ledger,
&grant,
&req,
self.channel.boot_id,
self.clock.now()?,
)?;
let id = grant.grant_id.to_string();
let mut running = self.envelope(Payload::JobStateChanged(Default::default()))?;
let tx = self.db.transaction()?;
let revision = jobs::transition(&tx, &offer, "running", &id)?;
running.payload = Some(Payload::JobStateChanged(JobStateChanged {
job_id: offer.job_id.clone(),
attempt_id: offer.attempt_id.clone(),
grant_id: id.clone(),
revision,
state: "running".into(),
}));
jobs::event(&tx, &running)?;
tx.commit()?;
let cancel = Arc::new(AtomicBool::new(false));
let flag = cancel.clone();
let deadline = self.sync.validity_deadline().context("SYNC_LEASE")?;
let binding = self.binding.clone();
let generation = self.channel.connection_generation;
let expected = expected_stdout.clone();
let seconds = job.max_runtime_seconds;
let digest = hash(script_utf8.as_bytes());
let clock = self.clock.clone();
let task = std::thread::spawn(move || {
if root {
return crate::root::execute(generation, req, &flag, seconds)
.unwrap_or_else(|_| Outcome::unknown("HELPER_TRANSPORT_EFFECT_UNKNOWN"));
}
let mut first = true;
let result = run_script_controlled(&script, || {
ensure!(!flag.load(Ordering::Acquire), "CANCEL_OR_FENCE");
if first {
let (lo, hi) = clock.bounds()?;
ensure!(hi < deadline, "SYNC_EXPIRED");
binding.verify(&req, lo)?;
binding.verify(&req, hi)?;
first = false;
} else {
clock.now()?;
}
Ok(())
});
match result {
Ok(o) => {
let ok = o.code == Some(0)
&& !o.timed_out
&& !o.interrupted
&& expected
.as_ref()
.is_none_or(|v| !o.truncated && o.stdout == v.as_bytes());
Outcome {
state: if ok {
"succeeded"
} else if o.interrupted || o.timed_out || o.code.is_none() {
"unknown"
} else {
"failed"
}
.into(),
stdout: o.stdout,
stderr: o.stderr,
output_truncated: o.truncated,
reboot_required: false,
exit_code: o.code,
evidence: serde_json::json!({"postconditions_passed":ok,"effective_uid":unsafe{libc::geteuid()},"script_sha256":digest}),
error_code: if ok { "" } else { "PROBE_POSTCONDITION_FAILED" }.into(),
}
}
Err(_) => Outcome::unknown("PROBE_EFFECT_UNCERTAIN"),
}
});
self.running = Some(Running {
offer,
grant,
task,
cancel,
});
Ok(())
}
}
pub fn main() -> Result<()> {
let args = env::args().skip(1).collect::<Vec<_>>();
ensure!(args.len() == 4, "bound channel required");
let uid = unsafe { libc::geteuid() };
ensure!(
uid != 0 && uid == unsafe { libc::getuid() },
"SERVICE_ACCOUNT_REQUIRED"
);
unsafe { libc::umask(0o077) };
let state = Path::new("/var/db/discovery-agent");
let m = fs::symlink_metadata(state)?;
ensure!(
m.is_dir() && m.uid() == uid && m.mode() & 0o077 == 0,
"PRIVATE_STATE_REQUIRED"
);
let lock = fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(false)
.mode(0o600)
.custom_flags(libc::O_NOFOLLOW)
.open(state.join("job-worker.lock"))?;
ensure!(
unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0,
"ACTIVE_JOB_WORKER"
);
let config = Path::new("/usr/local/etc/discovery-agent/job-binding.json");
for path in [config.parent().unwrap(), config] {
let m = fs::symlink_metadata(path)?;
ensure!(
!m.is_symlink() && m.uid() == 0 && m.mode() & 0o022 == 0,
"PROTECTED_BINDING_REQUIRED"
);
}
let binding: Binding = serde_json::from_slice(&fs::read(config)?)?;
ensure!(
args[0] == binding.agent_id.to_string() && args[1] == binding.asset_id.to_string(),
"WRONG_DEVICE"
);
let channel = Channel {
boot_id: args[2].parse()?,
connection_generation: args[3].parse()?,
};
ensure!(
channel.connection_generation > 0 && !channel.boot_id.is_nil(),
"CHANNEL_REQUIRED"
);
let db = Connection::open(state.join("channel.sqlite"))?;
ledger::bounded_journal_capacity(&db)?;
db.execute_batch("PRAGMA synchronous=FULL;
CREATE TABLE IF NOT EXISTS counter(id INTEGER PRIMARY KEY CHECK(id=1),seq INTEGER NOT NULL);
INSERT OR IGNORE INTO counter SELECT id,n FROM sequence;
UPDATE counter SET seq=max(seq,(SELECT n FROM sequence WHERE id=1)) WHERE id=1;
CREATE TRIGGER IF NOT EXISTS telemetry_sequence AFTER UPDATE ON sequence WHEN NEW.n>(SELECT seq FROM counter WHERE id=1)
BEGIN UPDATE counter SET seq=NEW.n WHERE id=1; END;
CREATE TRIGGER IF NOT EXISTS job_sequence AFTER UPDATE ON counter WHEN NEW.seq>(SELECT n FROM sequence WHERE id=1)
BEGIN UPDATE sequence SET n=NEW.seq WHERE id=1; END;
CREATE TABLE IF NOT EXISTS job_attempts(job TEXT NOT NULL,attempt TEXT NOT NULL,offer BLOB NOT NULL,state TEXT NOT NULL,
revision INTEGER NOT NULL DEFAULT 0,grant_id TEXT NOT NULL DEFAULT '',cancel_requested INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(job,attempt));
CREATE TABLE IF NOT EXISTS job_events(id TEXT PRIMARY KEY,payload BLOB NOT NULL);")?;
reconcile::initialize(&db)?;
let ledger = Connection::open(state.join("consumption.sqlite"))?;
ledger::initialize_ledger(&ledger)?;
let mut w = Worker {
sync: ClientSync::new(binding.clone()),
binding,
db,
ledger,
channel,
clock: NativeClock::default(),
sync_due: Instant::now(),
permit_after: Instant::now(),
pending_sync: None,
running: None,
root_enabled: env::var_os("DISCOVERY_ROOT_SESSION").is_some(),
};
w.recover()?;
let mut input = io::stdin().lock();
println!("ready");
io::stdout().flush()?;
loop {
let mut line = String::new();
let n = (&mut input).take(2_100_000).read_line(&mut line)?;
if n == 0 {
return Ok(());
}
ensure!(line.ends_with('\n'), "FRAME_LIMIT");
let line = line.trim_end();
if line == "next" {
println!(
"{}",
w.next()?
.map(|e| hex::encode(e.encode_to_vec()))
.unwrap_or_default()
);
} else {
let data = hex::decode(line)?;
w.receive(Envelope::decode(data.as_slice())?)?;
println!("ok");
}
io::stdout().flush()?;
}
}
@@ -0,0 +1,148 @@
use super::*;
use chrono::TimeDelta;
use ed25519_dalek::{Signer, SigningKey};
use serde_json::json;
/// Completely isolated identity, signing key, journal and grant. Never contacts
/// the gateway or reads a device key; run the fixture under the guest service uid.
#[test]
fn native_probe_requires_signature_and_redelivery_does_not_rerun() -> Result<()> {
ensure!(
unsafe { libc::geteuid() } != 0,
"run as unprivileged test account"
);
let key = SigningKey::from_bytes(&[31; 32]);
let public = key.verifying_key().to_bytes();
let b = Binding {
tenant_id: Uuid::new_v4(),
asset_id: Uuid::new_v4(),
agent_id: Uuid::new_v4(),
assignment_version: 1,
enrollment_generation: 1,
public_key_hex: hex::encode(public),
};
let db = Connection::open_in_memory()?;
db.execute_batch("CREATE TABLE counter(id INTEGER PRIMARY KEY,seq INTEGER);INSERT INTO counter VALUES(1,0);
CREATE TABLE job_attempts(job TEXT,attempt TEXT,offer BLOB,state TEXT,revision INTEGER DEFAULT 0,grant_id TEXT DEFAULT '',cancel_requested INTEGER DEFAULT 0,PRIMARY KEY(job,attempt));
CREATE TABLE job_events(id TEXT PRIMARY KEY,payload BLOB);")?;
reconcile::initialize(&db)?;
let ledger = Connection::open_in_memory()?;
ledger::initialize_ledger(&ledger)?;
let mut w = Worker {
channel: Channel {
boot_id: Uuid::new_v4(),
connection_generation: 2,
},
sync: ClientSync::new(b.clone()),
binding: b.clone(),
db,
ledger,
sync_due: Instant::now(),
permit_after: Instant::now(),
clock: NativeClock::default(),
pending_sync: None,
running: None,
root_enabled: false,
};
let now = w.clock.now()?;
let job = JobPayload {
schema_version: 1,
tenant_id: b.tenant_id,
asset_id: b.asset_id,
agent_id: b.agent_id,
enrollment_generation: 1,
assignment_version: 1,
job_id: Uuid::new_v4(),
attempt_id: Uuid::new_v4(),
execution_identity: "agent_service".into(),
max_runtime_seconds: 10,
max_output_bytes: 1024,
not_before: now - TimeDelta::minutes(1),
start_before: now + TimeDelta::minutes(2),
action: Action::RunScript {
script_utf8: "uname -s\n".into(),
expected_stdout: Some("FreeBSD\n".into()),
arguments: vec![],
interpreter: "posix_sh".into(),
windows_execution_profile: None,
privileged_script_profile: None,
},
};
let bytes = serde_json::to_vec(&job)?;
let offer = JobOffer {
job_id: job.job_id.to_string(),
attempt_id: job.attempt_id.to_string(),
plan_hash: hash(b"fixture"),
authorization_id: Uuid::new_v4().to_string(),
job_payload_hash: hash(&bytes),
payload_bytes: bytes,
};
w.receive(w.envelope(Payload::JobOffer(offer.clone()))?)?;
let event = w.next()?.unwrap();
ensure!(matches!(event.payload, Some(Payload::JobAccepted(_))));
jobs::ack(&mut w.db, &event.message_id)?;
let Some(Payload::SyncRequest(r)) = w.next()?.unwrap().payload else {
bail!("expected signed sync")
};
let decision = json!({"domain":"rmm.reconciliation-decision","schema_version":1,"decision_id":Uuid::new_v4(),
"request_id":r.request_id,"request_hash":hash(&r.encode_to_vec()),"tenant_id":b.tenant_id,
"asset_id":b.asset_id,"agent_id":b.agent_id,"enrollment_generation":1,"assignment_version":1,
"connection_generation":2,"boot_id":w.channel.boot_id,"journal_id":r.journal_id,"checkpoint":r.checkpoint,
"helper_journal_id":null,"helper_checkpoint":0,"issued_at":now-TimeDelta::seconds(1),"valid_until":now+TimeDelta::seconds(59),
"ready":true,"helper_ready":false,"reason":"CONSISTENT","key_id":hash(&public),"acknowledged_message_ids":[],
"attempts":[{"job_id":job.job_id,"attempt_id":job.attempt_id,"job_payload_hash":offer.job_payload_hash,
"action":"run_script","execution_identity":"agent_service","revision":0,"outcome_state":"accepted","outcome_bytes":[],
"unlock":false,"reason":"ACCEPTED_NOT_STARTED"}]});
let raw = serde_json::to_vec(&decision)?;
w.receive(w.envelope(Payload::SyncResponse(SyncResponse {
signature: key.sign(&raw).to_bytes().to_vec(),
decision_bytes: raw,
}))?)?;
ensure!(matches!(
w.next()?.unwrap().payload,
Some(Payload::ExecutionPermitRequest(_))
));
let raw = serde_json::to_vec(
&json!({"domain":"rmm.execution-permit","schema_version":1,"grant_id":Uuid::new_v4(),
"authorization_id":offer.authorization_id,"tenant_id":b.tenant_id,"asset_id":b.asset_id,"agent_id":b.agent_id,
"enrollment_generation":1,"assignment_version":1,"job_id":job.job_id,"attempt_id":job.attempt_id,
"plan_hash":offer.plan_hash,"job_payload_hash":offer.job_payload_hash,"action":"run_script",
"execution_identity":"agent_service","not_before":now-TimeDelta::seconds(6),"start_before":now+TimeDelta::seconds(50),
"max_runtime_seconds":10,"key_id":hash(&public)}),
)?;
let permit = ExecutionPermit {
signature: key.sign(&raw).to_bytes().to_vec(),
payload_bytes: raw,
..Default::default()
};
let mut invalid = permit.clone();
invalid.signature[0] ^= 1;
ensure!(w.permit(invalid).is_err());
let count =
|db: &Connection| db.query_row("SELECT count(*) FROM consumed", [], |r| r.get::<_, i64>(0));
ensure!(count(&w.ledger)? == 0);
w.permit(permit.clone())?;
let end = Instant::now() + Duration::from_secs(10);
while w.running.is_some() {
ensure!(Instant::now() < end, "execution timeout");
w.next()?;
std::thread::yield_now();
}
w.receive(w.envelope(Payload::JobOffer(offer))?)?;
ensure!(w.permit(permit).is_err() && count(&w.ledger)? == 1);
let results = jobs::events(&w.db)?
.into_iter()
.filter_map(|e| match e.payload {
Some(Payload::JobResult(r)) => Some(r),
_ => None,
})
.collect::<Vec<_>>();
ensure!(
results.len() == 1
&& results[0].state == "succeeded"
&& results[0].exit_code == Some(0)
&& results[0].stdout == b"FreeBSD\n",
"native output mismatch"
);
Ok(())
}
+543
View File
@@ -0,0 +1,543 @@
//! FreeBSD peer credentials, boot identity and executor lock around the same
//! independent HelperSync and consumption ledger used by the Linux root helper.
use anyhow::{Context, Result, bail, ensure};
use prost::Message;
use rmm_agent_core::{
auth::{Binding, Outcome, Request},
freebsd_clock::NativeClock,
helper_reconcile::{self as h, BootSource, ExecutorLedgerGuard},
ledger,
reconcile::{HelperSnapshot, SyncClock},
};
use rmm_agent_linux::actions::{Interpreter, ScriptRequest, run_script_controlled};
use rmm_domain::jobs::{Action, FULL_MAINTENANCE_CAPABILITY, JobPayload, hash};
use rmm_protocol::{SyncAttempt, SyncRequest, SyncResponse};
use rusqlite::{Connection, OptionalExtension};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use sha1::{Digest, Sha1};
use std::{
fs::{self, File, OpenOptions, Permissions},
io::{Read, Write},
os::{
fd::AsRawFd,
unix::{
fs::{FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt},
net::{UnixListener, UnixStream},
},
},
path::{Path, PathBuf},
process::Command,
sync::atomic::{AtomicBool, Ordering},
time::Duration,
};
use uuid::Uuid;
const DIR: &str = "/var/db/discovery-root-jobs";
const SOCK: &str = "/var/run/discovery-root-jobs/control.sock";
pub const POLICY: &str = "/usr/local/etc/discovery-agent/root-policy.json";
const BINDING: &str = "/usr/local/etc/discovery-agent/job-binding.json";
const LIMIT: usize = 8 * 1024 * 1024;
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Policy {
schema_version: u8,
profile: String,
agent_uid: u32,
agent_gid: u32,
binding_sha256: String,
helper_binary_sha256: String,
}
fn protected(path: &Path) -> Result<()> {
for p in path.ancestors() {
let m = fs::symlink_metadata(p)?;
ensure!(
m.uid() == 0
&& m.mode() & 0o022 == 0
&& !m.is_symlink()
&& (if p == path {
m.is_file() || m.is_dir()
} else {
m.is_dir()
}),
"UNPROTECTED_ROOT_PATH"
);
}
Ok(())
}
fn config() -> Result<(Policy, Binding, String)> {
protected(Path::new(POLICY))?;
protected(Path::new(BINDING))?;
let raw = fs::read(POLICY)?;
ensure!(raw.len() <= 8192, "POLICY_SIZE");
let p: Policy = serde_json::from_slice(&raw)?;
let bytes = fs::read(BINDING)?;
ensure!(
p.schema_version == 1
&& p.profile == "full_maintenance_v1"
&& p.agent_uid > 0
&& p.agent_gid > 0
&& p.binding_sha256 == hash(&bytes)
&& rmm_domain::agent_update::digest(&p.helper_binary_sha256),
"POLICY_INVALID"
);
Ok((p, serde_json::from_slice(&bytes)?, hash(&raw)))
}
struct Boot(Uuid);
impl BootSource for Boot {
fn current_boot(&self) -> Result<Uuid> {
// Same UUIDv5 derivation as the already enrolled Python agent. Obtain
// boottime independently, never trust a value supplied on the socket.
let r = Command::new("/sbin/sysctl")
.args(["-n", "kern.boottime"])
.env_clear()
.output()?;
ensure!(r.status.success(), "BOOT_UNAVAILABLE");
let s = std::str::from_utf8(&r.stdout)?
.split_once('}')
.context("BOOT_FORMAT")?
.0;
let mut sha = Sha1::new();
sha.update(self.0.as_bytes());
sha.update(s.as_bytes());
let mut b: [u8; 16] = sha.finalize()[..16].try_into()?;
b[6] = (b[6] & 15) | 0x50;
b[8] = (b[8] & 63) | 0x80;
Ok(Uuid::from_bytes(b))
}
}
struct Guard {
_lock: File,
db_file: File,
}
impl ExecutorLedgerGuard for Guard {
fn check(&self, db: &Connection) -> Result<()> {
let path: String = db.query_row(
"SELECT file FROM pragma_database_list WHERE name='main'",
[],
|r| r.get(0),
)?;
ensure!(
Path::new(&path) == Path::new(DIR).join("consumption.sqlite"),
"WRONG_HELPER_LEDGER"
);
let m = fs::symlink_metadata(path)?;
let f = self.db_file.metadata()?;
ensure!(
m.uid() == 0
&& m.mode() & 0o077 == 0
&& m.is_file()
&& (m.dev(), m.ino()) == (f.dev(), f.ino()),
"HELPER_LEDGER_REPLACED"
);
Ok(())
}
}
fn peer(s: &UnixStream) -> Result<u32> {
let (mut uid, mut gid) = (u32::MAX, u32::MAX);
ensure!(
unsafe { libc::getpeereid(s.as_raw_fd(), &mut uid, &mut gid) } == 0,
"PEER_IDENTITY"
);
Ok(uid)
}
fn frame<T: Serialize>(s: &mut UnixStream, value: &T) -> Result<()> {
let bytes = serde_json::to_vec(value)?;
ensure!(bytes.len() <= LIMIT, "IPC_SIZE");
s.write_all(&(bytes.len() as u32).to_be_bytes())?;
s.write_all(&bytes)?;
Ok(())
}
fn read<T: DeserializeOwned>(s: &mut UnixStream) -> Result<T> {
let mut len = [0; 4];
s.read_exact(&mut len)?;
let n = u32::from_be_bytes(len) as usize;
ensure!((1..=LIMIT).contains(&n), "IPC_SIZE");
let mut b = vec![0; n];
s.read_exact(&mut b)?;
Ok(serde_json::from_slice(&b)?)
}
#[derive(Serialize, Deserialize)]
enum Op {
Probe,
Snapshot(u64),
Apply(Vec<u8>, h::SignedResponse),
Execute(u64, Request),
}
#[derive(Serialize, Deserialize)]
struct Call {
nonce: Uuid,
policy: String,
image: String,
op: Op,
}
#[derive(Serialize, Deserialize)]
enum Data {
Pins,
Snapshot(h::Snapshot),
Outcome(Outcome),
}
#[derive(Serialize, Deserialize)]
struct Reply {
nonce: Uuid,
data: Data,
}
fn connect(op: Op) -> Result<(UnixStream, Uuid)> {
let (p, _, policy) = config()?;
let s = Path::new(SOCK);
protected(s.parent().unwrap())?;
let m = fs::symlink_metadata(s)?;
ensure!(
m.file_type().is_socket() && m.uid() == 0 && m.gid() == p.agent_gid && m.mode() & 7 == 0,
"HELPER_SOCKET_MODE"
);
let mut s = UnixStream::connect(s)?;
ensure!(peer(&s)? == 0, "HELPER_NOT_ROOT");
s.set_read_timeout(Some(Duration::from_secs(12)))?;
s.set_write_timeout(Some(Duration::from_secs(5)))?;
let nonce = Uuid::new_v4();
frame(
&mut s,
&Call {
nonce,
policy,
image: p.helper_binary_sha256,
op,
},
)?;
Ok((s, nonce))
}
fn call(op: Op) -> Result<Data> {
let (mut s, n) = connect(op)?;
let r: Reply = read(&mut s)?;
ensure!(r.nonce == n, "HELPER_CHALLENGE");
Ok(r.data)
}
pub fn caps() -> Result<Vec<String>> {
let (p, _, policy) = config()?;
ensure!(matches!(call(Op::Probe)?, Data::Pins), "HELPER_PROBE");
Ok(vec![
"opnsense.root.posix/1".into(),
"helper.root.v1".into(),
"root:run_script".into(),
FULL_MAINTENANCE_CAPABILITY.into(),
format!("helper.binary.sha256:{}", p.helper_binary_sha256),
format!("helper.policy.sha256:{policy}"),
])
}
fn mapped(data: Data) -> Result<HelperSnapshot> {
let Data::Snapshot(s) = data else {
bail!("HELPER_SNAPSHOT")
};
Ok(HelperSnapshot {
journal_id: s.journal_id,
checkpoint: s.checkpoint,
previous_decision_id: s.previous_decision_id,
attempts: s
.attempts
.into_iter()
.map(|a| SyncAttempt {
job_id: a.job_id.to_string(),
attempt_id: a.attempt_id.to_string(),
job_payload_hash: a.job_payload_hash,
grant_id: a.grant_id.to_string(),
consumption: a.consumption,
state: a.state,
revision: a.revision,
original_boot_id: a.original_boot_id.to_string(),
outcome_sha256: a.outcome_sha256,
outcome_bytes: a.outcome_bytes,
..Default::default()
})
.collect(),
})
}
pub fn snapshot(g: u64) -> Result<HelperSnapshot> {
mapped(call(Op::Snapshot(g))?)
}
pub fn apply(q: &SyncRequest, s: &SyncResponse) -> Result<HelperSnapshot> {
mapped(call(Op::Apply(
q.encode_to_vec(),
h::SignedResponse {
decision_bytes: s.decision_bytes.clone(),
signature: s.signature.clone(),
},
))?)
}
pub fn execute(g: u64, req: Request, cancel: &AtomicBool, seconds: u32) -> Result<Outcome> {
let (mut s, n) = connect(Op::Execute(g, req))?;
let started = std::time::Instant::now();
// Poll only for response availability. On cancellation dropping the stream
// fences the root executor, which records the actual result in its own DB.
loop {
ensure!(
!cancel.load(Ordering::Acquire)
&& started.elapsed() < Duration::from_secs(u64::from(seconds) + 12),
"CALLER_FENCED"
);
let mut fd = libc::pollfd {
fd: s.as_raw_fd(),
events: libc::POLLIN,
revents: 0,
};
let r = unsafe { libc::poll(&mut fd, 1, 100) };
if r < 0 {
return Err(std::io::Error::last_os_error().into());
}
if r != 0 {
break;
}
}
let r: Reply = read(&mut s)?;
ensure!(r.nonce == n, "HELPER_CHALLENGE");
let Data::Outcome(o) = r.data else {
bail!("HELPER_RESULT")
};
Ok(o)
}
pub fn supported(j: &JobPayload) -> bool {
j.execution_identity == "root"
&& j.action.opnsense_root_script()
&& j.action
.valid_job_limits(j.max_runtime_seconds, j.max_output_bytes)
}
struct Helper {
db: Connection,
guard: Guard,
b: Binding,
clock: NativeClock,
boot: Boot,
sync: h::HelperSync,
p: Policy,
policy: String,
image: PathBuf,
}
impl Helper {
fn invoke(&mut self, s: &mut UnixStream) -> Result<()> {
ensure!(peer(s)? == self.p.agent_uid, "AGENT_PEER_DENIED");
s.set_read_timeout(Some(Duration::from_secs(5)))?;
s.set_write_timeout(Some(Duration::from_secs(5)))?;
let Call {
nonce,
policy,
image,
op,
} = read(s)?;
ensure!(
!nonce.is_nil() && policy == self.policy && image == self.p.helper_binary_sha256,
"PIN_MISMATCH"
);
let data = match op {
Op::Probe => Data::Pins,
Op::Snapshot(g) => Data::Snapshot(self.sync.snapshot(
&mut self.db,
&self.guard,
g,
&self.clock,
&self.boot,
)?),
Op::Apply(q, r) => Data::Snapshot(
self.sync
.apply(&mut self.db, &self.guard, &r, &q, &self.clock, &self.boot)?
.snapshot,
),
Op::Execute(g, req) => {
let (lo, hi) = self.clock.bounds()?;
let (job, grant) = self.b.verify(&req, lo)?;
self.b.verify(&req, hi)?;
ensure!(supported(&job), "ROOT_PROFILE_REQUIRED");
self.guard.check(&self.db)?;
let prior:Option<Option<Vec<u8>>>=self.db.query_row("SELECT COALESCE(result,(SELECT outcome FROM execution_evidence e WHERE e.grant_id=c.grant_id)) FROM consumed c WHERE grant_id=?1",
[grant.grant_id.to_string()],|r|r.get(0)).optional()?;
if let Some(old) = prior {
Data::Outcome(match old {
Some(bytes) => serde_json::from_slice(&bytes)?,
None => Outcome::unknown("PREVIOUS_EFFECT_UNRESOLVED"),
})
} else {
let Action::RunScript {
script_utf8,
arguments,
expected_stdout,
..
} = &job.action
else {
bail!("SCRIPT_REQUIRED")
};
let script = ScriptRequest::new(
script_utf8.as_bytes().to_vec(),
Interpreter::PosixSh,
arguments.clone(),
Duration::from_secs(job.max_runtime_seconds.into()),
job.max_output_bytes as usize,
)?;
ensure!(
self.sync
.can_start(&self.db, &self.guard, g, &self.clock, &self.boot),
"HELPER_SYNC_REQUIRED"
);
let until = self.sync.validity_deadline().context("HELPER_LEASE")?;
ensure!(
hash(&fs::read(&self.image)?) == image && config()?.2 == policy,
"HELPER_POLICY_CHANGED"
);
ledger::begin_execution(
&mut self.db,
&grant,
&req,
self.boot.current_boot()?,
self.clock.now()?,
)?;
let mut first = true;
let res = run_script_controlled(&script, || {
let (lo, hi) = self.clock.bounds()?;
if first {
ensure!(hi < until, "HELPER_LEASE_EXPIRED");
self.b.verify(&req, lo)?;
self.b.verify(&req, hi)?;
first = false;
}
let mut byte = 0u8;
let rc = unsafe {
libc::recv(
s.as_raw_fd(),
(&mut byte as *mut u8).cast(),
1,
libc::MSG_PEEK | libc::MSG_DONTWAIT,
)
};
ensure!(
rc < 0
&& std::io::Error::last_os_error().kind()
== std::io::ErrorKind::WouldBlock,
"CALLER_FENCED"
);
Ok(())
});
let out = match res {
Err(_) => Outcome::unknown("HELPER_SCRIPT_EFFECT_UNKNOWN"),
Ok(o) => {
let unknown = o.interrupted || o.timed_out || o.code.is_none();
let ok = !unknown
&& o.code == Some(0)
&& expected_stdout
.as_ref()
.is_none_or(|v| !o.truncated && o.stdout == v.as_bytes());
Outcome {
state: if unknown {
"unknown"
} else if ok {
"succeeded"
} else {
"failed"
}
.into(),
stdout: o.stdout,
stderr: o.stderr,
output_truncated: o.truncated,
reboot_required: false,
exit_code: o.code,
evidence: serde_json::json!({
"postconditions_passed":ok,"script_sha256":hash(script_utf8.as_bytes()),"execution_uid":unsafe{libc::geteuid()},
"privileged_script_profile":"full_maintenance_v1","output_encoding":"raw_native_bytes","termination_does_not_prove_absence_of_effects":unknown}),
error_code: if unknown {
"HELPER_SCRIPT_EFFECT_UNKNOWN"
} else if ok {
""
} else {
"SCRIPT_POSTCONDITION_FAILED"
}
.into(),
}
}
};
ledger::finish(&self.db, &grant, &out)?;
Data::Outcome(out)
}
}
};
frame(s, &Reply { nonce, data })
}
}
pub fn serve() -> Result<()> {
ensure!(
unsafe { libc::geteuid() } == 0 && unsafe { libc::getuid() } == 0,
"ROOT_REQUIRED"
);
unsafe { libc::umask(0o077) };
let (p, b, policy) = config()?;
let image = std::env::current_exe()?;
protected(&image)?;
ensure!(
hash(&fs::read(&image)?) == p.helper_binary_sha256,
"RUNNING_IMAGE_PIN"
);
let directory = Path::new(DIR);
protected(directory)?;
ensure!(
fs::metadata(directory)?.mode() & 0o077 == 0,
"ROOT_STATE_NOT_PRIVATE"
);
let open = |name: &str| {
OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.mode(0o600)
.custom_flags(libc::O_NOFOLLOW)
.open(directory.join(name))
};
let lock = open("executor.lock")?;
ensure!(
unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0,
"HELPER_BUSY"
);
let guard = Guard {
_lock: lock,
db_file: open("consumption.sqlite")?,
};
let db = Connection::open(directory.join("consumption.sqlite"))?;
guard.check(&db)?;
ledger::initialize_ledger(&db)?;
let clock = NativeClock::default();
let sync = h::HelperSync::new(b.clone(), &clock)?;
let boot = Boot(b.agent_id);
let path = Path::new(SOCK);
protected(path.parent().unwrap())?;
if let Ok(m) = fs::symlink_metadata(path) {
ensure!(
m.uid() == 0 && m.file_type().is_socket(),
"UNEXPECTED_SOCKET"
);
fs::remove_file(path)?;
}
let listener = UnixListener::bind(path)?;
std::os::unix::fs::chown(path, Some(0), Some(p.agent_gid))?;
fs::set_permissions(path, Permissions::from_mode(0o660))?;
let mut helper = Helper {
db,
guard,
b,
p,
policy,
image,
clock,
boot,
sync,
};
for s in listener.incoming() {
if let Err(e) = helper.invoke(&mut s?) {
let code = e.to_string();
eprintln!(
"root helper: {}",
if code.len() < 80 && code.bytes().all(|v| v.is_ascii_uppercase() || v == b'_') {
&code
} else {
"REJECTED"
}
);
}
}
Ok(())
}
+28 -10
View File
@@ -277,18 +277,36 @@ pub fn snapshot() -> Result<Value> {
snapshot_with_boot(None) snapshot_with_boot(None)
} }
fn disk_space(root: &[u16]) -> Option<(u64, u64)> {
let (mut available, mut total) = (0, 0);
(unsafe { GetDiskFreeSpaceExW(root.as_ptr(), &mut available, &mut total, ptr::null_mut()) } != 0
&& total > 0 && available <= total).then_some((available, total))
}
fn fixed_volumes(system: &str, available: u64, total: u64) -> Vec<Value> {
use windows_sys::Win32::Storage::FileSystem::{GetDriveTypeW, GetLogicalDrives};
const DRIVE_FIXED: u32 = 3;
let mask = unsafe { GetLogicalDrives() };
let mut rows = vec![json!({"name":system,"free_bytes":available,"total_bytes":total})];
for letter in b'A'..=b'Z' {
if mask & (1 << (letter - b'A')) == 0 { continue; }
let name = format!("{}:", char::from(letter));
if name.eq_ignore_ascii_case(system) { continue; }
let root = wide(format!("{name}\\"));
if unsafe { GetDriveTypeW(root.as_ptr()) } != DRIVE_FIXED { continue; }
// Retain an identified but unreadable volume without claiming zero usage.
let sizes = disk_space(&root);
rows.push(json!({"name":name,"free_bytes":sizes.map(|s| s.0),"total_bytes":sizes.map(|s| s.1)}));
}
rows
}
pub fn snapshot_with_boot(booted_at: Option<DateTime<Utc>>) -> Result<Value> { pub fn snapshot_with_boot(booted_at: Option<DateTime<Utc>>) -> Result<Value> {
let started = Utc::now(); let started = Utc::now();
let hostname = computer_name(ComputerNameDnsHostname)?; let hostname = computer_name(ComputerNameDnsHostname)?;
let volume = wide(std::env::var("SystemDrive").context("SYSTEM_DRIVE")? + "\\"); let system = std::env::var("SystemDrive").context("SYSTEM_DRIVE")?.to_ascii_uppercase();
let mut available = 0; let (available, total) = disk_space(&wide(format!("{system}\\"))).context("VOLUME_QUERY")?;
let mut total = 0; let volumes = fixed_volumes(&system, available, total);
let mut free = 0;
ensure!(
unsafe { GetDiskFreeSpaceExW(volume.as_ptr(), &mut available, &mut total, &mut free) } != 0,
"VOLUME_QUERY"
);
ensure!(total > 0 && available <= total, "VOLUME_VALUES");
let product = registry_string("ProductName")?; let product = registry_string("ProductName")?;
let display = registry_string("DisplayVersion")?; let display = registry_string("DisplayVersion")?;
let build = registry_string("CurrentBuildNumber")?; let build = registry_string("CurrentBuildNumber")?;
@@ -298,7 +316,7 @@ pub fn snapshot_with_boot(booted_at: Option<DateTime<Utc>>) -> Result<Value> {
"collection_started_at":started,"collection_completed_at":completed, "collection_started_at":started,"collection_completed_at":completed,
"observations":[ "observations":[
{"scope":"windows.os","source_id":"windows.registry:CurrentVersion;GetComputerNameExW;Kernel-General/12","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"product_name":product,"display_version":display,"build":build,"installed_at":install_date(),"booted_at":booted_at}}, {"scope":"windows.os","source_id":"windows.registry:CurrentVersion;GetComputerNameExW;Kernel-General/12","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"product_name":product,"display_version":display,"build":build,"installed_at":install_date(),"booted_at":booted_at}},
{"scope":"windows.volumes","source_id":"windows.win32:GetDiskFreeSpaceExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"system_volume_total_bytes":total,"system_volume_available_bytes":available}}, {"scope":"windows.volumes","source_id":"windows.win32:GetLogicalDrives;GetDriveTypeW;GetDiskFreeSpaceExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"system_volume_total_bytes":total,"system_volume_available_bytes":available,"drives":volumes}},
{"scope":"windows.inodes","source_id":"windows.win32","observed_at":completed,"quality":"unsupported","completeness":"unknown","truncated":false,"error_code":"NOT_APPLICABLE","data":null} {"scope":"windows.inodes","source_id":"windows.win32","observed_at":completed,"quality":"unsupported","completeness":"unknown","truncated":false,"error_code":"NOT_APPLICABLE","data":null}
]}); ]});
snapshot["observations"] snapshot["observations"]
+3 -1
View File
@@ -3195,9 +3195,11 @@ pub fn main() -> Result<()> {
let runtime = tokio::runtime::Runtime::new()?; let runtime = tokio::runtime::Runtime::new()?;
let (boot, booted_at) = runtime.block_on(native::boot_identity())?; let (boot, booted_at) = runtime.block_on(native::boot_identity())?;
let inventory = native::snapshot_with_boot(Some(booted_at))?; let inventory = native::snapshot_with_boot(Some(booted_at))?;
let drives = inventory["observations"].as_array().and_then(|observations|
observations.iter().find(|o| o["scope"] == "windows.volumes")).map(|o| &o["data"]["drives"]);
println!( println!(
"{}", "{}",
serde_json::json!({"platform":"windows","architecture":std::env::consts::ARCH,"hostname_available":!inventory["hostname"].as_str().unwrap_or("").is_empty(),"system_volume_available":inventory["root_available_bytes"].as_u64().is_some(),"inodes":null,"boot_id":boot,"capabilities":CAPABILITIES,"jobs_supported":false}) serde_json::json!({"platform":"windows","architecture":std::env::consts::ARCH,"hostname_available":!inventory["hostname"].as_str().unwrap_or("").is_empty(),"system_volume_available":inventory["root_available_bytes"].as_u64().is_some(),"fixed_volumes":drives,"inodes":null,"boot_id":boot,"capabilities":CAPABILITIES,"jobs_supported":false})
); );
return Ok(()); return Ok(());
} }
+55 -1
View File
@@ -480,7 +480,25 @@ impl Action {
_ => None, _ => None,
} }
} }
/// Shared plan/revalidation/start gate. Passive Windows never implies job support. /// The first FreeBSD profile is one exact POSIX script. It does not make
/// an appliance eligible for the Linux library, arbitrary scripts or root.
pub fn opnsense_kernel_probe(&self) -> bool {
matches!(self, Self::RunScript { interpreter, script_utf8, arguments,
expected_stdout: Some(expected), windows_execution_profile: None, privileged_script_profile: None }
if interpreter == "posix_sh" && script_utf8 == "uname -s\n"
&& arguments.is_empty() && expected == "FreeBSD\n")
}
pub fn opnsense_root_script(&self) -> bool {
matches!(self, Self::RunScript {interpreter, windows_execution_profile:None,
privileged_script_profile:Some(PrivilegedScriptProfile::FullMaintenanceV1), ..}
if interpreter=="posix_sh") && self.validate()
}
pub fn opnsense_service_script(&self) -> bool {
matches!(self, Self::RunScript {interpreter,windows_execution_profile:None,privileged_script_profile:None,..}
if interpreter=="posix_sh") && self.validate()
}
/// Shared plan/revalidation/start gate. Passive inventory never implies job support.
pub fn available_for(&self, identity: &str, capabilities: &[String]) -> bool { pub fn available_for(&self, identity: &str, capabilities: &[String]) -> bool {
if !self.valid_execution_identity(identity) if !self.valid_execution_identity(identity)
|| (identity == "system" || (identity == "system"
@@ -490,6 +508,13 @@ impl Action {
return false; return false;
} }
let has = |cap: &str| capabilities.iter().any(|c| c == cap); let has = |cap: &str| capabilities.iter().any(|c| c == cap);
if has("opnsense.base/1") {
return has("run_script") && has("rmm.sync.v1") && !has("windows.base/1") && !has("linux.base/1")
&& ((identity=="agent_service" && ((has("opnsense.uname/1") && self.opnsense_kernel_probe())
|| (has("opnsense.posix/1") && self.opnsense_service_script())))
|| (identity=="root" && has("opnsense.root.posix/1") && has(FULL_MAINTENANCE_CAPABILITY)
&& has("helper.root.v1") && has("root:run_script") && self.opnsense_root_script()));
}
if !has(self.name()) if !has(self.name())
|| (self.full_maintenance() || (self.full_maintenance()
&& !((has(FULL_MAINTENANCE_CAPABILITY) && !((has(FULL_MAINTENANCE_CAPABILITY)
@@ -828,6 +853,35 @@ impl JobState {
mod tests { mod tests {
use super::*; use super::*;
#[test] #[test]
fn appliance_kernel_probe_rejects_unbound_or_changed_profiles() {
let caps: Vec<String> = ["run_script","opnsense.base/1","rmm.sync.v1","opnsense.uname/1"].map(String::from).into();
let mut a = Action::RunScript { interpreter:"posix_sh".into(),script_utf8:"uname -s\n".into(),
arguments:vec![],expected_stdout:Some("FreeBSD\n".into()),windows_execution_profile:None,privileged_script_profile:None };
assert!(a.available_for("agent_service",&caps));
for excluded in &caps {
let fewer = caps.iter().filter(|v| *v!=excluded).cloned().collect::<Vec<_>>();
assert!(!a.available_for("agent_service",&fewer));
}
assert!(!a.available_for("root",&caps));
let mut mixed = caps.clone(); mixed.push("linux.base/1".into());
assert!(!a.available_for("agent_service",&mixed));
if let Action::RunScript { script_utf8,.. } = &mut a { script_utf8.push(' '); }
assert!(!a.available_for("agent_service",&caps));
}
#[test]
fn opnsense_root_requires_full_profile_and_separate_capabilities() {
let caps:Vec<_>=["opnsense.base/1","run_script","rmm.sync.v1","opnsense.root.posix/1",
FULL_MAINTENANCE_CAPABILITY,"helper.root.v1","root:run_script"].map(str::to_owned).into();
let mut a=Action::RunScript{interpreter:"posix_sh".into(),script_utf8:"id -u\n".into(),
arguments:vec![],expected_stdout:None,windows_execution_profile:None,
privileged_script_profile:Some(PrivilegedScriptProfile::FullMaintenanceV1)};
assert!(a.available_for("root",&caps));
for omitted in &caps { assert!(!a.available_for("root",&caps.iter().filter(|x|*x!=omitted).cloned().collect::<Vec<_>>())); }
assert!(!a.available_for("agent_service",&caps));
if let Action::RunScript{interpreter,..}=&mut a { *interpreter="bash".into(); }
assert!(!a.available_for("root",&caps));
}
#[test]
fn windows_update_final_report_and_policy_are_exact() { fn windows_update_final_report_and_policy_are_exact() {
assert_eq!( assert_eq!(
windows_update_reboot_report( windows_update_reboot_report(
+23 -1
View File
@@ -261,7 +261,6 @@ pub async fn detail(
.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?; .ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?;
let hosts = assigned_hosts(&mut tx, tenant, now, std::slice::from_ref(&row)).await?; let hosts = assigned_hosts(&mut tx, tenant, now, std::slice::from_ref(&row)).await?;
let mut item = project(&row, now, true, &hosts); let mut item = project(&row, now, true, &hosts);
item["volumes"] = volumes(&item["inventory"]);
item["recent_jobs"] = if p.permits_scope("operations:read") item["recent_jobs"] = if p.permits_scope("operations:read")
&& crate::permissions::allowed(&mut tx, &p.name, "operations:read").await? && crate::permissions::allowed(&mut tx, &p.name, "operations:read").await?
{ {
@@ -296,6 +295,14 @@ fn observed<'a>(data: &'a Value, scope: &str) -> &'a Value {
} }
fn volumes(data: &Value) -> Value { fn volumes(data: &Value) -> Value {
let mut items = Vec::new(); let mut items = Vec::new();
if let Some(drives) = observed(data, "windows.volumes")["drives"].as_array() {
let mut seen = std::collections::HashSet::new();
for drive in drives.iter().take(26) {
let Some(name) = drive["name"].as_str() else { continue };
if !matches!(name.as_bytes(), [b'A'..=b'Z', b':']) || !seen.insert(name) { continue; }
items.push(json!({"name":name,"free_bytes":drive["free_bytes"].as_u64(),"total_bytes":drive["total_bytes"].as_u64()}));
}
}
if let Some(rows) = observed(data, "linux.volumes").as_array() { if let Some(rows) = observed(data, "linux.volumes").as_array() {
for entry in rows.iter().filter(|entry| entry["quality"] == "valid") { for entry in rows.iter().filter(|entry| entry["quality"] == "valid") {
let v = &entry["data"]; let v = &entry["data"];
@@ -552,6 +559,9 @@ fn project(row: &PgRow, now: DateTime<Utc>, full: bool, hosts: &HashMap<Uuid, Ho
"source_id":row.get::<Option<String>,_>("source_id"),"quality":if data.is_null(){"unknown"}else{"valid"}, "source_id":row.get::<Option<String>,_>("source_id"),"quality":if data.is_null(){"unknown"}else{"valid"},
"completeness":"partial","health":"unknown" "completeness":"partial","health":"unknown"
}); });
if full || observed(&data, "windows.volumes").is_object() {
item["volumes"] = volumes(&data);
}
if device_type == Some(DeviceType::Virtual) && row.get::<String, _>("lifecycle") == "current" { if device_type == Some(DeviceType::Virtual) && row.get::<String, _>("lifecycle") == "current" {
let assigned_id: Option<Uuid> = row.get("hypervisor_asset_id"); let assigned_id: Option<Uuid> = row.get("hypervisor_asset_id");
let assigned = assigned_id.and_then(|id| hosts.get(&id)); let assigned = assigned_id.and_then(|id| hosts.get(&id));
@@ -578,6 +588,18 @@ fn project(row: &PgRow, now: DateTime<Utc>, full: bool, hosts: &HashMap<Uuid, Ho
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn windows_drives_include_other_letters_and_preserve_legacy_system_volume() {
let mut snapshot = json!({"root_available_bytes":4,"root_total_bytes":8,"observations":[
{"scope":"windows.volumes","quality":"valid","data":{}}]});
assert_eq!(volumes(&snapshot)[0]["name"], "Systemvolume");
let drives = json!([{"name":"C:","free_bytes":4,"total_bytes":8},
{"name":"D:","free_bytes":0,"total_bytes":64},
{"name":"E:","free_bytes":null,"total_bytes":null}]);
snapshot["observations"][0]["data"]["drives"] = drives.clone();
assert_eq!(volumes(&snapshot), drives);
}
fn windows_os(name: &str, build: &str) -> String { fn windows_os(name: &str, build: &str) -> String {
let old = json!({"os":name,"observations":[{"scope":"windows.os","quality":"valid", let old = json!({"os":name,"observations":[{"scope":"windows.os","quality":"valid",
"data":{"product_name":name,"build":build,"display_version":"26H2"}}]}); "data":{"product_name":name,"build":build,"display_version":"26H2"}}]});
+10 -3
View File
@@ -292,7 +292,8 @@ fn validate_variants(variants: &[Variant]) -> Result<()> {
privileged_script_profile: None, privileged_script_profile: None,
}; };
if v.encoding != "utf-8" if v.encoding != "utf-8"
|| action.script_platform() != Some(v.os_family.as_str()) || !(action.script_platform() == Some(v.os_family.as_str())
|| (v.os_family == "opnsense" && v.interpreter == "posix_sh"))
|| !action.validate() || !action.validate()
{ {
return Err(fail("UNSUPPORTED_CAPABILITY")); return Err(fail("UNSUPPORTED_CAPABILITY"));
@@ -346,9 +347,11 @@ fn target_action(input: &PlanInput, caps: &[String]) -> Result<Action> {
let platform = match ( let platform = match (
caps.iter().any(|c| c == "linux.base/1"), caps.iter().any(|c| c == "linux.base/1"),
caps.iter().any(|c| c == "windows.base/1"), caps.iter().any(|c| c == "windows.base/1"),
caps.iter().any(|c| c == "opnsense.base/1"),
) { ) {
(true, false) => "linux", (true, false, false) => "linux",
(false, true) => "windows", (false, true, false) => "windows",
(false, false, true) => "opnsense",
_ => return Err(fail("UNSUPPORTED_CAPABILITY")), _ => return Err(fail("UNSUPPORTED_CAPABILITY")),
}; };
let v = input let v = input
@@ -438,6 +441,10 @@ pub(crate) async fn plan_resolved(
let row = &rows[0]; let row = &rows[0];
let caps = capabilities(row.get("capabilities"))?; let caps = capabilities(row.get("capabilities"))?;
let action = target_action(&input, &caps)?; let action = target_action(&input, &caps)?;
if input.execution_identity=="agent_service" && caps.iter().any(|s| s=="opnsense.base/1") && !caps.iter().any(|s| s=="opnsense.posix/1") &&
(input.max_runtime_seconds != 10 || input.max_output_bytes != 1024) {
return Err(fail("UNSUPPORTED_CAPABILITY"));
}
if !action.valid_job_limits(input.max_runtime_seconds, input.max_output_bytes) { if !action.valid_job_limits(input.max_runtime_seconds, input.max_output_bytes) {
return Err(fail("VALIDATION_ERROR")); return Err(fail("VALIDATION_ERROR"));
} }
+5 -1
View File
@@ -16,6 +16,8 @@ use uuid::Uuid;
struct Policy { struct Policy {
schema_version: u8, schema_version: u8,
linux: Vec<RootScope>, linux: Vec<RootScope>,
#[serde(default)]
opnsense: Vec<RootScope>,
windows: Vec<SystemScope>, windows: Vec<SystemScope>,
#[serde(default)] #[serde(default)]
release_anchors: Vec<ReleaseAnchor>, release_anchors: Vec<ReleaseAnchor>,
@@ -123,6 +125,8 @@ impl Policy {
return false; return false;
} }
let permits_subject = |subject: &str| match job.execution_identity.as_str() { let permits_subject = |subject: &str| match job.execution_identity.as_str() {
"root" if caps.iter().any(|c| c=="opnsense.base/1") => self.opnsense.iter()
.any(|scope| scope.permits(subject,job,caps,None)),
"root" => self "root" => self
.linux .linux
.iter() .iter()
@@ -206,7 +210,7 @@ pub(crate) async fn permits(
.map_err(|_| invalid())?; .map_err(|_| invalid())?;
let policy: Policy = serde_json::from_slice(&bytes).map_err(|_| invalid())?; let policy: Policy = serde_json::from_slice(&bytes).map_err(|_| invalid())?;
if policy.schema_version != 1 if policy.schema_version != 1
|| policy.linux.len() + policy.windows.len() > 64 || policy.linux.len() + policy.windows.len() + policy.opnsense.len() > 64
|| policy.release_anchors.len() > 64 || policy.release_anchors.len() > 64
|| policy || policy
.release_anchors .release_anchors
+3
View File
@@ -380,6 +380,9 @@ pub async fn authorize(
if crate::managed_scripts::permits(tx, principal, job, &caps).await? { if crate::managed_scripts::permits(tx, principal, job, &caps).await? {
return Ok(()); return Ok(());
} }
if caps.iter().any(|c| c=="opnsense.base/1") {
return Err(Error(StatusCode::FORBIDDEN,"SCRIPT_HELPER_SCOPE_DENIED"));
}
let policy = load()?; let policy = load()?;
let global_log_units = if matches!(job.action, Action::QueryLogs { .. }) { let global_log_units = if matches!(job.action, Action::QueryLogs { .. }) {
parse_log_units(std::env::var("RMM_ROOT_LOG_UNITS").ok().as_deref())? parse_log_units(std::env::var("RMM_ROOT_LOG_UNITS").ok().as_deref())?
+7 -1
View File
@@ -11,8 +11,14 @@ Der OPNsense-eigene Python-Interpreter führt zwei Zipapps aus. Der lokale Colle
3. Bei einer frischen Installation in der Discovery-WebUI den Testkunden wählen und einen Einmalcode erzeugen. Den Code über geschützte Standardeingabe an `su -m discovery -c '/usr/local/bin/python3 -I /usr/local/libexec/discovery-agent/agent.pyz enroll'` übergeben. Danach `service discovery_agent start`. Bei vorhandener Identität nicht neu enrollen. Der Dienst verwaltet beide Prozesse; `rc.conf.local` aktiviert sie beim Start. 3. Bei einer frischen Installation in der Discovery-WebUI den Testkunden wählen und einen Einmalcode erzeugen. Den Code über geschützte Standardeingabe an `su -m discovery -c '/usr/local/bin/python3 -I /usr/local/libexec/discovery-agent/agent.pyz enroll'` übergeben. Danach `service discovery_agent start`. Bei vorhandener Identität nicht neu enrollen. Der Dienst verwaltet beide Prozesse; `rc.conf.local` aktiviert sie beim Start.
4. In **Geräte** den Hostnamen öffnen. Das Inventar wird ungefähr einmal pro Minute erhoben, der Heartbeat etwa alle 20 Sekunden gesendet. Das Betriebssystem liefert CPU-Zeitdifferenzen und eine RAM-Schätzung aus freien und inaktiven Seiten. Fehlgeschlagene Quellen erscheinen als „Nicht ermittelbar“, ein erfolgreicher leerer Befund gesondert. Pro Liste werden höchstens 128 Zeilen gemeldet; Auszüge sind gekennzeichnet. 4. In **Geräte** den Hostnamen öffnen. Das Inventar wird ungefähr einmal pro Minute erhoben, der Heartbeat etwa alle 20 Sekunden gesendet. Das Betriebssystem liefert CPU-Zeitdifferenzen und eine RAM-Schätzung aus freien und inaktiven Seiten. Fehlgeschlagene Quellen erscheinen als „Nicht ermittelbar“, ein erfolgreicher leerer Befund gesondert. Pro Liste werden höchstens 128 Zeilen gemeldet; Auszüge sind gekennzeichnet.
**Systeminventar:** Kern-Bootzeit, VM-Erkennung, verfügbare SMBIOS-Daten, Netzwerkkarten mit MAC und IPs, angemeldete Benutzer und lokale FreeBSD-Pakete mit Version. Bei Software liegt die Obergrenze bei 1024 Paketen.
**VPN:** Beschreibungen und Aktivierung der OPNsense-Modelle für WireGuard-Instanzen/-Peers, OpenVPN-Instanzen und IPsec-Verbindungen. Separat: WireGuard-Handshakes (kein dauerhafter Online-Status), OpenVPN-Managementstatus und IKE-Sicherheitsassoziationen. Ohne erreichbaren IPsec-Dienst ist der Laufzeitstatus unbekannt. Keine privaten Schlüssel, PSKs, Zertifikate oder vollständige Gerätekonfiguration im Inventar. **VPN:** Beschreibungen und Aktivierung der OPNsense-Modelle für WireGuard-Instanzen/-Peers, OpenVPN-Instanzen und IPsec-Verbindungen. Separat: WireGuard-Handshakes (kein dauerhafter Online-Status), OpenVPN-Managementstatus und IKE-Sicherheitsassoziationen. Ohne erreichbaren IPsec-Dienst ist der Laufzeitstatus unbekannt. Keine privaten Schlüssel, PSKs, Zertifikate oder vollständige Gerätekonfiguration im Inventar.
**Firewall:** aktiver PF-Hauptregelsatz in Kernelreihenfolge, einschließlich automatisch erzeugter Regeln. Kein Editor und kein rekursives Auslesen der Anchor-Regelsätze. **Firewall:** aktiver PF-Hauptregelsatz in Kernelreihenfolge, einschließlich automatisch erzeugter Regeln. Kein Editor und kein rekursives Auslesen der Anchor-Regelsätze.
**Grenzen:** Das passive Profil meldet keine Skript-, Root- oder Release-Capability. Der bestehende Linux-Jobpfad verwendet Linux-spezifische Uhren, Helper und Interpreterprüfung. Für Parität benötigt OPNsense eigene native Adapter für den signierten Abgleich, den Startgrant und das Ausführungsjournal sowie einen eigenen signierten Installer-/Updatekanal. Der OPNsense-Gast darf nicht als Linuxziel für APT- oder Bash-Vorlagen angeboten werden. **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.
+111 -9
View File
@@ -1,5 +1,7 @@
"""Unprivileged OPNsense telemetry channel. Input never selects a local command.""" """Unprivileged OPNsense telemetry and signed job transport."""
import hashlib import hashlib
import contextlib
import fcntl
import http.client import http.client
import json import json
import os import os
@@ -18,7 +20,9 @@ STATE = Path('/var/db/discovery-agent')
CA = '/usr/local/etc/discovery-agent/ca.pem' CA = '/usr/local/etc/discovery-agent/ca.pem'
HOST = 'discovery.ease-technologies.de' HOST = 'discovery.ease-technologies.de'
MEDIA = 'application/x-protobuf' MEDIA = 'application/x-protobuf'
VERSION = '0.1.0-opnsense.4' 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')
def post(ctx, path, data, media): def post(ctx, path, data, media):
@@ -111,10 +115,73 @@ def usage(previous):
return sample,ticks return sample,ticks
class Jobs:
"""Private pipe to the non-root worker. The mTLS agent owns the transport."""
def __init__(self, process):
self.process = process
def read(self):
line = self.process.stdout.readline(2_100_000)
if not line.endswith(b'\n'):
raise ValueError('job worker disconnected')
return line[:-1]
def call(self, line):
self.process.stdin.write(line+b'\n')
self.process.stdin.flush()
return self.read()
def received(self, envelope):
if self.call(envelope.SerializeToString().hex().encode()) != b'ok':
raise ValueError('job response not committed')
def pump(self, ctx, agent, boot, generation):
for _ in range(12):
frame = self.call(b'next')
if not frame:
return
e = pb.Envelope.FromString(bytes.fromhex(frame.decode('ascii')))
kind = e.WhichOneof('payload')
if (e.protocol_major!=1 or e.agent_id!=agent or e.enrollment_generation!=1 or
e.connection_generation!=generation or kind not in (
'job_accepted','job_state_changed','job_result','sync_request','execution_permit_request')):
raise ValueError('invalid outbound job event')
batch = pb.MessageBatch(protocol_major=1,messages=[e])
reply = pb.MessageBatch.FromString(post(ctx,'messages',batch.SerializeToString(),MEDIA))
expected = {'sync_request':'sync_response','execution_permit_request':'execution_permit'}.get(kind,'ack')
check_reply(reply,e,expected)
for r in reply.messages:
self.received(r)
def check_reply(batch,e,expected):
if batch.protocol_major!=1 or not 1<=len(batch.messages)<=16:
raise ValueError('unexpected reply')
first = batch.messages[0]
generation = first.server_hello.connection_generation if expected=='server_hello' else e.connection_generation
for index,r in enumerate(batch.messages):
if (r.protocol_major,r.protocol_minor,r.agent_id,r.enrollment_generation,r.connection_generation,
r.boot_id,r.sequence)!=(1,0,e.agent_id,e.enrollment_generation,generation,e.boot_id,e.sequence):
raise ValueError('reply identity')
kind = r.WhichOneof('payload')
if (not index and kind!=expected) or (index and kind not in ('job_offer','cancel_request')):
raise ValueError('unexpected job reply')
if expected=='ack' and first.ack.message_id!=e.message_id:
raise ValueError('unconfirmed message')
return first
def session(db, identity, boot, instance): def session(db, identity, boot, instance):
with contextlib.ExitStack() as stack:
return run_channel(db, identity, boot, instance, stack)
def run_channel(db, identity, boot, instance, stack):
ctx = context() ctx = context()
ctx.load_cert_chain(STATE/'device.pem', STATE/'device.key') ctx.load_cert_chain(STATE/'device.pem', STATE/'device.key')
generation = 0 generation = 0
jobs = None
enabled = BINDING.is_file() and WORKER.is_file()
def send(kind, payload, captured=None): def send(kind, payload, captured=None):
# A lost inventory ACK replays the exact durable envelope, including its # A lost inventory ACK replays the exact durable envelope, including its
@@ -136,12 +203,11 @@ def session(db, identity, boot, instance):
db.execute('INSERT INTO pending VALUES(1,?,?)',(e.SerializeToString(),e.observed_at)) db.execute('INSERT INTO pending VALUES(1,?,?)',(e.SerializeToString(),e.observed_at))
batch = pb.MessageBatch(protocol_major=1, messages=[e]) batch = pb.MessageBatch(protocol_major=1, messages=[e])
reply = pb.MessageBatch.FromString(post(ctx, 'messages', batch.SerializeToString(), MEDIA)) reply = pb.MessageBatch.FromString(post(ctx, 'messages', batch.SerializeToString(), MEDIA))
if reply.protocol_major != 1 or len(reply.messages) != 1: r = check_reply(reply,e,'server_hello' if kind=='client_hello' else 'ack')
raise ValueError('unexpected reply') if len(reply.messages)>1 and jobs is None:
r = reply.messages[0] raise ValueError('work outside established job session')
if (r.protocol_major,r.agent_id,r.enrollment_generation,r.boot_id,r.sequence) != ( for extra in reply.messages[1:]:
1,e.agent_id,1,e.boot_id,e.sequence): jobs.received(extra)
raise ValueError('reply identity')
if kind == 'client_hello': if kind == 'client_hello':
if (r.WhichOneof('payload') != 'server_hello' or r.connection_generation == 0 or if (r.WhichOneof('payload') != 'server_hello' or r.connection_generation == 0 or
r.connection_generation != r.server_hello.connection_generation or r.connection_generation != r.server_hello.connection_generation or
@@ -158,7 +224,33 @@ def session(db, identity, boot, instance):
if renew(ctx, identity): if renew(ctx, identity):
ctx = context() ctx = context()
ctx.load_cert_chain(STATE/'device.pem', STATE/'device.key') ctx.load_cert_chain(STATE/'device.pem', STATE/'device.key')
generation = send('client_hello',pb.ClientHello(agent_version=VERSION, capabilities=['heartbeat/1','opnsense.base/1'])) caps = ['heartbeat/1','opnsense.base/1']
root_caps=[]
if enabled:
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:
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()
try:
p.wait(timeout=15)
except subprocess.TimeoutExpired:
p.kill(); p.wait()
finally:
p.stdout.close()
stack.callback(close)
jobs = Jobs(p)
if jobs.read()!=b'ready':
raise ValueError('job worker unavailable')
last = None last = None
previous = None previous = None
check_cert = time.monotonic()+12*3600 check_cert = time.monotonic()+12*3600
@@ -187,6 +279,13 @@ def session(db, identity, boot, instance):
scope='opnsense.base',schema_version=1,chunk_count=1,data=raw, scope='opnsense.base',schema_version=1,chunk_count=1,data=raw,
sha256=hashlib.sha256(raw).digest(),completeness='partial'),stamp//1_000_000) sha256=hashlib.sha256(raw).digest(),completeness='partial'),stamp//1_000_000)
last = stamp last = stamp
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) time.sleep(20)
@@ -194,6 +293,9 @@ def main():
os.umask(0o077) os.umask(0o077)
if sys.argv[1:] == ['enroll']: if sys.argv[1:] == ['enroll']:
return enroll() return enroll()
# Never allow a second network actor to fence or race an in-flight worker.
lock = (STATE/'channel.lock').open('ab')
fcntl.flock(lock,fcntl.LOCK_EX | fcntl.LOCK_NB)
identity = json.loads((STATE/'identity.json').read_bytes()) identity = json.loads((STATE/'identity.json').read_bytes())
db = sqlite3.connect(STATE/'channel.sqlite') db = sqlite3.connect(STATE/'channel.sqlite')
with db: with db:
+2 -2
View File
@@ -49,9 +49,9 @@ def rows(provider):
return dict(status='partial' if partial else 'ok', entries=entries) return dict(status='partial' if partial else 'ok', entries=entries)
def configured(): def configured(config_path='/conf/config.xml'):
# Project only these model paths and display fields. Never serialize XML. # Project only these model paths and display fields. Never serialize XML.
with open('/conf/config.xml', 'rb') as f: with open(config_path, 'rb') as f:
data = f.read(8 * 1024 * 1024 + 1) data = f.read(8 * 1024 * 1024 + 1)
if len(data) > 8 * 1024 * 1024: if len(data) > 8 * 1024 * 1024:
raise ValueError('config size') raise ValueError('config size')
+10 -1
View File
@@ -11,6 +11,15 @@ start_cmd=discovery_start
stop_cmd=discovery_stop stop_cmd=discovery_stop
discovery_start() { 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 for part in collect agent; do
pid=/var/run/discovery-$part.pid pid=/var/run/discovery-$part.pid
[ -z "$(check_pidfile "$pid" /usr/sbin/daemon)" ] || continue [ -z "$(check_pidfile "$pid" /usr/sbin/daemon)" ] || continue
@@ -21,7 +30,7 @@ discovery_start() {
done done
} }
discovery_stop() { 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) pid=$(check_pidfile "/var/run/discovery-$part.pid" /usr/sbin/daemon)
[ -z "$pid" ] || kill -TERM "$pid" [ -z "$pid" ] || kill -TERM "$pid"
done 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 if [ -x "$rc" ]; then
"$rc" onestop "$rc" onestop
for _ in 1 2 3 4 5; do 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 sleep 1
done 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 echo 'Existing service still running' >&2; exit 1
fi fi
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 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 0444 "$src/ca.pem" "$conf/ca.pem"
install -o root -g wheel -m 0555 "$src/discovery_agent" "$rc" install -o root -g wheel -m 0555 "$src/discovery_agent" "$rc"
+53
View File
@@ -0,0 +1,53 @@
"""Provision the first service-account probe on an existing development installation.
Run as root in FreeBSD with the operator-confirmed tenant/asset/agent UUIDs and
enrollment/assignment generations. Fetch only the public signing pin as discovery.
"""
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
import sys
import uuid
def main():
if os.geteuid() or len(sys.argv)!=6:
raise SystemExit('pin-probe.py TENANT ASSET AGENT ENROLLMENT_GENERATION ASSIGNMENT_VERSION')
tenant,asset,agent = (str(uuid.UUID(s)) for s in sys.argv[1:4])
enroll,assignment = map(int,sys.argv[4:])
if min(enroll,assignment)<1:
raise ValueError('invalid generation')
# Device-owned inputs are opened only after dropping privileges.
source = """
import hashlib,http.client,json,ssl
from pathlib import Path
p=Path('/var/db/discovery-agent')
i=json.loads((p/'identity.json').read_bytes())
ctx=ssl.create_default_context(cafile='/usr/local/etc/discovery-agent/ca.pem')
ctx.load_cert_chain(p/'device.pem',p/'device.key')
c=http.client.HTTPSConnection('discovery.ease-technologies.de',context=ctx,timeout=10)
c.request('GET','/api/v1/job-signing-key')
r=c.getresponse()
if r.status!=200:raise ValueError('device trust endpoint rejected')
print(json.dumps([i['agent_id'],i['asset_id'],json.loads(r.read(4097))]))
"""
current,bound_asset,k=json.loads(subprocess.check_output(
['su','-m','discovery','-c','/usr/local/bin/python3 -I -'],input=source.encode(),timeout=15))
key = k['public_key_hex']
if (current,bound_asset)!=(agent,asset) or not re.fullmatch('[a-f0-9]{64}',key) or (
k['algorithm'],k['schema_version'],k['key_id'])!=('Ed25519',1,hashlib.sha256(bytes.fromhex(key)).hexdigest()):
raise ValueError('conflicting device or signing key')
payload=dict(agent_id=agent,asset_id=asset,tenant_id=tenant,enrollment_generation=enroll,
assignment_version=assignment,public_key_hex=key)
p=Path('/usr/local/etc/discovery-agent/job-binding.json')
try:
with p.open('x') as f:
os.fchmod(f.fileno(),0o444); json.dump(payload,f); f.flush(); os.fsync(f.fileno())
except FileExistsError:
if p.is_symlink() or json.loads(p.read_bytes())!=payload: raise ValueError('existing binding differs')
if __name__=='__main__':
main()
+13
View File
@@ -16,6 +16,19 @@ spec.loader.exec_module(a)
class Reconnect(unittest.TestCase): class Reconnect(unittest.TestCase):
def test_piggybacked_work_requires_same_authenticated_channel_and_exact_receipt(self):
e=a.pb.Envelope(protocol_major=1,enrollment_generation=1,connection_generation=3,
agent_id=str(uuid.uuid4()),boot_id=str(uuid.uuid4()),sequence=42,message_id=str(uuid.uuid4()))
ack=a.pb.Envelope();ack.CopyFrom(e);ack.ack.message_id=e.message_id
offer=a.pb.Envelope();offer.CopyFrom(e);offer.job_offer.job_id=str(uuid.uuid4())
batch=a.pb.MessageBatch(protocol_major=1,messages=[ack,offer])
self.assertEqual(a.check_reply(batch,e,'ack'),ack)
batch.messages[1].connection_generation=2
with self.assertRaisesRegex(ValueError,'identity'): a.check_reply(batch,e,'ack')
del batch.messages[1:]
batch.messages[0].ack.message_id=str(uuid.uuid4())
with self.assertRaisesRegex(ValueError,'unconfirmed'): a.check_reply(batch,e,'ack')
def test_lost_ack_keeps_original_identity_after_restart(self): def test_lost_ack_keeps_original_identity_after_restart(self):
with tempfile.TemporaryDirectory() as temp: with tempfile.TemporaryDirectory() as temp:
db = sqlite3.connect(':memory:') db = sqlite3.connect(':memory:')
+28
View File
@@ -0,0 +1,28 @@
import tempfile
import unittest
from pathlib import Path
import collect
class ApplianceProjection(unittest.TestCase):
def test_configured_disabled_is_not_a_connection_and_secrets_stay_local(self):
with tempfile.TemporaryDirectory() as root:
p = Path(root)/'config.xml'
p.write_text('<opnsense><OPNsense><wireguard><server><servers><server uuid="uuid">'
'<name>Test</name><enabled>0</enabled><privkey>do-not-export</privkey>'
'</server></servers></server></wireguard><OpenVPN><Instances><Instance>'
'<enabled>1</enabled><description>Lab</description><tlskey>do-not-export</tlskey>'
'</Instance></Instances></OpenVPN></OPNsense></opnsense>')
self.assertEqual(collect.rows(lambda:collect.configured(p)), {
'status':'ok','entries':['WireGuard-Instanz · Test · deaktiviert','OpenVPN · Lab · aktiviert']})
p.write_text('<broken')
self.assertEqual(collect.rows(lambda:collect.configured(p)),{'status':'unavailable','entries':[]})
def test_truncation_is_explicit_and_utf8_stays_within_the_wire_limit(self):
result = collect.rows(lambda:iter(['ü'*1000]*200))
self.assertEqual((result['status'],len(result['entries'])),('partial',128))
self.assertTrue(all(len(s.encode())<=512 for s in result['entries']))
if __name__=='__main__':
unittest.main()
+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))
@@ -0,0 +1,28 @@
{
"verified_at": "2026-11-20T07:05:34Z",
"plan_id": "c3aa157c-4908-45c1-b7f4-0f588879d1af",
"operation_id": "67205987-0fda-4635-ae7a-4b7979c274dc",
"agent_id": "b4561fc5-d3b3-4ee4-810f-209d7e668e43",
"job_id": "446ac3ca-ee0a-4d33-bd0e-1c80f9edd5c9",
"attempt_id": "ea526a57-d3f0-4ae6-8d52-d6ffdf89dfa9",
"server": {
"approval_state": "approved",
"state": "succeeded",
"revision": 2,
"exit_code": 0,
"stdout": "FreeBSD\n",
"effective_uid": 1001,
"postconditions_passed": true,
"start_grants": 1
},
"guest": {
"account": "discovery",
"journal_state": "succeeded",
"revision": 2,
"consumed_grant_id": "8faf4595-61ef-442f-9d02-18f4429002d7",
"consumed_grants_for_attempt": 1,
"start_witness_present": true,
"outcome_persisted": true,
"consumption_finished": true
}
}
@@ -0,0 +1,15 @@
{
"jobs": 0,
"state": "pending_approval",
"outbox": 0,
"script": "uname -s\n",
"target": "b4561fc5-d3b3-4ee4-810f-209d7e668e43",
"attempt": "ea526a57-d3f0-4ae6-8d52-d6ffdf89dfa9",
"plan_id": "c3aa157c-4908-45c1-b7f4-0f588879d1af",
"plan_hash": "f615d46f5ac6e1a4e81eb498f29609da36c77613fe7d7ab55ccf0a395f368143",
"checked_at": "2026-11-19T19:53:19.073901+00:00",
"expires_at": "2026-11-20T19:52:59.134+00:00",
"uid_profile": "agent_service",
"operation_id": "67205987-0fda-4635-ae7a-4b7979c274dc",
"start_grants": 0
}
@@ -0,0 +1,53 @@
{
"server_revision": "2e3916b84bcfa0b99bcac7562a3bbccb2996df4c",
"helper_binary_sha256": "57f48d09541049b0e6ec8a4cc90d269866cfc9f22af441fb0f881d15e302a32b",
"public_device_detail_kernel_submit_absent": true,
"native_isolated_helper": {
"uid": 0,
"stdout": "0\n",
"exit_code": 0,
"consumptions_after_replay": 1,
"rejections": [
"foreign_peer",
"invalid_signature",
"changed_script",
"wrong_channel"
]
},
"public_order_readback": [
{
"now": "2026-11-20T07:26:45.296935+00:00",
"jobs": 0,
"grants": 0,
"source": "custom",
"plan_id": "69d9f89d-159e-4a9a-aacd-6666ec55aace",
"agent_id": "b4561fc5-d3b3-4ee4-810f-209d7e668e43",
"identity": "root",
"revision": null,
"attempt_id": "8efca471-0665-4ab9-906f-50653da14d16",
"expires_at": "2026-11-20T08:20:00+00:00",
"sync_ready": true,
"helper_ready": true,
"operation_id": "042e156b-7d5c-4458-936d-d22fb162a3e7",
"agent_version": "0.1.0-opnsense.6",
"approval_state": "pending_approval"
},
{
"now": "2026-11-20T07:26:45.296935+00:00",
"jobs": 0,
"grants": 0,
"source": "OPNsense · Version und Ausführungskonto",
"plan_id": "5683ab96-e321-4f9c-a27c-c17403e6bacd",
"agent_id": "b4561fc5-d3b3-4ee4-810f-209d7e668e43",
"identity": "agent_service",
"revision": 1,
"attempt_id": "f86e06cf-b4c1-48f9-b6c2-5d0013852aa6",
"expires_at": "2026-11-20T08:26:00+00:00",
"sync_ready": true,
"helper_ready": true,
"operation_id": "6f109d89-29f4-466b-9b99-f713d31e03d0",
"agent_version": "0.1.0-opnsense.6",
"approval_state": "pending_approval"
}
]
}
@@ -0,0 +1,40 @@
{
"rules": 91,
"source": "opnsense.base",
"tenant": "Ease Testserver - For development",
"agent_id": "b4561fc5-d3b3-4ee4-810f-209d7e668e43",
"asset_id": "1d0b9642-9f31-4fba-95f3-8cc15a11aa34",
"tenant_id": "9d730e0a-ba31-402c-8b82-8995c2585f59",
"transport": "https",
"cpu_reported": true,
"inventory_at": "2026-11-19T19:11:42.453+00:00",
"ram_reported": true,
"agent_version": "0.1.0-opnsense.4",
"last_contact_at": "2026-11-19T19:12:03.492329+00:00",
"wireguard_after_cleanup": 0,
"current_certificate_authenticated": true,
"vm": "discovery-opnsense",
"native_runtime_checks": {
"rust_freebsd_toolchain": "1.99.1",
"shared_contract_and_reconciliation_tests_passed": 71,
"qualified_clock_and_step_rejection": true,
"owned_process_group_tests_as_service_account_passed": 2,
"approved_rmm_script_executed": false,
"signed_agent_self_update_verified": false
},
"native_os": "OPNsense 26.7 (amd64), FreeBSD 15.1-RELEASE-p1",
"agent_sha256": "1e545467e0e96b87210aa39c4ab7e0f3e0ca5bf0bbbf3cb0140e2f229875e1a4",
"server_revision": "b7d9046996fdf4778d04b24a8ab2effd19647db7",
"public_browser": {
"rules_rendered": 91,
"wireguard_loopback_test_peer_handshakes_rendered": 2,
"test_interfaces_removed": true,
"vpn_section_rendered": true,
"native_interface_rendered": true,
"native_package_search_verified": true
},
"packages": 169,
"interfaces": 6,
"device_type": "virtual",
"collector_sha256": "6c4b2fd8a6d2bb9d435a00e40bca63bd53b6430006f044b3edac3655efad30db"
}
+12
View File
@@ -13,6 +13,18 @@
## Ergänzungen zur Geräteansicht ## Ergänzungen zur Geräteansicht
- **Windows-Laufwerke, 20.11.2026:** Der signierte Client `0.1.27` aus `52c352c` (Sequenz 28) wurde auf Basis des ausgelieferten `0.1.26` gebaut. Die native Probe auf `discwindowstest` erkannte neben `C:` zwei temporäre lokale Testbuchstaben `X:` und `Y:`; das DVD-Laufwerk `D:` fehlte wie vorgesehen. Die Buchstaben waren Testzuordnungen auf demselben Volume. Nach dem regulären Update meldete der echte Dienst unter seiner bisherigen Geräteidentität `C:` mit Kapazität und freien Bytes. Server und WebUI `04037c7` zeigen ein eigenes Wertepaar pro Laufwerk. [Browserprüfung mit drei Laufwerken](../tests/browser/customer-management.spec.ts) · [Abwärtskompatible Projektion](../crates/server/src/devices.rs)
- **Belegt / gesamt, 20.11.2026:** Bei 12 GiB frei von 16 GiB zeigte die Geräteübersicht für Speicher und RAM jeweils „4 / 16 GiB“ und „25 % belegt“. Die [Browserprüfung](../tests/browser/customer-management.spec.ts) bestätigte Farben und Segmentbreiten (rot belegt, grün frei) bei 0 %, 25 % und 100 % Belegung auf 1280, 900 und 390 px. Fehlende oder widersprüchliche Messwerte ergaben keine Belegungsangabe.
- **Speicherbalken, 20.11.2026:** Die Geräteübersicht verwendet für Laufwerk und RAM dieselbe Darstellung. Die [Browserprüfung](../tests/browser/customer-management.spec.ts) bestätigte für beide Spalten bei 1280, 900 und 390 px die Segmentbreiten und Beschriftungen für 0 %, 75 % und 100 % frei. Bei fehlenden oder ungültigen Werten erschien kein Balken.
- **OPNsense-Standardaufträge, 20.11.2026:** Server/WebUI `2e3916b`, Schema 47, Client `0.1.0-opnsense.6`. Im öffentlichen Browser fehlt der frühere Sonderknopf im Gerätedetail. Über **Aufträge** wurden ein einmaliges POSIX-Skript `id -u` als `root` und die mitgelieferte Bibliotheksrevision „OPNsense · Version und Ausführungskonto“ v1 als Dienstkonto eingereicht. Beide standen beim Nachlesen auf `pending_approval`, ohne Jobs oder Grants. Derselbe Gast meldete Agent- und Helper-Abgleich bereit. Ein separater nativer Test des installierten FreeBSD-Helpers mit Wegwerfschlüssel und unabhängigen Journalen lieferte UID 0 und bestätigte nach Wiederzustellung nur einen Start. Fremder Peer, manipuliertes Skript, ungültige Signatur und falsche Verbindung wurden abgelehnt. Für die Live-Abnahme fehlen die persönlichen Freigaben und Ergebnisse dieser beiden Versuche. [Nachweis](evidence/opnsense-root-orders-20261120.json)
- **OPNsense-Kernelabfrage, 20.11.2026 — abgenommen:** Vor der persönlichen Freigabe hatte der [Geräteantrag](evidence/opnsense-probe-submission-20261119.json) null Jobs, Outbox-Einträge und Startgrants. Danach lieferte genau der geplante Versuch `ea526a57…` auf der bestehenden VM `FreeBSD\n`, Exitcode 0, als `discovery` (UID 1001). Server und Gastjournal meldeten `succeeded`, Revision 2. Ein ausgestellter Startgrant, ein lokaler Verbrauch mit Start- und Ergebnisbeleg. Der getrennte native Integrationstest prüfte die doppelte Zustellung. [End-to-End-Ergebnis](evidence/opnsense-probe-result-20261120.json)
- **OPNsense-Testgerät:** OPNsense 26.7/FreeBSD 15.1 nativ in der Notebook-VM gestartet; Aufnahme per Kunden-Einmalcode, lokaler P-256-Schlüssel, ausgehendes mTLS. Die öffentliche Geräteansicht zeigte 91 aktive PF-Regeln und beide tatsächlichen Handshakes eines vorübergehenden lokalen WireGuard-Testpaars. Beide Testinterfaces wurden danach entfernt. OpenVPN ohne Verbindungen, IPsec-Dienst nicht erreichbar. Heartbeats, Inventar, CPU und RAM mit derselben Installation nach Agentwechsel geprüft. Version `0.1.0-opnsense.4` meldete Gerätetyp `virtual`, sechs Interfaces und 169 Pakete; Netzwerkkarte und Paketsuche wurden im öffentlichen Browser nachgelesen. Im Gast bestanden 71 Rust-Vertrags-/Abgleichtests, der Test der FreeBSD-Kerneluhr und zwei Prozessgruppenprüfungen als Dienstkonto. Noch offen: durchgängiger Skript-/Root-Jobpfad, signierter OPNsense-Releasekanal und öffentliche Erstinstallation. [Betrieb](../deploy/opnsense/README.md) · [Nachweis](evidence/opnsense-test-device-20261119.json)
- **RAM-Balken:** Der alte Balken hob bei „RAM frei / gesamt“ den belegten Anteil hervor. Der neue Balken färbt verfügbare Kapazität grün und belegte grau und beschriftet den freien Anteil direkt. Bei fehlenden oder ungültigen Werten wird kein Balken gezeichnet. Build, 80 Komponententests und sechs Browserprüfungen einschließlich 0 %, 75 % und 100 % frei bestanden. WebUI `577a6ee` am 19. November 2026 um 18:38 UTC ausgeliefert. Angemeldetes Chromium bestätigte für neun reale Geräte die gerenderten Segmentbreiten und Beschriftungen bei 1280, 900 und 390 px. API, Datenbank und Agenten mussten nicht geändert werden. [Browserregression](../tests/browser/customer-management.spec.ts) - **RAM-Balken:** Der alte Balken hob bei „RAM frei / gesamt“ den belegten Anteil hervor. Der neue Balken färbt verfügbare Kapazität grün und belegte grau und beschriftet den freien Anteil direkt. Bei fehlenden oder ungültigen Werten wird kein Balken gezeichnet. Build, 80 Komponententests und sechs Browserprüfungen einschließlich 0 %, 75 % und 100 % frei bestanden. WebUI `577a6ee` am 19. November 2026 um 18:38 UTC ausgeliefert. Angemeldetes Chromium bestätigte für neun reale Geräte die gerenderten Segmentbreiten und Beschriftungen bei 1280, 900 und 390 px. API, Datenbank und Agenten mussten nicht geändert werden. [Browserregression](../tests/browser/customer-management.spec.ts)
- **Zweck je Gerät:** Optionale Spalte im Bestand und in der Historie, Freitextpflege im Gerätedetail. WebUI-Build, 80 Komponententests, fünf Browserprüfungen und HTTP-Rundlauf auf isoliertem PostgreSQL mit Schreib-, Lese- und Fremdkundenfällen bestanden. Am 19. November 2026 um 14:10 UTC wurde `2070ae9` mit [Migration 45](../migrations/0045_device_purpose.sql) aktiviert. API, öffentliche API und Gateway bestanden die TLS-Healthchecks; der öffentliche WebUI-Index entsprach dem Build. Angemeldetes Chromium zeigte die Zweck-Spalte für sechs Geräte, den Editor im Gerätedetail und die Spalte bei 390 px Breite. Bei der Live-Sichtprüfung wurde nichts gespeichert; kein Agentwechsel. [Bedienung](public-access.md#zweck-eines-geräts-pflegen) · [Browserregression](../tests/browser/device-purpose.spec.ts) - **Zweck je Gerät:** Optionale Spalte im Bestand und in der Historie, Freitextpflege im Gerätedetail. WebUI-Build, 80 Komponententests, fünf Browserprüfungen und HTTP-Rundlauf auf isoliertem PostgreSQL mit Schreib-, Lese- und Fremdkundenfällen bestanden. Am 19. November 2026 um 14:10 UTC wurde `2070ae9` mit [Migration 45](../migrations/0045_device_purpose.sql) aktiviert. API, öffentliche API und Gateway bestanden die TLS-Healthchecks; der öffentliche WebUI-Index entsprach dem Build. Angemeldetes Chromium zeigte die Zweck-Spalte für sechs Geräte, den Editor im Gerätedetail und die Spalte bei 390 px Breite. Bei der Live-Sichtprüfung wurde nichts gespeichert; kein Agentwechsel. [Bedienung](public-access.md#zweck-eines-geräts-pflegen) · [Browserregression](../tests/browser/device-purpose.spec.ts)
+1 -1
View File
@@ -4,7 +4,7 @@ Die öffentliche WebUI verwendet ein lokales Benutzerkonto mit Passwort und eine
## Geräte und Kunden ## Geräte und Kunden
**Geräte** zeigt bestätigte Online- und Offline-Geräte der berechtigten Kunden mit Hostname, Betriebssystem, Status, freiem und gesamtem Speicherplatz, RAM, CPU und Kunde. Die Historie enthält unter anderem archivierte und widerrufene Installationen. Ein Klick auf den Hostnamen öffnet das Inventar und die letzten Aufträge. Der Kundenname in der Kopfzeile zeigt, in welchem Kunden die nächste Änderung erfolgt. **Geräte** zeigt bestätigte Online- und Offline-Geräte der berechtigten Kunden mit Hostname, Betriebssystem, Status, Speicher, RAM, CPU und Kunde. Speicher und RAM stehen als **belegt / gesamt** in GiB. Ab Windows-Client `0.1.27` erscheinen nach der nächsten Inventur alle lokalen Festplattenlaufwerke mit Buchstaben untereinander, jeweils mit eigenem Balken (rot belegt, grün frei). Ein DVD- oder Netzlaufwerk zählt nicht dazu. Ältere Clients melden nur die Systemplatte. Die Historie enthält unter anderem archivierte und widerrufene Installationen. Ein Klick auf den Hostnamen öffnet das Inventar und die letzten Aufträge. Der Kundenname in der Kopfzeile zeigt, in welchem Kunden die nächste Änderung erfolgt.
Berechtigte Benutzer können Kunden anlegen und umbenennen. Zur Aufnahme den Zielkunden wählen und unter **Verwaltung → Geräteaufnahme** einen Einmalcode erzeugen. Der Code gilt für diesen Kunden und verfällt bei erfolgreicher Aufnahme oder nach 15 Minuten. Die WebUI zeigt für die veröffentlichten Plattformen Download und Installationsbefehl. Auf dem neuen Gerät das HTTPS-Skript mit Administratorrechten aufrufen und den Code am Prompt eingeben. Für lokale Administrator-Skripte die dafür angebotene Installationsoption wählen. Der Windows-Kanal ist `x86_64-pc-windows-gnu`. [Linux-Installer](https://discovery.ease-technologies.de:8443/install/linux.sh) · [Windows-Installer](https://discovery.ease-technologies.de:8443/install/windows.ps1) Berechtigte Benutzer können Kunden anlegen und umbenennen. Zur Aufnahme den Zielkunden wählen und unter **Verwaltung → Geräteaufnahme** einen Einmalcode erzeugen. Der Code gilt für diesen Kunden und verfällt bei erfolgreicher Aufnahme oder nach 15 Minuten. Die WebUI zeigt für die veröffentlichten Plattformen Download und Installationsbefehl. Auf dem neuen Gerät das HTTPS-Skript mit Administratorrechten aufrufen und den Code am Prompt eingeben. Für lokale Administrator-Skripte die dafür angebotene Installationsoption wählen. Der Windows-Kanal ist `x86_64-pc-windows-gnu`. [Linux-Installer](https://discovery.ease-technologies.de:8443/install/linux.sh) · [Windows-Installer](https://discovery.ease-technologies.de:8443/install/windows.ps1)
+47
View File
@@ -0,0 +1,47 @@
-- As with the Linux/Windows starting revisions, preserve any existing customer revision.
CREATE FUNCTION seed_opnsense_scripts(target_tenant uuid) RETURNS void
LANGUAGE plpgsql SET search_path = pg_catalog, public AS $$
DECLARE previous_tenant text := coalesce(current_setting('app.tenant_id', true), '');
BEGIN
PERFORM set_config('app.tenant_id', target_tenant::text, true);
INSERT INTO public.script_revisions(tenant_id,name,version,interpreter,execution_identity,created_by,script_utf8)
SELECT target_tenant,name,1,'posix_sh',identity,'system:bootstrap',body
FROM (VALUES
('OPNsense · Version und Ausführungskonto','agent_service',$sh$#!/bin/sh
set -eu
/usr/local/sbin/opnsense-version
/usr/bin/uname -sr
/usr/bin/id
$sh$),
('OPNsense · Aktive Firewallregeln anzeigen','root',$sh$#!/bin/sh
set -eu
[ -x /usr/local/sbin/opnsense-version ]
exec /sbin/pfctl -sr
$sh$)) AS scripts(name,identity,body)
ON CONFLICT (tenant_id,name,version) DO NOTHING;
PERFORM set_config('app.tenant_id', previous_tenant, true);
END
$$;
REVOKE ALL ON FUNCTION seed_opnsense_scripts(uuid) FROM PUBLIC;
CREATE OR REPLACE FUNCTION seed_tenant_script_library() RETURNS trigger
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$
DECLARE previous_tenant text := coalesce(current_setting('app.tenant_id', true), '');
BEGIN
PERFORM set_config('app.tenant_id', NEW.tenant_id::text, true);
PERFORM public.seed_windows_update_script(NEW.tenant_id);
PERFORM public.seed_standard_diagnostic_scripts(NEW.tenant_id);
PERFORM public.seed_restart_scripts(NEW.tenant_id);
PERFORM public.seed_windows_restart_receipt(NEW.tenant_id);
PERFORM public.seed_opnsense_scripts(NEW.tenant_id);
PERFORM set_config('app.tenant_id', previous_tenant, true);
RETURN NEW;
END
$$;
DO $$
BEGIN
LOCK TABLE tenants IN SHARE ROW EXCLUSIVE MODE;
PERFORM public.seed_opnsense_scripts(tenant_id) FROM tenants;
END
$$;
+40 -24
View File
@@ -20,7 +20,7 @@ test.beforeAll(async () => {
test.afterAll(async () => { await server?.close(); }); test.afterAll(async () => { await server?.close(); });
test('draws the free RAM share accurately on desktop and mobile', async ({ page }) => { test('shows used disk and RAM in GiB and draws the occupied share in red on desktop and mobile', async ({ page }) => {
const customer = { tenant_id: '11111111-1111-4111-8111-111111111111', name: 'RAM-Test' }; const customer = { tenant_id: '11111111-1111-4111-8111-111111111111', name: 'RAM-Test' };
const gib = 2 ** 30; const gib = 2 ** 30;
const readings = [ const readings = [
@@ -48,32 +48,50 @@ test('draws the free RAM share accurately on desktop and mobile', async ({ page
json: listing(readings.map(([hostname, free, total]) => ({ json: listing(readings.map(([hostname, free, total]) => ({
tenant_id: customer.tenant_id, customer_name: customer.name, asset_id: hostname, agent_id: hostname, tenant_id: customer.tenant_id, customer_name: customer.name, asset_id: hostname, agent_id: hostname,
lifecycle: 'current', status: 'online', hostname, ram_available_bytes: free, ram_total_bytes: total, lifecycle: 'current', status: 'online', hostname, ram_available_bytes: free, ram_total_bytes: total,
disk_free_bytes: 12 * gib, disk_total_bytes: 16 * gib disk_free_bytes: free, disk_total_bytes: total,
...(hostname === 'mostly-free' ? { volumes: [
{ name: 'C:', free_bytes: free, total_bytes: total },
{ name: 'D:', free_bytes: 0, total_bytes: 64 * gib },
{ name: 'E:', free_bytes: null, total_bytes: null }
] } : {})
}))) })))
}); });
return route.fulfill({ status: 404 }); return route.fulfill({ status: 404 });
}); });
await page.goto(`${origin}/#geraete`); await page.goto(`${origin}/#geraete`);
const row = (host: string) => page.getByRole('row').filter({ has: page.getByRole('button', { name: host, exact: true }) }); const row = (host: string) => page.getByRole('row').filter({ has: page.getByRole('button', { name: host, exact: true }) });
const ram = (host: string) => row(host).locator('[data-label="RAM frei / gesamt"]');
await expect(ram('mostly-free')).toContainText('12 / 16 GiB');
await expect(ram('mostly-free').locator('.capacity-caption')).toHaveText('75 % frei');
await expect(row('mostly-free').locator('[data-label="Speicher frei / gesamt"] .capacity-track i'))
.toHaveAttribute('style', 'width: 25%;');
for (const width of [1280, 900, 390]) { for (const width of [1280, 900, 390]) {
await page.setViewportSize({ width, height: 844 }); await page.setViewportSize({ width, height: 844 });
for (const [host, free] of [['mostly-free', 75], ['all-used', 0], ['all-free', 100]] as const) { for (const label of ['RAM', 'Speicher']) {
const bar = ram(host).getByRole('img', { name: `${free} % frei, ${100 - free} % belegt` }); const cell = (host: string) => {
await expect(bar).toBeVisible(); const column = row(host).locator(`[data-label="${label} belegt / gesamt"]`);
const [track = 0, freeWidth = 0, usedWidth = 0] = await bar.evaluate(el => [el, ...Array.from(el.children)] return host === 'mostly-free' && label === 'Speicher'
.map(part => part.getBoundingClientRect().width)); ? column.locator('.drive-capacity').filter({ hasText: 'C:' }) : column;
expect(track).toBeGreaterThan(0); };
expect(freeWidth / track).toBeCloseTo(free / 100, 2); for (const [host, used, usedGiB] of [['mostly-free', 25, 4], ['all-used', 100, 16], ['all-free', 0, 0]] as const) {
expect(usedWidth / track).toBeCloseTo((100 - free) / 100, 2); await expect(cell(host)).toContainText(`${usedGiB} / 16 GiB`);
await expect(cell(host).locator('.capacity-caption')).toHaveText(`${used} % belegt`);
const bar = cell(host).getByRole('img', { name: `${used} % belegt, ${100 - used} % frei` });
await expect(bar).toBeVisible();
await expect(bar.locator('.capacity-used')).toHaveCSS('background-color', 'rgb(199, 137, 128)');
await expect(bar.locator('.capacity-free')).toHaveCSS('background-color', 'rgb(46, 118, 87)');
const [track = 0, usedWidth = 0, freeWidth = 0] = await bar.evaluate(el => [el, ...Array.from(el.children)]
.map(part => part.getBoundingClientRect().width));
expect(track).toBeGreaterThan(0);
expect(usedWidth / track).toBeCloseTo(used / 100, 2);
expect(freeWidth / track).toBeCloseTo((100 - used) / 100, 2);
}
for (const host of ['missing-available', 'invalid-range', 'invalid-total']) {
await expect(cell(host).locator('.capacity-track')).toHaveCount(0);
await expect(cell(host)).toHaveText(host === 'invalid-total' ? 'Nicht gemeldet' : '– / 16 GiB');
}
} }
} const drives = row('mostly-free').locator('.drive-capacity');
for (const host of ['missing-available', 'invalid-range', 'invalid-total']) { await expect(drives).toHaveCount(3);
await expect(ram(host).locator('.capacity-track')).toHaveCount(0); await expect(drives.nth(1)).toContainText('D: 64 / 64 GiB');
await expect(drives.nth(1).getByRole('img', { name: '100 % belegt, 0 % frei' })).toBeVisible();
await expect(drives.nth(2)).toHaveText('E: Nicht gemeldet');
await expect(drives.nth(2).getByRole('img')).toHaveCount(0);
} }
}); });
@@ -167,12 +185,10 @@ test('creates and renames a customer, opens its inventory, and hides editing for
await expect(headers.nth(1)).toHaveText('Type'); await expect(headers.nth(1)).toHaveText('Type');
await expect(device.locator('[data-label="Type"]')).toHaveText('hypervisor'); await expect(device.locator('[data-label="Type"]')).toHaveText('hypervisor');
await expect(device.locator('[data-label="OS"]')).toHaveText('Proxmox VE'); await expect(device.locator('[data-label="OS"]')).toHaveText('Proxmox VE');
const memory = device.locator('[data-label="RAM frei / gesamt"]'); const memory = device.locator('[data-label="RAM belegt / gesamt"]');
await expect(memory).toContainText('6 / 16 GiB'); await expect(memory).toContainText('10 / 16 GiB');
await expect(memory.getByRole('img', { name: '37,5 % frei, 62,5 % belegt' })).toBeVisible(); await expect(memory.getByRole('img', { name: '62,5 % belegt, 37,5 % frei' })).toBeVisible();
await expect(memory.locator('.capacity-free')).toHaveAttribute('style', 'width: 37.5%;'); await expect(device.locator('[data-label="Speicher belegt / gesamt"]').getByRole('img', { name: '25 % belegt, 75 % frei' })).toBeVisible();
await expect(device.locator('[data-label="Speicher frei / gesamt"] .capacity-track i'))
.toHaveAttribute('style', 'width: 25%;');
await expect(device.getByText('Auslastung 0 %', { exact: true })).toBeVisible(); await expect(device.getByText('Auslastung 0 %', { exact: true })).toBeVisible();
const navigation = page.getByRole('navigation', { name: 'Hauptnavigation' }); const navigation = page.getByRole('navigation', { name: 'Hauptnavigation' });
await navigation.getByRole('link', { name: 'Aufträge', exact: true }).click(); await navigation.getByRole('link', { name: 'Aufträge', exact: true }).click();
+1 -1
View File
@@ -568,7 +568,7 @@ test('publishes versions in the library and keeps the earlier script readable',
await page.getByRole('button', { name: 'Version veröffentlichen' }).click(); await page.getByRole('button', { name: 'Version veröffentlichen' }).click();
await expect(page.getByRole('status')).toContainText('Version 2 veröffentlicht.'); await expect(page.getByRole('status')).toContainText('Version 2 veröffentlicht.');
await page.getByText('Frühere Versionen (1)').click(); await page.getByText('Frühere Versionen (1)').click();
await page.getByText('Version 1 · Linux · Shell · Agent-Dienstkonto').click(); await page.getByText('Version 1 · POSIX-Shell · Agent-Dienstkonto').click();
await expect(page.locator('pre').filter({ hasText: 'uname -s' })).toBeVisible(); await expect(page.locator('pre').filter({ hasText: 'uname -s' })).toBeVisible();
await page.getByRole('button', { name: 'Zur Skriptbibliothek' }).click(); await page.getByRole('button', { name: 'Zur Skriptbibliothek' }).click();
await expect(page.getByRole('row').filter({ hasText: script.name })).toHaveCount(1); await expect(page.getByRole('row').filter({ hasText: script.name })).toHaveCount(1);
+54
View File
@@ -0,0 +1,54 @@
"""Register an explicitly pinned FreeBSD helper in the existing managed-script policy."""
import argparse
import fcntl
import inspect
import json
import re
import stat
import subprocess
import uuid
from dev_linux_helper_rollover import POLICY, encoded, protected, replace, require
from dev_stage import ssh_prefix
def register(path, scope):
uid=(path.parent.parent/'jobs/ed25519.pem').lstat().st_uid
lock=path.with_name('operator.lock')
info=lock.lstat()
require(stat.S_ISREG(info.st_mode) and info.st_uid in (0,uid) and not info.st_mode&0o022,'bad operator lock')
with lock.open('rb') as guard:
fcntl.flock(guard,fcntl.LOCK_EX)
info=protected(path,uid)
require(stat.S_IMODE(info.st_mode)==0o600 and info.st_size<=65536,'unsafe policy')
p=json.loads(path.read_bytes())
require(p['schema_version']==1,'unsupported policy')
rows=p.setdefault('opnsense',[])
existing=[r for r in rows if r['agent_id']==scope['agent_id']]
if existing:
require(existing==[scope],'existing rule differs')
else:
rows.append(scope)
data=encoded(p)
require(len(data)<=65536 and sum(len(p[k]) for k in ('windows','linux','opnsense'))<=64,'policy capacity')
replace(path,data)
def main():
parser=argparse.ArgumentParser(description=__doc__)
for k in ('tenant','asset','agent','principal'): parser.add_argument('--'+k,required=True,type=uuid.UUID)
for k in ('policy','binary'): parser.add_argument('--'+k,required=True)
for k in ('enrollment-generation','assignment-version'):parser.add_argument('--'+k,required=True,type=int)
a=parser.parse_args()
require(all(re.fullmatch('[a-f0-9]{64}',s) for s in [a.policy,a.binary]) and
min(a.enrollment_generation,a.assignment_version)>0,'invalid pins or generations')
scope=dict(tenant_id=str(a.tenant),asset_id=str(a.asset),agent_id=str(a.agent),
enrollment_generation=a.enrollment_generation,assignment_version=a.assignment_version,
principals=['local:'+str(a.principal)],helper_policy_sha256=a.policy,helper_binary_sha256=a.binary,
allowed_script_profiles=['full_maintenance_v1'],allow_root_scripts=True,allow_reboot=False,
allowed_services=[],acceptance_evidence_id='opnsense-root-'+str(a.agent))
program='import fcntl,json,os,stat,tempfile\nfrom pathlib import Path\n'
for f in (require,protected,encoded,replace,register):program+=inspect.getsource(f)+'\n'
subprocess.run([*ssh_prefix('server'),'python3 -I -'],input=program+f'register(Path({str(POLICY)!r}),{scope!r})\n',text=True,check=True)
if __name__=='__main__': main()
+1
View File
@@ -193,6 +193,7 @@ export function validateInput(input: PlanInput): void {
validateScriptIdentityProfile(input.parameters, input.parameters.execution_identity, variant.interpreter); validateScriptIdentityProfile(input.parameters, input.parameters.execution_identity, variant.interpreter);
const bytes = new TextEncoder().encode(script).length; const bytes = new TextEncoder().encode(script).length;
const platform = variant.os_family === 'linux' && ['posix_sh', 'bash'].includes(String(variant.interpreter)) const platform = variant.os_family === 'linux' && ['posix_sh', 'bash'].includes(String(variant.interpreter))
|| variant.os_family === 'opnsense' && variant.interpreter === 'posix_sh'
|| variant.os_family === 'windows' && variant.interpreter === 'powershell'; || variant.os_family === 'windows' && variant.interpreter === 'powershell';
return bytes > 0 && bytes <= 32768 && !script.includes('\0') && variant.encoding === 'utf-8' && platform return bytes > 0 && bytes <= 32768 && !script.includes('\0') && variant.encoding === 'utf-8' && platform
&& (variant.os_family !== 'windows' || /^[\x00-\x7f]*$/.test(script) || script.startsWith('\ufeff')); && (variant.os_family !== 'windows' || /^[\x00-\x7f]*$/.test(script) || script.startsWith('\ufeff'));
+42 -33
View File
@@ -44,9 +44,13 @@ function gib(v: unknown) {
return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? number.format(v / 2 ** 30) : null; return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? number.format(v / 2 ** 30) : null;
} }
function capacity(free: unknown, total: unknown) { function capacity(free: unknown, total: unknown) {
const f = gib(free), if (typeof total !== 'number' || !Number.isFinite(total) || total <= 0)
t = gib(total); return { text: unknown, usedPercent: null };
return f === null && t === null ? unknown : `${f ?? '–'} / ${t ?? '–'} GiB`; const used = typeof free === 'number' && free >= 0 && free <= total ? total - free : null;
return {
text: `${gib(used) ?? '–'} / ${gib(total)} GiB`,
usedPercent: used === null ? null : (used / total) * 100
};
} }
function cpuUsage(value: unknown) { function cpuUsage(value: unknown) {
return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 100 return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 100
@@ -90,39 +94,44 @@ function Presence({ d }: { d: RecordValue }) {
</span> </span>
); );
} }
function Capacity({ free, total, showBreakdown = false }: { function Capacity({ free, total }: {
free: unknown; free: unknown;
total: unknown; total: unknown;
showBreakdown?: boolean;
}) { }) {
const freePercent = typeof free === 'number' && typeof total === 'number' && const { text, usedPercent } = capacity(free, total);
Number.isFinite(total) && free >= 0 && free <= total && total > 0 const displayUsed = usedPercent === null ? null : Math.round(usedPercent * 10) / 10;
? (free / total) * 100 const usedLabel = displayUsed === null ? '' : `${number.format(displayUsed)} % belegt`;
: null; const breakdown = displayUsed === null ? '' : `${usedLabel}, ${number.format(100 - displayUsed)} % frei`;
const displayFree = freePercent === null ? null : Math.round(freePercent * 10) / 10;
const freeLabel = displayFree === null ? '' : `${number.format(displayFree)} % frei`;
const breakdown = displayFree === null ? '' : `${freeLabel}, ${number.format(100 - displayFree)} % belegt`;
return ( return (
<> <>
<span>{capacity(free, total)}</span> <span>{text}</span>
{freePercent !== null && (showBreakdown ? ( {usedPercent !== null && (
<> <>
<span className="capacity-track capacity-breakdown" role="img" <span className="capacity-track" role="img"
aria-label={breakdown} title={breakdown}> aria-label={breakdown} title={breakdown}>
<span className="capacity-free" style={{ width: `${freePercent}%` }} /> <span className="capacity-used" style={{ width: `${usedPercent}%` }} />
<span className="capacity-used" /> <span className="capacity-free" />
</span> </span>
<small className="capacity-caption" aria-hidden="true">{freeLabel}</small> <small className="capacity-caption" aria-hidden="true">{usedLabel}</small>
</> </>
) : ( )}
<span className="capacity-track" title={freeLabel} aria-hidden="true">
<i style={{ width: `${100 - freePercent}%` }} />
</span>
))}
</> </>
); );
} }
function DiskCapacity({ device }: { device: RecordValue }) {
// Only Windows fleet rows use drive letters. Linux mount inventories remain
// available in the detail view, without expanding every fleet row.
const drives = Array.isArray(device.volumes)
? device.volumes.map(v => record(v)).filter(v => typeof v.name === 'string' && /^[A-Z]:$/.test(v.name)) : [];
if (!drives.length) return <Capacity free={device.disk_free_bytes} total={device.disk_total_bytes} />;
return <>{drives.map(drive => (
<div className="drive-capacity" key={String(drive.name)}>
<strong>{String(drive.name)}</strong>{' '}<Capacity free={drive.free_bytes} total={drive.total_bytes} />
</div>
))}</>;
}
type Target = { customer: string; ids: string[] }; type Target = { customer: string; ids: string[] };
type Props = { type Props = {
detailPath: string; detailPath: string;
@@ -205,7 +214,7 @@ function reportedScriptProfiles(device: RecordValue) {
if (!caps.has('run_script')) return 'Nicht gemeldet'; if (!caps.has('run_script')) return 'Nicht gemeldet';
const windows = os === 'windows'; const windows = os === 'windows';
const identity = windows ? 'system' : 'root'; const identity = windows ? 'system' : 'root';
const service = windows ? 'PowerShell als Dienstkonto' : 'Shell als Dienstkonto'; const service = os==='opnsense' && !caps.has('opnsense.posix/1') ? 'Kernelabfrage als Dienstkonto' : windows ? 'PowerShell als Dienstkonto' : 'Shell als Dienstkonto';
if (!caps.has(os + '.base/1') || caps.has(windows ? 'linux.base/1' : 'windows.base/1')) return 'Nicht gemeldet'; if (!caps.has(os + '.base/1') || caps.has(windows ? 'linux.base/1' : 'windows.base/1')) return 'Nicht gemeldet';
if (windows && !['rmm.sync.v1', 'script.powershell/1', 'script.powershell.process_remote_signed/1'].every(cap => caps.has(cap))) if (windows && !['rmm.sync.v1', 'script.powershell/1', 'script.powershell.process_remote_signed/1'].every(cap => caps.has(cap)))
return 'Nicht gemeldet'; return 'Nicht gemeldet';
@@ -257,10 +266,10 @@ function DeviceDetail({
['Type', label(d.device_type)], ['Type', label(d.device_type)],
['Betriebssystem', label(d.os)], ['Betriebssystem', label(d.os)],
...systemDetails(d, time), ...systemDetails(d, time),
['RAM frei / gesamt', capacity(d.ram_available_bytes, d.ram_total_bytes)], ['RAM belegt / gesamt', capacity(d.ram_available_bytes, d.ram_total_bytes).text],
['CPU', [cpu(d).primary, cpu(d).secondary].filter(Boolean).join(' · ')], ['CPU', [cpu(d).primary, cpu(d).secondary].filter(Boolean).join(' · ')],
['CPU-Auslastung', [cpuUsage(d.cpu_usage_percent), measuredAt(d.cpu_usage_observed_at)].filter(Boolean).join(' · ')], ['CPU-Auslastung', [cpuUsage(d.cpu_usage_percent), measuredAt(d.cpu_usage_observed_at)].filter(Boolean).join(' · ')],
['Speicher frei / gesamt', capacity(d.disk_free_bytes, d.disk_total_bytes)], ['Speicher belegt / gesamt', capacity(d.disk_free_bytes, d.disk_total_bytes).text],
['Letzter Kontakt', time(d.last_contact_at)], ['Letzter Kontakt', time(d.last_contact_at)],
['Inventar erhoben', time(d.observed_at)], ['Inventar erhoben', time(d.observed_at)],
['Agentversion', label(d.agent_version)], ['Agentversion', label(d.agent_version)],
@@ -311,14 +320,14 @@ function DeviceDetail({
<thead> <thead>
<tr> <tr>
<th>Laufwerk</th> <th>Laufwerk</th>
<th>Speicher frei / gesamt</th> <th>Speicher belegt / gesamt</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{volumes.map((v, i) => ( {volumes.map((v, i) => (
<tr key={i}> <tr key={i}>
<td>{label(v.name)}</td> <td>{label(v.name)}</td>
<td>{capacity(v.free_bytes, v.total_bytes)}</td> <td>{capacity(v.free_bytes, v.total_bytes).text}</td>
</tr> </tr>
))} ))}
</tbody> </tbody>
@@ -638,7 +647,7 @@ export function Devices({
<span className="sr-only">Ziel auswählen</span> <span className="sr-only">Ziel auswählen</span>
</th> </th>
)} )}
{['Hostname', 'Type', 'Zweck', 'OS', 'Status', 'Speicher frei / gesamt', 'RAM frei / gesamt', 'CPU', 'Kunde'].map( {['Hostname', 'Type', 'Zweck', 'OS', 'Status', 'Speicher belegt / gesamt', 'RAM belegt / gesamt', 'CPU', 'Kunde'].map(
(h) => ( (h) => (
<th scope="col" key={h} className={h === 'Zweck' ? 'purpose-col' : undefined}> <th scope="col" key={h} className={h === 'Zweck' ? 'purpose-col' : undefined}>
{h} {h}
@@ -702,11 +711,11 @@ export function Devices({
<small>Zuletzt {time(d.last_contact_at)}</small> <small>Zuletzt {time(d.last_contact_at)}</small>
)} )}
</td> </td>
<td data-label="Speicher frei / gesamt" className="capacity-cell"> <td data-label="Speicher belegt / gesamt" className="capacity-cell">
<Capacity free={d.disk_free_bytes} total={d.disk_total_bytes} /> <DiskCapacity device={d} />
</td> </td>
<td data-label="RAM frei / gesamt" className="capacity-cell" title={measuredAt(d.ram_observed_at)}> <td data-label="RAM belegt / gesamt" className="capacity-cell" title={measuredAt(d.ram_observed_at)}>
<Capacity free={d.ram_available_bytes} total={d.ram_total_bytes} showBreakdown /> <Capacity free={d.ram_available_bytes} total={d.ram_total_bytes} />
</td> </td>
<td data-label="CPU"> <td data-label="CPU">
{model.primary} {model.primary}
+24
View File
@@ -0,0 +1,24 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, it } from 'vitest';
import { OPNsenseDetails } from './opnsense';
import { DeviceInventoryPanels } from './device-inventory';
it('keeps missing, empty and partial appliance sources distinct and limits panels to OPNsense', () => {
const d = { source_id:'opnsense.base', inventory:{
ipsec:{status:'unavailable',entries:[]}, openvpn:{status:'ok',entries:[]},
firewall:{status:'partial', entries:['pass in on vtnet0']},
interfaces:{status:'ok', entries:[{name:'vtnet0',addresses:['192.0.2.1/24']}]},
software:{status:'ok',entries:[{name:'opnsense',version:'26.7'}]},
users:{status:'unavailable',entries:[]}
}};
const view = renderToStaticMarkup(<OPNsenseDetails device={d}/>);
expect(view).toMatch(/IPsec[^<]*<\/h3><p>Nicht ermittelbar/);
expect(view).toMatch(/OpenVPN[^<]*<\/h3><p>Keine Einträge/);
expect(view).toContain('unvollständige Liste');
expect(view).toContain('pass in on vtnet0');
expect(renderToStaticMarkup(<OPNsenseDetails device={{...d,source_id:'linux.base'}}/>)).toBe('');
const system = renderToStaticMarkup(<DeviceInventoryPanels device={d}/>);
expect(system).toContain('192.0.2.1/24');
expect(system).toContain('26.7');
expect(system).not.toContain('Keine Benutzer angemeldet');
});
+19 -10
View File
@@ -43,7 +43,7 @@ type Target = {
id: string; id: string;
name: string; name: string;
os: string; os: string;
platform: 'linux' | 'windows' | null; platform: 'linux' | 'windows' | 'opnsense' | null;
state: string; state: string;
current: boolean; current: boolean;
}; };
@@ -143,6 +143,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
const [libraryIdentity, setLibraryIdentity] = useState<Identity | null>(null); const [libraryIdentity, setLibraryIdentity] = useState<Identity | null>(null);
const [linux, setLinux] = useState<Script>(() => emptyScript('posix_sh')); const [linux, setLinux] = useState<Script>(() => emptyScript('posix_sh'));
const [windows, setWindows] = useState<Script>(() => emptyScript('powershell')); const [windows, setWindows] = useState<Script>(() => emptyScript('powershell'));
const [opnsense,setOpnsense] = useState<Script>(() => emptyScript('posix_sh'));
const [reason, setReason] = useState(''); const [reason, setReason] = useState('');
const [start, setStart] = useState(() => localDate(Date.now())); const [start, setStart] = useState(() => localDate(Date.now()));
const [end, setEnd] = useState(() => localDate(Date.now() + 3600000)); const [end, setEnd] = useState(() => localDate(Date.now() + 3600000));
@@ -217,6 +218,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
const targets = selected.map((id) => directory.get(id)); const targets = selected.map((id) => directory.get(id));
const hasLinux = targets.some((d) => d?.platform === 'linux'); const hasLinux = targets.some((d) => d?.platform === 'linux');
const hasWindows = targets.some((d) => d?.platform === 'windows'); const hasWindows = targets.some((d) => d?.platform === 'windows');
const hasOPNsense = targets.some((d) => d?.platform === 'opnsense');
const scripts = useResource( const scripts = useResource(
(signal) => (canPlan && step === 2 && !ticket && mode === 'library' ? loadRevisions(tenantId, signal) : Promise.resolve([])), (signal) => (canPlan && step === 2 && !ticket && mode === 'library' ? loadRevisions(tenantId, signal) : Promise.resolve([])),
[tenantId, canPlan, step, !!ticket, mode] [tenantId, canPlan, step, !!ticket, mode]
@@ -225,21 +227,23 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
const heads = latestRevisions(scripts.data ?? []); const heads = latestRevisions(scripts.data ?? []);
const identity = mode === 'library' const identity = mode === 'library'
? libraryIdentity ?? revision?.execution_identity ? libraryIdentity ?? revision?.execution_identity
: (hasWindows ? windows : linux).execution_identity; : (hasOPNsense ? opnsense : hasWindows ? windows : linux).execution_identity;
const restartPlatform = hasLinux === hasWindows ? null : hasWindows ? 'windows' : 'linux'; const restartPlatform = hasOPNsense || hasLinux === hasWindows ? null : hasWindows ? 'windows' : 'linux';
const restartScript = restartPlatform && heads.find(revision => const restartScript = restartPlatform && heads.find(revision =>
revision.name === (hasWindows ? 'Windows neu starten' : 'Linux neu starten') && revision.name === (hasWindows ? 'Windows neu starten' : 'Linux neu starten') &&
scriptPlatform(revision.interpreter) === restartPlatform && scriptPlatform(revision.interpreter) === restartPlatform &&
revision.execution_identity === (hasWindows ? 'system' : 'root') revision.execution_identity === (hasWindows ? 'system' : 'root')
); );
const issues: string[] = []; const issues: string[] = [];
if (hasOPNsense && (hasLinux || hasWindows)) issues.push('OPNsense-Geräte bitte in einem eigenen Auftrag planen.');
if (targets.some((d) => !d?.current)) if (targets.some((d) => !d?.current))
issues.push('Ein Zielgerät fehlt im aktuellen Bestand. Entfernen Sie es aus der Auswahl.'); issues.push('Ein Zielgerät fehlt im aktuellen Bestand. Entfernen Sie es aus der Auswahl.');
const unidentified = targets.filter((d) => d && !d.platform); const unidentified = targets.filter((d) => d && !d.platform);
if (unidentified.length) if (unidentified.length)
issues.push('Das Betriebssystem ist noch nicht bestätigt: ' + unidentified.map((d) => d?.name).join(', ')); issues.push('Das Betriebssystem ist noch nicht bestätigt: ' + unidentified.map((d) => d?.name).join(', '));
if (mode === 'library' && revision) { if (mode === 'library' && revision) {
const incompatible = targets.filter((d) => d?.platform && d.platform !== scriptPlatform(revision.interpreter)); const incompatible = targets.filter((d) => d?.platform && (d.platform==='opnsense'
? revision.interpreter!=='posix_sh' : d.platform !== scriptPlatform(revision.interpreter)));
if (incompatible.length) if (incompatible.length)
issues.push( issues.push(
`Dieses Skript unterstützt ${interpreterNames[revision.interpreter]}. Inkompatible Geräte: ${incompatible.map((d) => d?.name).join(', ')}.` `Dieses Skript unterstützt ${interpreterNames[revision.interpreter]}. Inkompatible Geräte: ${incompatible.map((d) => d?.name).join(', ')}.`
@@ -304,10 +308,10 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
} }
}); });
} else { } else {
const variants = [hasLinux ? linux : null, hasWindows ? windows : null] const variants = [hasLinux ? linux : null, hasWindows ? windows : null, hasOPNsense ? opnsense : null]
.filter((s): s is Script => !!s) .filter((s): s is Script => !!s)
.map((s) => ({ .map((s) => ({
os_family: scriptPlatform(s.interpreter), os_family: s===opnsense ? 'opnsense' : scriptPlatform(s.interpreter),
interpreter: s.interpreter, interpreter: s.interpreter,
encoding: 'utf-8', encoding: 'utf-8',
script_utf8: s.script_utf8, script_utf8: s.script_utf8,
@@ -341,7 +345,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
const checked = await verifiedScriptOrder(raw, tenantId, auth.principal.id); const checked = await verifiedScriptOrder(raw, tenantId, auth.principal.id);
const mismatchedJob = checked.jobs.some((j) => { const mismatchedJob = checked.jobs.some((j) => {
const script = const script =
mode === 'library' ? revision : directory.get(j.assetId)?.platform === 'windows' ? windows : linux; mode === 'library' ? revision : hasOPNsense ? opnsense : directory.get(j.assetId)?.platform === 'windows' ? windows : linux;
return ( return (
!selected.includes(j.assetId) || !selected.includes(j.assetId) ||
j.revision?.id !== (mode === 'library' ? revisionId : undefined) || j.revision?.id !== (mode === 'library' ? revisionId : undefined) ||
@@ -643,8 +647,8 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
Neustartskript auswählen Neustartskript auswählen
</button> </button>
)} )}
<label> <label>
Bibliotheksskript Bibliotheksskript
<select <select
required required
value={revision?.name ?? ''} value={revision?.name ?? ''}
@@ -659,7 +663,8 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
</option> </option>
))} ))}
</select> </select>
</label> </label>
{hasOPNsense && <p className="muted">OPNsense verwendet die POSIX-Shell von FreeBSD. Wählen Sie eine passende Revision; Linux-spezifische Programme wie systemctl stehen hier nicht zur Verfügung.</p>}
{scripts.data && !heads.length && <p>Für diesen Kunden sind noch keine Skripte veröffentlicht.</p>} {scripts.data && !heads.length && <p>Für diesen Kunden sind noch keine Skripte veröffentlicht.</p>}
{revision && ( {revision && (
<> <>
@@ -703,6 +708,10 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
<> <>
{hasLinux && <ScriptFieldsForPlatform script={linux} change={setLinux} auth={auth} windows={false} />} {hasLinux && <ScriptFieldsForPlatform script={linux} change={setLinux} auth={auth} windows={false} />}
{hasWindows && <ScriptFieldsForPlatform script={windows} change={setWindows} auth={auth} windows />} {hasWindows && <ScriptFieldsForPlatform script={windows} change={setWindows} auth={auth} windows />}
{hasOPNsense && <fieldset><legend>OPNsense-Skript</legend>
<ScriptFields script={opnsense} change={setOpnsense}
ids={allowed(auth,'root:execute') ? ['agent_service','root'] : ['agent_service']} interpreters={['posix_sh']} />
</fieldset>}
</> </>
)} )}
{identity && identity !== 'agent_service' && ( {identity && identity !== 'agent_service' && (
+2 -1
View File
@@ -14,7 +14,7 @@ export interface Revision extends Script {
script_sha256: string; script_sha256: string;
} }
export const interpreterNames: Record<Interpreter, string> = { export const interpreterNames: Record<Interpreter, string> = {
posix_sh: 'Linux · Shell', posix_sh: 'POSIX-Shell',
bash: 'Linux · Bash', bash: 'Linux · Bash',
powershell: 'Windows · PowerShell' powershell: 'Windows · PowerShell'
}; };
@@ -71,6 +71,7 @@ export function latestRevisions(revisions: Revision[]) {
} }
export function devicePlatform(row: RecordValue) { export function devicePlatform(row: RecordValue) {
if (row.source_id === 'opnsense.base') return 'opnsense';
if (row.source_id === 'windows.base') return 'windows'; if (row.source_id === 'windows.base') return 'windows';
if (row.source_id === 'linux.base') return 'linux'; if (row.source_id === 'linux.base') return 'linux';
return null; return null;
+3 -2
View File
@@ -117,7 +117,7 @@ export function ScriptLibrary({ tenantId, auth }: { tenantId: string; auth: Sess
const latest = versions[0]; const latest = versions[0];
const query = search.trim().normalize('NFC').toLocaleLowerCase('de'); const query = search.trim().normalize('NFC').toLocaleLowerCase('de');
const shown = latestRevisions(library.data ?? []).filter((item) => const shown = latestRevisions(library.data ?? []).filter((item) =>
(!platform || scriptPlatform(item.interpreter) === platform) && (!platform || (platform==='opnsense' ? item.interpreter==='posix_sh' : scriptPlatform(item.interpreter) === platform)) &&
item.name.normalize('NFC').toLocaleLowerCase('de').includes(query)); item.name.normalize('NFC').toLocaleLowerCase('de').includes(query));
function edit(existing?: Revision) { function edit(existing?: Revision) {
setBase(existing?.version ?? 0); setBase(existing?.version ?? 0);
@@ -258,7 +258,8 @@ export function ScriptLibrary({ tenantId, auth }: { tenantId: string; auth: Sess
<label><span>Plattform</span> <label><span>Plattform</span>
<select aria-label="Plattform" value={platform} onChange={e => setPlatform(e.target.value)}> <select aria-label="Plattform" value={platform} onChange={e => setPlatform(e.target.value)}>
<option value="">Alle Plattformen</option> <option value="">Alle Plattformen</option>
<option value="linux">Linux</option> <option value="linux">Linux</option>
<option value="opnsense">OPNsense (POSIX-Shell)</option>
<option value="windows">Windows</option> <option value="windows">Windows</option>
</select> </select>
</label> </label>
+4 -5
View File
@@ -105,11 +105,10 @@ section.fleet { padding:0; overflow:hidden; }
.fleet-table input[type=checkbox] { margin:0; } .fleet-table input[type=checkbox] { margin:0; }
.host-link { padding:0; background:none; color:var(--accent); text-align:left; font-weight:680; margin:0; overflow-wrap:anywhere; } .host-link { padding:0; background:none; color:var(--accent); text-align:left; font-weight:680; margin:0; overflow-wrap:anywhere; }
.fleet-table .capacity-cell { font-variant-numeric:tabular-nums; } .fleet-table .capacity-cell { font-variant-numeric:tabular-nums; }
.capacity-track { display:block; width:min(90px,100%); border-radius:2px; background:#e1ebe6; height:4px; margin-top:6px; overflow:hidden; } .drive-capacity + .drive-capacity { margin-top:8px; }
.capacity-track i { display:block; height:100%; background:#659d84; } .capacity-track { display:flex; width:min(90px,100%); border-radius:2px; background:#e1ebe6; height:6px; margin-top:6px; overflow:hidden; }
.capacity-breakdown { display:flex; height:6px; } .capacity-used { flex:none; background:#c78980; }
.capacity-free { flex:none; background:#2e7657; } .capacity-free { flex:1; background:#2e7657; }
.capacity-used { flex:1; background:#b5c2be; }
.capacity-caption { display:block; color:var(--subtle); } .capacity-caption { display:block; color:var(--subtle); }
.presence { display:inline-flex; align-items:center; gap:5px; border-radius:20px; padding:2px 8px; background:#edf1ef; color:#4d5f59; font-size:.8rem; font-weight:650; } .presence { display:inline-flex; align-items:center; gap:5px; border-radius:20px; padding:2px 8px; background:#edf1ef; color:#4d5f59; font-size:.8rem; font-weight:650; }
.presence i { width:6px; height:6px; border-radius:50%; background:currentColor; } .presence i { width:6px; height:6px; border-radius:50%; background:currentColor; }