Add gated agent update planning, preserved handoff and Linux worker ports
Rust development slice / linux (push) Failing after 6s

This commit is contained in:
2026-11-14 21:48:21 +01:00
parent dc9cb1b096
commit 1e89c4577f
82 changed files with 25052 additions and 69 deletions
+43
View File
@@ -0,0 +1,43 @@
//! Current native clock evidence, independent of agent/IPC timestamps.
use anyhow::{Result, ensure};
use chrono::{DateTime, Utc};
use rmm_agent_core::reconcile::SyncClock;
use std::time::Instant;
pub struct NativeClock {
wall: DateTime<Utc>,
monotonic: Instant,
}
impl NativeClock {
pub fn new() -> Result<Self> {
let value = Self {
wall: Utc::now(),
monotonic: Instant::now(),
};
value.now()?;
Ok(value)
}
}
impl SyncClock for NativeClock {
fn now(&self) -> Result<DateTime<Utc>> {
let mut timex = std::mem::MaybeUninit::<libc::timex>::zeroed();
// modes=0 is strictly a read-only kernel synchronization/error query.
let status = unsafe { libc::adjtimex(timex.as_mut_ptr()) };
let timex = unsafe { timex.assume_init() };
ensure!(
status >= 0
&& status != libc::TIME_ERROR
&& timex.status & libc::STA_UNSYNC == 0
&& timex.maxerror >= 0
&& timex.maxerror <= 5_000_000,
"UPDATE_CLOCK_UNTRUSTED"
);
let now = Utc::now();
let elapsed = i64::try_from(self.monotonic.elapsed().as_millis())?;
ensure!(
((now - self.wall).num_milliseconds() - elapsed).unsigned_abs() <= 5000,
"UPDATE_CLOCK_CHANGED"
);
Ok(now)
}
}
+119
View File
@@ -0,0 +1,119 @@
//! Concrete durable Save/Publish fence against the ORIGINAL helper ledger.
//! One live forward pass; construction cannot resume a partial ReplaceIntent.
use crate::ledger::OwnedLedger;
use anyhow::{Result, ensure};
use rmm_agent_core::update_handoff::{NativeEffect, NativeEffectClaim, NativeFileRole};
use rmm_updater_handoff::{Evidence, Phase};
use rmm_updater_linux::{DurableEffectFence, Effect, files::Role};
fn native_role(role: Role) -> NativeFileRole {
match role {
Role::Agent => NativeFileRole::AgentBinary,
Role::Helper => NativeFileRole::HelperBinary,
Role::FullConfig => NativeFileRole::FullConfig,
Role::FullPin => NativeFileRole::FullPin,
}
}
pub struct LedgerFence<'w, 'a, 's> {
ledger: &'w mut OwnedLedger<'a, 's>,
pending: Option<(Effect, NativeEffectClaim)>,
saved: Option<Role>,
poisoned: bool,
}
impl<'w, 'a, 's> LedgerFence<'w, 'a, 's> {
pub fn new(ledger: &'w mut OwnedLedger<'a, 's>) -> Result<Self> {
ensure!(
ledger.journal()?.phase() == Phase::UpdaterOwnsLedger,
"UPDATE_NO_FENCE_RESUME"
);
Ok(Self {
ledger,
pending: None,
saved: None,
poisoned: false,
})
}
/// A failed native call must poison/drop this fence. No reentry/retry API.
pub fn finish(self) -> Result<()> {
ensure!(
!self.poisoned
&& self.pending.is_none()
&& self.saved.is_none()
&& self.ledger.journal()?.phase() == Phase::Replaced,
"UPDATE_FENCE_INCOMPLETE"
);
self.ledger.verify_pair()?;
Ok(())
}
fn claim(&mut self, effect: &Effect) -> Result<()> {
ensure!(
!self.poisoned && self.pending.is_none(),
"UPDATE_FENCE_REENTRY"
);
// Poison BEFORE a fallible commit or OS operation. Only a fully
// observed matching callback can return the live pass to idle.
self.poisoned = true;
let native = match *effect {
Effect::SavePredecessor { role } => {
ensure!(self.saved.is_none(), "UPDATE_SAVE_ORDER");
self.ledger.append_observed(Evidence::ReplaceIntent {
role: role.handoff_role(),
})?;
NativeEffect::SavePredecessor {
role: native_role(role),
}
}
Effect::PublishReplacement { role } => {
ensure!(self.saved == Some(role), "UPDATE_PUBLISH_WITHOUT_SAVE");
NativeEffect::PublishReplacement {
role: native_role(role),
}
}
_ => anyhow::bail!("UPDATE_OWNED_FENCE_EFFECT_NOT_ALLOWED"),
};
let claim = self.ledger.claim_native(&native)?;
self.pending = Some((effect.clone(), claim));
Ok(())
}
fn observe(&mut self, effect: &Effect, observation: &str) -> Result<()> {
let Some((expected, claim)) = self.pending.take() else {
anyhow::bail!("UPDATE_EFFECT_NOT_CLAIMED")
};
ensure!(
self.poisoned && expected == *effect,
"UPDATE_EFFECT_CALLBACK_CHANGED"
);
let (role, replaced) = match *effect {
Effect::SavePredecessor { role } => (role, false),
Effect::PublishReplacement { role } => (role, true),
_ => anyhow::bail!("UPDATE_OWNED_FENCE_EFFECT_NOT_ALLOWED"),
};
ensure!(
self.ledger
.native_observation_sha256(role.handoff_role(), replaced)?
== observation,
"UPDATE_NATIVE_OBSERVATION_CHANGED"
);
self.ledger.observe_native(&claim, observation)?;
if replaced {
let observed_sha256 = self.ledger.target_sha256(role.handoff_role())?;
self.ledger.append_observed(Evidence::Replaced {
role: role.handoff_role(),
observed_sha256,
})?;
self.saved = None;
} else {
self.saved = Some(role);
}
self.poisoned = false;
Ok(())
}
}
impl DurableEffectFence for LedgerFence<'_, '_, '_> {
fn before_effect(&mut self, effect: &Effect) -> Result<()> {
self.claim(effect)
}
fn after_effect(&mut self, effect: &Effect, observation_sha256: &str) -> Result<()> {
self.observe(effect, observation_sha256)
}
}
+197
View File
@@ -0,0 +1,197 @@
//! Exact fixed target/stage proofs, captured before atomic consumption and
//! independently reread under the existing lock before each native operation.
use anyhow::{Context, Result, ensure};
use rmm_domain::jobs::hash;
use rmm_updater_handoff::{FileRole, Handoff};
use rmm_updater_linux::{
Budget,
files::{Directory, FileProof, Role, Staged},
};
use serde::Serialize;
use std::{ffi::OsStr, path::Path};
use uuid::Uuid;
const ROLES: [Role; 4] = [Role::Agent, Role::Helper, Role::FullConfig, Role::FullPin];
fn label(role: Role) -> &'static str {
match role {
Role::Agent => "agent",
Role::Helper => "helper",
Role::FullConfig => "full-config",
Role::FullPin => "full-pin",
}
}
fn role(role: FileRole) -> Result<Role> {
match role {
FileRole::AgentBinary => Ok(Role::Agent),
FileRole::HelperBinary => Ok(Role::Helper),
FileRole::LinuxFullConfig => Ok(Role::FullConfig),
FileRole::LinuxFullPin => Ok(Role::FullPin),
_ => anyhow::bail!("UPDATE_LINUX_FILE_ROLE"),
}
}
#[derive(Serialize)]
struct Proof {
role: Role,
original: FileProof,
staged: FileProof,
}
pub struct FileWitnesses {
files: Vec<Proof>,
nonce: Uuid,
sha256: String,
}
impl FileWitnesses {
/// Exactly Agent, Helper, Fullconfig, Fullpin, all fully staged. Reopening
/// each fixed stage name also rejects a mislabeled `Staged` object.
pub fn capture(stages: &[Staged; 4], nonce: Uuid, budget: &Budget) -> Result<Self> {
ensure!(!nonce.is_nil(), "UPDATE_STAGE_NONCE");
let mut files = Vec::new();
for (role, stage) in ROLES.iter().copied().zip(stages) {
budget.check()?;
let path = Path::new(role.target());
let directory =
Directory::open(path.parent().context("UPDATE_TARGET_PARENT")?, 0, false)?;
let original = directory.inspect(
path.file_name().context("UPDATE_TARGET_NAME")?,
0,
256 * 1024 * 1024,
)?;
directory.file(
OsStr::new(&format!(".rmm-update-{nonce}-{}.stage", label(role))),
stage.proof(),
256 * 1024 * 1024,
)?;
ensure!(
stage.proof().identity.links == 1
&& stage.proof().identity.uid == original.proof().identity.uid
&& stage.proof().identity.gid == original.proof().identity.gid
&& stage.proof().identity.mode == original.proof().identity.mode,
"UPDATE_STAGE_METADATA_CHANGED"
);
files.push(Proof {
role,
original: original.proof().clone(),
staged: stage.proof().clone(),
});
}
let digest = hash(&serde_json::to_vec(&files)?);
Ok(Self {
files,
nonce,
sha256: digest,
})
}
pub fn sha256(&self) -> &str {
&self.sha256
}
pub fn bind(&self, handoff: &Handoff) -> Result<()> {
ensure!(
handoff.files.len() == 4
&& handoff.owner_nonce == self.nonce
&& handoff.staged_files_sha256 == self.sha256,
"UPDATE_FILESET_BINDING"
);
for (file, plan) in self.files.iter().zip(&handoff.files) {
ensure!(
plan.role == file.role.handoff_role()
&& plan.old_sha256 == file.original.sha256
&& plan.new_sha256 == file.staged.sha256,
"UPDATE_FILESET_PLAN_CHANGED"
);
}
Ok(())
}
pub fn verify_original_and_stage(&self, which: FileRole, budget: &Budget) -> Result<()> {
let file = self.file(which)?;
budget.check()?;
let path = Path::new(file.role.target());
let dir = Directory::open(path.parent().context("UPDATE_TARGET_PARENT")?, 0, false)?;
dir.file(
path.file_name().context("UPDATE_TARGET_NAME")?,
&file.original,
256 * 1024 * 1024,
)?;
dir.file(
OsStr::new(&format!(
".rmm-update-{}-{}.stage",
self.nonce,
label(file.role)
)),
&file.staged,
256 * 1024 * 1024,
)?;
Ok(())
}
pub fn verify_replaced(&self, which: FileRole, budget: &Budget) -> Result<()> {
let file = self.file(which)?;
budget.check()?;
let path = Path::new(file.role.target());
let dir = Directory::open(path.parent().context("UPDATE_TARGET_PARENT")?, 0, false)?;
dir.file(
path.file_name().context("UPDATE_TARGET_NAME")?,
&file.staged,
256 * 1024 * 1024,
)?;
dir.file(
OsStr::new(&format!(
".rmm-update-{}-{}.previous",
self.nonce,
label(file.role)
)),
&file.original,
256 * 1024 * 1024,
)?;
Ok(())
}
pub fn verify_saved(&self, which: FileRole, budget: &Budget) -> Result<()> {
let file = self.file(which)?;
budget.check()?;
let path = Path::new(file.role.target());
let dir = Directory::open(path.parent().context("UPDATE_TARGET_PARENT")?, 0, false)?;
dir.file(
OsStr::new(&format!(
".rmm-update-{}-{}.previous",
self.nonce,
label(file.role)
)),
&file.original,
256 * 1024 * 1024,
)?;
dir.file(
OsStr::new(&format!(
".rmm-update-{}-{}.stage",
self.nonce,
label(file.role)
)),
&file.staged,
256 * 1024 * 1024,
)?;
ensure!(
std::fs::symlink_metadata(path)
.is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound),
"UPDATE_PUBLISH_TARGET_NOT_ABSENT"
);
dir.verify()
}
pub fn native_observation_sha256(&self, which: FileRole, replaced: bool) -> Result<String> {
let file = self.file(which)?;
Ok(hash(&serde_json::to_vec(if replaced {
&file.staged
} else {
&file.original
})?))
}
pub fn verify_pair(&self, budget: &Budget) -> Result<()> {
for file in &self.files {
self.verify_replaced(file.role.handoff_role(), budget)?;
}
Ok(())
}
fn file(&self, which: FileRole) -> Result<&Proof> {
let role = role(which)?;
self.files
.iter()
.find(|f| f.role == role)
.context("UPDATE_FILE_NOT_BOUND")
}
}
+185
View File
@@ -0,0 +1,185 @@
//! Exact protected Full raw files and the independently provisioned public
//! signing-key record. This is a closed renderer, never a JSON patch/ACL change.
use anyhow::{Context, Result, ensure};
use ed25519_dalek::VerifyingKey;
use rmm_domain::{
agent_update::{PeerPinTransition, ResolvedAgentUpdate},
jobs::hash,
};
use rmm_updater_handoff::{LinuxFullTransition, render_linux_full};
use rmm_updater_linux::{
Budget,
files::{Directory, HeldFile, Role, StageDescriptor, Staged},
};
use serde::Deserialize;
use std::{
ffi::OsStr,
path::{Path, PathBuf},
};
use uuid::Uuid;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SigningKeyRecord {
key_id: String,
algorithm: String,
schema_version: u32,
public_key_hex: String,
}
pub struct FullFiles {
directory: Directory,
config: HeldFile,
pin: HeldFile,
key_directory: Directory,
key_file: HeldFile,
key_path: PathBuf,
rendered: LinuxFullTransition,
}
impl FullFiles {
/// `job_key_path` and `job_key_raw_sha256` come from independently protected
/// LOCAL policy, not an update job, IPC request or manifest. The exact key
/// identity is additionally bound to the approved Full transition proof.
pub fn open(
update: &ResolvedAgentUpdate,
job_key_path: &Path,
job_key_raw_sha256: &str,
budget: &Budget,
) -> Result<Self> {
budget.check()?;
ensure!(
update.validate() && job_key_path.is_absolute(),
"UPDATE_FULL_INPUT"
);
let PeerPinTransition::LinuxGeneralFullV1 { full, .. } = &update.peer_pin_transition else {
anyhow::bail!("UPDATE_FULL_REQUIRED")
};
let key_directory = Directory::open(
job_key_path.parent().context("UPDATE_FULL_KEY_PARENT")?,
0,
false,
)?;
let mut key_file = key_directory.inspect(
job_key_path.file_name().context("UPDATE_FULL_KEY_NAME")?,
0,
4096,
)?;
ensure!(
key_file.proof().sha256 == job_key_raw_sha256,
"UPDATE_FULL_KEY_RAW_HASH"
);
let key: SigningKeyRecord = serde_json::from_slice(&key_file.bytes(4096)?)?;
let raw = hex::decode(&key.public_key_hex)?;
ensure!(
key.schema_version == 1
&& key.algorithm == "Ed25519"
&& key.key_id == hash(&raw)
&& key.key_id == full.effective_signing_key_id,
"UPDATE_FULL_KEY_IDENTITY"
);
let key = VerifyingKey::from_bytes(
&raw.try_into()
.map_err(|_| anyhow::anyhow!("UPDATE_FULL_KEY_SIZE"))?,
)?;
ensure!(!key.is_weak(), "UPDATE_FULL_WEAK_KEY");
let directory = Directory::open(Path::new("/etc/rmm-remote"), 0, false)?;
let mut config = directory.inspect(OsStr::new("helper-full-maintenance.json"), 0, 16384)?;
let mut pin =
directory.inspect(OsStr::new("full-maintenance-helper-proof.json"), 0, 8192)?;
ensure!(
config.proof().sha256 == full.old_config_sha256
&& pin.proof().sha256 == full.old_pin_sha256,
"UPDATE_FULL_OLD_RAW_CHANGED"
);
let config_bytes = config.bytes(16384)?;
// The renderer authenticates the effective public key but deliberately
// does not load it. Bind the actual raw Config's key path independently.
let value: serde_json::Value = serde_json::from_slice(&config_bytes)?;
if let Some(path) = value.get("signing_key_file").and_then(|v| v.as_str()) {
ensure!(
Path::new(path) == job_key_path,
"UPDATE_FULL_KEY_PATH_CHANGED"
);
} else {
ensure!(
value["binding"]["public_key_hex"].as_str() == Some(&hex::encode(key.as_bytes())),
"UPDATE_FULL_INLINE_KEY_CHANGED"
);
}
let rendered = render_linux_full(
&config_bytes,
&pin.bytes(8192)?,
&full.new_helper_sha256,
&key,
)?;
ensure!(
serde_json::to_vec(rendered.proof())? == serde_json::to_vec(full)?,
"UPDATE_FULL_RENDER_DIFFERS_FROM_APPROVED"
);
budget.check()?;
Ok(Self {
directory,
config,
pin,
key_directory,
key_file,
key_path: job_key_path.to_owned(),
rendered,
})
}
pub fn verify_original(&mut self, budget: &Budget) -> Result<()> {
budget.check()?;
self.directory.verify()?;
self.key_directory.verify()?;
self.config.verify(16384)?;
self.pin.verify(8192)?;
self.key_file.verify(4096)?;
self.directory.file(
OsStr::new("helper-full-maintenance.json"),
self.config.proof(),
16384,
)?;
self.directory.file(
OsStr::new("full-maintenance-helper-proof.json"),
self.pin.proof(),
8192,
)?;
self.key_directory.file(
self.key_path.file_name().context("UPDATE_FULL_KEY_NAME")?,
self.key_file.proof(),
4096,
)?;
Ok(())
}
/// Only after real WebUI approval and independent live original-grant /
/// download checks by the enclosing admission path. No activation here.
pub fn stage(&mut self, owner_nonce: Uuid, budget: &Budget) -> Result<[Staged; 2]> {
self.verify_original(budget)?;
let mut config = self.rendered.new_config_bytes();
let mut pin = self.rendered.new_pin_bytes();
let config = Staged::write(
&self.directory,
StageDescriptor {
role: Role::FullConfig,
nonce: owner_nonce,
original: self.config.proof(),
expected_sha: &self.rendered.proof().new_config_sha256,
length: config.len() as u64,
},
&mut config,
budget,
)?;
let pin = Staged::write(
&self.directory,
StageDescriptor {
role: Role::FullPin,
nonce: owner_nonce,
original: self.pin.proof(),
expected_sha: &self.rendered.proof().new_pin_sha256,
length: pin.len() as u64,
},
&mut pin,
budget,
)?;
Ok([config, pin])
}
}
+335
View File
@@ -0,0 +1,335 @@
//! The one existing SQLite file, opened without CREATE only after the real
//! OS guard confirms every reader stopped. This module performs no bootstrap,
//! consumption, schema reset, outcome healing or readiness transition.
use crate::{
clock::NativeClock, files::FileWitnesses, original::Original, participants::StableParticipant,
retained::RetainedSet, trust::TrustState,
};
use anyhow::{Result, ensure};
use rmm_agent_core::{
auth::Binding,
helper_reconcile::ExecutorLedgerGuard,
reconcile::SyncClock,
update_handoff::{
self, NativeEffect, NativeEffectClaim, NativeEffectStage, NativeFileRole, Participant,
UpdateParticipantGuard,
},
};
use rmm_domain::agent_update::UpdateDelegation;
use rmm_domain::jobs::hash;
use rmm_updater_handoff::{Event, Evidence, Handoff, Journal, Phase};
use rmm_updater_linux::services::StoppedServices;
use rmm_updater_linux::{Budget, files::LedgerGuard};
use rusqlite::{Connection, OpenFlags};
use std::time::Duration;
const LEDGER: &str = "/var/lib/rmm-helper/consumption.sqlite";
pub struct OwnedGuard<'a, 'stopped> {
os: &'a LedgerGuard<'stopped>,
original: &'a Original,
binding: &'a Binding,
clock: &'a NativeClock,
budget: &'a Budget,
updater: &'a StableParticipant,
retained: &'a RetainedSet,
files: &'a FileWitnesses,
stopped: &'a StoppedServices,
trust: &'a TrustState,
sqlite_handle: usize,
}
pub struct OwnedInputs<'a, 'stopped> {
pub os: &'a LedgerGuard<'stopped>,
pub original: &'a Original,
pub binding: &'a Binding,
pub clock: &'a NativeClock,
pub budget: &'a Budget,
pub updater: &'a StableParticipant,
pub retained: &'a RetainedSet,
pub files: &'a FileWitnesses,
pub stopped: &'a StoppedServices,
pub trust: &'a TrustState,
}
pub struct OwnedLedger<'a, 'stopped> {
db: Connection,
guard: OwnedGuard<'a, 'stopped>,
}
impl<'a, 'stopped> OwnedLedger<'a, 'stopped> {
pub fn open(input: OwnedInputs<'a, 'stopped>) -> Result<Self> {
input.os.verify_for_effect(input.budget)?;
ensure!(
input.os.identity().sha256()? == input.original.handoff().ledger_identity_sha256
&& input.retained.sha256() == input.original.handoff().retained_state_sha256,
"UPDATE_OWNED_LEDGER_OR_STATE_BINDING"
);
let db = Connection::open_with_flags(
LEDGER,
OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_NO_MUTEX,
)?;
db.busy_timeout(Duration::ZERO)?;
// Per-connection durability/finite capacity, preserving DELETE journal
// mode, all existing schema/rows, and the already held file identities.
let mode: String = db.query_row("PRAGMA journal_mode", [], |r| r.get(0))?;
let sync: u32 = db.query_row("PRAGMA synchronous", [], |r| r.get(0))?;
ensure!(
mode == "delete" && sync >= 2,
"UPDATE_LEDGER_DURABILITY_REQUIRED"
);
input.files.bind(input.original.handoff())?;
let guard = OwnedGuard {
os: input.os,
original: input.original,
binding: input.binding,
clock: input.clock,
budget: input.budget,
updater: input.updater,
retained: input.retained,
files: input.files,
stopped: input.stopped,
trust: input.trust,
sqlite_handle: unsafe { db.handle() } as usize,
};
guard.check(&db)?;
// Replay the complete original retained chain and its durable head.
update_handoff::read(&db, &guard, input.original.permit().grant_id)?;
db.execute_batch("PRAGMA foreign_keys=ON")?;
rmm_agent_core::ledger::bounded_journal_capacity(&db)?;
Ok(Self { db, guard })
}
pub fn journal(&self) -> Result<Journal> {
update_handoff::read(&self.db, &self.guard, self.guard.original.permit().grant_id)
}
pub fn append_observed(&mut self, evidence: Evidence) -> Result<()> {
let journal = self.journal()?;
let event = journal.prepare(
u64::try_from(self.guard.clock.now()?.timestamp())?,
evidence,
)?;
update_handoff::append(
&mut self.db,
&self.guard,
self.guard.original.permit().grant_id,
journal.head_sha256(),
&event,
)
}
pub fn claim_native(&mut self, effect: &NativeEffect) -> Result<NativeEffectClaim> {
let journal = self.journal()?;
update_handoff::claim_native_effect(
&mut self.db,
&self.guard,
self.guard.original.permit().grant_id,
journal.head_sha256(),
effect,
self.guard.clock.now()?,
)
}
pub fn observe_native(&mut self, claim: &NativeEffectClaim, observation: &str) -> Result<()> {
update_handoff::observe_native_effect(
&mut self.db,
&self.guard,
claim,
observation,
self.guard.clock.now()?,
)
}
pub fn native_observation_sha256(
&self,
role: rmm_updater_handoff::FileRole,
replaced: bool,
) -> Result<String> {
self.guard.files.native_observation_sha256(role, replaced)
}
pub fn target_sha256(&self, role: rmm_updater_handoff::FileRole) -> Result<String> {
self.guard
.original
.handoff()
.files
.iter()
.find(|f| f.role == role)
.map(|f| f.new_sha256.clone())
.ok_or_else(|| anyhow::anyhow!("UPDATE_TARGET_ROLE"))
}
pub fn verify_pair(&self) -> Result<()> {
self.guard.files.verify_pair(self.guard.budget)
}
/// Close the actual SQLite connection BEFORE returning the OS flock. An
/// open/failed-close connection never produces a released-ledger witness.
pub fn close(self) -> Result<()> {
self.guard.check(&self.db)?;
self.db.close().map_err(|(_, e)| e)?;
self.guard.os.verify_for_effect(self.guard.budget)
}
}
impl ExecutorLedgerGuard for OwnedGuard<'_, '_> {
fn check(&self, db: &Connection) -> Result<()> {
self.os.verify_for_effect(self.budget)?;
ensure!(
unsafe { db.handle() } as usize == self.sqlite_handle,
"UPDATE_SQLITE_CONNECTION_CHANGED"
);
let path: String = db.query_row(
"SELECT file FROM pragma_database_list WHERE name='main'",
[],
|r| r.get(0),
)?;
ensure!(path == LEDGER, "UPDATE_SQLITE_PATH_CHANGED");
self.original
.check_current(self.binding, self.clock, self.budget)?;
self.trust.recheck(self.original, self.clock)?;
self.updater
.verify_delegation(self.original.delegation(), self.budget)?;
self.retained.verify()?;
let grant = self.original.permit().grant_id.to_string();
let start: Vec<u8> = db.query_row(
"SELECT start FROM execution_evidence WHERE grant_id=?1",
[&grant],
|r| r.get(0),
)?;
ensure!(
start == self.original.start_bytes(),
"UPDATE_RETAINED_START_CHANGED"
);
let unresolved: u64 = db.query_row(
"SELECT count(*) FROM consumed WHERE result IS NULL AND grant_id<>?1",
[grant],
|r| r.get(0),
)?;
ensure!(unresolved == 0, "UPDATE_OTHER_UNRESOLVED_ATTEMPT");
self.os.verify_for_effect(self.budget)
}
fn check_update_owner(
&self,
handoff: &Handoff,
delegation: &UpdateDelegation,
phase: Phase,
_events: &[Event],
) -> Result<()> {
ensure!(
!matches!(
phase,
Phase::HandoffConsumed
| Phase::ServicesStarted
| Phase::HealthVerified
| Phase::OutcomePersisted
| Phase::Unknown
) && handoff.bytes()? == self.original.handoff().bytes()?
&& delegation == self.original.delegation(),
"UPDATE_OWNED_WRITER_CONTEXT_CHANGED"
);
self.os.verify_for_effect(self.budget)?;
self.updater.verify_delegation(delegation, self.budget)
}
}
impl UpdateParticipantGuard for OwnedGuard<'_, '_> {
fn participant(&self) -> Participant {
Participant::StableUpdater
}
fn verify_update_event(
&self,
handoff: &Handoff,
delegation: &UpdateDelegation,
event: &Event,
) -> Result<()> {
ensure!(
handoff.bytes()? == self.original.handoff().bytes()?
&& delegation == self.original.delegation(),
"UPDATE_EVENT_ORIGINAL_CHANGED"
);
self.original
.check_current(self.binding, self.clock, self.budget)?;
self.updater.verify_delegation(delegation, self.budget)?;
self.os.verify_for_effect(self.budget)?;
self.retained.verify()?;
match &event.evidence {
Evidence::AllStopped { observation_sha256 } => {
self.stopped.verify_still_stopped(self.budget)?;
ensure!(
*observation_sha256 == hash(&serde_json::to_vec(&self.stopped.proofs())?),
"UPDATE_ALL_STOPPED_OBSERVATION"
);
}
Evidence::UpdaterOwnsLedger {
process,
ledger_identity_sha256,
} => ensure!(
process.pid == delegation.updater.pid
&& process.birth == delegation.updater.birth
&& process.image_sha256 == delegation.updater.image_sha256
&& *ledger_identity_sha256 == self.os.identity().sha256()?,
"UPDATE_OWNER_EVENT_OBSERVATION"
),
Evidence::ReplaceIntent { role } => {
self.files.verify_original_and_stage(*role, self.budget)?
}
Evidence::Replaced {
role,
observed_sha256,
} => {
self.files.verify_replaced(*role, self.budget)?;
ensure!(
handoff
.files
.iter()
.any(|f| f.role == *role && f.new_sha256 == *observed_sha256),
"UPDATE_REPLACED_OBSERVATION"
);
}
Evidence::PairVerified {
pair,
retained_state_sha256,
} => {
self.files.verify_pair(self.budget)?;
ensure!(
*pair == handoff.target && retained_state_sha256 == self.retained.sha256(),
"UPDATE_PAIR_OBSERVATION"
);
}
Evidence::LedgerReturnIntent => self.files.verify_pair(self.budget)?,
_ => anyhow::bail!("UPDATE_EVENT_WRITER_NOT_ALLOWED"),
}
Ok(())
}
fn verify_native_effect(
&self,
handoff: &Handoff,
delegation: &UpdateDelegation,
effect: &NativeEffect,
stage: NativeEffectStage,
) -> Result<()> {
ensure!(
handoff.bytes()? == self.original.handoff().bytes()?
&& delegation == self.original.delegation(),
"UPDATE_NATIVE_ORIGINAL_CHANGED"
);
self.original
.check_current(self.binding, self.clock, self.budget)?;
self.updater.verify_delegation(delegation, self.budget)?;
self.os.verify_for_effect(self.budget)?;
self.retained.verify()?;
let role = |role: &NativeFileRole| match role {
NativeFileRole::AgentBinary => rmm_updater_handoff::FileRole::AgentBinary,
NativeFileRole::HelperBinary => rmm_updater_handoff::FileRole::HelperBinary,
NativeFileRole::FullConfig => rmm_updater_handoff::FileRole::LinuxFullConfig,
NativeFileRole::FullPin => rmm_updater_handoff::FileRole::LinuxFullPin,
};
match (effect, stage) {
(NativeEffect::SavePredecessor { role: r }, NativeEffectStage::Claim) => {
self.files.verify_original_and_stage(role(r), self.budget)?
}
(NativeEffect::SavePredecessor { role: r }, NativeEffectStage::Observe)
| (NativeEffect::PublishReplacement { role: r }, NativeEffectStage::Claim) => {
self.files.verify_saved(role(r), self.budget)?
}
(NativeEffect::PublishReplacement { role: r }, NativeEffectStage::Observe) => {
self.files.verify_replaced(role(r), self.budget)?
}
(NativeEffect::ReturnLedger, NativeEffectStage::Claim)
| (NativeEffect::StartService { .. }, NativeEffectStage::ReserveFutureStart) => {
self.files.verify_pair(self.budget)?
}
_ => anyhow::bail!("UPDATE_NATIVE_OWNED_EFFECT_DENIED"),
}
Ok(())
}
}
+12
View File
@@ -0,0 +1,12 @@
//! Concrete, original-attempt-bound Linux worker. No approval or retry path.
#![cfg(target_os = "linux")]
pub mod clock;
pub mod fence;
pub mod files;
pub mod full;
pub mod ledger;
pub mod original;
pub mod participants;
pub mod retained;
pub mod trust;
+191
View File
@@ -0,0 +1,191 @@
//! Independently reverify the retained ORIGINAL request, never an IPC-supplied
//! approval bit, a replacement request or a renewed start window.
use anyhow::{Result, ensure};
use rmm_agent_core::{
auth::{Binding, Request},
reconcile::SyncClock,
};
use rmm_domain::{
agent_update::{ParticipantRole, ResolvedAgentUpdate, UpdateDelegation},
jobs::{Action, ExecutionPermitPayload, JobPayload, hash},
};
use rmm_updater_handoff::{Handoff, PinTransition, Service};
use rmm_updater_linux::Budget;
pub struct Original {
request: Request,
permit: ExecutionPermitPayload,
job: JobPayload,
update: ResolvedAgentUpdate,
handoff: Handoff,
delegation: UpdateDelegation,
start_bytes: Vec<u8>,
}
impl Original {
/// `start_bytes` must come from execution_evidence.start in the SAME
/// existing guarded ledger. This is validation only; callers must re-read
/// and compare that immutable row at each subsequent guarded operation.
pub fn verify(
binding: &Binding,
start_bytes: &[u8],
record: &[u8],
delegation: UpdateDelegation,
clock: &impl SyncClock,
budget: &Budget,
) -> Result<Self> {
ensure!(
!start_bytes.is_empty()
&& start_bytes.len() <= 512 * 1024
&& !record.is_empty()
&& record.len() <= rmm_updater_handoff::MAX_RECORD_BYTES,
"UPDATE_ORIGINAL_LIMIT"
);
budget.check()?;
let handoff: Handoff = serde_json::from_slice(record)?;
handoff.validate()?;
ensure!(
handoff.bytes()? == record
&& delegation.validate()
&& delegation.handoff_sha256 == hash(record)
&& delegation.owner_nonce == handoff.owner_nonce
&& delegation.boot_id == handoff.boot_id
&& delegation.updater.role == ParticipantRole::LinuxUpdater
&& delegation.updater.image_sha256 == handoff.updater_sha256
&& delegation.original_helper.image_sha256 == handoff.predecessor.helper_sha256
&& u64::try_from(delegation.prepared_at.timestamp())? == handoff.consumed_at,
"UPDATE_ORIGINAL_DELEGATION"
);
let start: serde_json::Value = serde_json::from_slice(start_bytes)?;
let request: Request = serde_json::from_value(start["request"].clone())?;
ensure!(
hash(start_bytes) == handoff.attempt.original_start_witness_sha256
&& hash(&serde_json::to_vec(&request)?) == handoff.attempt.original_request_sha256,
"UPDATE_ORIGINAL_START_CHANGED"
);
// Original consumption happened at the immutable prepared_at. It must
// have had a valid live start grant THEN. Current checks below constrain
// this one already consumed attempt; they grant no new start window.
let (job, permit) = binding.verify(&request, delegation.prepared_at)?;
ensure!(
rmm_agent_core::ledger::start_witness_bytes(
&permit,
&request,
handoff.boot_id,
delegation.prepared_at
)? == start_bytes
&& std::fs::read_to_string("/proc/sys/kernel/random/boot_id")?
.trim()
.parse::<uuid::Uuid>()?
== handoff.boot_id,
"UPDATE_ORIGINAL_START_OR_BOOT_CHANGED"
);
ensure!(
job.execution_identity == "root"
&& permit.action == "update_agent"
&& Some(handoff.attempt.plan_id) == permit.agent_update_plan_id
&& handoff.attempt.tenant_id == permit.tenant_id
&& handoff.attempt.asset_id == permit.asset_id
&& handoff.attempt.agent_id == permit.agent_id
&& handoff.attempt.enrollment_generation == permit.enrollment_generation
&& handoff.attempt.assignment_version == permit.assignment_version
&& handoff.attempt.job_id == permit.job_id
&& handoff.attempt.attempt_id == permit.attempt_id
&& handoff.attempt.grant_id == permit.grant_id
&& handoff.attempt.authorization_id == permit.authorization_id
&& handoff.attempt.plan_sha256 == permit.plan_hash
&& handoff.attempt.job_payload_sha256 == permit.job_payload_hash,
"UPDATE_ORIGINAL_JOB_BINDING"
);
let Action::UpdateAgent { update } = &job.action else {
anyhow::bail!("UPDATE_ACTION_REQUIRED")
};
ensure!(
rmm_domain::agent_update::handoff_matches_job(&handoff, &job)
&& update.validate()
&& update.manifest_sha256 == handoff.target.manifest_sha256
&& update.predecessor.manifest_sha256 == handoff.predecessor.manifest_sha256
&& update.predecessor.agent_sha256 == handoff.predecessor.agent_sha256
&& update.predecessor.helper_sha256 == handoff.predecessor.helper_sha256
&& update.predecessor.installed_record_sha256 == handoff.predecessor_record_sha256
&& update.updater.binary_sha256 == handoff.updater_sha256
&& update.updater.policy_sha256 == handoff.updater_policy_sha256
&& matches!(handoff.pin_transition, PinTransition::LinuxGeneralFullV1)
&& (handoff.stop_set
== [
Service::LinuxAgent,
Service::LinuxGeneralHelper,
Service::LinuxFullHelper
]
|| handoff.stop_set
== [
Service::LinuxAgent,
Service::LinuxGeneralHelper,
Service::LinuxFullHelper,
Service::LinuxAptHelper
]),
"UPDATE_ORIGINAL_CODE_POLICY_BINDING"
);
let update = update.as_ref().clone();
let decoded = update
.release_envelope
.decode()
.map_err(anyhow::Error::msg)?;
ensure!(
decoded.manifest.artifacts[0].sha256 == handoff.target.agent_sha256
&& decoded.manifest.artifacts[1].sha256 == handoff.target.helper_sha256,
"UPDATE_ORIGINAL_TARGET_PAIR"
);
let result = Self {
request,
permit,
job,
update,
handoff,
delegation,
start_bytes: start_bytes.to_vec(),
};
result.check_current(binding, clock, budget)?;
Ok(result)
}
pub fn check_current(
&self,
binding: &Binding,
clock: &impl SyncClock,
budget: &Budget,
) -> Result<()> {
budget.check()?;
let now = clock.now()?;
ensure!(
now >= self.delegation.prepared_at
&& u64::try_from(now.timestamp())? < self.handoff.finish_before
&& now
< self.job.start_before
+ chrono::Duration::seconds(i64::from(self.job.max_runtime_seconds))
&& self.handoff.finish_before
<= self.handoff.consumed_at + u64::from(self.job.max_runtime_seconds),
"UPDATE_ORIGINAL_EXPIRED"
);
let (job, permit) = binding.verify(&self.request, self.delegation.prepared_at)?;
ensure!(
serde_json::to_vec(&job)? == serde_json::to_vec(&self.job)?
&& serde_json::to_vec(&permit)? == serde_json::to_vec(&self.permit)?,
"UPDATE_ORIGINAL_CHANGED"
);
Ok(())
}
pub fn handoff(&self) -> &Handoff {
&self.handoff
}
pub fn delegation(&self) -> &UpdateDelegation {
&self.delegation
}
pub fn update(&self) -> &ResolvedAgentUpdate {
&self.update
}
pub fn permit(&self) -> &ExecutionPermitPayload {
&self.permit
}
pub fn start_bytes(&self) -> &[u8] {
&self.start_bytes
}
}
+78
View File
@@ -0,0 +1,78 @@
//! Concrete native service/process binding. A denied /proc read is a denial;
//! UID0, process names and installed file hashes are never image fallbacks.
use anyhow::{Result, ensure};
use rmm_domain::{
agent_update::{ParticipantIdentity, ParticipantRole, UpdateDelegation},
jobs::hash,
};
use rmm_updater_linux::{
Budget,
services::{HeldService, Service, ServicePolicy, Systemd},
};
pub struct StableParticipant {
held: HeldService,
identity: ParticipantIdentity,
}
impl StableParticipant {
pub fn observe(policy: ServicePolicy, budget: &Budget) -> Result<Self> {
let held = Systemd::observe_updater(policy, budget)?;
let proof = held.proof();
ensure!(
proof.process.pid == std::process::id()
&& proof.process.uid == 0
&& proof.process.gid == 0,
"UPDATE_WORKER_MUST_BE_EXACT_STABLE_SERVICE"
);
let identity = ParticipantIdentity {
role: ParticipantRole::LinuxUpdater,
pid: proof.process.pid,
birth: proof.process.birth,
image_sha256: proof.process.image_sha256.clone(),
security_principal: "uid:0".into(),
service_instance_sha256: hash(&serde_json::to_vec(proof)?),
};
ensure!(identity.validate(), "UPDATE_WORKER_IDENTITY");
Ok(Self { held, identity })
}
pub fn verify_delegation(&self, delegation: &UpdateDelegation, budget: &Budget) -> Result<()> {
self.held.verify(budget)?;
ensure!(
delegation.validate() && delegation.updater == self.identity,
"UPDATE_WORKER_DELEGATION_CHANGED"
);
Ok(())
}
pub fn identity(&self) -> &ParticipantIdentity {
&self.identity
}
}
/// Before stopping the independently checking original helper, compare its
/// actual concrete process instance with the immutable atomic delegation.
pub fn verify_original_helper(
services: &Systemd,
delegation: &UpdateDelegation,
budget: &Budget,
) -> Result<HeldService> {
ensure!(delegation.validate(), "UPDATE_ORIGINAL_DELEGATION");
let service = match delegation.original_helper.role {
ParticipantRole::LinuxGeneralHelper => Service::General,
ParticipantRole::LinuxFullHelper => Service::Full,
_ => anyhow::bail!("UPDATE_ORIGINAL_LINUX_HELPER_REQUIRED"),
};
let held = services.observe(service, budget)?;
let proof = held.proof();
let expected = &delegation.original_helper;
ensure!(
proof.process.pid == expected.pid
&& proof.process.birth == expected.birth
&& proof.process.image_sha256 == expected.image_sha256
&& proof.process.uid == 0
&& expected.security_principal == "uid:0"
&& hash(&serde_json::to_vec(proof)?) == expected.service_instance_sha256,
"UPDATE_ORIGINAL_HELPER_INSTANCE_CHANGED"
);
held.verify(budget)?;
Ok(held)
}
+163
View File
@@ -0,0 +1,163 @@
//! Held state identities without reading/exporting private key contents.
//! Paths must come from independently provisioned LOCAL policy, never IPC/jobs.
use anyhow::{Context, Result, ensure};
use rmm_domain::jobs::hash;
use rmm_updater_linux::files::{Directory, Identity};
use serde::{Deserialize, Serialize};
use std::{
fs::File,
os::unix::fs::{MetadataExt, OpenOptionsExt},
path::{Path, PathBuf},
};
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Retention {
/// Journal content is expected to advance, but the actual file stays held.
MutableDatabase,
/// Keys/configs remain byte-unread: additionally bind size/mtime/ctime.
ImmutableMetadata,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RetainedFileSpec {
pub path: PathBuf,
pub parent_uid: u32,
pub identity: Identity,
pub retention: Retention,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
struct Stamp {
size: u64,
mtime: i64,
mtime_nsec: i64,
ctime: i64,
ctime_nsec: i64,
}
impl Stamp {
fn of(meta: &std::fs::Metadata) -> Self {
Self {
size: meta.len(),
mtime: meta.mtime(),
mtime_nsec: meta.mtime_nsec(),
ctime: meta.ctime(),
ctime_nsec: meta.ctime_nsec(),
}
}
}
struct HeldState {
spec: RetainedFileSpec,
directory: Directory,
file: File,
stamp: Stamp,
}
pub struct RetainedSet {
files: Vec<HeldState>,
digest: String,
}
impl RetainedSet {
pub fn capture(specs: Vec<RetainedFileSpec>) -> Result<Self> {
ensure!(
!specs.is_empty() && specs.len() <= 64,
"UPDATE_RETAINED_FILESET_LIMIT"
);
let mut files = Vec::new();
for spec in specs {
ensure!(
spec.path.is_absolute()
&& spec.path.components().all(|c| matches!(
c,
std::path::Component::RootDir | std::path::Component::Normal(_)
))
&& !files.iter().any(|v: &HeldState| v.spec.path == spec.path),
"UPDATE_RETAINED_PATH"
);
// No state-reset/namespace substitution and no effect code files in
// this preservation set. Historical bound hardlinks are allowed.
ensure!(
![
rmm_updater_linux::files::Role::Agent,
rmm_updater_linux::files::Role::Helper,
rmm_updater_linux::files::Role::FullConfig,
rmm_updater_linux::files::Role::FullPin
]
.iter()
.any(|role| Path::new(role.target()) == spec.path),
"UPDATE_RETAINED_CODE_PATH"
);
let parent = spec.path.parent().context("UPDATE_RETAINED_PARENT")?;
let directory = Directory::open(parent, spec.parent_uid, false)?;
let file = std::fs::OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC)
.open(&spec.path)?;
let stamp = Stamp::of(&file.metadata()?);
let held = HeldState {
spec,
directory,
file,
stamp,
};
held.verify()?;
files.push(held);
}
let serial: Vec<_> = files
.iter()
.map(|f| {
(
&f.spec,
if f.spec.retention == Retention::ImmutableMetadata {
Some(&f.stamp)
} else {
None
},
)
})
.collect();
let digest = hash(&serde_json::to_vec(&serial)?);
Ok(Self { files, digest })
}
pub fn sha256(&self) -> &str {
&self.digest
}
pub fn verify(&self) -> Result<()> {
for file in &self.files {
file.verify()?;
}
Ok(())
}
}
fn identity(meta: &std::fs::Metadata) -> Identity {
Identity {
device: meta.dev(),
inode: meta.ino(),
uid: meta.uid(),
gid: meta.gid(),
mode: meta.mode(),
links: meta.nlink(),
}
}
impl HeldState {
fn verify(&self) -> Result<()> {
self.directory.verify()?;
let held = self.file.metadata()?;
let named = std::fs::symlink_metadata(&self.spec.path)?;
ensure!(
held.is_file()
&& named.is_file()
&& !named.file_type().is_symlink()
&& identity(&held) == self.spec.identity
&& identity(&named) == self.spec.identity
&& held.mode() & 0o022 == 0
&& held.nlink() > 0,
"UPDATE_RETAINED_IDENTITY_CHANGED"
);
if self.spec.retention == Retention::ImmutableMetadata {
ensure!(
Stamp::of(&held) == self.stamp && Stamp::of(&named) == self.stamp,
"UPDATE_RETAINED_METADATA_CHANGED"
);
}
self.directory.verify()
}
}
+428
View File
@@ -0,0 +1,428 @@
//! Actual protected local policy/keyring/health/baseline verification. No key
//! returned in a job/manifest is promoted to trust and no floor is guessed.
use crate::{clock::NativeClock, original::Original};
use anyhow::{Context, Result, ensure};
use ed25519_dalek::{Signature, VerifyingKey};
use rmm_agent_core::{auth::Binding, reconcile::SyncClock};
use rmm_domain::{
agent_update::{Platform, UpdateKeyringFile},
agent_update_provisioning::{
ActivationEvidence, BASELINE_SIGNATURE_DOMAIN, HealthKeyPin, InstalledReleaseRecord,
LocalUpdatePolicy,
},
jobs::hash,
};
use rmm_updater::{
ActiveRelease, Platform as ReleasePlatform, SignedRelease, TrustedContext, TrustedUpdateKey,
UpdateKeyring, verify_release,
};
use rmm_updater_linux::files::{Directory, HeldFile};
use std::{ffi::OsStr, path::Path};
struct Protected {
dir: Directory,
file: HeldFile,
name: String,
max: u64,
}
impl Protected {
fn read(path: &Path, max: u64) -> Result<(Self, Vec<u8>)> {
let dir = Directory::open(path.parent().context("UPDATE_TRUST_PARENT")?, 0, false)?;
let name = path
.file_name()
.context("UPDATE_TRUST_NAME")?
.to_str()
.context("UPDATE_TRUST_NAME")?
.to_owned();
let mut file = dir.inspect(OsStr::new(&name), 0, max)?;
let raw = file.bytes(max)?;
Ok((
Self {
dir,
file,
name,
max,
},
raw,
))
}
fn verify(&self) -> Result<()> {
self.dir
.file(OsStr::new(&self.name), self.file.proof(), self.max)?;
Ok(())
}
}
pub struct TrustState {
protected: Vec<Protected>,
policy: LocalUpdatePolicy,
installed: InstalledReleaseRecord,
keyring: UpdateKeyring,
health_public_key: [u8; 32],
}
impl TrustState {
pub fn load(original: &Original, binding: &Binding, clock: &NativeClock) -> Result<Self> {
let update = original.update();
let mut protected = Vec::new();
let (file, raw) = Protected::read(Path::new("/etc/rmm-agent-updater/policy.json"), 65536)?;
let (policy, policy_hash) =
LocalUpdatePolicy::from_bytes(&raw).map_err(anyhow::Error::msg)?;
ensure!(
policy_hash == update.updater.policy_sha256
&& policy.tenant_id == binding.tenant_id
&& policy.asset_id == binding.asset_id
&& policy.agent_id == binding.agent_id
&& policy.enrollment_generation == binding.enrollment_generation
&& policy.assignment_version == binding.assignment_version
&& policy.updater_binary_sha256 == update.updater.binary_sha256,
"UPDATE_PROTECTED_POLICY_CHANGED"
);
protected.push(file);
let (file, raw) = Protected::read(Path::new(&policy.keyring_path), 16384)?;
let keys: UpdateKeyringFile = serde_json::from_slice(&raw)?;
ensure!(
keys.validate()
&& keys.generation == update.updater.keyring_generation
&& hash(&raw) == update.updater.keyring_sha256,
"UPDATE_PROTECTED_KEYRING_CHANGED"
);
protected.push(file);
let job_key = hex::decode(&binding.public_key_hex)?;
let mut trusted = Vec::new();
let mut baseline_key = None;
for entry in &keys.keys {
ensure!(entry.platform == Platform::LinuxX64, "UPDATE_KEY_PLATFORM");
let public: [u8; 32] = hex::decode(&entry.public_key_hex)?
.try_into()
.map_err(|_| anyhow::anyhow!("UPDATE_KEY_SIZE"))?;
ensure!(
public.as_slice() != job_key,
"UPDATE_JOB_RELEASE_KEYS_NOT_SEPARATE"
);
if hash(&public) == policy.initial_baseline.key_id {
baseline_key = Some((entry, public));
}
trusted.push(TrustedUpdateKey::new(
public,
ReleasePlatform::LinuxX64,
entry.first_sequence,
entry.last_sequence,
entry.revoked,
)?);
}
let keyring = UpdateKeyring::new(keys.generation, trusted)?;
let baseline = policy
.initial_baseline
.decode()
.map_err(anyhow::Error::msg)?;
let (baseline_entry, public) = baseline_key.context("UPDATE_BASELINE_KEY_NOT_TRUSTED")?;
ensure!(
!baseline_entry.revoked
&& baseline
.record
.release_envelope
.decode()
.map_err(anyhow::Error::msg)?
.manifest
.release_sequence
>= baseline_entry.first_sequence
&& baseline
.record
.release_envelope
.decode()
.map_err(anyhow::Error::msg)?
.manifest
.release_sequence
<= baseline_entry.last_sequence,
"UPDATE_BASELINE_KEY_REVOKED_OR_RANGE"
);
let public = VerifyingKey::from_bytes(&public)?;
ensure!(!public.is_weak(), "UPDATE_BASELINE_WEAK_KEY");
let mut message = BASELINE_SIGNATURE_DOMAIN.to_vec();
message.extend_from_slice(&baseline.payload_bytes);
public.verify_strict(&message, &Signature::from_bytes(&baseline.signature))?;
let (file, raw) = Protected::read(Path::new(&policy.health_pin_path), 4096)?;
let health: HealthKeyPin = serde_json::from_slice(&raw)?;
let health_public_key = health.public_key().map_err(anyhow::Error::msg)?;
ensure!(
!VerifyingKey::from_bytes(&health_public_key)?.is_weak()
&& hash(&raw) == update.updater.health_key_pin_sha256
&& hex::encode(health_public_key) == update.updater.health_public_key_hex
&& health_public_key.as_slice() != job_key
&& keys
.keys
.iter()
.all(|key| key.public_key_hex != hex::encode(health_public_key)),
"UPDATE_HEALTH_KEY_NOT_SEPARATE_OR_CHANGED"
);
protected.push(file);
let (file, raw) = Protected::read(Path::new(&policy.installed_record_path), 32768)?;
ensure!(
hash(&raw) == update.predecessor.installed_record_sha256,
"UPDATE_INSTALLED_RECORD_CHANGED"
);
let installed = InstalledReleaseRecord::from_bytes(&raw).map_err(anyhow::Error::msg)?;
// This first concrete activation is bootstrap-bound. A future Updated
// predecessor must have its complete guarded Health/record chain proved;
// never accept its mutable fields merely because parsing succeeded.
ensure!(
matches!(
installed.activation_evidence,
ActivationEvidence::Bootstrap { .. }
) && raw == baseline.payload_bytes
&& hash(&raw) == policy.initial_record_sha256
&& installed.activation_floor == policy.initial_activation_floor,
"UPDATE_INSTALLED_CHAIN_NOT_QUALIFIED"
);
let active = installed
.release_envelope
.decode()
.map_err(anyhow::Error::msg)?;
ensure!(
active.manifest.release_id == update.predecessor.release_id
&& active.manifest.release_sequence == update.predecessor.release_sequence
&& installed.manifest_sha256 == update.predecessor.manifest_sha256
&& active.manifest.artifacts[0].sha256 == update.predecessor.agent_sha256
&& active.manifest.artifacts[1].sha256 == update.predecessor.helper_sha256,
"UPDATE_INSTALLED_PREDECESSOR_BINDING"
);
verify_installed_release(&keyring, &installed, keys.generation)?;
verify(
&keyring,
&update.release_envelope,
&TrustedContext {
platform: ReleasePlatform::LinuxX64,
now_utc_seconds: u64::try_from(clock.now()?.timestamp())?,
keyring_generation: keys.generation,
protocol_major: active.manifest.protocol_major,
state_schema: active.manifest.state_schema,
updater_version: 1,
minimum_release_sequence: installed.activation_floor,
active_release: Some(ActiveRelease {
sequence: active.manifest.release_sequence,
manifest_sha256: installed.manifest_sha256.clone(),
}),
},
)?;
protected.push(file);
Ok(Self {
protected,
policy,
installed,
keyring,
health_public_key,
})
}
pub fn recheck(&self, original: &Original, clock: &NativeClock) -> Result<()> {
for file in &self.protected {
file.verify()?;
}
let active = self
.installed
.release_envelope
.decode()
.map_err(anyhow::Error::msg)?;
verify(
&self.keyring,
&original.update().release_envelope,
&TrustedContext {
platform: ReleasePlatform::LinuxX64,
now_utc_seconds: u64::try_from(clock.now()?.timestamp())?,
keyring_generation: original.update().updater.keyring_generation,
protocol_major: active.manifest.protocol_major,
state_schema: active.manifest.state_schema,
updater_version: 1,
minimum_release_sequence: self.installed.activation_floor,
active_release: Some(ActiveRelease {
sequence: active.manifest.release_sequence,
manifest_sha256: self.installed.manifest_sha256.clone(),
}),
},
)
}
pub fn policy(&self) -> &LocalUpdatePolicy {
&self.policy
}
pub fn health_public_key(&self) -> [u8; 32] {
self.health_public_key
}
}
fn verify(
keyring: &UpdateKeyring,
envelope: &rmm_domain::agent_update::ReleaseEnvelope,
context: &TrustedContext,
) -> Result<()> {
let decoded = envelope.decode().map_err(anyhow::Error::msg)?;
verify_release(
SignedRelease {
schema_version: envelope.schema_version,
key_id: &envelope.key_id,
payload_bytes: &decoded.payload_bytes,
signature: &decoded.signature,
},
keyring,
context,
)?;
Ok(())
}
fn verify_installed_release(
keyring: &UpdateKeyring,
installed: &InstalledReleaseRecord,
generation: u64,
) -> Result<()> {
let active = installed
.release_envelope
.decode()
.map_err(anyhow::Error::msg)?;
verify(
keyring,
&installed.release_envelope,
&TrustedContext {
platform: ReleasePlatform::LinuxX64,
now_utc_seconds: installed.activated_at,
keyring_generation: generation,
protocol_major: active.manifest.protocol_major,
state_schema: active.manifest.state_schema,
updater_version: 1,
minimum_release_sequence: installed.activation_floor,
active_release: Some(ActiveRelease {
sequence: active.manifest.release_sequence,
manifest_sha256: installed.manifest_sha256.clone(),
}),
},
)
}
#[cfg(test)]
mod tests {
use super::*;
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use ed25519_dalek::{Signer, SigningKey};
use rmm_domain::agent_update::{
ArtifactDescriptor, ArtifactRole, ReleaseEnvelope, ReleaseManifest,
};
use rmm_domain::agent_update_provisioning::SignedBaselineRecord;
use uuid::Uuid;
fn release(sequence: u64, published: u64, expires: u64) -> ReleaseEnvelope {
let signer = SigningKey::from_bytes(&[83; 32]); // public TEST fixture only
let manifest = ReleaseManifest {
schema_version: 1,
release_id: Uuid::from_u128(u128::from(sequence)),
release_sequence: sequence,
version: format!("test-{sequence}"),
platform: Platform::LinuxX64,
published_at: published,
expires_at: expires,
protocol_major: 1,
state_schema: 1,
minimum_updater_version: 1,
artifacts: [
ArtifactDescriptor {
role: ArtifactRole::Agent,
artifact_id: Uuid::from_u128(101),
sha256: hash(b"test agent"),
bytes: 10,
},
ArtifactDescriptor {
role: ArtifactRole::Helper,
artifact_id: Uuid::from_u128(102),
sha256: hash(b"test helper"),
bytes: 11,
},
],
};
let raw = serde_json::to_vec(&manifest).unwrap();
let mut signed = rmm_updater::RELEASE_SIGNATURE_DOMAIN.to_vec();
signed.extend_from_slice(&raw);
ReleaseEnvelope {
schema_version: 1,
key_id: hash(signer.verifying_key().as_bytes()),
payload_bytes: URL_SAFE_NO_PAD.encode(raw),
signature: URL_SAFE_NO_PAD.encode(signer.sign(&signed).to_bytes()),
}
}
#[test]
fn separately_signed_baseline_at_floor_is_historical_only_and_candidate_stays_strict() {
let signer = SigningKey::from_bytes(&[83; 32]);
let keyring = UpdateKeyring::new(
7,
vec![
TrustedUpdateKey::new(
signer.verifying_key().to_bytes(),
ReleasePlatform::LinuxX64,
1,
20,
false,
)
.unwrap(),
],
)
.unwrap();
let envelope = release(7, 90, 110);
let record = InstalledReleaseRecord {
schema_version: 1,
profile: "decoder_compatible_handoff_v1".into(),
platform: Platform::LinuxX64,
manifest_sha256: hash(&envelope.decode().unwrap().payload_bytes),
release_envelope: envelope,
activation_floor: 7,
activated_at: 95,
previous_record_sha256: None,
activation_evidence: ActivationEvidence::Bootstrap {
qualification_receipt_sha256: hash(b"local synthetic qualification receipt"),
},
rolled_back: false,
};
let raw = record.bytes().unwrap();
let mut message = BASELINE_SIGNATURE_DOMAIN.to_vec();
message.extend_from_slice(&raw);
let baseline = SignedBaselineRecord {
schema_version: 1,
key_id: hash(signer.verifying_key().as_bytes()),
payload_bytes: URL_SAFE_NO_PAD.encode(&raw),
signature: URL_SAFE_NO_PAD.encode(signer.sign(&message).to_bytes()),
};
let decoded = baseline.decode().unwrap();
signer
.verifying_key()
.verify_strict(&message, &Signature::from_bytes(&decoded.signature))
.unwrap();
assert_eq!(decoded.payload_bytes, raw);
// Exercise the ACTUAL production context builder, where None at the
// confirmed floor previously rejected every legitimate initial record.
verify_installed_release(&keyring, &decoded.record, 7).unwrap();
let candidate_context = TrustedContext {
platform: ReleasePlatform::LinuxX64,
now_utc_seconds: 200,
keyring_generation: 7,
protocol_major: 1,
state_schema: 1,
updater_version: 1,
minimum_release_sequence: 7,
active_release: Some(ActiveRelease {
sequence: 7,
manifest_sha256: record.manifest_sha256.clone(),
}),
};
verify(&keyring, &release(8, 190, 210), &candidate_context).unwrap();
assert!(verify(&keyring, &release(7, 190, 210), &candidate_context).is_err());
assert!(verify(&keyring, &record.release_envelope, &candidate_context).is_err());
assert!(verify(&keyring, &release(6, 190, 210), &candidate_context).is_err());
let revoked = UpdateKeyring::new(
7,
vec![
TrustedUpdateKey::new(
signer.verifying_key().to_bytes(),
ReleasePlatform::LinuxX64,
1,
20,
true,
)
.unwrap(),
],
)
.unwrap();
assert!(verify_installed_release(&revoked, &record, 7).is_err());
}
}