Files
rust-discovery/crates/agent/src/helper_sync.rs
T

353 lines
14 KiB
Rust

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<String>,
}
#[derive(Clone)]
pub struct Helpers {
binding: Binding,
endpoints: Vec<Endpoint>,
}
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 script_helper(binding: &Binding) -> Result<control::Response> {
let (socket_name, pin_name, profile) = (
"RMM_FULL_MAINTENANCE_HELPER_SOCKET",
"RMM_FULL_MAINTENANCE_POLICY_FILE",
"full_maintenance_v1",
);
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<Self> {
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<Option<reconcile::HelperSnapshot>> {
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<Option<reconcile::HelperSnapshot>> {
use prost::Message;
let mut applied: Option<root::Snapshot> = 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 script_capabilities(binding: &Binding) -> Vec<String> {
(|| -> Result<Vec<String>> {
let response = script_helper(binding)?;
let binary = response
.helper_binary_sha256
.context("SCRIPT_HELPER_BINARY_PROOF_REQUIRED")?;
ensure!(
rmm_agent_linux::actions::Interpreter::PosixSh.available(),
"SCRIPT_INTERPRETER_UNAVAILABLE"
);
let mut caps = vec![
"run_script".into(),
"root:run_script".into(),
"helper.root.v1".into(),
rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY.into(),
format!("helper.policy.sha256:{}", response.policy_sha256),
format!("helper.binary.sha256:{binary}"),
];
if let Some(release) = std::env::var("RMM_SCRIPT_HELPER_RELEASE")
.ok()
.and_then(|value| Uuid::parse_str(&value).ok())
.filter(|id| !id.is_nil())
{
caps.push(format!("script.helper.release:{release}"));
}
Ok(caps)
})()
.unwrap_or_default()
}
pub fn script_supported(binding: &Binding, job: &rmm_domain::jobs::JobPayload) -> bool {
let rmm_domain::jobs::Action::RunScript { interpreter, .. } = &job.action else {
return false;
};
job.execution_identity == "root"
&& job.action.full_maintenance()
&& job.action.valid_execution_identity(&job.execution_identity)
&& job
.action
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
&& match interpreter.as_str() {
"posix_sh" => rmm_agent_linux::actions::Interpreter::PosixSh.available(),
"bash" => rmm_agent_linux::actions::Interpreter::Bash.available(),
_ => false,
}
&& script_helper(binding).is_ok()
}
pub fn invoke_script(
binding: &Binding,
job: &rmm_domain::jobs::JobPayload,
request: &rmm_privileged_helper::Request,
observe: impl FnMut() -> Result<()>,
) -> Result<rmm_privileged_helper::Outcome> {
ensure!(
script_supported(binding, job),
"SCRIPT_HELPER_POLICY_REQUIRED"
);
let socket = std::env::var_os("RMM_FULL_MAINTENANCE_HELPER_SOCKET")
.context("SCRIPT_HELPER_SOCKET_REQUIRED")?;
rmm_privileged_helper::invoke_controlled(
Path::new(&socket),
request,
job.max_runtime_seconds,
observe,
)
}
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(())
}
}