Plan an exact service-account OPNsense kernel probe through normal approval

This commit is contained in:
2026-11-19 20:48:41 +01:00
parent 71adc2adf6
commit 2e060e9507
5 changed files with 92 additions and 5 deletions
+31 -1
View File
@@ -480,7 +480,16 @@ 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")
}
/// 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 +499,11 @@ 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 identity == "agent_service" && has("run_script") && has("rmm.sync.v1")
&& has("opnsense.uname/1") && !has("windows.base/1") && !has("linux.base/1")
&& self.opnsense_kernel_probe();
}
if !has(self.name()) if !has(self.name())
|| (self.full_maintenance() || (self.full_maintenance()
&& !((has(FULL_MAINTENANCE_CAPABILITY) && !((has(FULL_MAINTENANCE_CAPABILITY)
@@ -828,6 +842,22 @@ 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 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(
+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 caps.iter().any(|s| s=="opnsense.base/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"));
} }
+2
View File
@@ -18,6 +18,7 @@ import { CatalogCheckNotice } from './catalog-check';
import { devicePlatform } from './script-catalog'; import { devicePlatform } from './script-catalog';
import { DeviceInventoryPanels, systemDetails } from './device-inventory'; import { DeviceInventoryPanels, systemDetails } from './device-inventory';
import { OPNsenseDetails } from './opnsense'; import { OPNsenseDetails } from './opnsense';
import { OPNsenseProbe } from './opnsense-probe';
import { DeviceCustomerTransfer } from './device-customer-transfer'; import { DeviceCustomerTransfer } from './device-customer-transfer';
import { HypervisorAssignment, HypervisorLabel } from './device-hypervisor'; import { HypervisorAssignment, HypervisorLabel } from './device-hypervisor';
import { ErrorBox, errorText, useResource } from './resource'; import { ErrorBox, errorText, useResource } from './resource';
@@ -302,6 +303,7 @@ function DeviceDetail({
onSaved={() => { setPurposeSaved(true); detail.reload(); }} onSaved={() => { setPurposeSaved(true); detail.reload(); }}
/> />
<OPNsenseDetails device={d} /> <OPNsenseDetails device={d} />
{scoped && <OPNsenseProbe key={`${customer}/${asset}/${agent}`} device={d} auth={scoped}/>}
<DeviceInventoryPanels device={d} /> <DeviceInventoryPanels device={d} />
{volumes.length > 0 && ( {volumes.length > 0 && (
<section> <section>
+48
View File
@@ -0,0 +1,48 @@
import { useState } from 'react';
import { objectId, record, request, tenantPath, type RecordValue, type Session } from './api';
import { allowed } from './safety';
import { verifiedScriptOrder } from './order-composer';
import { ErrorBox, errorText } from './resource';
export function OPNsenseProbe({ device, auth }: {device: RecordValue; auth: Session}) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [ticket, setTicket] = useState<{id:string; hash:string} | null>(null);
const [operation, setOperation] = useState<string | null>(null);
if (device.source_id !== 'opnsense.base' || device.lifecycle !== 'current' ||
!Array.isArray(device.capabilities) || !device.capabilities.includes('opnsense.uname/1') ||
!allowed(auth,'operations:plan') || !allowed(auth,'scripts:execute')) return null;
const customer = objectId(device,'tenant'), asset = objectId(device,'asset'), agent = objectId(device,'agent');
const path = tenantPath(customer,'/operation-plans');
async function submit() {
setBusy(true); setError(null);
try {
let pending = ticket;
if (!pending) {
const now = Date.now(), start = new Date(now).toISOString(), end = new Date(now+86400000).toISOString();
const reason = 'OPNsense: Kernelname auf dem Dienstkonto prüfen';
const raw = await request(path, {csrf:auth.csrf_token,body:{tenant_id:customer,action:'run_script',
targets:{asset_ids:[asset]},parameters:{execution_identity:'agent_service',timeout_seconds:10,
max_output_bytes:1024,arguments:[],expected_stdout:'FreeBSD\n',
variants:[{os_family:'opnsense',interpreter:'posix_sh',encoding:'utf-8',script_utf8:'uname -s\n'}]},
schedule:{not_before:start,start_before:end,offline_policy:'wait_until_deadline'},
rollout:{max_parallel:1,halt_after_failures:1},reason}});
const checked = await verifiedScriptOrder(raw,customer,auth.principal.id), j = checked.jobs[0];
if (!j || checked.jobs.length!==1 || j.assetId!==asset || j.agentId!==agent || j.identity!=='agent_service' ||
j.script!=='uname -s\n' || j.expectedStdout!=='FreeBSD\n' || j.interpreter!=='posix_sh' ||
j.arguments.length || j.runtimeSeconds!==10 || j.outputBytes!==1024 || checked.reason!==reason ||
Date.parse(j.notBefore)!==now || Date.parse(j.startBefore)!==Date.parse(end) ||
checked.maxParallel!==1 || checked.halt!==1) throw Error('Plan weicht von der Kernelabfrage ab.');
pending = {id:objectId(checked.plan,'plan'),hash:String(checked.plan.plan_hash)};
setTicket(pending);
}
const r = record(await request(path+'/'+pending.id+'/submit',{csrf:auth.csrf_token,body:{idempotency_key:pending.id}}));
if (r.plan_id!==pending.id || r.plan_hash!==pending.hash) throw Error('Planbindung stimmt nicht.');
setOperation(objectId(r,'operation'));
} catch (e) { setError(errorText(e)); } finally { setBusy(false); }
}
return <section><h2>OPNsense-Kernelabfrage</h2><p><code>uname -s</code> als Dienstkonto · ein Versuch · 10 Sekunden · 1 KiB Ausgabe.</p>
{operation && ticket ? <p>Auftrag eingereicht. <a href={`#genehmigungen/pruefen/${customer}/${ticket.id}`}>Zur Genehmigung</a></p>
: <button disabled={busy} onClick={submit}>Kernelabfrage zur Genehmigung einreichen</button>}
<ErrorBox error={error}/></section>;
}
+1 -1
View File
@@ -81,7 +81,7 @@ function resumeTicket(key: string): Ticket | null {
} }
return data; return data;
} }
async function verifiedScriptOrder(value: unknown, tenantId: string, principal: string) { export async function verifiedScriptOrder(value: unknown, tenantId: string, principal: string) {
const plan = record(value, 'Auftragsplan'); const plan = record(value, 'Auftragsplan');
await verifyPlanIntegrity(plan); await verifyPlanIntegrity(plan);
await verifyScriptPlan(plan); await verifyScriptPlan(plan);