Plan OPNsense POSIX root scripts with explicit device policy, profile and approval

This commit is contained in:
2026-11-20 08:12:52 +01:00
parent 47249644b9
commit 8a1ea58d86
8 changed files with 50 additions and 13 deletions
+22 -3
View File
@@ -488,6 +488,11 @@ impl Action {
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()
}
/// Shared plan/revalidation/start gate. Passive inventory never implies job support.
pub fn available_for(&self, identity: &str, capabilities: &[String]) -> bool {
@@ -500,9 +505,10 @@ impl Action {
}
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();
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())
|| (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())
|| (self.full_maintenance()
@@ -858,6 +864,19 @@ mod tests {
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() {
assert_eq!(
windows_update_reboot_report(
+1 -1
View File
@@ -441,7 +441,7 @@ pub(crate) async fn plan_resolved(
let row = &rows[0];
let caps = capabilities(row.get("capabilities"))?;
let action = target_action(&input, &caps)?;
if caps.iter().any(|s| s=="opnsense.base/1") &&
if input.execution_identity=="agent_service" && caps.iter().any(|s| s=="opnsense.base/1") &&
(input.max_runtime_seconds != 10 || input.max_output_bytes != 1024) {
return Err(fail("UNSUPPORTED_CAPABILITY"));
}
+5 -1
View File
@@ -16,6 +16,8 @@ use uuid::Uuid;
struct Policy {
schema_version: u8,
linux: Vec<RootScope>,
#[serde(default)]
opnsense: Vec<RootScope>,
windows: Vec<SystemScope>,
#[serde(default)]
release_anchors: Vec<ReleaseAnchor>,
@@ -123,6 +125,8 @@ impl Policy {
return false;
}
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
.linux
.iter()
@@ -206,7 +210,7 @@ pub(crate) async fn permits(
.map_err(|_| invalid())?;
let policy: Policy = serde_json::from_slice(&bytes).map_err(|_| invalid())?;
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
+3
View File
@@ -380,6 +380,9 @@ pub async fn authorize(
if crate::managed_scripts::permits(tx, principal, job, &caps).await? {
return Ok(());
}
if caps.iter().any(|c| c=="opnsense.base/1") {
return Err(Error(StatusCode::FORBIDDEN,"SCRIPT_HELPER_SCOPE_DENIED"));
}
let policy = load()?;
let global_log_units = if matches!(job.action, Action::QueryLogs { .. }) {
parse_log_units(std::env::var("RMM_ROOT_LOG_UNITS").ok().as_deref())?
+1
View File
@@ -193,6 +193,7 @@ export function validateInput(input: PlanInput): void {
validateScriptIdentityProfile(input.parameters, input.parameters.execution_identity, variant.interpreter);
const bytes = new TextEncoder().encode(script).length;
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';
return bytes > 0 && bytes <= 32768 && !script.includes('\0') && variant.encoding === 'utf-8' && platform
&& (variant.os_family !== 'windows' || /^[\x00-\x7f]*$/.test(script) || script.startsWith('\ufeff'));
+1 -1
View File
@@ -206,7 +206,7 @@ function reportedScriptProfiles(device: RecordValue) {
if (!caps.has('run_script')) return 'Nicht gemeldet';
const windows = os === 'windows';
const identity = windows ? 'system' : 'root';
const service = windows ? 'PowerShell als Dienstkonto' : 'Shell als Dienstkonto';
const service = os==='opnsense' ? '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 (windows && !['rmm.sync.v1', 'script.powershell/1', 'script.powershell.process_remote_signed/1'].every(cap => caps.has(cap)))
return 'Nicht gemeldet';
+16 -7
View File
@@ -43,7 +43,7 @@ type Target = {
id: string;
name: string;
os: string;
platform: 'linux' | 'windows' | null;
platform: 'linux' | 'windows' | 'opnsense' | null;
state: string;
current: boolean;
};
@@ -143,6 +143,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
const [libraryIdentity, setLibraryIdentity] = useState<Identity | null>(null);
const [linux, setLinux] = useState<Script>(() => emptyScript('posix_sh'));
const [windows, setWindows] = useState<Script>(() => emptyScript('powershell'));
const [opnsense,setOpnsense] = useState<Script>(() => ({...emptyScript('posix_sh'),execution_identity:'root'}));
const [reason, setReason] = useState('');
const [start, setStart] = useState(() => localDate(Date.now()));
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 hasLinux = targets.some((d) => d?.platform === 'linux');
const hasWindows = targets.some((d) => d?.platform === 'windows');
const hasOPNsense = targets.some((d) => d?.platform === 'opnsense');
const scripts = useResource(
(signal) => (canPlan && step === 2 && !ticket && mode === 'library' ? loadRevisions(tenantId, signal) : Promise.resolve([])),
[tenantId, canPlan, step, !!ticket, mode]
@@ -225,21 +227,25 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
const heads = latestRevisions(scripts.data ?? []);
const identity = mode === 'library'
? libraryIdentity ?? revision?.execution_identity
: (hasWindows ? windows : linux).execution_identity;
const restartPlatform = hasLinux === hasWindows ? null : hasWindows ? 'windows' : 'linux';
: (hasOPNsense ? opnsense : hasWindows ? windows : linux).execution_identity;
const restartPlatform = hasOPNsense || hasLinux === hasWindows ? null : hasWindows ? 'windows' : 'linux';
const restartScript = restartPlatform && heads.find(revision =>
revision.name === (hasWindows ? 'Windows neu starten' : 'Linux neu starten') &&
scriptPlatform(revision.interpreter) === restartPlatform &&
revision.execution_identity === (hasWindows ? 'system' : 'root')
);
const issues: string[] = [];
if (hasOPNsense && (hasLinux || hasWindows)) issues.push('OPNsense-Geräte bitte in einem eigenen Auftrag planen.');
if (hasOPNsense && (!allowed(auth,'root:execute') || identity!=='root'))
issues.push('OPNsense-Skripte benötigen die Ausführungsidentität root und das Recht root:execute.');
if (targets.some((d) => !d?.current))
issues.push('Ein Zielgerät fehlt im aktuellen Bestand. Entfernen Sie es aus der Auswahl.');
const unidentified = targets.filter((d) => d && !d.platform);
if (unidentified.length)
issues.push('Das Betriebssystem ist noch nicht bestätigt: ' + unidentified.map((d) => d?.name).join(', '));
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)
issues.push(
`Dieses Skript unterstützt ${interpreterNames[revision.interpreter]}. Inkompatible Geräte: ${incompatible.map((d) => d?.name).join(', ')}.`
@@ -304,10 +310,10 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
}
});
} 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)
.map((s) => ({
os_family: scriptPlatform(s.interpreter),
os_family: s===opnsense ? 'opnsense' : scriptPlatform(s.interpreter),
interpreter: s.interpreter,
encoding: 'utf-8',
script_utf8: s.script_utf8,
@@ -341,7 +347,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
const checked = await verifiedScriptOrder(raw, tenantId, auth.principal.id);
const mismatchedJob = checked.jobs.some((j) => {
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 (
!selected.includes(j.assetId) ||
j.revision?.id !== (mode === 'library' ? revisionId : undefined) ||
@@ -703,6 +709,9 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
<>
{hasLinux && <ScriptFieldsForPlatform script={linux} change={setLinux} auth={auth} windows={false} />}
{hasWindows && <ScriptFieldsForPlatform script={windows} change={setWindows} auth={auth} windows />}
{hasOPNsense && <fieldset><legend>OPNsense-Skript</legend>
<ScriptFields script={opnsense} change={setOpnsense} ids={['root']} interpreters={['posix_sh']} />
</fieldset>}
</>
)}
{identity && identity !== 'agent_service' && (
+1
View File
@@ -71,6 +71,7 @@ export function latestRevisions(revisions: Revision[]) {
}
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 === 'linux.base') return 'linux';
return null;