393 lines
14 KiB
Rust
393 lines
14 KiB
Rust
//! Approved artifact prefetch before a grant; Full independently admits the handoff.
|
|
use anyhow::{Context, Result, ensure};
|
|
use rmm_domain::{
|
|
agent_update::{
|
|
APPLY_CAPABILITY, ArtifactDescriptor, ArtifactRole, CHECK_CAPABILITY, Platform,
|
|
},
|
|
jobs::{Action, JobPayload},
|
|
};
|
|
use rmm_privileged_helper::{Binding, Request, control, update_admission::Accepted};
|
|
use sha2::{Digest, Sha256};
|
|
use std::{
|
|
fs::{self, File, OpenOptions},
|
|
io::{Read, Write},
|
|
os::unix::fs::{MetadataExt, OpenOptionsExt},
|
|
path::{Path, PathBuf},
|
|
time::{Duration, Instant},
|
|
};
|
|
const MAXIMUM: u64 = 256 * 1024 * 1024;
|
|
const CHUNK: u64 = 512 * 1024;
|
|
pub struct Prefetch(pub tokio::task::JoinHandle<Result<()>>);
|
|
impl Drop for Prefetch {
|
|
fn drop(&mut self) {
|
|
self.0.abort();
|
|
}
|
|
}
|
|
fn directory(path: &Path, create: bool) -> Result<()> {
|
|
if create && !path.try_exists()? {
|
|
std::fs::DirBuilder::new().mode(0o700).create(path)?;
|
|
}
|
|
let m = fs::symlink_metadata(path)?;
|
|
ensure!(
|
|
m.is_dir() && !m.file_type().is_symlink() && m.uid() == 993 && m.mode() & 0o777 == 0o700,
|
|
"UPDATE_PREFETCH_DIRECTORY"
|
|
);
|
|
Ok(())
|
|
}
|
|
use std::os::unix::fs::DirBuilderExt;
|
|
fn parent(job: &JobPayload) -> Result<PathBuf> {
|
|
ensure!(
|
|
unsafe { libc::geteuid() } == 993,
|
|
"UPDATE_PREFETCH_AGENT_UID"
|
|
);
|
|
let base = Path::new("/var/lib/rmm-agent-remote");
|
|
directory(base, false)?;
|
|
let base = base.join("update-downloads");
|
|
directory(&base, true)?;
|
|
let base = base.join(job.job_id.to_string());
|
|
directory(&base, true)?;
|
|
let base = base.join(job.attempt_id.to_string());
|
|
directory(&base, true)?;
|
|
Ok(base)
|
|
}
|
|
fn label(a: &ArtifactDescriptor) -> &'static str {
|
|
match a.role {
|
|
ArtifactRole::Agent => "agent.bin",
|
|
ArtifactRole::Helper => "helper.bin",
|
|
}
|
|
}
|
|
fn checked(path: &Path, a: &ArtifactDescriptor) -> Result<()> {
|
|
let mut f = OpenOptions::new()
|
|
.read(true)
|
|
.custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
|
|
.open(path)?;
|
|
let m = f.metadata()?;
|
|
ensure!(
|
|
m.is_file()
|
|
&& m.uid() == 993
|
|
&& m.mode() & 0o777 == 0o600
|
|
&& m.nlink() == 1
|
|
&& m.len() == a.bytes,
|
|
"UPDATE_PREFETCH_FILE"
|
|
);
|
|
let mut h = Sha256::new();
|
|
let mut n = 0;
|
|
let mut buf = [0; 65536];
|
|
loop {
|
|
let size = f.read(&mut buf)?;
|
|
if size == 0 {
|
|
break;
|
|
}
|
|
n += size as u64;
|
|
ensure!(n <= a.bytes, "UPDATE_PREFETCH_LENGTH");
|
|
h.update(&buf[..size]);
|
|
}
|
|
ensure!(
|
|
n == a.bytes && format!("{:x}", h.finalize()) == a.sha256,
|
|
"UPDATE_PREFETCH_DIGEST"
|
|
);
|
|
Ok(())
|
|
}
|
|
pub async fn prefetch(client: reqwest::Client, base: String, job: JobPayload) -> Result<()> {
|
|
let Action::UpdateAgent { update } = &job.action else {
|
|
anyhow::bail!("UPDATE_ACTION_REQUIRED")
|
|
};
|
|
let manifest = update.manifest().map_err(anyhow::Error::msg)?;
|
|
ensure!(
|
|
manifest.validate() && manifest.platform == Platform::LinuxX64,
|
|
"UPDATE_PREFETCH_MANIFEST"
|
|
);
|
|
let pjob = job.clone();
|
|
let folder = tokio::task::spawn_blocking(move || parent(&pjob)).await??;
|
|
let deadline = Instant::now() + Duration::from_secs(600);
|
|
for artifact in manifest.artifacts {
|
|
ensure!(
|
|
artifact.bytes > 0 && artifact.bytes <= MAXIMUM,
|
|
"UPDATE_PREFETCH_LIMIT"
|
|
);
|
|
let path = folder.join(label(&artifact));
|
|
let existing = path.clone();
|
|
let desc = artifact.clone();
|
|
if tokio::task::spawn_blocking(move || -> Result<bool> {
|
|
if existing.try_exists()? {
|
|
checked(&existing, &desc)?;
|
|
Ok(true)
|
|
} else {
|
|
Ok(false)
|
|
}
|
|
})
|
|
.await??
|
|
{
|
|
continue;
|
|
}
|
|
let stage = folder.join(format!("{}.partial", label(&artifact)));
|
|
let stage_path = stage.clone();
|
|
let mut file = tokio::task::spawn_blocking(move || {
|
|
OpenOptions::new()
|
|
.write(true)
|
|
.create_new(true)
|
|
.mode(0o600)
|
|
.custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
|
|
.open(stage_path)
|
|
})
|
|
.await??;
|
|
let mut offset = 0;
|
|
let mut hash = Sha256::new();
|
|
while offset < artifact.bytes {
|
|
ensure!(
|
|
Instant::now() < deadline && chrono::Utc::now() < job.start_before,
|
|
"UPDATE_PREFETCH_EXPIRED"
|
|
);
|
|
let length = CHUNK.min(artifact.bytes - offset);
|
|
let url = format!(
|
|
"{base}/agent/v1/update-artifacts/{}?job_id={}&attempt_id={}&offset={offset}&length={length}",
|
|
artifact.artifact_id, job.job_id, job.attempt_id
|
|
);
|
|
let mut response = client.get(&url).send().await?;
|
|
let partial = offset != 0 || length != artifact.bytes;
|
|
ensure!(
|
|
response.url().as_str() == url
|
|
&& response.status()
|
|
== if partial {
|
|
reqwest::StatusCode::PARTIAL_CONTENT
|
|
} else {
|
|
reqwest::StatusCode::OK
|
|
},
|
|
"UPDATE_PREFETCH_HTTP"
|
|
);
|
|
let h = response.headers();
|
|
ensure!(
|
|
h.get("x-artifact-sha256").and_then(|v| v.to_str().ok())
|
|
== Some(artifact.sha256.as_str())
|
|
&& h.get("content-type").and_then(|v| v.to_str().ok())
|
|
== Some("application/octet-stream")
|
|
&& !h.contains_key("content-encoding")
|
|
&& response.content_length() == Some(length),
|
|
"UPDATE_PREFETCH_HEADERS"
|
|
);
|
|
if partial {
|
|
ensure!(
|
|
h.get("content-range").and_then(|v| v.to_str().ok())
|
|
== Some(
|
|
format!(
|
|
"bytes {}-{}/{}",
|
|
offset,
|
|
offset + length - 1,
|
|
artifact.bytes
|
|
)
|
|
.as_str()
|
|
),
|
|
"UPDATE_PREFETCH_RANGE"
|
|
);
|
|
} else {
|
|
ensure!(!h.contains_key("content-range"), "UPDATE_PREFETCH_RANGE");
|
|
}
|
|
let mut bytes = Vec::with_capacity(length as usize);
|
|
while let Some(chunk) = response.chunk().await? {
|
|
ensure!(
|
|
bytes.len() + chunk.len() <= length as usize,
|
|
"UPDATE_PREFETCH_BODY_LIMIT"
|
|
);
|
|
bytes.extend_from_slice(&chunk);
|
|
}
|
|
ensure!(
|
|
bytes.len() == length as usize && Instant::now() < deadline,
|
|
"UPDATE_PREFETCH_BODY_LENGTH"
|
|
);
|
|
hash.update(&bytes);
|
|
file = tokio::task::spawn_blocking(move || -> Result<File> {
|
|
file.write_all(&bytes)?;
|
|
Ok(file)
|
|
})
|
|
.await??;
|
|
offset += length;
|
|
}
|
|
ensure!(
|
|
format!("{:x}", hash.finalize()) == artifact.sha256,
|
|
"UPDATE_PREFETCH_DIGEST"
|
|
);
|
|
let dir = folder.clone();
|
|
tokio::task::spawn_blocking(move || -> Result<()> {
|
|
file.sync_all()?;
|
|
drop(file);
|
|
fs::hard_link(&stage, &path)?;
|
|
fs::remove_file(stage)?;
|
|
File::open(dir)?.sync_all()?;
|
|
checked(&path, &artifact)
|
|
})
|
|
.await??;
|
|
}
|
|
Ok(())
|
|
}
|
|
/// No Outcome is invented on acceptance; loss after write stays ambiguous.
|
|
pub fn handoff(binding: &Binding, request: &Request, grant: uuid::Uuid) -> Result<Accepted> {
|
|
let socket = std::env::var_os("RMM_FULL_MAINTENANCE_HELPER_SOCKET")
|
|
.context("UPDATE_FULL_SOCKET_REQUIRED")?;
|
|
let pin =
|
|
std::env::var_os("RMM_FULL_MAINTENANCE_POLICY_FILE").context("UPDATE_FULL_PIN_REQUIRED")?;
|
|
let pin = control::GeneralPin::read(Path::new(&pin), binding)?;
|
|
ensure!(
|
|
pin.profile == "full_maintenance_v1",
|
|
"UPDATE_FULL_PROFILE_REQUIRED"
|
|
);
|
|
control::general_probe(Path::new(&socket), binding, &pin)?;
|
|
let ack: Accepted =
|
|
control::exchange(Path::new(&socket), request, Duration::from_secs(50), 4096)?;
|
|
ack.matches(request, grant)?;
|
|
Ok(ack)
|
|
}
|
|
|
|
/// Opaque public metadata authenticated by the current protected Full peer,
|
|
/// with complete guarded history verified there. No caller JSON constructor.
|
|
#[derive(Clone)]
|
|
pub struct GuardedRecord {
|
|
raw: Vec<u8>,
|
|
observation: rmm_domain::agent_update::AgentUpdateObservation,
|
|
}
|
|
impl GuardedRecord {
|
|
pub fn bytes(&self, policy_raw: &[u8], keys_raw: &[u8]) -> Result<&[u8]> {
|
|
use rmm_domain::agent_update::ObservationQuality;
|
|
let o = &self.observation;
|
|
let age = chrono::Utc::now() - o.observed_at;
|
|
let p = o
|
|
.predecessor
|
|
.as_ref()
|
|
.context("UPDATE_CATALOG_PREDECESSOR")?;
|
|
let u = o.updater.as_ref().context("UPDATE_CATALOG_UPDATER")?;
|
|
ensure!(
|
|
o.validate()
|
|
&& o.quality == ObservationQuality::Valid
|
|
&& o.platform == Platform::LinuxX64
|
|
&& age >= chrono::Duration::zero()
|
|
&& age <= chrono::Duration::seconds(90)
|
|
&& rmm_domain::jobs::hash(policy_raw) == u.policy_sha256
|
|
&& rmm_domain::jobs::hash(keys_raw) == u.keyring_sha256
|
|
&& rmm_domain::jobs::hash(&self.raw) == p.installed_record_sha256,
|
|
"UPDATE_CATALOG_GUARDED_RECORD"
|
|
);
|
|
Ok(&self.raw)
|
|
}
|
|
}
|
|
/// Passive cached Full observations only; never a live MCP collection.
|
|
type Observation = rmm_domain::agent_update::AgentUpdateObservation;
|
|
struct Observing {
|
|
receiver: tokio::sync::oneshot::Receiver<Result<(Observation, Vec<u8>)>>,
|
|
task: tokio::task::JoinHandle<()>,
|
|
}
|
|
impl Drop for Observing {
|
|
fn drop(&mut self) {
|
|
self.task.abort();
|
|
}
|
|
}
|
|
#[derive(Default)]
|
|
pub struct Observer {
|
|
current: Option<Observation>,
|
|
record: Option<GuardedRecord>,
|
|
pending: Option<Observing>,
|
|
}
|
|
impl Observer {
|
|
pub fn cached(&self) -> Option<&Observation> {
|
|
let value = self.current.as_ref()?;
|
|
let age = chrono::Utc::now() - value.observed_at;
|
|
(value.validate()
|
|
&& age >= chrono::Duration::zero()
|
|
&& age <= chrono::Duration::seconds(90))
|
|
.then_some(value)
|
|
}
|
|
pub fn poll(
|
|
&mut self,
|
|
binding: Option<&Binding>,
|
|
candidate: Option<(rmm_domain::agent_update::ReleaseEnvelope, u64)>,
|
|
) -> Observation {
|
|
if let Some(pending) = &mut self.pending {
|
|
match pending.receiver.try_recv() {
|
|
Ok(Ok((value, raw))) if value.validate() => {
|
|
self.record = Some(GuardedRecord {
|
|
raw,
|
|
observation: value.clone(),
|
|
});
|
|
self.current = Some(value);
|
|
self.pending = None;
|
|
}
|
|
Ok(_) | Err(tokio::sync::oneshot::error::TryRecvError::Closed) => {
|
|
self.current = None;
|
|
self.record = None;
|
|
self.pending = None;
|
|
}
|
|
Err(tokio::sync::oneshot::error::TryRecvError::Empty) => {}
|
|
}
|
|
}
|
|
if self.pending.is_none()
|
|
&& let Some(binding) = binding.cloned()
|
|
{
|
|
let (sender, receiver) = tokio::sync::oneshot::channel();
|
|
let task = tokio::task::spawn_blocking(move || {
|
|
let (envelope, generation) =
|
|
candidate.map_or((None, None), |(e, g)| (Some(e), Some(g)));
|
|
let value = rmm_privileged_helper::update_admission::observe_record(
|
|
Path::new("/run/rmm-helper-maintenance/control.sock"),
|
|
&binding,
|
|
envelope,
|
|
generation,
|
|
);
|
|
let _ = sender.send(value);
|
|
});
|
|
self.pending = Some(Observing { receiver, task });
|
|
}
|
|
self.cached()
|
|
.cloned()
|
|
.unwrap_or_else(|| Observation::not_configured(Platform::LinuxX64, chrono::Utc::now()))
|
|
}
|
|
pub fn catalog_record(&self) -> Option<GuardedRecord> {
|
|
self.cached()?;
|
|
self.record.clone()
|
|
}
|
|
pub fn capabilities(&self) -> Vec<String> {
|
|
let Some(value) = self
|
|
.cached()
|
|
.filter(|v| v.quality == rmm_domain::agent_update::ObservationQuality::Valid)
|
|
else {
|
|
return vec![];
|
|
};
|
|
let (Some(updater), Some(predecessor)) = (&value.updater, &value.predecessor) else {
|
|
return vec![];
|
|
};
|
|
vec![
|
|
APPLY_CAPABILITY.into(),
|
|
CHECK_CAPABILITY.into(),
|
|
"update_agent".into(),
|
|
"root:update_agent".into(),
|
|
"helper.root.v1".into(),
|
|
format!("updater.binary.sha256:{}", updater.binary_sha256),
|
|
format!("updater.policy.sha256:{}", updater.policy_sha256),
|
|
format!("helper.binary.sha256:{}", predecessor.helper_sha256),
|
|
]
|
|
}
|
|
}
|
|
pub fn supported(binding: &Binding, job: &JobPayload) -> bool {
|
|
(|| -> Result<bool> {
|
|
ensure!(
|
|
unsafe { libc::geteuid() } == 993 && job.execution_identity == "root",
|
|
"UPDATE_AGENT_PRINCIPAL"
|
|
);
|
|
let Action::UpdateAgent { update } = &job.action else {
|
|
return Ok(false);
|
|
};
|
|
let observation = rmm_privileged_helper::update_admission::observe(
|
|
Path::new("/run/rmm-helper-maintenance/control.sock"),
|
|
binding,
|
|
Some(update.release_envelope.clone()),
|
|
Some(update.updater.keyring_generation),
|
|
)?;
|
|
Ok(observation.validate()
|
|
&& observation.quality == rmm_domain::agent_update::ObservationQuality::Valid
|
|
&& observation.predecessor.as_ref() == Some(&update.predecessor)
|
|
&& observation.updater.as_ref() == Some(&update.updater)
|
|
&& observation.candidate_previews.iter().any(|c| {
|
|
c.manifest_sha256 == update.manifest_sha256
|
|
&& c.peer_pin_transition == update.peer_pin_transition
|
|
}))
|
|
})()
|
|
.unwrap_or(false)
|
|
}
|