//! Independently verified SYSTEM admission for an approved code-pair update. //! This never inherits script, MSI or SCM permissions. Its nonterminal ACK is //! flushed before the original delegation is dispatched once to the updater. use crate::{ helper_ipc::{self as ipc, PeerProof}, helper_system::{LedgerGuard, WindowsBoot}, signed_clock::BoundClock, update_cache, update_ipc, update_native::{ Budget, DurableEffectFence, Effect, Role, files::{self, StageDescriptor, Staged}, services, transition, }, update_state::{BoundFile, Bundle, LedgerIdentity, QualifiedRegistry, RetainedSet}, update_trust::{Protected, TrustState}, }; use anyhow::{Context, Result, ensure}; use rmm_agent_core::{ auth::{Binding, Request}, crypto::DalekVerifier, helper_reconcile::{BootSource, ExecutorLedgerGuard, HelperSync}, reconcile::SyncClock, update_handoff::{PreparedHandoff, UpdateAdmissionGuard}, }; use rmm_domain::{ agent_update::{ParticipantRole, PeerPinTransition, ResolvedAgentUpdate, UpdateDelegation}, jobs::{Action, hash}, }; use rmm_updater_handoff::{AttemptBinding, CodePair, FileTransition, Handoff, PinTransition}; use rusqlite::Connection; use serde::{Deserialize, Serialize}; use std::{cell::RefCell, path::Path, time::Duration}; use uuid::Uuid; #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Accepted { pub schema_version: u32, pub operation: String, pub grant_id: Uuid, pub owner_nonce: Uuid, pub handoff_sha256: String, pub original_request_sha256: String, pub ready: bool, pub terminal: bool, } impl Accepted { pub fn matches(&self, request: &Request, grant: Uuid) -> Result<()> { ensure!( self.schema_version == 1 && self.operation == "agent_update_handoff_accepted_v1" && self.grant_id == grant && !self.owner_nonce.is_nil() && ipc::digest(&self.handoff_sha256) && self.original_request_sha256 == hash(&serde_json::to_vec(request)?) && !self.ready && !self.terminal, "UPDATE_TYPED_HANDOFF_ACK" ); Ok(()) } } pub fn initialize(db: &Connection, guard: &impl ExecutorLedgerGuard) -> Result<()> { rmm_agent_core::update_handoff::initialize(db, guard)?; db.execute_batch("CREATE TABLE IF NOT EXISTS windows_update_stage_claims(grant_id TEXT NOT NULL,role TEXT NOT NULL,owner_nonce TEXT NOT NULL,original_request_sha256 TEXT NOT NULL,claimed_at TEXT NOT NULL,PRIMARY KEY(grant_id,role)); CREATE TABLE IF NOT EXISTS windows_update_stage_observations(grant_id TEXT NOT NULL,role TEXT NOT NULL,observation_sha256 TEXT NOT NULL,observed_at TEXT NOT NULL,PRIMARY KEY(grant_id,role),FOREIGN KEY(grant_id,role) REFERENCES windows_update_stage_claims(grant_id,role)); CREATE TRIGGER IF NOT EXISTS windows_update_stage_claim_no_update BEFORE UPDATE ON windows_update_stage_claims BEGIN SELECT RAISE(ABORT,'UPDATE_STAGE_IMMUTABLE');END; CREATE TRIGGER IF NOT EXISTS windows_update_stage_claim_no_delete BEFORE DELETE ON windows_update_stage_claims BEGIN SELECT RAISE(ABORT,'UPDATE_STAGE_IMMUTABLE');END; CREATE TRIGGER IF NOT EXISTS windows_update_stage_obs_no_update BEFORE UPDATE ON windows_update_stage_observations BEGIN SELECT RAISE(ABORT,'UPDATE_STAGE_IMMUTABLE');END; CREATE TRIGGER IF NOT EXISTS windows_update_stage_obs_no_delete BEFORE DELETE ON windows_update_stage_observations BEGIN SELECT RAISE(ABORT,'UPDATE_STAGE_IMMUTABLE');END;")?; guard.check(db) } pub struct Local<'a> { pub binding: &'a Binding, pub guard: &'a LedgerGuard, pub clock: &'a BoundClock, pub boot: &'a WindowsBoot, pub pin: &'a ipc::Pin, pub generation: u64, } fn fresh( local: &Local<'_>, request: &Request, ) -> Result<( rmm_domain::jobs::JobPayload, rmm_domain::jobs::ExecutionPermitPayload, )> { local.clock.require_generation(local.generation)?; let (lower, upper) = local.clock.bounds()?; let (job, grant) = local.binding.verify(request, lower)?; local.binding.verify(request, upper)?; ensure!( job.execution_identity == "system" && job.max_runtime_seconds == 600 && matches!(&job.action,Action::UpdateAgent{update} if update.validate() && update.execution_identity()==Some("system")), "UPDATE_ADMISSION_ACTION" ); Ok((job, grant)) } struct StageFence<'a, 'b> { local: &'a Local<'b>, db: &'a Connection, sync: &'a HelperSync, request: &'a Request, grant: Uuid, nonce: Uuid, trust: &'a TrustState, pending: Option, } impl DurableEffectFence for StageFence<'_, '_> { fn before_effect(&mut self, effect: &Effect) -> Result<()> { let Effect::StageFile { role } = effect else { anyhow::bail!("UPDATE_PREPARE_STAGE_ONLY"); }; ensure!(self.pending.is_none(), "UPDATE_STAGE_PENDING"); self.local.guard.check(self.db)?; fresh(self.local, self.request)?; self.trust.recheck_protected()?; ensure!( self.sync.can_start( self.db, self.local.guard, self.local.generation, self.local.clock, self.local.boot ), "UPDATE_STAGE_SIGNED_SYNC_REQUIRED" ); let role = serde_json::to_string(role)?; self.db.execute( "INSERT INTO windows_update_stage_claims VALUES(?1,?2,?3,?4,?5)", rusqlite::params![ self.grant.to_string(), role, self.nonce.to_string(), hash(&serde_json::to_vec(self.request)?), self.local.clock.now()?.to_rfc3339() ], )?; self.pending = Some(role); Ok(()) } fn after_effect(&mut self, effect: &Effect, observation: &str) -> Result<()> { let Effect::StageFile { role } = effect else { anyhow::bail!("UPDATE_PREPARE_STAGE_ONLY"); }; let role = serde_json::to_string(role)?; ensure!( self.pending.as_ref() == Some(&role) && ipc::digest(observation), "UPDATE_STAGE_OBSERVATION" ); self.local.guard.check(self.db)?; fresh(self.local, self.request)?; self.db.execute( "INSERT INTO windows_update_stage_observations VALUES(?1,?2,?3,?4)", rusqlite::params![ self.grant.to_string(), role, observation, self.local.clock.now()?.to_rfc3339() ], )?; self.pending = None; Ok(()) } } pub struct Prepared<'a> { local: Local<'a>, request: Request, update: ResolvedAgentUpdate, bundle: Bundle, trust: TrustState, registry: QualifiedRegistry, retained: RetainedSet, ledger: LedgerIdentity, running: RefCell, updater: RefCell, original: RefCell, stages: Vec, protected: Vec, sqlite: usize, } impl<'a> Prepared<'a> { pub fn new( db: &Connection, local: Local<'a>, sync: &HelperSync, request: &Request, ) -> Result { local.guard.check(db)?; let (job, permit) = fresh(&local, request)?; let Action::UpdateAgent { update } = &job.action else { unreachable!() }; let trust = TrustState::load_prepared(update, local.binding, local.clock)?; trust.qualify_history(db, local.guard, local.binding)?; initialize(db, local.guard)?; let boot = local.boot.current_boot()?; let budget = Budget::new( local.boot, boot, (permit.start_before - local.clock.now()?).to_std()?, )?; let registry = QualifiedRegistry::load(&trust)?; let running = services::Running::observe( [local.pin.agent.clone(), local.pin.helper.clone()], &budget, )?; let (updater, updater_id) = services::observe_updater(trust.policy(), &budget)?; let ipc_pin = update_ipc::Pin { schema_version: 1, binding: local.binding.clone(), policy_sha256: update.updater.policy_sha256.clone(), helper: local.pin.helper.clone(), updater: services::updater_pin(trust.policy())?, }; let description = update_ipc::exchange( &ipc_pin, &update_ipc::Request::Describe {}, Duration::from_secs(5), )?; ensure!( description.state == update_ipc::State::Described && description.head_sha256.is_none() && description.updater == updater_id, "UPDATE_ADMISSION_LIVE_UPDATER" ); registry.verify_observed( &running.proofs(), &services::updater_configuration_sha256(&ipc_pin.updater)?, )?; let (original, helper_id) = update_ipc::observe(&local.pin.helper, ParticipantRole::WindowsHelper)?; ensure!( helper_id.pid == std::process::id(), "UPDATE_ACTUAL_SYSTEM_HELPER" ); let manifest = update.manifest().map_err(anyhow::Error::msg)?; ensure!( manifest.artifacts[0].sha256 != update.predecessor.agent_sha256 || manifest.artifacts[1].sha256 != update.predecessor.helper_sha256, "UPDATE_NO_CODE_CHANGE" ); let readers = [ ipc::service_sid(crate::SERVICE_NAME)?, ipc::service_sid(ipc::HELPER_SERVICE)?, ]; let mut protected = Vec::new(); let (f, settings) = Protected::read_shared(Path::new(Role::Settings.target()), 32768, &readers)?; protected.push(f); let (f, pin) = Protected::read_shared(Path::new(Role::Pin.target()), 32768, &readers)?; protected.push(f); let (f, time) = Protected::read_shared(Path::new(Role::TimeProfile.target()), 32768, &readers)?; protected.push(f); let (f, candidate_time) = Protected::read( Path::new(r"C:\ProgramData\RustDiscoveryUpdater\candidate-time-profile.json"), 32768, )?; protected.push(f); let rendered = transition::render(transition::Inputs { settings: &settings, pin: &pin, time_profile: &time, qualified_candidate_time_profile: &candidate_time, target_agent_sha256: &manifest.artifacts[0].sha256, target_helper_sha256: &manifest.artifacts[1].sha256, })?; ensure!( rendered.proof() == &update.peer_pin_transition, "UPDATE_APPROVED_WINDOWS_RENDER_CHANGED" ); let nonce = Uuid::new_v4(); let mut fence = StageFence { local: &local, db, sync, request, grant: permit.grant_id, nonce, trust: &trust, pending: None, }; let mut stages = Vec::new(); for (role, artifact, expected_old) in [ ( Role::Agent, &manifest.artifacts[0], &update.predecessor.agent_sha256, ), ( Role::Helper, &manifest.artifacts[1], &update.predecessor.helper_sha256, ), ] { let original = files::observe(role, &budget)?; ensure!( &original.sha256 == expected_old, "UPDATE_PREDECESSOR_BINARY_CHANGED" ); let mut source = update_cache::Source::open(artifact)?; stages.push(Staged::create( StageDescriptor { role, owner_nonce: nonce, original: &original, replacement_sha256: &artifact.sha256, replacement_bytes: artifact.bytes, }, &mut source.file, &budget, &mut fence, )?); source.check()?; } for (role, bytes) in [ (Role::Settings, rendered.settings_bytes()), (Role::Pin, rendered.pin_bytes()), (Role::TimeProfile, rendered.time_profile_bytes()), ] { let original = files::observe(role, &budget)?; stages.push(Staged::create( StageDescriptor { role, owner_nonce: nonce, original: &original, replacement_sha256: &hash(bytes), replacement_bytes: bytes.len() as u64, }, &mut std::io::Cursor::new(bytes), &budget, &mut fence, )?); } drop(fence); let retained = RetainedSet::capture()?; let ledger = local.guard.update_identity(db)?; let bound_files = stages .iter() .zip([ Role::Agent, Role::Helper, Role::Settings, Role::Pin, Role::TimeProfile, ]) .map(|(s, role)| BoundFile { role, original: s.original().clone(), staged: s.staged().clone(), }) .collect::>(); let PeerPinTransition::WindowsCodePairV1 { old_pin_sha256, new_pin_sha256, .. } = &update.peer_pin_transition else { anyhow::bail!("UPDATE_WINDOWS_TRANSITION_REQUIRED"); }; let (helper_journal,checkpoint,decision,agent_journal,generation):(String,u64,String,String,u64)=db.query_row("SELECT journal_id,checkpoint,last_decision,agent_journal_id,generation FROM helper_sync_meta WHERE id=1 AND fault IS NULL",[],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?)))?; let (sync_response, sync_request): (Vec, Vec) = db.query_row( "SELECT response,request FROM helper_sync_decisions WHERE decision_id=?1", [&decision], |r| Ok((r.get(0)?, r.get(1)?)), )?; let now = local.clock.now()?; let consumed_at = u64::try_from(now.timestamp())?; let start = rmm_agent_core::ledger::start_witness_bytes(&permit, request, boot, now)?; let h = Handoff { schema_version: 2, attempt: AttemptBinding { tenant_id: permit.tenant_id, asset_id: permit.asset_id, agent_id: permit.agent_id, enrollment_generation: permit.enrollment_generation, assignment_version: permit.assignment_version, plan_id: permit .agent_update_plan_id .context("UPDATE_PLAN_ID_REQUIRED")?, plan_sha256: permit.plan_hash.clone(), job_id: permit.job_id, attempt_id: permit.attempt_id, job_payload_sha256: permit.job_payload_hash.clone(), grant_id: permit.grant_id, authorization_id: permit.authorization_id, original_request_sha256: hash(&serde_json::to_vec(request)?), original_start_witness_sha256: hash(&start), }, agent_journal_id: agent_journal.parse()?, helper_journal_id: helper_journal.parse()?, helper_checkpoint: checkpoint, previous_decision_id: decision.parse()?, boot_id: boot, connection_generation: generation, owner_nonce: nonce, updater_sha256: update.updater.binary_sha256.clone(), updater_policy_sha256: update.updater.policy_sha256.clone(), predecessor_record_sha256: update.predecessor.installed_record_sha256.clone(), retained_state_sha256: retained.sha256()?, ledger_identity_sha256: ledger.sha256()?, staged_files_sha256: hash(&serde_json::to_vec(&bound_files)?), predecessor: CodePair { manifest_sha256: update.predecessor.manifest_sha256.clone(), agent_sha256: update.predecessor.agent_sha256.clone(), helper_sha256: update.predecessor.helper_sha256.clone(), pin_sha256: old_pin_sha256.clone(), }, target: CodePair { manifest_sha256: update.manifest_sha256.clone(), agent_sha256: manifest.artifacts[0].sha256.clone(), helper_sha256: manifest.artifacts[1].sha256.clone(), pin_sha256: new_pin_sha256.clone(), }, pin_transition: PinTransition::WindowsCodePairClockV1, pin_transition_sha256: hash(&serde_json::to_vec(&update.peer_pin_transition)?), files: bound_files .iter() .map(|f| FileTransition { role: f.role.handoff_role(), old_sha256: f.original.sha256.clone(), new_sha256: f.staged.sha256.clone(), }) .collect(), stop_set: vec![ rmm_updater_handoff::Service::WindowsAgent, rmm_updater_handoff::Service::WindowsHelper, ], consumed_at, finish_before: consumed_at .checked_add(600) .context("UPDATE_FINISH_OVERFLOW")?, }; let delegation = UpdateDelegation { schema_version: 1, handoff_sha256: hash(&h.bytes()?), owner_nonce: nonce, boot_id: boot, prepared_at: now, updater: updater_id, original_helper: helper_id, }; let bundle = Bundle { schema_version: 1, original: request.clone(), handoff_record: h.bytes()?, delegation, files: bound_files, retained: retained.proofs().to_vec(), ledger: ledger.clone(), signed_sync_response: sync_response, signed_sync_request: sync_request, }; bundle.write_before_consume()?; let prepared = Self { local, request: request.clone(), update: update.as_ref().clone(), bundle, trust, registry, retained, ledger, running: RefCell::new(running), updater: RefCell::new(updater), original: RefCell::new(original), stages, protected, sqlite: unsafe { db.handle() } as usize, }; prepared.check(db)?; Ok(prepared) } pub fn consume( &self, db: &mut Connection, sync: &mut HelperSync, ) -> Result { let h = self.bundle.validate()?; sync.begin_update_handoff( db, self, self.local.generation, &PreparedHandoff { request: &self.request, handoff: &h, delegation: &self.bundle.delegation, recorded_at: self.bundle.delegation.prepared_at, }, self.local.clock, self.local.boot, )?; Ok(Accepted { schema_version: 1, operation: "agent_update_handoff_accepted_v1".into(), grant_id: h.attempt.grant_id, owner_nonce: h.owner_nonce, handoff_sha256: hash(&h.bytes()?), original_request_sha256: h.attempt.original_request_sha256, ready: false, terminal: false, }) } pub fn into_activation(self) -> Activation { Activation { pin: update_ipc::Pin { schema_version: 1, binding: self.local.binding.clone(), policy_sha256: self.update.updater.policy_sha256.clone(), helper: self.local.pin.helper.clone(), updater: services::updater_pin(self.trust.policy()).expect("validated updater pin"), }, bundle: self.bundle, trust: self.trust, registry: self.registry, retained: self.retained, running: self.running, updater: self.updater, original: self.original, _stages: self.stages, _protected: self.protected, } } } impl ExecutorLedgerGuard for Prepared<'_> { fn check(&self, db: &Connection) -> Result<()> { self.local.guard.check(db)?; ensure!( unsafe { db.handle() } as usize == self.sqlite && self.local.guard.update_identity(db)?.sha256()? == self.ledger.sha256()?, "UPDATE_ADMISSION_ORIGINAL_LEDGER" ); self.trust .recheck_prepared(&self.update, self.local.clock)?; self.registry.verify()?; self.retained.verify()?; let h = self.bundle.validate()?; let budget = Budget::new(self.local.boot, h.boot_id, Duration::from_secs(1))?; self.running.try_borrow_mut()?.check(&budget)?; self.updater.try_borrow_mut()?.check()?; self.original.try_borrow_mut()?.check()?; for f in &self.protected { f.verify()?; } for f in &self.bundle.files { ensure!( files::observe_bound(f.role, h.owner_nonce, files::Location::Stage, &budget)? == f.staged, "UPDATE_ADMISSION_STAGED_CHANGED" ); } Ok(()) } } impl UpdateAdmissionGuard for Prepared<'_> { fn health_public_key(&self) -> Result<[u8; 32]> { Ok(self.trust.health_public_key()) } fn verify_prepared_update( &self, request: &Request, h: &Handoff, d: &UpdateDelegation, _now: chrono::DateTime, ) -> Result<()> { ensure!( serde_json::to_vec(request)? == serde_json::to_vec(&self.request)? && h.bytes()? == self.bundle.handoff_record && d == &self.bundle.delegation, "UPDATE_ADMISSION_EXACT_PREPARED" ); Ok(()) } } /// Retains all original process/file witnesses until the one dispatch finishes /// or the original helper is stopped. No restart/replay constructor exists. pub struct Activation { pin: update_ipc::Pin, bundle: Bundle, trust: TrustState, registry: QualifiedRegistry, retained: RetainedSet, running: RefCell, updater: RefCell, original: RefCell, _stages: Vec, _protected: Vec, } impl Activation { pub fn dispatch_after_reply( self, db: &Connection, guard: &LedgerGuard, clock: &BoundClock, boot: &WindowsBoot, ) -> Result<()> { guard.check(db)?; let h = self.bundle.validate()?; let raw: Vec = db.query_row( "SELECT record FROM agent_update_handoffs WHERE grant_id=?1", [h.attempt.grant_id.to_string()], |r| r.get(0), )?; ensure!( raw == h.bytes()? && rmm_agent_core::update_handoff::read_delegation(db, h.attempt.grant_id)? == self.bundle.delegation, "UPDATE_DISPATCH_ORIGINAL_CONSUMED" ); let now = u64::try_from(clock.now()?.timestamp())?; ensure!( now < h.finish_before && boot.current_boot()? == h.boot_id, "UPDATE_DISPATCH_DEADLINE_BOOT" ); self.trust.recheck_protected()?; self.registry.verify()?; self.retained.verify()?; let budget = Budget::new(boot, h.boot_id, Duration::from_secs(5))?; self.running.try_borrow_mut()?.check(&budget)?; self.original.try_borrow_mut()?.check()?; self.updater.try_borrow_mut()?.check()?; let reply = update_ipc::exchange( &self.pin, &update_ipc::Request::Activate { grant_id: h.attempt.grant_id, owner_nonce: h.owner_nonce, handoff_sha256: hash(&h.bytes()?), }, Duration::from_secs(5), )?; ensure!( reply.state == update_ipc::State::Inflight && reply.updater == self.bundle.delegation.updater, "UPDATE_DISPATCH_NOT_ACCEPTED" ); Ok(()) } } /// Presence is a separate protected deny-only local update policy, never a /// consequence of Full/SCM/MSI settings. This does not advertise capability, /// attest readiness or authorize an effect. pub fn configured(binding: &Binding) -> bool { (|| -> Result<()> { let (_guard, raw) = Protected::read( Path::new(r"C:\ProgramData\RustDiscoveryUpdater\policy.json"), 65536, )?; let (p, _) = rmm_domain::agent_update_provisioning::LocalUpdatePolicy::from_bytes(&raw) .map_err(anyhow::Error::msg)?; ensure!( p.schema_version == 2 && p.tenant_id == binding.tenant_id && p.asset_id == binding.asset_id && p.agent_id == binding.agent_id && p.enrollment_generation == binding.enrollment_generation && p.assignment_version == binding.assignment_version, "UPDATE_LOCAL_POLICY_BINDING" ); Ok(()) })() .is_ok() } pub fn permits_denial(binding: &Binding, job: &rmm_domain::jobs::JobPayload) -> bool { configured(binding) && job.execution_identity == "system" && job.max_runtime_seconds == 600 && matches!(&job.action,Action::UpdateAgent{update} if update.validate() && update.execution_identity()==Some("system")) }