//! Permanent authorization ceilings for installed, pinned script helpers. //! Plan submission, interactive approval and signed start grants are unchanged. use crate::{jobs::Error, root_policy::RootScope, windows_policy::SystemScope}; use axum::http::StatusCode; use rmm_domain::{ agent_update::{ArtifactRole, Platform, ReleaseManifest, digest}, jobs::{Action, FULL_MAINTENANCE_CAPABILITY, JobPayload}, }; use serde::Deserialize; use sqlx::{Postgres, Transaction}; use std::{fs, os::unix::fs::MetadataExt, path::Path}; use uuid::Uuid; #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Policy { schema_version: u8, linux: Vec, windows: Vec, #[serde(default)] release_anchors: Vec, } /// Operator-pinned canonical bytes of an already authorized local policy. /// A signed pair changes only the two image digests and the Windows release directory. #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct ReleaseAnchor { agent_id: Uuid, release_id: Uuid, agent_sha256: String, helper_sha256: String, policy_json: String, } impl ReleaseAnchor { fn policy_for(&self, manifest: &ReleaseManifest) -> Option { if self.policy_json.len() > 8192 || self.release_id.is_nil() || !digest(&self.agent_sha256) || !digest(&self.helper_sha256) || self.agent_sha256 == self.helper_sha256 { return None; } let next = |role| { manifest .artifacts .iter() .find(|a| a.role == role) .map(|a| a.sha256.as_str()) }; let mut raw = self.policy_json.clone(); let mut replace = |from: String, to: String, count| { if raw.matches(&from).count() != count { return None; } raw = raw.replace(&from, &to); Some(()) }; let field = |name: &str, value: &str| format!(r#""{name}":"{value}""#); match manifest.platform { Platform::LinuxX64 => replace( field("helper_binary_sha256", &self.helper_sha256), field("helper_binary_sha256", next(ArtifactRole::Helper)?), 1, )?, Platform::WindowsGnuX64 => { replace( field("binary_sha256", &self.agent_sha256), field("binary_sha256", next(ArtifactRole::Agent)?), 1, )?; replace( field("binary_sha256", &self.helper_sha256), field("binary_sha256", next(ArtifactRole::Helper)?), 1, )?; let directory = |release| format!(r"\\releases\\{release}\\"); replace( directory(self.release_id), directory(manifest.release_id), 2, )?; } _ => return None, } Some(rmm_domain::jobs::hash(raw.as_bytes())) } } fn invalid() -> Error { Error(StatusCode::CONFLICT, "MANAGED_SCRIPT_POLICY_INVALID") } impl Policy { fn permits(&self, principal: &str, job: &JobPayload, caps: &[String]) -> bool { if !matches!(job.action, Action::RunScript { .. }) || !job.action.full_maintenance() || !job.action.validate() || !job.action.available_for(&job.execution_identity, caps) || !job .action .valid_job_limits(job.max_runtime_seconds, job.max_output_bytes) { return false; } match job.execution_identity.as_str() { "root" => self .linux .iter() .any(|scope| scope.permits(principal, job, caps, None)), "system" => self .windows .iter() .any(|scope| scope.permits(principal, job, caps, false, true, false)), _ => false, } } } fn binding_error() -> Error { Error(StatusCode::CONFLICT, "SCRIPT_HELPER_BINDING_INVALID") } // Multiple helper roles may coexist on older clients. For the release-managed // script profile we require exactly one unambiguous release, policy and binary. fn single_value<'a>(caps: &'a [String], prefix: &str) -> Result<&'a str, Error> { let mut values = caps.iter().filter_map(|c| c.strip_prefix(prefix)); let value = values.next().ok_or_else(binding_error)?; if value.is_empty() || values.next().is_some() { return Err(binding_error()); } Ok(value) } fn check_pair( manifest: &ReleaseManifest, version: Option<&str>, identity: &str, caps: &[String], ) -> Result<(), Error> { let platform = match identity { "root" => Platform::LinuxX64, "system" => Platform::WindowsGnuX64, _ => return Err(binding_error()), }; let binary = single_value(caps, "helper.binary.sha256:")?; if version != Some(manifest.version.as_str()) || platform != manifest.platform || !digest(single_value(caps, "helper.policy.sha256:")?) || !manifest .artifacts .iter() .any(|a| a.role == ArtifactRole::Helper && a.sha256 == binary) { return Err(binding_error()); } Ok(()) } pub(crate) async fn permits( tx: &mut Transaction<'_, Postgres>, principal: &str, job: &JobPayload, caps: &[String], ) -> Result { if !job.action.full_maintenance() { return Ok(false); } let Some(path) = std::env::var_os("RMM_MANAGED_SCRIPT_POLICY_FILE") else { return Ok(false); }; let key = std::env::var_os("RMM_JOB_KEY_FILE").ok_or_else(invalid)?; let signer = fs::symlink_metadata(key).map_err(|_| invalid())?; if !signer.is_file() { return Err(invalid()); } let bytes = crate::windows_policy::protected_bytes(Path::new(&path), signer.uid()) .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.release_anchors.len() > 64 || policy .release_anchors .iter() .any(|a| a.policy_json.len() > 8192) || !policy.windows.iter().all(SystemScope::valid) { return Err(invalid()); } let direct = policy.permits(principal, job, caps); if !caps .iter() .any(|cap| cap.starts_with("script.helper.release:")) { return Ok(direct); } { let release = Uuid::parse_str(single_value(caps, "script.helper.release:")?) .map_err(|_| binding_error())?; if !caps.iter().any(|cap| cap == FULL_MAINTENANCE_CAPABILITY) { return Err(binding_error()); } let version: Option = sqlx::query_scalar( "SELECT reported_agent_version FROM agent_installations WHERE tenant_id=$1 AND agent_id=$2 AND asset_id=$3 AND revoked_at IS NULL", ) .bind(job.tenant_id) .bind(job.agent_id) .bind(job.asset_id) .fetch_optional(&mut **tx) .await? .flatten(); let manifest = crate::agent_updates::checked_installed_helper_release(tx, release) .await .map_err(|err| { if err.0.is_server_error() { err } else { binding_error() } })?; check_pair(&manifest, version.as_deref(), &job.execution_identity, caps)?; if direct { return Ok(true); } let current_policy = single_value(caps, "helper.policy.sha256:")?; for anchor in policy .release_anchors .iter() .filter(|a| a.agent_id == job.agent_id) { if anchor.policy_for(&manifest).as_deref() != Some(current_policy) { continue; } let original = rmm_domain::jobs::hash(anchor.policy_json.as_bytes()); let mut pinned = caps.to_owned(); pinned.retain(|c| { !c.starts_with("helper.binary.sha256:") && !c.starts_with("helper.policy.sha256:") }); pinned.push(format!("helper.binary.sha256:{}", anchor.helper_sha256)); pinned.push(format!("helper.policy.sha256:{original}")); if policy.permits(principal, job, &pinned) { return Ok(true); } } } Err(Error(StatusCode::FORBIDDEN, "SCRIPT_HELPER_SCOPE_DENIED")) } #[cfg(test)] mod tests { use super::*; use rmm_domain::agent_update::ArtifactDescriptor; #[test] fn signed_helper_is_bound_to_platform_reported_version_and_unambiguous_local_pins() { let binary = "ab".repeat(32); let policy = "cd".repeat(32); let artifact = |role, sha256| ArtifactDescriptor { role, sha256, artifact_id: Uuid::new_v4(), bytes: 4096, }; let m = ReleaseManifest { schema_version: 1, release_id: Uuid::new_v4(), release_sequence: 7, version: "0.1.12".into(), platform: Platform::WindowsGnuX64, published_at: 10, expires_at: 500, protocol_major: 1, state_schema: 1, minimum_updater_version: 2, artifacts: [ artifact(ArtifactRole::Agent, "ef".repeat(32)), artifact(ArtifactRole::Helper, binary.clone()), ], }; // Rollover may substitute signed image pins and their release directory only. let previous = Uuid::new_v4(); let original_agent = "12".repeat(32); let original_helper = "34".repeat(32); let windows = |release: Uuid, agent: &str, helper: &str, runtime: u32| { format!( r#"{{"agent":{{"binary":"C:\\releases\\{release}\\agent.exe","binary_sha256":"{agent}"}},"helper":{{"binary":"C:\\releases\\{release}\\helper.exe","binary_sha256":"{helper}"}},"max_runtime_seconds":{runtime}}}"# ) }; let mut anchor = ReleaseAnchor { agent_id: Uuid::new_v4(), release_id: previous, policy_json: windows(previous, &original_agent, &original_helper, 30), agent_sha256: original_agent, helper_sha256: original_helper, }; let next_agent = &m.artifacts[0].sha256; let expected = |limit| { rmm_domain::jobs::hash(windows(m.release_id, next_agent, &binary, limit).as_bytes()) }; assert_eq!(anchor.policy_for(&m), Some(expected(30))); assert_ne!(anchor.policy_for(&m), Some(expected(120))); anchor .policy_json .push_str(&format!(r#","binary_sha256":"{}""#, anchor.helper_sha256)); assert!(anchor.policy_for(&m).is_none()); let mut caps = vec![ format!("helper.binary.sha256:{binary}"), format!("helper.policy.sha256:{policy}"), ]; assert!(check_pair(&m, Some("0.1.12"), "system", &caps).is_ok()); assert!(check_pair(&m, Some("0.1.11"), "system", &caps).is_err()); assert!(check_pair(&m, Some("0.1.12"), "root", &caps).is_err()); caps.push(format!("helper.binary.sha256:{binary}")); assert!(check_pair(&m, Some("0.1.12"), "system", &caps).is_err()); caps.remove(0); caps[1] = format!("helper.binary.sha256:{policy}"); assert!(check_pair(&m, Some("0.1.12"), "system", &caps).is_err()); } }