use crate::reconcile; use anyhow::{Context, Result, ensure}; use rmm_privileged_helper::{Binding, control, readiness, reconcile as root}; use rmm_protocol::{SyncAttempt, SyncRequest, SyncResponse}; use std::path::{Path, PathBuf}; use uuid::Uuid; #[derive(Clone)] struct Endpoint { socket: PathBuf, profile: String, hash: String, binary_hash: Option, } #[derive(Clone)] pub struct Helpers { binding: Binding, endpoints: Vec, } fn map(s: &root::Snapshot) -> reconcile::HelperSnapshot { reconcile::HelperSnapshot { journal_id: s.journal_id, checkpoint: s.checkpoint, previous_decision_id: s.previous_decision_id, attempts: s .attempts .iter() .map(|a| SyncAttempt { update_handoff_bytes: a.update_handoff_bytes.clone(), job_id: a.job_id.to_string(), attempt_id: a.attempt_id.to_string(), job_payload_hash: a.job_payload_hash.clone(), grant_id: a.grant_id.to_string(), consumption: a.consumption.clone(), state: a.state.clone(), revision: a.revision, original_boot_id: a.original_boot_id.to_string(), outcome_sha256: a.outcome_sha256.clone(), outcome_bytes: a.outcome_bytes.clone(), ..Default::default() }) .collect(), } } fn general(binding: &Binding, full: bool) -> Result { let (socket_name, pin_name, profile) = if full { ( "RMM_FULL_MAINTENANCE_HELPER_SOCKET", "RMM_FULL_MAINTENANCE_POLICY_FILE", "full_maintenance_v1", ) } else { ("RMM_HELPER_SOCKET", "RMM_HELPER_POLICY_FILE", "general") }; let socket = std::env::var_os(socket_name).context("NO_GENERAL_HELPER")?; let path = std::env::var_os(pin_name).context("GENERAL_POLICY_PIN_REQUIRED")?; let pin = control::GeneralPin::read(Path::new(&path), binding)?; ensure!(pin.profile == profile, "HELPER_PROFILE_ROUTE_MISMATCH"); control::general_probe(Path::new(&socket), binding, &pin) } impl Helpers { pub fn configured(binding: &Binding) -> Result { let mut endpoints = vec![]; for (socket_name, pin_name, profile) in [ ("RMM_HELPER_SOCKET", "RMM_HELPER_POLICY_FILE", "general"), ( "RMM_FULL_MAINTENANCE_HELPER_SOCKET", "RMM_FULL_MAINTENANCE_POLICY_FILE", "full_maintenance_v1", ), ] { if let Some(socket) = std::env::var_os(socket_name) { let path = std::env::var_os(pin_name).context("GENERAL_POLICY_PIN_REQUIRED")?; let pin = control::GeneralPin::read(Path::new(&path), binding)?; ensure!(pin.profile == profile, "HELPER_PROFILE_ROUTE_MISMATCH"); endpoints.push(Endpoint { socket: socket.into(), profile: profile.into(), hash: pin.policy_sha256, binary_hash: pin.helper_binary_sha256, }); } } if let Some(socket) = std::env::var_os("RMM_APT_HELPER_SOCKET") { ensure!( Path::new(&socket) == Path::new(readiness::SOCKET), "APT_HELPER_ROUTE" ); let path = std::env::var_os("RMM_APT_HELPER_PROOF_FILE").context("APT_PROOF_REQUIRED")?; let pin = readiness::Pin::read(Path::new(&path), binding)?; endpoints.push(Endpoint { socket: socket.into(), profile: "apt_only".into(), hash: pin.provider_stack_sha256, binary_hash: None, }); } Ok(Self { binding: binding.clone(), endpoints, }) } fn validate(&self, e: &Endpoint, r: &control::Response) -> Result<()> { ensure!( r.profile == e.profile && r.policy_sha256 == e.hash && r.helper_binary_sha256 == e.binary_hash, "HELPER_PIN_PROFILE_MISMATCH" ); Ok(()) } pub fn snapshot(&self, generation: u64) -> Result> { if self.endpoints.is_empty() { return Ok(None); } for _ in 0..3 { let mut snapshots = vec![]; let mut inodes = None; // Full is the only provisioned update owner authority. General // cannot inspect its broader process capability context; it must // stay closed without classifying the original effect Unknown. let mut ordered: Vec<_> = self.endpoints.iter().collect(); ordered.sort_by_key(|e| e.profile != "full_maintenance_v1"); for e in ordered { let q = control::Request::Snapshot { challenge: Uuid::new_v4(), identity: readiness::Identity::from_binding(&self.binding)?, generation, }; let r = control::call(&e.socket, &self.binding, &q)?; self.validate(e, &r)?; let ids = (r.ledger_device, r.ledger_inode, r.lock_device, r.lock_inode); if let Some(old) = inodes { ensure!(old == ids, "HELPERS_MUST_SHARE_LEDGER_AND_LOCK"); } inodes = Some(ids); let snapshot = r.snapshot.context("HELPER_SNAPSHOT_REQUIRED")?; if snapshot .attempts .iter() .any(|a| !a.update_handoff_bytes.is_empty()) { ensure!( e.profile == "full_maintenance_v1", "UPDATE_FULL_OWNER_REQUIRED" ); return Ok(Some(map(&snapshot))); } snapshots.push(snapshot); } let first = &snapshots[0]; if snapshots.iter().all(|s| { s.journal_id == first.journal_id && s.checkpoint == first.checkpoint && s.previous_decision_id == first.previous_decision_id && serde_json::to_vec(&s.attempts).ok() == serde_json::to_vec(&first.attempts).ok() }) { return Ok(Some(map(first))); } } anyhow::bail!("HELPER_CHECKPOINTS_DID_NOT_CONVERGE") } pub fn apply( &self, response: &SyncResponse, request: &SyncRequest, ) -> Result> { use prost::Message; let mut applied: Option = None; let update_control = request .attempts .iter() .any(|a| !a.update_handoff_bytes.is_empty()); let endpoints: Vec<_> = self .endpoints .iter() .filter(|e| !update_control || e.profile == "full_maintenance_v1") .collect(); ensure!( !update_control || endpoints.len() == 1, "UPDATE_FULL_OWNER_REQUIRED" ); for e in endpoints { let q = control::Request::Apply { challenge: Uuid::new_v4(), identity: readiness::Identity::from_binding(&self.binding)?, response: root::SignedResponse { decision_bytes: response.decision_bytes.clone(), signature: response.signature.clone(), }, request_bytes: request.encode_to_vec(), }; let r = control::call(&e.socket, &self.binding, &q)?; self.validate(e, &r)?; let s = r.snapshot.context("APPLIED_HELPER_SNAPSHOT_REQUIRED")?; if let Some(old) = &applied { ensure!( old.journal_id == s.journal_id && old.checkpoint == s.checkpoint && old.previous_decision_id == s.previous_decision_id, "HELPER_APPLY_CHECKPOINT_MISMATCH" ); } applied = Some(s); } Ok(applied.as_ref().map(map)) } } pub fn general_capabilities(binding: &Binding) -> Vec { let mut caps = profile_capabilities(binding, false); caps.extend(profile_capabilities(binding, true)); caps.sort(); caps.dedup(); caps } fn profile_capabilities(binding: &Binding, full: bool) -> Vec { (|| -> Result> { let response = general(binding, full)?; let policy = response.policy.context("NO_GENERAL_POLICY")?; let mut caps = vec![ "helper.root.v1".into(), format!("helper.policy.sha256:{}", response.policy_sha256), ]; if full { ensure!( policy.schema_version == 2 && policy.profile == "full_maintenance_v1" && policy.allowed_script_profiles.as_deref() == Some(&[rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1]), "FULL_MAINTENANCE_POLICY_REQUIRED" ); let binary = policy .helper_binary_sha256 .as_ref() .context("FULL_MAINTENANCE_BINARY_PIN_REQUIRED")?; ensure!( response.helper_binary_sha256.as_ref() == Some(binary), "FULL_MAINTENANCE_BINARY_PROOF_REQUIRED" ); caps.push(format!("helper.binary.sha256:{binary}")); caps.push(rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY.into()); } let mut actions = vec![]; if policy.allow_root_scripts && rmm_agent_linux::actions::Interpreter::PosixSh.available() { actions.push("run_script"); } if !policy.allowed_services.is_empty() { actions.extend(["set_service_state", "query_logs"]); } if policy.allow_reboot { actions.push("reboot"); } for action in actions { caps.push(action.into()); caps.push(format!("root:{action}")); } Ok(caps) })() .unwrap_or_default() } pub fn general_supported(binding: &Binding, job: &rmm_domain::jobs::JobPayload) -> bool { (|| -> Result { let p = general(binding, job.action.full_maintenance())? .policy .context("NO_GENERAL_POLICY")?; Ok(match &job.action { rmm_domain::jobs::Action::RunScript { interpreter, .. } => { p.allow_root_scripts && job.action.valid_execution_identity(&job.execution_identity) && job .action .valid_job_limits(job.max_runtime_seconds, job.max_output_bytes) && (!job.action.full_maintenance() || p.allowed_script_profiles.as_ref().is_some_and(|v| { v.contains( &rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1, ) })) && match interpreter.as_str() { "posix_sh" => rmm_agent_linux::actions::Interpreter::PosixSh.available(), "bash" => rmm_agent_linux::actions::Interpreter::Bash.available(), _ => false, } } rmm_domain::jobs::Action::SetServiceState { unit, state } => { p.allowed_services.contains(unit) && matches!(state.as_str(), "running" | "stopped") && job.max_runtime_seconds >= 180 } rmm_domain::jobs::Action::QueryLogs { unit, .. } => { p.allowed_services.contains(unit) && job.max_runtime_seconds >= 20 } rmm_domain::jobs::Action::Reboot { .. } => { p.allow_reboot && job.max_runtime_seconds >= 60 } _ => false, }) })() .unwrap_or(false) } impl Helpers { /// Evidence-only delivery to the actual new Fullhelper. The independent /// helper reads its own applied control/retained inventory before writing. pub fn submit_update_health( &self, header: &rmm_updater_handoff::Handoff, key: [u8; 32], receipt: &rmm_updater_handoff::SignedHealth, ) -> Result<()> { use rmm_agent_core::update_handoff::{ NativeControlOperation, NativeControlReply, NativeControlRequest, }; let endpoint = self .endpoints .iter() .find(|e| e.profile == "full_maintenance_v1") .context("UPDATE_FULL_HELPER_REQUIRED")?; ensure!( endpoint.socket == Path::new("/run/rmm-helper-maintenance/control.sock"), "UPDATE_FIXED_FULL_SOCKET_REQUIRED" ); let challenge = Uuid::new_v4(); let request = NativeControlRequest { operation: "agent_update_control_v1".into(), schema_version: 1, challenge, tenant_id: self.binding.tenant_id, asset_id: self.binding.asset_id, agent_id: self.binding.agent_id, enrollment_generation: self.binding.enrollment_generation, assignment_version: self.binding.assignment_version, grant_id: header.attempt.grant_id, owner_nonce: header.owner_nonce, handoff_sha256: rmm_domain::jobs::hash(&header.bytes()?), method: NativeControlOperation::Health { receipt: receipt.clone(), }, }; let reply: NativeControlReply = control::exchange( &endpoint.socket, &request, std::time::Duration::from_secs(10), 1536 * 1024, )?; ensure!( reply.schema_version == 1 && reply.challenge == challenge && reply.tenant_id == request.tenant_id && reply.asset_id == request.asset_id && reply.agent_id == request.agent_id && reply.enrollment_generation == request.enrollment_generation && reply.assignment_version == request.assignment_version && reply.grant_id == request.grant_id && reply.owner_nonce == request.owner_nonce && reply.handoff_sha256 == request.handoff_sha256 && !reply.ready && reply.claim.is_none() && reply.original_start_base64url.is_none() && reply.original_outcome_base64url.is_none(), "UPDATE_HEALTH_REPLY_BINDING" ); let proof = reply.proof.context("UPDATE_HEALTH_REPLY_PROOF_REQUIRED")?; let (bound, journal) = rmm_domain::agent_update::verify_inflight_proof(&proof, key) .map_err(anyhow::Error::msg)?; ensure!( bound.bytes()? == header.bytes()? && journal.phase() == rmm_updater_handoff::Phase::HealthVerified, "UPDATE_HEALTH_REPLY_ORIGINAL_PHASE" ); let decoded = proof.decode().map_err(anyhow::Error::msg)?; let event: rmm_updater_handoff::Event = serde_json::from_slice(decoded.events.last().context("UPDATE_HEALTH_REPLY_EVENT")?)?; ensure!( matches!(event.evidence,rmm_updater_handoff::Evidence::HealthVerified{receipt:ref saved} if saved==receipt), "UPDATE_HEALTH_REPLY_RECEIPT_CHANGED" ); Ok(()) } }