Integrate signed agent catalog, tenant enrollment and HTTPS installers
This commit is contained in:
@@ -0,0 +1,417 @@
|
||||
//! Once-only native service fences. They consume committed ORIGINAL claims,
|
||||
//! keep real live witnesses, and never open SQLite beside a running helper.
|
||||
use super::{
|
||||
Budget, DurableEffectFence, Effect, Service,
|
||||
services::{Proof, Stopped},
|
||||
};
|
||||
use crate::{
|
||||
helper_ipc::PeerProof, signed_clock::BoundClock, update_ipc, update_original::Original,
|
||||
update_state::RetainedSet, update_trust::TrustState,
|
||||
};
|
||||
use anyhow::{Result, ensure};
|
||||
use rmm_agent_core::{
|
||||
auth::Binding,
|
||||
reconcile::SyncClock,
|
||||
update_handoff::{NativeEffect, NativeEffectClaim, NativeService},
|
||||
};
|
||||
use rmm_domain::{
|
||||
agent_update::{ParticipantRole, UpdateInflightProof, verify_inflight_proof},
|
||||
jobs::hash,
|
||||
};
|
||||
use rmm_updater_handoff::Phase;
|
||||
use std::cell::RefCell;
|
||||
|
||||
pub struct Context<'a, 'b> {
|
||||
pub original: &'a Original,
|
||||
pub binding: &'a Binding,
|
||||
pub clock: &'a BoundClock,
|
||||
pub budget: &'a Budget<'b>,
|
||||
pub updater: &'a RefCell<PeerProof>,
|
||||
pub retained: &'a RetainedSet,
|
||||
pub trust: &'a TrustState,
|
||||
}
|
||||
impl Context<'_, '_> {
|
||||
fn check(&self) -> Result<()> {
|
||||
self.original
|
||||
.check_current(self.binding, self.clock, self.budget)?;
|
||||
self.trust
|
||||
.recheck_prepared(self.original.update(), self.clock)?;
|
||||
self.retained.verify()?;
|
||||
let mut updater = self.updater.try_borrow_mut()?;
|
||||
updater.check()?;
|
||||
ensure!(
|
||||
update_ipc::participant(&updater, ParticipantRole::WindowsUpdater)?
|
||||
== self.original.delegation().updater,
|
||||
"UPDATE_ORIGINAL_UPDATER_PROCESS_CHANGED"
|
||||
);
|
||||
let pin = super::services::updater_pin(self.trust.policy())?;
|
||||
ensure!(
|
||||
super::services::updater_configuration_sha256(&pin)?
|
||||
== self.trust.policy().updater_service.unit_sha256,
|
||||
"UPDATE_UPDATER_CONFIGURATION_CHANGED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
pub struct StopFence<'a, 'b> {
|
||||
context: Context<'a, 'b>,
|
||||
claims: [NativeEffectClaim; 2],
|
||||
proofs: [Proof; 2],
|
||||
next: usize,
|
||||
pending: bool,
|
||||
poisoned: bool,
|
||||
observations: Vec<String>,
|
||||
}
|
||||
/// No deserializer or public constructor: actual successful native stop
|
||||
/// callbacks and the still-stopped SCM instances create this value.
|
||||
pub struct StopObservations {
|
||||
pub(crate) claims: [NativeEffectClaim; 2],
|
||||
pub(crate) observations: [String; 2],
|
||||
pub(crate) proofs: [Proof; 2],
|
||||
}
|
||||
impl<'a, 'b> StopFence<'a, 'b> {
|
||||
pub fn new(
|
||||
context: Context<'a, 'b>,
|
||||
claims: [NativeEffectClaim; 2],
|
||||
proofs: [Proof; 2],
|
||||
proof: &UpdateInflightProof,
|
||||
) -> Result<Self> {
|
||||
context.check()?;
|
||||
let (header, journal) = verify_inflight_proof(proof, context.trust.health_public_key())
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
ensure!(
|
||||
header.bytes()? == context.original.handoff().bytes()?
|
||||
&& proof.delegation == *context.original.delegation()
|
||||
&& journal.phase() == Phase::StopIntent,
|
||||
"UPDATE_STOP_ORIGINAL_PREFIX_REQUIRED"
|
||||
);
|
||||
for (index, claim) in claims.iter().enumerate() {
|
||||
let service = [NativeService::WindowsAgent, NativeService::WindowsHelper][index];
|
||||
ensure!(
|
||||
claim.grant_id() == header.attempt.grant_id
|
||||
&& claim.owner_nonce() == header.owner_nonce
|
||||
&& claim.head_sha256() == journal.head_sha256()
|
||||
&& claim.effect() == &NativeEffect::StopService { service }
|
||||
&& claim.claimed_at() >= context.original.delegation().prepared_at
|
||||
&& claim.claimed_at() <= context.clock.reading()?.upper,
|
||||
"UPDATE_STOP_COMMITTED_ORIGINAL_CLAIM_REQUIRED"
|
||||
);
|
||||
}
|
||||
ensure!(
|
||||
proofs[0].configuration.service == Service::Agent
|
||||
&& proofs[1].configuration.service == Service::Helper
|
||||
&& proofs[0].process.image_sha256 == header.predecessor.agent_sha256
|
||||
&& proofs[1].process.image_sha256 == header.predecessor.helper_sha256,
|
||||
"UPDATE_ORIGINAL_STOP_PROCESS_PROOFS_REQUIRED"
|
||||
);
|
||||
Ok(Self {
|
||||
context,
|
||||
claims,
|
||||
proofs,
|
||||
next: 0,
|
||||
pending: false,
|
||||
poisoned: false,
|
||||
observations: vec![],
|
||||
})
|
||||
}
|
||||
pub fn finish(self, stopped: &Stopped) -> Result<StopObservations> {
|
||||
self.context.check()?;
|
||||
stopped.check(self.context.budget)?;
|
||||
ensure!(
|
||||
!self.pending && !self.poisoned && self.next == 2 && stopped.proofs() == self.proofs,
|
||||
"UPDATE_STOP_NOT_FULLY_OBSERVED"
|
||||
);
|
||||
Ok(StopObservations {
|
||||
claims: self.claims,
|
||||
observations: self
|
||||
.observations
|
||||
.try_into()
|
||||
.map_err(|_| anyhow::anyhow!("UPDATE_STOP_OBSERVATIONS_REQUIRED"))?,
|
||||
proofs: self.proofs,
|
||||
})
|
||||
}
|
||||
}
|
||||
impl DurableEffectFence for StopFence<'_, '_> {
|
||||
fn before_effect(&mut self, effect: &Effect) -> Result<()> {
|
||||
ensure!(
|
||||
!self.poisoned && !self.pending && self.next < 2,
|
||||
"UPDATE_STOP_NO_RETRY"
|
||||
);
|
||||
self.poisoned = true;
|
||||
self.context.check()?;
|
||||
ensure!(
|
||||
*effect
|
||||
== Effect::StopService {
|
||||
service: [Service::Agent, Service::Helper][self.next]
|
||||
},
|
||||
"UPDATE_STOP_CLOSED_SEQUENCE"
|
||||
);
|
||||
self.pending = true;
|
||||
Ok(())
|
||||
}
|
||||
fn after_effect(&mut self, effect: &Effect, observation: &str) -> Result<()> {
|
||||
ensure!(
|
||||
self.poisoned
|
||||
&& self.pending
|
||||
&& self.next < 2
|
||||
&& *effect
|
||||
== Effect::StopService {
|
||||
service: [Service::Agent, Service::Helper][self.next]
|
||||
}
|
||||
&& observation == hash(&serde_json::to_vec(&self.proofs[self.next])?),
|
||||
"UPDATE_STOP_ACTUAL_OBSERVATION_REQUIRED"
|
||||
);
|
||||
self.context.check()?;
|
||||
self.observations.push(observation.into());
|
||||
self.next += 1;
|
||||
self.pending = false;
|
||||
self.poisoned = false;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
/// Original reservations returned only after the guarded SQLite connection
|
||||
/// closes. Holds no mutable connection beside the new helper.
|
||||
pub struct PreparedStart {
|
||||
claims: rmm_agent_core::update_handoff::PreparedReturnClaims<2>,
|
||||
proof: UpdateInflightProof,
|
||||
}
|
||||
impl PreparedStart {
|
||||
pub(crate) fn after_closed_connection(
|
||||
claims: rmm_agent_core::update_handoff::PreparedReturnClaims<2>,
|
||||
proof: UpdateInflightProof,
|
||||
) -> Self {
|
||||
Self { claims, proof }
|
||||
}
|
||||
pub fn bind<'a, 'b>(
|
||||
self,
|
||||
context: Context<'a, 'b>,
|
||||
released: crate::update_owned::ReleasedFiles,
|
||||
bundle: &'a crate::update_state::Bundle,
|
||||
) -> Result<StartFence<'a, 'b>> {
|
||||
let result = StartFence {
|
||||
context,
|
||||
released,
|
||||
bundle,
|
||||
reservation: self,
|
||||
next: 0,
|
||||
pending: false,
|
||||
poisoned: false,
|
||||
};
|
||||
result.check()?;
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
pub struct StartFence<'a, 'b> {
|
||||
context: Context<'a, 'b>,
|
||||
released: crate::update_owned::ReleasedFiles,
|
||||
bundle: &'a crate::update_state::Bundle,
|
||||
reservation: PreparedStart,
|
||||
next: usize,
|
||||
pending: bool,
|
||||
poisoned: bool,
|
||||
}
|
||||
impl StartFence<'_, '_> {
|
||||
fn check(&self) -> Result<()> {
|
||||
self.context.check()?;
|
||||
self.released.check(self.bundle)?;
|
||||
let header = self.context.original.handoff();
|
||||
let (actual, journal) = verify_inflight_proof(
|
||||
&self.reservation.proof,
|
||||
self.context.trust.health_public_key(),
|
||||
)
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
ensure!(
|
||||
actual.bytes()? == header.bytes()?
|
||||
&& self.reservation.proof.delegation == *self.context.original.delegation()
|
||||
&& matches!(
|
||||
journal.phase(),
|
||||
Phase::LedgerReturnIntent | Phase::RollbackLedgerReturnIntent
|
||||
),
|
||||
"UPDATE_RETURN_ORIGINAL_PREFIX_REQUIRED"
|
||||
);
|
||||
let rollback = journal.phase() == Phase::RollbackLedgerReturnIntent;
|
||||
let return_at = self
|
||||
.reservation
|
||||
.proof
|
||||
.decode()
|
||||
.map_err(anyhow::Error::msg)?
|
||||
.events
|
||||
.iter()
|
||||
.map(|raw| serde_json::from_slice::<rmm_updater_handoff::Event>(raw))
|
||||
.collect::<std::result::Result<Vec<_>, _>>()?
|
||||
.into_iter()
|
||||
.find(|event| {
|
||||
matches!(
|
||||
event.evidence,
|
||||
rmm_updater_handoff::Evidence::LedgerReturnIntent
|
||||
)
|
||||
})
|
||||
.ok_or_else(|| anyhow::anyhow!("UPDATE_ORIGINAL_RETURN_DEADLINE_REQUIRED"))?
|
||||
.observed_at;
|
||||
ensure!(
|
||||
u64::try_from(self.context.clock.reading()?.upper.timestamp())?
|
||||
< return_at
|
||||
.checked_add(180)
|
||||
.ok_or_else(|| anyhow::anyhow!("UPDATE_RETURN_DEADLINE_OVERFLOW"))?,
|
||||
"UPDATE_ORIGINAL_HEALTH_WINDOW_EXPIRED"
|
||||
);
|
||||
let return_claim = &self.reservation.claims.return_ledger;
|
||||
ensure!(
|
||||
return_claim.effect()
|
||||
== &if rollback {
|
||||
NativeEffect::RollbackReturnLedger
|
||||
} else {
|
||||
NativeEffect::ReturnLedger
|
||||
},
|
||||
"UPDATE_ORIGINAL_RETURN_CLAIM_REQUIRED"
|
||||
);
|
||||
for (index, claim) in self.reservation.claims.starts.iter().enumerate() {
|
||||
let service = [NativeService::WindowsHelper, NativeService::WindowsAgent][index];
|
||||
ensure!(
|
||||
claim.effect()
|
||||
== &if rollback {
|
||||
NativeEffect::RollbackStartService { service }
|
||||
} else {
|
||||
NativeEffect::StartService { service }
|
||||
},
|
||||
"UPDATE_START_ORIGINAL_ORDER"
|
||||
);
|
||||
}
|
||||
for claim in std::iter::once(return_claim).chain(self.reservation.claims.starts.iter()) {
|
||||
ensure!(
|
||||
claim.grant_id() == header.attempt.grant_id
|
||||
&& claim.owner_nonce() == header.owner_nonce
|
||||
&& claim.head_sha256() == journal.head_sha256()
|
||||
&& u64::try_from(claim.claimed_at().timestamp())? >= header.consumed_at
|
||||
&& u64::try_from(claim.claimed_at().timestamp())? < header.finish_before,
|
||||
"UPDATE_START_COMMITTED_ORIGINAL_CLAIM_REQUIRED"
|
||||
);
|
||||
}
|
||||
for file in &self.bundle.files {
|
||||
ensure!(
|
||||
super::files::observe_bound(
|
||||
file.role,
|
||||
header.owner_nonce,
|
||||
super::files::Location::Target,
|
||||
self.context.budget
|
||||
)? == if rollback {
|
||||
file.original.clone()
|
||||
} else {
|
||||
file.staged.clone()
|
||||
},
|
||||
"UPDATE_RETURN_TARGET_CHANGED"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn finish(self, running: &mut super::services::Running) -> Result<()> {
|
||||
self.check()?;
|
||||
ensure!(
|
||||
!self.pending && !self.poisoned && self.next == 2,
|
||||
"UPDATE_START_NOT_FULLY_OBSERVED"
|
||||
);
|
||||
running.check(self.context.budget)
|
||||
}
|
||||
}
|
||||
impl DurableEffectFence for StartFence<'_, '_> {
|
||||
fn before_effect(&mut self, effect: &Effect) -> Result<()> {
|
||||
ensure!(
|
||||
!self.poisoned && !self.pending && self.next < 2,
|
||||
"UPDATE_START_NO_RETRY"
|
||||
);
|
||||
self.poisoned = true;
|
||||
self.check()?;
|
||||
ensure!(
|
||||
*effect
|
||||
== Effect::StartService {
|
||||
service: [Service::Helper, Service::Agent][self.next]
|
||||
},
|
||||
"UPDATE_START_CLOSED_SEQUENCE"
|
||||
);
|
||||
self.pending = true;
|
||||
Ok(())
|
||||
}
|
||||
fn after_effect(&mut self, effect: &Effect, observation: &str) -> Result<()> {
|
||||
ensure!(
|
||||
self.poisoned
|
||||
&& self.pending
|
||||
&& self.next < 2
|
||||
&& *effect
|
||||
== Effect::StartService {
|
||||
service: [Service::Helper, Service::Agent][self.next]
|
||||
},
|
||||
"UPDATE_START_CALLBACK_CHANGED"
|
||||
);
|
||||
self.check()?;
|
||||
let header = self.context.original.handoff();
|
||||
let mut pin = if self.next == 0 {
|
||||
self.bundle_helper_pin()?
|
||||
} else {
|
||||
self.bundle_agent_pin()?
|
||||
};
|
||||
let (_, journal) = verify_inflight_proof(
|
||||
&self.reservation.proof,
|
||||
self.context.trust.health_public_key(),
|
||||
)
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let pair = if journal.phase() == Phase::RollbackLedgerReturnIntent {
|
||||
&header.predecessor
|
||||
} else {
|
||||
&header.target
|
||||
};
|
||||
pin.binary_sha256 = if self.next == 0 {
|
||||
pair.helper_sha256.clone()
|
||||
} else {
|
||||
pair.agent_sha256.clone()
|
||||
};
|
||||
let proof = super::services::observe_public(
|
||||
[Service::Helper, Service::Agent][self.next],
|
||||
&pin,
|
||||
self.context.budget,
|
||||
)?;
|
||||
ensure!(
|
||||
hash(&serde_json::to_vec(&proof)?) == observation,
|
||||
"UPDATE_START_ACTUAL_OBSERVATION_REQUIRED"
|
||||
);
|
||||
self.next += 1;
|
||||
self.pending = false;
|
||||
self.poisoned = false;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl StartFence<'_, '_> {
|
||||
fn bundle_helper_pin(&self) -> Result<crate::helper_ipc::PeerPin> {
|
||||
crate::helper_system::read_settings().map(|(s, _)| s.helper)
|
||||
}
|
||||
fn bundle_agent_pin(&self) -> Result<crate::helper_ipc::PeerPin> {
|
||||
crate::helper_system::read_settings().map(|(s, _)| s.agent)
|
||||
}
|
||||
}
|
||||
impl StartFence<'_, '_> {
|
||||
/// Only failure of the FIRST (helper) native start can produce a new
|
||||
/// all-stopped token without additional authorized stops. A partially
|
||||
/// started helper/agent pair does not qualify through this path.
|
||||
pub fn helper_failed(self, failed: super::services::KnownStartupFailure) -> Result<Stopped> {
|
||||
self.check()?;
|
||||
let (_, journal) = verify_inflight_proof(
|
||||
&self.reservation.proof,
|
||||
self.context.trust.health_public_key(),
|
||||
)
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
ensure!(
|
||||
journal.phase() == Phase::LedgerReturnIntent
|
||||
&& self.next == 0
|
||||
&& self.pending
|
||||
&& self.poisoned
|
||||
&& failed.failure().service() == Service::Helper
|
||||
&& failed.started().is_empty(),
|
||||
"UPDATE_HELPER_FAILED_START_LINEAGE_REQUIRED"
|
||||
);
|
||||
let mut stopped = failed.into_all_stopped(self.context.budget)?;
|
||||
stopped.bind_failure(
|
||||
self.reservation.claims,
|
||||
self.context.original.delegation().updater.clone(),
|
||||
)?;
|
||||
Ok(stopped)
|
||||
}
|
||||
}
|
||||
@@ -276,3 +276,233 @@ impl<G: UpdateParticipantGuard, C: SyncClock> DurableEffectFence for LedgerFence
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A distinct one-shot V2 return fence. It cannot be constructed from Unknown,
|
||||
/// a partial forward replacement, a completed update or a future grant.
|
||||
pub struct RestoreFence<'a, 'b, G, C> {
|
||||
db: &'a mut Connection,
|
||||
guard: &'a G,
|
||||
clock: &'a C,
|
||||
budget: &'a Budget<'b>,
|
||||
original: Handoff,
|
||||
originals: &'a [Proof; 5],
|
||||
staged: &'a [Proof; 5],
|
||||
pending: Option<(Effect, NativeEffectClaim)>,
|
||||
next: usize,
|
||||
saved: bool,
|
||||
poisoned: bool,
|
||||
}
|
||||
impl<'a, 'b, G: UpdateParticipantGuard, C: SyncClock> RestoreFence<'a, 'b, G, C> {
|
||||
pub fn new(input: Inputs<'a, 'b, G, C>) -> Result<Self> {
|
||||
input.budget.check()?;
|
||||
input.original.validate()?;
|
||||
let grant = input.original.attempt.grant_id;
|
||||
let journal = core::read(input.db, input.guard, grant)?;
|
||||
ensure!(
|
||||
input.original.schema_version == 2
|
||||
&& input.original.pin_transition == PinTransition::WindowsCodePairClockV1
|
||||
&& input.guard.participant() == Participant::StableUpdater
|
||||
&& journal.phase() == Phase::RollbackStopped,
|
||||
"UPDATE_WINDOWS_NO_RESTORE_RESUME"
|
||||
);
|
||||
let raw: Vec<u8> = input.db.query_row(
|
||||
"SELECT record FROM agent_update_handoffs WHERE grant_id=?1",
|
||||
[grant.to_string()],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(
|
||||
raw == input.original.bytes()?,
|
||||
"UPDATE_WINDOWS_ORIGINAL_HANDOFF"
|
||||
);
|
||||
for (i, role) in ROLES.iter().copied().enumerate() {
|
||||
ensure!(
|
||||
input.original.files[i].role == role.handoff_role()
|
||||
&& input.original.files[i].old_sha256 == input.originals[i].sha256
|
||||
&& input.original.files[i].new_sha256 == input.staged[i].sha256
|
||||
&& files::observe_bound(
|
||||
role,
|
||||
input.original.owner_nonce,
|
||||
Location::Target,
|
||||
input.budget
|
||||
)? == input.staged[i]
|
||||
&& files::observe_bound(
|
||||
role,
|
||||
input.original.owner_nonce,
|
||||
Location::Previous,
|
||||
input.budget
|
||||
)? == input.originals[i],
|
||||
"UPDATE_WINDOWS_RESTORE_FILES"
|
||||
);
|
||||
}
|
||||
Ok(Self {
|
||||
db: input.db,
|
||||
guard: input.guard,
|
||||
clock: input.clock,
|
||||
budget: input.budget,
|
||||
original: input.original.clone(),
|
||||
originals: input.originals,
|
||||
staged: input.staged,
|
||||
pending: None,
|
||||
next: 0,
|
||||
saved: false,
|
||||
poisoned: false,
|
||||
})
|
||||
}
|
||||
fn append(&mut self, evidence: Evidence) -> Result<()> {
|
||||
self.budget.check()?;
|
||||
let grant = self.original.attempt.grant_id;
|
||||
let journal = core::read(self.db, self.guard, grant)?;
|
||||
let raw = journal.prepare(u64::try_from(self.clock.bounds()?.1.timestamp())?, evidence)?;
|
||||
core::append(self.db, self.guard, grant, journal.head_sha256(), &raw)
|
||||
}
|
||||
pub fn finish(mut self) -> Result<()> {
|
||||
ensure!(
|
||||
!self.poisoned && self.pending.is_none() && !self.saved && self.next == ROLES.len(),
|
||||
"UPDATE_WINDOWS_RESTORE_INCOMPLETE"
|
||||
);
|
||||
for (i, role) in ROLES.iter().copied().enumerate() {
|
||||
ensure!(
|
||||
files::observe_bound(
|
||||
role,
|
||||
self.original.owner_nonce,
|
||||
Location::Target,
|
||||
self.budget
|
||||
)? == self.originals[i]
|
||||
&& files::observe_bound(
|
||||
role,
|
||||
self.original.owner_nonce,
|
||||
Location::Rejected,
|
||||
self.budget
|
||||
)? == self.staged[i],
|
||||
"UPDATE_WINDOWS_RESTORED_STATE_CHANGED"
|
||||
);
|
||||
}
|
||||
self.append(Evidence::PredecessorVerified {
|
||||
pair: self.original.predecessor.clone(),
|
||||
retained_state_sha256: self.original.retained_state_sha256.clone(),
|
||||
predecessor_record_sha256: self.original.predecessor_record_sha256.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
impl<G: UpdateParticipantGuard, C: SyncClock> DurableEffectFence for RestoreFence<'_, '_, G, C> {
|
||||
fn before_effect(&mut self, effect: &Effect) -> Result<()> {
|
||||
ensure!(
|
||||
!self.poisoned && self.pending.is_none() && self.next < ROLES.len(),
|
||||
"UPDATE_WINDOWS_RESTORE_REENTRY"
|
||||
);
|
||||
self.poisoned = true;
|
||||
self.budget.check()?;
|
||||
let i = ROLES.len() - 1 - self.next;
|
||||
let role = ROLES[i];
|
||||
let effect_kind = match *effect {
|
||||
Effect::SaveRejectedCandidate { role: r } if r == role && !self.saved => {
|
||||
ensure!(
|
||||
files::observe_bound(
|
||||
role,
|
||||
self.original.owner_nonce,
|
||||
Location::Target,
|
||||
self.budget
|
||||
)? == self.staged[i]
|
||||
&& files::observe_bound(
|
||||
role,
|
||||
self.original.owner_nonce,
|
||||
Location::Previous,
|
||||
self.budget
|
||||
)? == self.originals[i],
|
||||
"UPDATE_WINDOWS_RESTORE_FILES_CHANGED"
|
||||
);
|
||||
self.append(Evidence::RestoreIntent {
|
||||
role: role.handoff_role(),
|
||||
})?;
|
||||
NativeEffect::SaveRejectedCandidate { role: native(role) }
|
||||
}
|
||||
Effect::RestorePredecessor { role: r } if r == role && self.saved => {
|
||||
ensure!(
|
||||
files::observe_bound(
|
||||
role,
|
||||
self.original.owner_nonce,
|
||||
Location::Rejected,
|
||||
self.budget
|
||||
)? == self.staged[i]
|
||||
&& files::observe_bound(
|
||||
role,
|
||||
self.original.owner_nonce,
|
||||
Location::Previous,
|
||||
self.budget
|
||||
)? == self.originals[i],
|
||||
"UPDATE_WINDOWS_RESTORE_FILES_CHANGED"
|
||||
);
|
||||
NativeEffect::RestorePredecessor { role: native(role) }
|
||||
}
|
||||
_ => anyhow::bail!("UPDATE_WINDOWS_RESTORE_SCOPE"),
|
||||
};
|
||||
let journal = core::read(self.db, self.guard, self.original.attempt.grant_id)?;
|
||||
let claim = core::claim_native_effect(
|
||||
self.db,
|
||||
self.guard,
|
||||
self.original.attempt.grant_id,
|
||||
journal.head_sha256(),
|
||||
&effect_kind,
|
||||
self.clock.bounds()?.1,
|
||||
)?;
|
||||
self.pending = Some((effect.clone(), claim));
|
||||
Ok(())
|
||||
}
|
||||
fn after_effect(&mut self, effect: &Effect, observation: &str) -> Result<()> {
|
||||
let (expected, claim) = self
|
||||
.pending
|
||||
.take()
|
||||
.ok_or_else(|| anyhow::anyhow!("UPDATE_WINDOWS_RESTORE_NOT_CLAIMED"))?;
|
||||
ensure!(
|
||||
self.poisoned && *effect == expected,
|
||||
"UPDATE_WINDOWS_RESTORE_CALLBACK_CHANGED"
|
||||
);
|
||||
self.budget.check()?;
|
||||
let i = ROLES.len() - 1 - self.next;
|
||||
let role = ROLES[i];
|
||||
let restored = matches!(effect, Effect::RestorePredecessor { .. });
|
||||
let proof = files::observe_bound(
|
||||
role,
|
||||
self.original.owner_nonce,
|
||||
if restored {
|
||||
Location::Target
|
||||
} else {
|
||||
Location::Rejected
|
||||
},
|
||||
self.budget,
|
||||
)?;
|
||||
ensure!(
|
||||
proof
|
||||
== if restored {
|
||||
self.originals[i].clone()
|
||||
} else {
|
||||
self.staged[i].clone()
|
||||
}
|
||||
&& digest(&serde_json::to_vec(&proof)?) == observation,
|
||||
"UPDATE_WINDOWS_RESTORE_READBACK"
|
||||
);
|
||||
core::observe_native_effect(
|
||||
self.db,
|
||||
self.guard,
|
||||
&claim,
|
||||
observation,
|
||||
self.clock.bounds()?.1,
|
||||
)?;
|
||||
if restored {
|
||||
self.append(Evidence::PredecessorRestored {
|
||||
role: role.handoff_role(),
|
||||
observed_sha256: proof.sha256,
|
||||
})?;
|
||||
self.next += 1;
|
||||
self.saved = false;
|
||||
} else {
|
||||
self.append(Evidence::CandidatePreserved {
|
||||
role: role.handoff_role(),
|
||||
observation_sha256: observation.into(),
|
||||
})?;
|
||||
self.saved = true;
|
||||
}
|
||||
self.poisoned = false;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,10 +2,7 @@
|
||||
//! No archive extraction, free target path, overwrite, replacement of journals,
|
||||
//! or implicit retry/rollback. A failed rename/readback is an uncertain effect.
|
||||
use super::{Budget, DurableEffectFence, Effect, Role, digest, valid_digest};
|
||||
use crate::{
|
||||
helper_ipc::{self as ipc, FileIdentity, PinnedFile},
|
||||
job_binding,
|
||||
};
|
||||
use crate::helper_ipc::{self as ipc, FileIdentity, PinnedFile};
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
@@ -45,6 +42,16 @@ struct Directory {
|
||||
root: PinnedFile,
|
||||
ancestors: Vec<File>,
|
||||
}
|
||||
fn readers() -> Result<Vec<String>> {
|
||||
let mut values = vec![
|
||||
ipc::service_sid(crate::SERVICE_NAME)?,
|
||||
ipc::service_sid(ipc::HELPER_SERVICE)?,
|
||||
];
|
||||
if let Ok(updater) = ipc::service_sid(crate::update_ipc::SERVICE) {
|
||||
values.push(updater);
|
||||
}
|
||||
Ok(values)
|
||||
}
|
||||
fn regular(file: &File, directory: bool) -> Result<()> {
|
||||
let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { zeroed() };
|
||||
ensure!(
|
||||
@@ -87,11 +94,7 @@ impl Directory {
|
||||
let path = Path::new(role.target())
|
||||
.parent()
|
||||
.context("UPDATE_TARGET_DIRECTORY")?;
|
||||
let readers = vec![
|
||||
ipc::service_sid(crate::SERVICE_NAME)?,
|
||||
ipc::service_sid(ipc::HELPER_SERVICE)?,
|
||||
];
|
||||
let root = PinnedFile::open_read_shared(path, true, &readers, &[])?;
|
||||
let root = PinnedFile::open_read_shared(path, true, &readers()?, &[])?;
|
||||
let mut ancestors = Vec::new();
|
||||
for ancestor in path.ancestors().skip(1) {
|
||||
let raw = unsafe {
|
||||
@@ -123,6 +126,9 @@ impl Directory {
|
||||
self.root.path.join(name)
|
||||
}
|
||||
}
|
||||
pub(crate) fn security_sha256(file: &File) -> Result<String> {
|
||||
SecurityDescriptor::read(file)?.hash()
|
||||
}
|
||||
struct SecurityDescriptor(*mut core::ffi::c_void);
|
||||
impl Drop for SecurityDescriptor {
|
||||
fn drop(&mut self) {
|
||||
@@ -230,9 +236,13 @@ fn hash_file(file: &mut File, max: u64) -> Result<String> {
|
||||
}
|
||||
Ok(format!("{:x}", hash.finalize()))
|
||||
}
|
||||
fn proof(file: &mut File, path: &Path, max: u64) -> Result<Proof> {
|
||||
pub(crate) fn proof(file: &mut File, path: &Path, max: u64) -> Result<Proof> {
|
||||
regular(file, false)?;
|
||||
job_binding::check_admin_readonly(path)?;
|
||||
// The agent-only binding reader rejects the helper service's legitimate
|
||||
// read ACE. These are the SAME fixed three service readers used by the
|
||||
// updater; none gets write/delete/owner/DACL rights. Check the held object,
|
||||
// not an unrelated path-based collector ACL helper.
|
||||
ipc::check_acl(file.as_raw_handle(), &readers()?, &[], None)?;
|
||||
let identity = ipc::file_identity(file)?;
|
||||
let bytes = file.metadata()?.len();
|
||||
ensure!(bytes > 0 && bytes <= max, "UPDATE_FILE_SIZE");
|
||||
@@ -291,6 +301,7 @@ pub(crate) enum Location {
|
||||
Target,
|
||||
Stage,
|
||||
Previous,
|
||||
Rejected,
|
||||
}
|
||||
/// Independent readback while the actual swap retains DELETE/write handles.
|
||||
/// Opening this read-only observer grants no write/delete access or authority.
|
||||
@@ -309,6 +320,9 @@ pub(crate) fn observe_bound(
|
||||
Location::Previous => {
|
||||
directory.child(&format!(".rmm-update-{nonce}-{}.previous", role.label()))
|
||||
}
|
||||
Location::Rejected => {
|
||||
directory.child(&format!(".rmm-update-{nonce}-{}.rejected", role.label()))
|
||||
}
|
||||
};
|
||||
let raw = unsafe {
|
||||
CreateFileW(
|
||||
@@ -336,6 +350,12 @@ pub struct StageDescriptor<'a> {
|
||||
pub replacement_sha256: &'a str,
|
||||
pub replacement_bytes: u64,
|
||||
}
|
||||
pub struct BoundStage<'a> {
|
||||
pub role: Role,
|
||||
pub owner_nonce: Uuid,
|
||||
pub original: &'a Proof,
|
||||
pub staged: &'a Proof,
|
||||
}
|
||||
pub struct Staged {
|
||||
role: Role,
|
||||
nonce: Uuid,
|
||||
@@ -346,6 +366,52 @@ pub struct Staged {
|
||||
staged: Proof,
|
||||
}
|
||||
impl Staged {
|
||||
/// Reopen only the exact prepared stage in the immutable consumed bundle.
|
||||
/// A partial publication/old predecessor name is never treated as a stage.
|
||||
pub fn reopen_bound(bound: BoundStage<'_>, budget: &Budget<'_>) -> Result<Self> {
|
||||
ensure!(!bound.owner_nonce.is_nil(), "UPDATE_STAGE_NONCE");
|
||||
budget.check()?;
|
||||
let mut directory = Directory::open(bound.role)?;
|
||||
let path = directory.child(&format!(
|
||||
".rmm-update-{}-{}.stage",
|
||||
bound.owner_nonce,
|
||||
bound.role.label()
|
||||
));
|
||||
let previous = directory.child(&format!(
|
||||
".rmm-update-{}-{}.previous",
|
||||
bound.owner_nonce,
|
||||
bound.role.label()
|
||||
));
|
||||
ensure!(!previous.try_exists()?, "UPDATE_NO_STAGE_RESUME");
|
||||
ensure!(
|
||||
observe_bound(bound.role, bound.owner_nonce, Location::Target, budget)?
|
||||
== *bound.original,
|
||||
"UPDATE_STAGE_PREDECESSOR_CHANGED"
|
||||
);
|
||||
let mut file = open(
|
||||
&path,
|
||||
FILE_GENERIC_READ | FILE_GENERIC_WRITE | DELETE,
|
||||
OPEN_EXISTING,
|
||||
ptr::null(),
|
||||
)?;
|
||||
ensure!(
|
||||
proof(&mut file, &path, bound.role.max_bytes())? == *bound.staged
|
||||
&& bound.original.identity != bound.staged.identity
|
||||
&& bound.original.identity.volume_serial == bound.staged.identity.volume_serial
|
||||
&& bound.original.security_sha256 == bound.staged.security_sha256,
|
||||
"UPDATE_BOUND_STAGE_CHANGED"
|
||||
);
|
||||
directory.check()?;
|
||||
Ok(Self {
|
||||
role: bound.role,
|
||||
nonce: bound.owner_nonce,
|
||||
directory,
|
||||
path,
|
||||
file,
|
||||
original: bound.original.clone(),
|
||||
staged: bound.staged.clone(),
|
||||
})
|
||||
}
|
||||
/// Source is a bounded stream of already independently release-verified
|
||||
/// artifact bytes. No URL or caller-chosen destination is accepted. Both
|
||||
/// code files MUST be fully staged before original activation consumption.
|
||||
@@ -548,6 +614,53 @@ pub struct Published {
|
||||
replacement_proof: Proof,
|
||||
}
|
||||
impl Published {
|
||||
/// Reopening exact files is an observation only. The separate V2 restore
|
||||
/// fence still requires a known failure, original owner and current guard.
|
||||
pub fn reopen_bound(
|
||||
bound: BoundStage<'_>,
|
||||
stopped: &super::services::Stopped,
|
||||
budget: &Budget<'_>,
|
||||
) -> Result<Self> {
|
||||
stopped.check(budget)?;
|
||||
ensure!(!bound.owner_nonce.is_nil(), "UPDATE_RESTORE_NONCE");
|
||||
let mut directory = Directory::open(bound.role)?;
|
||||
let predecessor = directory.child(&format!(
|
||||
".rmm-update-{}-{}.previous",
|
||||
bound.owner_nonce,
|
||||
bound.role.label()
|
||||
));
|
||||
let mut original = open(
|
||||
&predecessor,
|
||||
FILE_GENERIC_READ | FILE_GENERIC_WRITE | DELETE,
|
||||
OPEN_EXISTING,
|
||||
ptr::null(),
|
||||
)?;
|
||||
let mut replacement = open(
|
||||
Path::new(bound.role.target()),
|
||||
FILE_GENERIC_READ | FILE_GENERIC_WRITE | DELETE,
|
||||
OPEN_EXISTING,
|
||||
ptr::null(),
|
||||
)?;
|
||||
ensure!(
|
||||
proof(&mut original, &predecessor, bound.role.max_bytes())? == *bound.original
|
||||
&& proof(
|
||||
&mut replacement,
|
||||
Path::new(bound.role.target()),
|
||||
bound.role.max_bytes()
|
||||
)? == *bound.staged,
|
||||
"UPDATE_RESTORE_BOUND_FILES_CHANGED"
|
||||
);
|
||||
directory.check()?;
|
||||
Ok(Self {
|
||||
role: bound.role,
|
||||
directory,
|
||||
original,
|
||||
predecessor,
|
||||
original_proof: bound.original.clone(),
|
||||
replacement,
|
||||
replacement_proof: bound.staged.clone(),
|
||||
})
|
||||
}
|
||||
pub fn proof(&self) -> &Proof {
|
||||
&self.replacement_proof
|
||||
}
|
||||
@@ -573,4 +686,86 @@ impl Published {
|
||||
self.verify(budget)?;
|
||||
Ok((self.original_proof, self.replacement_proof))
|
||||
}
|
||||
/// V2-only caller fence: preserve the rejected candidate and restore the
|
||||
/// exact predecessor with TWO distinct durable intents and readbacks.
|
||||
pub fn restore(
|
||||
mut self,
|
||||
stopped: &super::services::Stopped,
|
||||
budget: &Budget<'_>,
|
||||
fence: &mut impl DurableEffectFence,
|
||||
) -> Result<(Proof, Proof)> {
|
||||
stopped.check(budget)?;
|
||||
self.verify(budget)?;
|
||||
let rejected = self.predecessor.with_extension("rejected");
|
||||
let save = Effect::SaveRejectedCandidate { role: self.role };
|
||||
fence.before_effect(&save)?;
|
||||
budget.check()?;
|
||||
stopped.check(budget)?;
|
||||
self.directory.check()?;
|
||||
rename_new(&self.replacement, &rejected)?;
|
||||
let saved = proof(&mut self.replacement, &rejected, self.role.max_bytes())?;
|
||||
ensure!(
|
||||
saved == self.replacement_proof,
|
||||
"UPDATE_REJECTED_CANDIDATE_CHANGED"
|
||||
);
|
||||
fence.after_effect(&save, &digest(&serde_json::to_vec(&saved)?))?;
|
||||
let restore = Effect::RestorePredecessor { role: self.role };
|
||||
fence.before_effect(&restore)?;
|
||||
budget.check()?;
|
||||
stopped.check(budget)?;
|
||||
self.directory.check()?;
|
||||
rename_new(&self.original, Path::new(self.role.target()))?;
|
||||
let restored = proof(
|
||||
&mut self.original,
|
||||
Path::new(self.role.target()),
|
||||
self.role.max_bytes(),
|
||||
)?;
|
||||
ensure!(
|
||||
restored == self.original_proof,
|
||||
"UPDATE_RESTORED_PREDECESSOR_CHANGED"
|
||||
);
|
||||
fence.after_effect(&restore, &digest(&serde_json::to_vec(&restored)?))?;
|
||||
Ok((restored, saved))
|
||||
}
|
||||
}
|
||||
|
||||
/// Fixed installed-record namespace only; the caller's original native claim
|
||||
/// remains mandatory. This primitive grants no approval or retry authority.
|
||||
pub(crate) fn rename_record(file: &File, target: &Path) -> Result<()> {
|
||||
let root = Path::new(r"C:\ProgramData\RustDiscoveryUpdater");
|
||||
let name = target.file_name().and_then(|n| n.to_str()).unwrap_or("");
|
||||
ensure!(
|
||||
(target.parent() == Some(root) && name == "installed-record.json")
|
||||
|| (target.parent() == Some(root.join("records").as_path())
|
||||
&& name.strip_suffix(".json").is_some_and(valid_digest)),
|
||||
"UPDATE_RECORD_FIXED_NAMESPACE"
|
||||
);
|
||||
rename_new(file, target)
|
||||
}
|
||||
pub(crate) fn create_record_stage(source: &File, target: &Path) -> Result<File> {
|
||||
ensure!(
|
||||
target.parent() == Some(Path::new(r"C:\ProgramData\RustDiscoveryUpdater"))
|
||||
&& target
|
||||
.file_name()
|
||||
.and_then(|n| n.to_str())
|
||||
.is_some_and(|n| n.starts_with(".rmm-record-") && n.ends_with(".stage")),
|
||||
"UPDATE_RECORD_FIXED_STAGE"
|
||||
);
|
||||
let descriptor = SecurityDescriptor::read(source)?;
|
||||
let attributes = SECURITY_ATTRIBUTES {
|
||||
nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
|
||||
lpSecurityDescriptor: descriptor.0,
|
||||
bInheritHandle: 0,
|
||||
};
|
||||
let file = open(
|
||||
target,
|
||||
FILE_GENERIC_READ | FILE_GENERIC_WRITE | DELETE,
|
||||
CREATE_NEW,
|
||||
&attributes,
|
||||
)?;
|
||||
ensure!(
|
||||
SecurityDescriptor::read(&file)?.hash()? == descriptor.hash()?,
|
||||
"UPDATE_RECORD_STAGE_SECURITY"
|
||||
);
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
@@ -14,6 +14,8 @@ use uuid::Uuid;
|
||||
#[cfg(windows)]
|
||||
pub mod fence;
|
||||
#[cfg(windows)]
|
||||
pub mod control_fence;
|
||||
#[cfg(windows)]
|
||||
pub mod files;
|
||||
#[cfg(windows)]
|
||||
pub mod services;
|
||||
@@ -109,6 +111,10 @@ impl<'a> Budget<'a> {
|
||||
value.check()?;
|
||||
Ok(value)
|
||||
}
|
||||
pub fn boot_id(&self) -> Result<Uuid> {
|
||||
self.check()?;
|
||||
Ok(self.boot_id)
|
||||
}
|
||||
pub fn check(&self) -> Result<()> {
|
||||
ensure!(Instant::now() < self.until, "UPDATE_DEADLINE");
|
||||
ensure!(
|
||||
@@ -127,6 +133,7 @@ pub enum Effect {
|
||||
SavePredecessor { role: Role },
|
||||
PublishReplacement { role: Role },
|
||||
RestorePredecessor { role: Role },
|
||||
SaveRejectedCandidate { role: Role },
|
||||
StartService { service: Service },
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
use super::{Budget, DurableEffectFence, Effect, Service, digest};
|
||||
use crate::helper_ipc::{PeerPin, PeerProof, utf16_pointer, wide};
|
||||
use anyhow::{Result, ensure};
|
||||
use rmm_domain::agent_update_provisioning::LocalUpdatePolicy;
|
||||
use rmm_updater_handoff::{Process, StartedService};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
@@ -11,7 +12,12 @@ use std::{
|
||||
ptr, thread,
|
||||
time::Duration,
|
||||
};
|
||||
use windows_sys::Win32::System::Services::*;
|
||||
use windows_sys::Win32::{
|
||||
Foundation::{
|
||||
ERROR_ACCESS_DENIED, ERROR_PATH_NOT_FOUND, ERROR_SERVICE_LOGON_FAILED, GetLastError,
|
||||
},
|
||||
System::Services::*,
|
||||
};
|
||||
|
||||
struct Handle(SC_HANDLE);
|
||||
impl Drop for Handle {
|
||||
@@ -115,12 +121,11 @@ fn configuration(handle: &Handle, service: Service, pin: &PeerPin) -> Result<Con
|
||||
ensure!(
|
||||
cfg.dwServiceType == SERVICE_WIN32_OWN_PROCESS
|
||||
&& command == expected
|
||||
&& cfg.dwStartType
|
||||
== if service == Service::Agent {
|
||||
SERVICE_AUTO_START
|
||||
} else {
|
||||
SERVICE_DEMAND_START
|
||||
}
|
||||
&& if service == Service::Agent {
|
||||
cfg.dwStartType == SERVICE_AUTO_START
|
||||
} else {
|
||||
matches!(cfg.dwStartType, SERVICE_DEMAND_START | SERVICE_AUTO_START)
|
||||
}
|
||||
&& (cfg.lpDependencies.is_null() || unsafe { *cfg.lpDependencies } == 0)
|
||||
&& (cfg.lpLoadOrderGroup.is_null() || unsafe { *cfg.lpLoadOrderGroup } == 0),
|
||||
"UPDATE_SCM_UNEXPECTED_CONFIGURATION"
|
||||
@@ -205,6 +210,16 @@ fn observe(service: Service, pin: &PeerPin, budget: &Budget<'_>) -> Result<HeldS
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn observe_public(
|
||||
service: Service,
|
||||
pin: &PeerPin,
|
||||
budget: &Budget<'_>,
|
||||
) -> Result<Proof> {
|
||||
let mut held = observe(service, pin, budget)?;
|
||||
held.peer.check()?;
|
||||
Ok(held.proof.clone())
|
||||
}
|
||||
|
||||
/// Observation holds both original processes/images, not a freely constructible
|
||||
/// Running flag. Drop these witnesses only after confirmed process termination.
|
||||
pub struct Running {
|
||||
@@ -262,10 +277,7 @@ impl Running {
|
||||
loop {
|
||||
budget.check()?;
|
||||
let state = status(&service.handle)?;
|
||||
if state.dwCurrentState == SERVICE_STOPPED
|
||||
&& state.dwProcessId == 0
|
||||
&& service.peer.exited()?
|
||||
{
|
||||
if state.dwCurrentState == SERVICE_STOPPED && service.peer.exited()? {
|
||||
break;
|
||||
}
|
||||
ensure!(
|
||||
@@ -283,6 +295,9 @@ impl Running {
|
||||
proofs[0].configuration.clone(),
|
||||
proofs[1].configuration.clone(),
|
||||
],
|
||||
proofs,
|
||||
failed_start: None,
|
||||
failure_binding: None,
|
||||
};
|
||||
// Held image handles intentionally close here, after BOTH exact original
|
||||
// processes have terminated. Neither PID reuse nor SCM state suffices.
|
||||
@@ -297,8 +312,15 @@ impl Running {
|
||||
pub struct Stopped {
|
||||
pins: [PeerPin; 2],
|
||||
configurations: [Configuration; 2],
|
||||
proofs: Vec<Proof>,
|
||||
failed_start: Option<FailedStartProof>,
|
||||
failure_binding: Option<FailureBinding>,
|
||||
}
|
||||
impl Stopped {
|
||||
pub fn proofs(&self) -> &[Proof] {
|
||||
&self.proofs
|
||||
}
|
||||
|
||||
pub fn check(&self, budget: &Budget<'_>) -> Result<()> {
|
||||
budget.check()?;
|
||||
for (i, service) in [Service::Agent, Service::Helper].into_iter().enumerate() {
|
||||
@@ -309,7 +331,6 @@ impl Stopped {
|
||||
let state = status(&handle)?;
|
||||
ensure!(
|
||||
state.dwCurrentState == SERVICE_STOPPED
|
||||
&& state.dwProcessId == 0
|
||||
&& configuration(&handle, service, &self.pins[i])? == self.configurations[i],
|
||||
"UPDATE_STOPPED_STATE_CHANGED"
|
||||
);
|
||||
@@ -325,6 +346,19 @@ impl Stopped {
|
||||
budget: &Budget<'_>,
|
||||
fence: &mut impl DurableEffectFence,
|
||||
) -> Result<Running> {
|
||||
match self.start_observed(replacement_pins, budget, fence)? {
|
||||
StartResult::Running(running) => Ok(*running),
|
||||
StartResult::KnownFailure(_) => {
|
||||
anyhow::bail!("UPDATE_KNOWN_STARTUP_FAILURE_REQUIRES_ORIGINAL_ROLLBACK")
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn start_observed(
|
||||
self,
|
||||
replacement_pins: [PeerPin; 2],
|
||||
budget: &Budget<'_>,
|
||||
fence: &mut impl DurableEffectFence,
|
||||
) -> Result<StartResult> {
|
||||
self.check(budget)?;
|
||||
let mut started = Vec::with_capacity(2);
|
||||
for (i, service) in [(1, Service::Helper), (0, Service::Agent)] {
|
||||
@@ -354,16 +388,52 @@ impl Stopped {
|
||||
status(&handle)?.dwCurrentState == SERVICE_STOPPED,
|
||||
"UPDATE_START_ALREADY_RUNNING"
|
||||
);
|
||||
ensure!(
|
||||
unsafe { StartServiceW(handle.0, 0, ptr::null()) } != 0,
|
||||
"UPDATE_START_REQUEST_UNCERTAIN"
|
||||
);
|
||||
if unsafe { StartServiceW(handle.0, 0, ptr::null()) } == 0 {
|
||||
let error = unsafe { GetLastError() };
|
||||
let state = status(&handle)?;
|
||||
ensure!(
|
||||
matches!(
|
||||
error,
|
||||
ERROR_ACCESS_DENIED | ERROR_PATH_NOT_FOUND | ERROR_SERVICE_LOGON_FAILED
|
||||
) && state.dwCurrentState == SERVICE_STOPPED,
|
||||
"UPDATE_START_REQUEST_UNCERTAIN"
|
||||
);
|
||||
let failure = FailedStartProof::capture(
|
||||
service,
|
||||
&replacement_pins[i],
|
||||
&handle,
|
||||
error,
|
||||
false,
|
||||
)?;
|
||||
let mut known = KnownStartupFailure {
|
||||
original: self,
|
||||
pins: replacement_pins,
|
||||
failure,
|
||||
started,
|
||||
};
|
||||
known.verify(budget)?;
|
||||
return Ok(StartResult::KnownFailure(Box::new(known)));
|
||||
}
|
||||
loop {
|
||||
budget.check()?;
|
||||
let state = status(&handle)?;
|
||||
if state.dwCurrentState == SERVICE_RUNNING {
|
||||
break;
|
||||
}
|
||||
if state.dwCurrentState == SERVICE_STOPPED
|
||||
&& (state.dwWin32ExitCode != 0 || state.dwServiceSpecificExitCode != 0)
|
||||
{
|
||||
let failure =
|
||||
FailedStartProof::capture(service, &replacement_pins[i], &handle, 0, true)?;
|
||||
let mut known = KnownStartupFailure {
|
||||
original: self,
|
||||
pins: replacement_pins,
|
||||
failure,
|
||||
started,
|
||||
};
|
||||
known.verify(budget)?;
|
||||
return Ok(StartResult::KnownFailure(Box::new(known)));
|
||||
}
|
||||
ensure!(
|
||||
state.dwCurrentState == SERVICE_START_PENDING,
|
||||
"UPDATE_START_STATE_UNCERTAIN"
|
||||
@@ -380,7 +450,7 @@ impl Stopped {
|
||||
held: started,
|
||||
};
|
||||
running.check(budget)?;
|
||||
Ok(running)
|
||||
Ok(StartResult::Running(Box::new(running)))
|
||||
}
|
||||
}
|
||||
impl Proof {
|
||||
@@ -391,3 +461,391 @@ impl Proof {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The stable updater is independently pinned and never part of the stop set.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct UpdaterConfiguration {
|
||||
pub service_name: String,
|
||||
pub command: String,
|
||||
pub account: String,
|
||||
pub start_type: u32,
|
||||
pub error_control: u32,
|
||||
pub sid_type: u32,
|
||||
}
|
||||
pub fn updater_pin(policy: &LocalUpdatePolicy) -> Result<PeerPin> {
|
||||
ensure!(
|
||||
policy.validate()
|
||||
&& policy.schema_version == 2
|
||||
&& policy.profile == "windows_code_pair_clock_v1",
|
||||
"UPDATE_WINDOWS_LOCAL_POLICY"
|
||||
);
|
||||
Ok(PeerPin {
|
||||
service_name: crate::update_ipc::SERVICE.into(),
|
||||
service_sid: crate::helper_ipc::service_sid(crate::update_ipc::SERVICE)?,
|
||||
user_sid: "S-1-5-18".into(),
|
||||
binary: crate::update_ipc::BINARY.into(),
|
||||
binary_sha256: policy.updater_binary_sha256.clone(),
|
||||
})
|
||||
}
|
||||
pub fn updater_configuration(pin: &PeerPin) -> Result<UpdaterConfiguration> {
|
||||
updater_configuration_inner(pin, true)
|
||||
}
|
||||
/// Bootstrap metadata of an already registered fixed service. This does not
|
||||
/// authenticate a running updater, qualify its clock, or create readiness.
|
||||
pub fn updater_bootstrap_definition(pin: &PeerPin) -> Result<UpdaterConfiguration> {
|
||||
updater_configuration_inner(pin, false)
|
||||
}
|
||||
fn updater_configuration_inner(
|
||||
pin: &PeerPin,
|
||||
require_running: bool,
|
||||
) -> Result<UpdaterConfiguration> {
|
||||
ensure!(
|
||||
pin.service_name == crate::update_ipc::SERVICE
|
||||
&& pin.service_sid == crate::helper_ipc::service_sid(crate::update_ipc::SERVICE)?
|
||||
&& pin.user_sid == "S-1-5-18"
|
||||
&& pin.binary == std::path::Path::new(crate::update_ipc::BINARY)
|
||||
&& super::valid_digest(&pin.binary_sha256),
|
||||
"UPDATE_UPDATER_FIXED_SERVICE"
|
||||
);
|
||||
let manager = Handle(unsafe { OpenSCManagerW(ptr::null(), ptr::null(), SC_MANAGER_CONNECT) });
|
||||
ensure!(!manager.0.is_null(), "UPDATE_SCM_MANAGER");
|
||||
let service = Handle(unsafe {
|
||||
OpenServiceW(
|
||||
manager.0,
|
||||
wide(crate::update_ipc::SERVICE).as_ptr(),
|
||||
SERVICE_QUERY_CONFIG | SERVICE_QUERY_STATUS | SERVICE_ENUMERATE_DEPENDENTS,
|
||||
)
|
||||
});
|
||||
ensure!(!service.0.is_null(), "UPDATE_UPDATER_SCM");
|
||||
let mut needed = 0;
|
||||
unsafe {
|
||||
QueryServiceConfigW(service.0, ptr::null_mut(), 0, &mut needed);
|
||||
}
|
||||
ensure!((1..=32768).contains(&needed), "UPDATE_SCM_CONFIG_SIZE");
|
||||
let mut bytes = vec![0usize; (needed as usize).div_ceil(size_of::<usize>())];
|
||||
ensure!(
|
||||
unsafe { QueryServiceConfigW(service.0, bytes.as_mut_ptr().cast(), needed, &mut needed) }
|
||||
!= 0,
|
||||
"UPDATE_SCM_CONFIG"
|
||||
);
|
||||
let cfg = unsafe { &*bytes.as_ptr().cast::<QUERY_SERVICE_CONFIGW>() };
|
||||
let command = unsafe { utf16_pointer(cfg.lpBinaryPathName) }?;
|
||||
let account = unsafe { utf16_pointer(cfg.lpServiceStartName) }?;
|
||||
ensure!(
|
||||
cfg.dwServiceType == SERVICE_WIN32_OWN_PROCESS
|
||||
&& cfg.dwStartType == SERVICE_AUTO_START
|
||||
&& command == format!("\"{}\"", crate::update_ipc::BINARY)
|
||||
&& account == "LocalSystem"
|
||||
&& (cfg.lpDependencies.is_null() || unsafe { *cfg.lpDependencies } == 0)
|
||||
&& (cfg.lpLoadOrderGroup.is_null() || unsafe { *cfg.lpLoadOrderGroup } == 0),
|
||||
"UPDATE_UPDATER_SCM_CONFIGURATION"
|
||||
);
|
||||
let recovery = config2(&service, SERVICE_CONFIG_FAILURE_ACTIONS)?;
|
||||
ensure!(
|
||||
unsafe { (*recovery.as_ptr().cast::<SERVICE_FAILURE_ACTIONSW>()).cActions } == 0,
|
||||
"UPDATE_UPDATER_RECOVERY_ACTIONS"
|
||||
);
|
||||
let triggers = config2(&service, SERVICE_CONFIG_TRIGGER_INFO)?;
|
||||
ensure!(
|
||||
unsafe { (*triggers.as_ptr().cast::<SERVICE_TRIGGER_INFO>()).cTriggers } == 0,
|
||||
"UPDATE_UPDATER_TRIGGERS"
|
||||
);
|
||||
let sid = config2(&service, SERVICE_CONFIG_SERVICE_SID_INFO)?;
|
||||
let sid_type = unsafe { (*sid.as_ptr().cast::<SERVICE_SID_INFO>()).dwServiceSidType };
|
||||
ensure!(
|
||||
sid_type == SERVICE_SID_TYPE_UNRESTRICTED,
|
||||
"UPDATE_UPDATER_SERVICE_SID"
|
||||
);
|
||||
let mut dependent_bytes = 0;
|
||||
let mut dependent_count = 0;
|
||||
ensure!(
|
||||
unsafe {
|
||||
EnumDependentServicesW(
|
||||
service.0,
|
||||
SERVICE_ACTIVE,
|
||||
ptr::null_mut(),
|
||||
0,
|
||||
&mut dependent_bytes,
|
||||
&mut dependent_count,
|
||||
)
|
||||
} != 0
|
||||
&& dependent_bytes == 0
|
||||
&& dependent_count == 0,
|
||||
"UPDATE_UPDATER_ACTIVE_DEPENDENTS"
|
||||
);
|
||||
ensure!(
|
||||
!require_running || status(&service)?.dwCurrentState == SERVICE_RUNNING,
|
||||
"UPDATE_UPDATER_NOT_RUNNING"
|
||||
);
|
||||
Ok(UpdaterConfiguration {
|
||||
service_name: pin.service_name.clone(),
|
||||
command,
|
||||
account,
|
||||
start_type: cfg.dwStartType,
|
||||
error_control: cfg.dwErrorControl,
|
||||
sid_type,
|
||||
})
|
||||
}
|
||||
pub fn updater_configuration_sha256(pin: &PeerPin) -> Result<String> {
|
||||
Ok(digest(&serde_json::to_vec(&updater_configuration(pin)?)?))
|
||||
}
|
||||
pub fn observe_updater(
|
||||
policy: &LocalUpdatePolicy,
|
||||
budget: &Budget<'_>,
|
||||
) -> Result<(PeerProof, rmm_domain::agent_update::ParticipantIdentity)> {
|
||||
budget.check()?;
|
||||
let pin = updater_pin(policy)?;
|
||||
ensure!(
|
||||
updater_configuration_sha256(&pin)? == policy.updater_service.unit_sha256,
|
||||
"UPDATE_UPDATER_SCM_PIN"
|
||||
);
|
||||
let (mut peer, identity) = crate::update_ipc::observe(
|
||||
&pin,
|
||||
rmm_domain::agent_update::ParticipantRole::WindowsUpdater,
|
||||
)?;
|
||||
peer.check()?;
|
||||
ensure!(
|
||||
updater_configuration_sha256(&pin)? == policy.updater_service.unit_sha256,
|
||||
"UPDATE_UPDATER_SCM_PIN"
|
||||
);
|
||||
budget.check()?;
|
||||
Ok((peer, identity))
|
||||
}
|
||||
/// The native API actually rejected the start, or the accepted service exited
|
||||
/// with an observed failure before RUNNING. An ambiguous API error, timeout,
|
||||
/// lost callback, unknown state or incomplete identity is never this token.
|
||||
pub enum StartResult {
|
||||
Running(Box<Running>),
|
||||
KnownFailure(Box<KnownStartupFailure>),
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct FailedStartProof {
|
||||
service: Service,
|
||||
image_sha256: String,
|
||||
configuration: Configuration,
|
||||
request_error: u32,
|
||||
accepted_then_exited: bool,
|
||||
win32_exit: u32,
|
||||
service_exit: u32,
|
||||
}
|
||||
impl FailedStartProof {
|
||||
fn capture(
|
||||
service: Service,
|
||||
pin: &PeerPin,
|
||||
handle: &Handle,
|
||||
error: u32,
|
||||
accepted_then_exited: bool,
|
||||
) -> Result<Self> {
|
||||
let state = status(handle)?;
|
||||
ensure!(
|
||||
state.dwCurrentState == SERVICE_STOPPED,
|
||||
"UPDATE_FAILED_START_NOT_STOPPED"
|
||||
);
|
||||
Ok(Self {
|
||||
service,
|
||||
image_sha256: pin.binary_sha256.clone(),
|
||||
configuration: configuration(handle, service, pin)?,
|
||||
request_error: error,
|
||||
accepted_then_exited,
|
||||
win32_exit: state.dwWin32ExitCode,
|
||||
service_exit: state.dwServiceSpecificExitCode,
|
||||
})
|
||||
}
|
||||
pub fn service(&self) -> Service {
|
||||
self.service
|
||||
}
|
||||
pub fn sha256(&self) -> Result<String> {
|
||||
Ok(digest(&serde_json::to_vec(self)?))
|
||||
}
|
||||
}
|
||||
pub struct KnownStartupFailure {
|
||||
original: Stopped,
|
||||
pins: [PeerPin; 2],
|
||||
failure: FailedStartProof,
|
||||
started: Vec<HeldService>,
|
||||
}
|
||||
impl KnownStartupFailure {
|
||||
pub fn failure(&self) -> &FailedStartProof {
|
||||
&self.failure
|
||||
}
|
||||
pub fn started(&self) -> Vec<Proof> {
|
||||
self.started.iter().map(|s| s.proof.clone()).collect()
|
||||
}
|
||||
pub fn verify(&mut self, budget: &Budget<'_>) -> Result<()> {
|
||||
budget.check()?;
|
||||
for held in &mut self.started {
|
||||
held.peer.check()?;
|
||||
}
|
||||
let index = match self.failure.service {
|
||||
Service::Agent => 0,
|
||||
Service::Helper => 1,
|
||||
};
|
||||
let h = handle(
|
||||
self.failure.service,
|
||||
SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG | SERVICE_ENUMERATE_DEPENDENTS,
|
||||
)?;
|
||||
ensure!(
|
||||
FailedStartProof::capture(
|
||||
self.failure.service,
|
||||
&self.pins[index],
|
||||
&h,
|
||||
self.failure.request_error,
|
||||
self.failure.accepted_then_exited
|
||||
)? == self.failure,
|
||||
"UPDATE_FAILED_START_OBSERVATION_CHANGED"
|
||||
);
|
||||
if self.failure.service == Service::Helper {
|
||||
ensure!(
|
||||
self.started.is_empty(),
|
||||
"UPDATE_HELPER_FAILURE_STARTED_AGENT"
|
||||
);
|
||||
self.original.check(budget)?;
|
||||
} else {
|
||||
ensure!(
|
||||
self.started.len() == 1 && self.started[0].service == Service::Helper,
|
||||
"UPDATE_AGENT_FAILURE_HELPER_LINEAGE"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn into_all_stopped(mut self, budget: &Budget<'_>) -> Result<Stopped> {
|
||||
self.verify(budget)?;
|
||||
ensure!(
|
||||
self.failure.service == Service::Helper && self.started.is_empty(),
|
||||
"UPDATE_PARTIAL_START_REQUIRES_AUTHORIZED_STOPS"
|
||||
);
|
||||
self.original.failed_start = Some(self.failure);
|
||||
self.original.check(budget)?;
|
||||
Ok(self.original)
|
||||
}
|
||||
}
|
||||
impl Stopped {
|
||||
pub(crate) fn failed_start(&self) -> Option<&FailedStartProof> {
|
||||
self.failed_start.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
struct FailureBinding {
|
||||
claims: rmm_agent_core::update_handoff::PreparedReturnClaims<2>,
|
||||
updater: rmm_domain::agent_update::ParticipantIdentity,
|
||||
}
|
||||
impl Stopped {
|
||||
pub(crate) fn bind_failure(
|
||||
&mut self,
|
||||
claims: rmm_agent_core::update_handoff::PreparedReturnClaims<2>,
|
||||
updater: rmm_domain::agent_update::ParticipantIdentity,
|
||||
) -> Result<()> {
|
||||
ensure!(
|
||||
self.failed_start.is_some() && self.failure_binding.is_none(),
|
||||
"UPDATE_FAILED_START_BINDING_REQUIRED"
|
||||
);
|
||||
self.failure_binding = Some(FailureBinding { claims, updater });
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn verify_failure_claims(
|
||||
&self,
|
||||
db: &rusqlite::Connection,
|
||||
h: &rmm_updater_handoff::Handoff,
|
||||
) -> Result<()> {
|
||||
if let Some(binding) = &self.failure_binding {
|
||||
for claim in
|
||||
std::iter::once(&binding.claims.return_ledger).chain(binding.claims.starts.iter())
|
||||
{
|
||||
ensure!(
|
||||
claim.grant_id() == h.attempt.grant_id && claim.owner_nonce() == h.owner_nonce,
|
||||
"UPDATE_FAILURE_ORIGINAL_RESERVATION_REQUIRED"
|
||||
);
|
||||
let raw: Vec<u8> = db.query_row(
|
||||
"SELECT claim FROM agent_update_native_claims WHERE grant_id=?1 AND claim=?2",
|
||||
rusqlite::params![h.attempt.grant_id.to_string(), serde_json::to_vec(claim)?],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(
|
||||
raw == serde_json::to_vec(claim)?,
|
||||
"UPDATE_FAILURE_RESERVATION_CHANGED"
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn failure_observation(
|
||||
&self,
|
||||
h: &rmm_updater_handoff::Handoff,
|
||||
d: &rmm_domain::agent_update::UpdateDelegation,
|
||||
effect: &rmm_agent_core::update_handoff::NativeEffect,
|
||||
budget: &Budget<'_>,
|
||||
) -> Result<String> {
|
||||
use rmm_agent_core::update_handoff::{NativeEffect as E, NativeService as S};
|
||||
self.check(budget)?;
|
||||
let failure = self
|
||||
.failed_start
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("UPDATE_KNOWN_START_FAILURE_REQUIRED"))?;
|
||||
let binding = self
|
||||
.failure_binding
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("UPDATE_FAILURE_ORIGINAL_START_BINDING_REQUIRED"))?;
|
||||
ensure!(
|
||||
failure.service == Service::Helper
|
||||
&& failure.image_sha256 == h.target.helper_sha256
|
||||
&& binding.updater == d.updater,
|
||||
"UPDATE_FAILURE_ACTUAL_ORIGINAL_CONTEXT_REQUIRED"
|
||||
);
|
||||
let helper = handle(
|
||||
Service::Helper,
|
||||
SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG | SERVICE_ENUMERATE_DEPENDENTS,
|
||||
)?;
|
||||
let mut pin = self.pins[1].clone();
|
||||
pin.binary_sha256 = failure.image_sha256.clone();
|
||||
ensure!(
|
||||
FailedStartProof::capture(
|
||||
Service::Helper,
|
||||
&pin,
|
||||
&helper,
|
||||
failure.request_error,
|
||||
failure.accepted_then_exited
|
||||
)? == *failure,
|
||||
"UPDATE_FAILED_START_OBSERVATION_CHANGED"
|
||||
);
|
||||
let service = match effect {
|
||||
E::StartService {
|
||||
service: S::WindowsHelper | S::WindowsAgent,
|
||||
}
|
||||
| E::RollbackStopService {
|
||||
service: S::WindowsHelper | S::WindowsAgent,
|
||||
} => {
|
||||
if matches!(
|
||||
effect,
|
||||
E::StartService {
|
||||
service: S::WindowsHelper
|
||||
} | E::RollbackStopService {
|
||||
service: S::WindowsHelper
|
||||
}
|
||||
) {
|
||||
S::WindowsHelper
|
||||
} else {
|
||||
S::WindowsAgent
|
||||
}
|
||||
}
|
||||
_ => anyhow::bail!("UPDATE_FAILURE_NONSTART_SCOPE_REQUIRED"),
|
||||
};
|
||||
ensure!(
|
||||
binding.claims.starts[0].effect()
|
||||
== &E::StartService {
|
||||
service: S::WindowsHelper
|
||||
}
|
||||
&& binding.claims.starts[1].effect()
|
||||
== &E::StartService {
|
||||
service: S::WindowsAgent
|
||||
},
|
||||
"UPDATE_FAILURE_START_SEQUENCE_CHANGED"
|
||||
);
|
||||
Ok(digest(&serde_json::to_vec(&(
|
||||
failure,
|
||||
&binding.updater,
|
||||
service,
|
||||
&binding.claims.starts,
|
||||
))?))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -211,12 +211,12 @@ pub fn render(input: Inputs<'_>) -> Result<CodePairTransition> {
|
||||
let mut settings: Settings = serde_json::from_slice(input.settings)?;
|
||||
let mut pin: Pin = serde_json::from_slice(input.pin)?;
|
||||
ensure!(
|
||||
matches!(settings.schema_version, 1..=3)
|
||||
&& !settings.allow_reboot
|
||||
matches!(settings.schema_version, 1..=4)
|
||||
&& (settings.schema_version == 4 || !settings.allow_reboot)
|
||||
&& (1..=120).contains(&settings.max_runtime_seconds)
|
||||
&& settings.allowed_services.len() <= 16
|
||||
&& (settings.schema_version >= 2 || settings.allowed_msi_recipe_sha256.is_none())
|
||||
&& (settings.schema_version == 3 || settings.allowed_script_profiles.is_none())
|
||||
&& (settings.schema_version >= 3 || settings.allowed_script_profiles.is_none())
|
||||
&& bound_peer(&settings.agent, false)
|
||||
&& bound_peer(&settings.helper, true)
|
||||
&& !settings.binding.tenant_id.is_nil()
|
||||
|
||||
Reference in New Issue
Block a user