//! Shared Windows protected update trust. No network input provisions a key, //! policy, floor, baseline or compatible-reader qualification. SYSTEM helper //! and stable updater each open these exact files independently. use crate::helper_ipc::{self as ipc, PinnedFile}; use anyhow::{Context, Result, ensure}; use ed25519_dalek::{Signature, VerifyingKey}; use rmm_agent_core::{auth::Binding, helper_reconcile::ExecutorLedgerGuard, reconcile::SyncClock}; use rmm_domain::{ agent_update::{ResolvedAgentUpdate, UpdateKeyringFile}, agent_update_provisioning::{ ActivationEvidence, BASELINE_SIGNATURE_DOMAIN, HealthKeyPin, InstalledReleaseRecord, LocalUpdatePolicy, }, jobs::hash, }; use rmm_updater::{ ActiveRelease, SignedRelease, TrustedContext, TrustedUpdateKey, UpdateKeyring, verify_release, }; use std::{cell::RefCell, io::Read, path::Path}; pub(crate) struct Protected { file: RefCell, root: RefCell, sha256: String, } impl Protected { pub(crate) fn read(path: &Path, max: u64) -> Result<(Self, Vec)> { Self::read_shared(path, max, &[]) } pub(crate) fn read_shared( path: &Path, max: u64, readers: &[String], ) -> Result<(Self, Vec)> { let root = PinnedFile::open( path.parent().context("UPDATE_TRUST_PARENT")?, true, readers, &[], false, )?; let mut file = PinnedFile::open(path, false, readers, &[], false)?; ensure!( file.file.metadata()?.len() <= max, "UPDATE_TRUST_FILE_LIMIT" ); let mut raw = Vec::new(); (&mut file.file).take(max + 1).read_to_end(&mut raw)?; ensure!(raw.len() as u64 <= max, "UPDATE_TRUST_FILE_LIMIT"); file.check()?; Ok(( Self { file: RefCell::new(file), root: RefCell::new(root), sha256: hash(&raw), }, raw, )) } pub(crate) fn verify(&self) -> Result<()> { self.root.try_borrow_mut()?.check()?; let mut file = self.file.try_borrow_mut()?; file.check()?; ensure!(file.sha256()? == self.sha256, "UPDATE_TRUST_BYTES_CHANGED"); Ok(()) } } pub struct TrustState { updater_binding: rmm_domain::agent_update::UpdaterBinding, predecessor: rmm_domain::agent_update::Predecessor, protected: Vec, policy: LocalUpdatePolicy, installed: InstalledReleaseRecord, installed_raw: Vec, installed_pin: RefCell>, keyring: UpdateKeyring, keyring_file: UpdateKeyringFile, baseline_signer_revoked: bool, health_public_key: [u8; 32], } impl TrustState { pub fn load_prepared( update: &ResolvedAgentUpdate, binding: &Binding, clock: &crate::signed_clock::BoundClock, ) -> Result { ensure!( update.validate() && update.execution_identity() == Some("system"), "UPDATE_PREPARED_ACTION" ); let state = Self::load_inputs(Some(update), binding, clock.now()?)?; state.recheck_prepared(update, clock)?; Ok(state) } pub fn load_retained( update: &ResolvedAgentUpdate, binding: &Binding, prepared_at: chrono::DateTime, ) -> Result { ensure!( update.validate() && update.execution_identity() == Some("system"), "UPDATE_RETAINED_ACTION" ); Self::load_inputs(Some(update), binding, prepared_at) } /// Passive protected originals only. No candidate, staging, admission or /// synthetic execution plan is used to discover the installed trust state. pub fn load_observed( binding: &Binding, clock: &crate::signed_clock::BoundClock, ) -> Result { let state = Self::load_inputs(None, binding, clock.now()?)?; ensure!( !state.baseline_signer_revoked, "UPDATE_BASELINE_SIGNER_REVOKED" ); verify_installed_release( &state.keyring, &state.installed, state.updater_binding.keyring_generation, )?; state.recheck_protected()?; Ok(state) } fn load_inputs( expected: Option<&ResolvedAgentUpdate>, binding: &Binding, prepared_at: chrono::DateTime, ) -> Result { let mut protected = Vec::new(); let (file, raw) = Protected::read( Path::new(r"C:\ProgramData\RustDiscoveryUpdater\policy.json"), 65536, )?; let (policy, policy_hash) = LocalUpdatePolicy::from_bytes(&raw).map_err(anyhow::Error::msg)?; ensure!( policy.schema_version == 2 && policy.profile == "windows_code_pair_clock_v1" && 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, "UPDATE_PROTECTED_POLICY_CHANGED" ); protected.push(file); let (file, raw) = Protected::read(Path::new(&policy.registry_path), 65536)?; ensure!( hash(&raw) == policy.reader_registry_sha256, "UPDATE_PROTECTED_READER_REGISTRY_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(), "UPDATE_PROTECTED_KEYRING_CHANGED"); let keyring_sha256 = hash(&raw); protected.push(file); let job_key = hex::decode(&binding.public_key_hex)?; let mut trusted = Vec::new(); let mut historical_keys = Vec::new(); let mut baseline_key = None; for entry in &keys.keys { ensure!( entry.platform == crate::release_platform::WIRE, "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, crate::release_platform::VERIFY, entry.first_sequence, entry.last_sequence, entry.revoked, )?); historical_keys.push(TrustedUpdateKey::new( public, crate::release_platform::VERIFY, entry.first_sequence, entry.last_sequence, false, )?); } let keyring = UpdateKeyring::new(keys.generation, trusted)?; let historical = UpdateKeyring::new(keys.generation, historical_keys)?; 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 .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() && 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" ); let updater_binding = rmm_domain::agent_update::UpdaterBinding { binary_sha256: policy.updater_binary_sha256.clone(), policy_sha256: policy_hash, keyring_generation: keys.generation, keyring_sha256, health_public_key_hex: hex::encode(health_public_key), health_key_pin_sha256: hash(&raw), }; protected.push(file); let (file, raw) = Protected::read(Path::new(&policy.installed_record_path), 32768)?; let installed = InstalledReleaseRecord::from_bytes(&raw).map_err(anyhow::Error::msg)?; ensure!( !installed.rolled_back && installed.activation_floor >= policy.initial_activation_floor && installed.activated_at <= u64::try_from(prepared_at.timestamp())?, "UPDATE_INSTALLED_FLOOR_OR_TIME" ); if matches!( installed.activation_evidence, ActivationEvidence::Bootstrap { .. } ) { ensure!( raw == baseline.payload_bytes && hash(&raw) == policy.initial_record_sha256 && installed.activation_floor == policy.initial_activation_floor, "UPDATE_INSTALLED_BASELINE_CHANGED" ); } let active = installed .release_envelope .decode() .map_err(anyhow::Error::msg)?; let predecessor = rmm_domain::agent_update::Predecessor { release_id: active.manifest.release_id, release_sequence: active.manifest.release_sequence, manifest_sha256: installed.manifest_sha256.clone(), installed_record_sha256: hash(&raw), agent_sha256: active.manifest.artifacts[0].sha256.clone(), helper_sha256: active.manifest.artifacts[1].sha256.clone(), }; verify_installed_release(&historical, &installed, keys.generation)?; if let Some(update) = expected { ensure!( update.updater == updater_binding && update.predecessor == predecessor, "UPDATE_INSTALLED_PREDECESSOR_OR_TRUST_BINDING" ); verify( &historical, &update.release_envelope, &TrustedContext { platform: crate::release_platform::VERIFY, now_utc_seconds: u64::try_from(prepared_at.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(), }), }, )?; } let installed_pin = RefCell::new(Some(file)); let baseline_signer_revoked = baseline_entry.revoked; Ok(Self { updater_binding, predecessor, protected, policy, installed, installed_raw: raw, installed_pin, keyring, keyring_file: keys, baseline_signer_revoked, health_public_key, }) } pub fn recheck_prepared( &self, update: &ResolvedAgentUpdate, clock: &crate::signed_clock::BoundClock, ) -> Result<()> { self.recheck_protected()?; self.recheck_crypto(update, clock) } pub(crate) fn recheck_crypto( &self, update: &ResolvedAgentUpdate, clock: &crate::signed_clock::BoundClock, ) -> Result<()> { ensure!( update.updater == self.updater_binding && update.predecessor == self.predecessor, "UPDATE_TRUST_CONTEXT_CHANGED" ); ensure!( !self.baseline_signer_revoked, "UPDATE_BASELINE_SIGNER_REVOKED" ); verify_installed_release( &self.keyring, &self.installed, update.updater.keyring_generation, )?; let active = self .installed .release_envelope .decode() .map_err(anyhow::Error::msg)?; let (lower, upper) = clock.bounds()?; for now in [lower, upper] { verify( &self.keyring, &update.release_envelope, &TrustedContext { platform: crate::release_platform::VERIFY, now_utc_seconds: u64::try_from(now.timestamp())?, keyring_generation: 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(), }), }, )?; } Ok(()) } pub fn recheck_protected(&self) -> Result<()> { self.recheck_other_protected()?; self.installed_pin .try_borrow()? .as_ref() .context("UPDATE_INSTALLED_NAMESPACE_PROOF_REQUIRED")? .verify() } pub(crate) fn recheck_other_protected(&self) -> Result<()> { for p in &self.protected { p.verify()?; } Ok(()) } pub(crate) fn release_installed_pin( &self, claim: &rmm_agent_core::update_handoff::NativeEffectClaim, new_sha256: &str, ) -> Result<()> { ensure!( claim.effect() == &rmm_agent_core::update_handoff::NativeEffect::SaveInstalledRecord { old_sha256: hash(&self.installed_raw), new_sha256: new_sha256.into() }, "UPDATE_RECORD_ORIGINAL_SAVE_CLAIM_REQUIRED" ); self.recheck_protected()?; self.installed_pin .try_borrow_mut()? .take() .context("UPDATE_RECORD_PIN_ALREADY_RELEASED")?; Ok(()) } pub fn qualify_history( &self, db: &rusqlite::Connection, guard: &impl ExecutorLedgerGuard, binding: &Binding, ) -> Result<()> { self.recheck_protected()?; let baseline = self .policy .initial_baseline .decode() .map_err(anyhow::Error::msg)?; let baseline_hash = hash(&baseline.payload_bytes); let mut records = Vec::new(); let mut held = Vec::new(); let mut seen = std::collections::BTreeSet::new(); let mut next = self.installed.previous_record_sha256.clone(); let mut total = self.installed_raw.len() + baseline.payload_bytes.len(); while let Some(digest) = next { ensure!( ipc::digest(&digest) && seen.insert(digest.clone()) && seen.len() < 64, "UPDATE_RECORD_ARCHIVE_CHAIN" ); if digest == baseline_hash { break; } let (file, raw) = Protected::read( &Path::new(r"C:\ProgramData\RustDiscoveryUpdater\records") .join(format!("{digest}.json")), 32768, )?; ensure!(hash(&raw) == digest, "UPDATE_RECORD_ARCHIVE_HASH"); total = total .checked_add(raw.len()) .context("UPDATE_RECORD_ARCHIVE_SIZE")?; ensure!(total <= 2 * 1024 * 1024, "UPDATE_RECORD_ARCHIVE_SIZE"); let record = InstalledReleaseRecord::from_bytes(&raw).map_err(anyhow::Error::msg)?; next = record.previous_record_sha256; records.push(raw); held.push(file); } let record = rmm_update_history::verify_history( db, guard, binding, &self.keyring_file, &self.policy.initial_baseline, &records, &self.installed_raw, )?; ensure!( record.bytes().map_err(anyhow::Error::msg)? == self.installed_raw, "UPDATE_HISTORY_ACTIVE_CHANGED" ); for file in held { file.verify()?; } self.recheck_protected() } pub fn predecessor(&self) -> &rmm_domain::agent_update::Predecessor { &self.predecessor } pub fn updater_binding(&self) -> &rmm_domain::agent_update::UpdaterBinding { &self.updater_binding } pub fn activation_floor(&self) -> u64 { self.installed.activation_floor } pub fn verify_candidate( &self, envelope: &rmm_domain::agent_update::ReleaseEnvelope, clock: &crate::signed_clock::BoundClock, ) -> Result<()> { self.recheck_protected()?; ensure!( !self.baseline_signer_revoked, "UPDATE_BASELINE_SIGNER_REVOKED" ); let active = self .installed .release_envelope .decode() .map_err(anyhow::Error::msg)? .manifest; let (lower, upper) = clock.bounds()?; for now in [lower, upper] { verify( &self.keyring, envelope, &TrustedContext { platform: crate::release_platform::VERIFY, now_utc_seconds: u64::try_from(now.timestamp())?, keyring_generation: self.updater_binding.keyring_generation, protocol_major: active.protocol_major, state_schema: active.state_schema, updater_version: 1, minimum_release_sequence: self.installed.activation_floor, active_release: Some(ActiveRelease { sequence: active.release_sequence, manifest_sha256: self.installed.manifest_sha256.clone(), }), }, )?; } self.recheck_protected() } pub fn policy(&self) -> &LocalUpdatePolicy { &self.policy } pub fn installed_raw(&self) -> &[u8] { &self.installed_raw } 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: crate::release_platform::VERIFY, 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(), }), }, ) } /// A released worker READ pin is not an observed record-save effect. Its exact /// original identity/bytes/security must reappear under the archive namespace. pub(crate) struct ReleasedRecordReadPin { original: crate::update_native::files::Proof, } impl ReleasedRecordReadPin { pub(crate) fn verify_archive(&self) -> Result<()> { let path = Path::new(r"C:\ProgramData\RustDiscoveryUpdater\records") .join(format!("{}.json", self.original.sha256)); let (file, raw) = Protected::read(&path, 32768)?; ensure!( hash(&raw) == self.original.sha256, "UPDATE_WORKER_ARCHIVE_BYTES_CHANGED" ); let mut handle = file.file.try_borrow_mut()?; ensure!( crate::update_native::files::proof(&mut handle.file, &path, 32768)? == self.original, "UPDATE_WORKER_ARCHIVE_IDENTITY_CHANGED" ); Ok(()) } } impl TrustState { /// Only after actual authenticated HealthVerified, release this worker's /// old-name READ handle so the independent helper can commit its native /// Save/Observe and Publish/Observe. ALL other trust handles remain held; /// no filesystem mutation, floor change or effect observation happens here. pub(crate) fn release_worker_record_pin_after_health( &self, header: &rmm_updater_handoff::Handoff, proof: &rmm_domain::agent_update::UpdateInflightProof, ) -> Result { let (actual, journal) = rmm_domain::agent_update::verify_inflight_proof(proof, self.health_public_key) .map_err(anyhow::Error::msg)?; ensure!( journal.phase() == rmm_updater_handoff::Phase::HealthVerified && actual.bytes()? == header.bytes()? && header.predecessor_record_sha256 == hash(&self.installed_raw) && header.updater_sha256 == self.policy.updater_binary_sha256, "UPDATE_ACTUAL_HEALTH_BEFORE_WORKER_READ_PIN_RELEASE" ); self.recheck_protected()?; let pin = self .installed_pin .try_borrow_mut()? .take() .context("UPDATE_WORKER_RECORD_PIN_ALREADY_RELEASED")?; let mut file = pin.file.try_borrow_mut()?; let original = crate::update_native::files::proof( &mut file.file, Path::new(&self.policy.installed_record_path), 32768, )?; ensure!( original.sha256 == hash(&self.installed_raw), "UPDATE_WORKER_ORIGINAL_RECORD_CHANGED" ); drop(file); drop(pin); Ok(ReleasedRecordReadPin { original }) } }