Use script-only execution on Linux and preserve the enrolled helper through updates

This commit is contained in:
2026-11-18 12:01:02 +01:00
parent c692316abe
commit adc04f0148
9 changed files with 494 additions and 1010 deletions
+4 -284
View File
@@ -1,241 +1,8 @@
//! Approved artifact prefetch before a grant; Full independently admits the handoff.
//! Passive signed-release observations and retained update evidence.
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)
}
use rmm_domain::agent_update::Platform;
use rmm_privileged_helper::Binding;
use std::path::Path;
/// Opaque public metadata authenticated by the current protected Full peer,
/// with complete guarded history verified there. No caller JSON constructor.
@@ -342,51 +109,4 @@ impl Observer {
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)
}