Integrate signed agent catalog, tenant enrollment and HTTPS installers

This commit is contained in:
2026-11-17 15:56:18 +01:00
parent 689f326460
commit 7fd17272d5
70 changed files with 12982 additions and 327 deletions
+5
View File
@@ -13,6 +13,11 @@ name = "rmm-helper-windows"
path = "src/bin/rmm-helper-windows.rs"
required-features = ["system-helper"]
[[bin]]
name = "rmm-updater-windows"
path = "src/bin/rmm-updater-windows.rs"
required-features = ["system-helper"]
[dependencies]
anyhow.workspace = true
base64 = "=0.22.1"
@@ -7,6 +7,10 @@
#[path = "../src/helper_ipc.rs"]
pub mod helper_ipc;
#[cfg(all(windows, feature = "system-helper"))]
pub mod update_admission { pub use rmm_agent_windows::update_admission::Accepted; }
#[cfg(all(windows, feature = "system-helper"))]
pub mod update_observer { pub use rmm_agent_windows::update_observer::{Request,Response}; }
#[cfg(all(windows, feature = "system-helper"))]
pub use rmm_agent_windows::SERVICE_NAME;
#[cfg(all(windows, feature = "system-helper"))]
mod platform {
@@ -0,0 +1,532 @@
//! One reviewed development bootstrap: normal stop of the exact old agent,
//! while an existing SQLite reservation excludes a new Sync/permit journal
//! commit. No job, approval, SQL row change, helper stop, reset or force kill.
#[cfg(all(windows, feature = "system-helper"))]
mod platform {
use anyhow::{Context, Result, ensure};
use prost::Message;
use rmm_agent_core::{
auth::{Binding, Outcome, Request},
crypto::DalekVerifier,
helper_reconcile::SignedResponse,
reconcile::{Channel, verify_response_with},
};
use rmm_agent_windows::{
helper_ipc::{self as ipc, PeerProof, PinnedFile},
native,
};
use rmm_domain::{jobs::hash, reconciliation::ReconcileDecisionPayload};
use rmm_protocol::{SyncRequest, SyncResponse,Envelope,Payload};
use rusqlite::{Connection, OpenFlags};
use serde_json::json;
use std::{
fs::{File, OpenOptions},
io::{Read, Write},
mem::{size_of, zeroed},
os::windows::fs::OpenOptionsExt,
path::Path,
ptr,
time::{Duration, Instant},
};
use uuid::Uuid;
use windows_sys::Win32::{
Foundation::*, Security::*, Storage::FileSystem::*, System::Services::*,
};
const AGENT: &str = "9651b2e518b315029cebfa432261a57f0a305aeddde29c56ac22a5ccbc417b32";
const HELPER: &str = "59675a3cbb3a5d213fc764f38379d6b81baaf9d47a7124470cc2767d4985763e";
const PIN: &str = "9d46dffe88f565b8b04554335d9669f5c83211b32419908a579b1cd4560443ec";
const SETTINGS: &str = "4c073cd3d4badb09d8c0f1c270b4cee9df533df416550f68bf3e336e3da7673c";
const CONFIG: &str = "5cd4cb9802d0dd20b961de7e3cd4e5874a1e9a72fc57b577e075e2d2918baac6";
const CASE: &str = "c6c80ac4-a52e-4b69-8170-466bcf52049d";
const JOB: &str = "0a50aae9-a784-4535-b62f-ef24c301d546";
const ATTEMPT: &str = "78295f74-4565-459a-87b0-641a8b95feec";
const AGENT_STATE: &str = r"C:\ProgramData\RustDiscovery\state";
const HELPER_STATE: &str = r"C:\ProgramData\RustDiscoverySystem\state";
struct Handle(SC_HANDLE);
impl Drop for Handle {
fn drop(&mut self) {
unsafe {
CloseServiceHandle(self.0);
}
}
}
fn admin() -> Result<()> {
let mut sid = [0usize; 16];
let mut len = std::mem::size_of_val(&sid) as u32;
let mut member = 0;
ensure!(
unsafe {
CreateWellKnownSid(
WinBuiltinAdministratorsSid,
ptr::null_mut(),
sid.as_mut_ptr().cast(),
&mut len,
)
} != 0
&& unsafe {
CheckTokenMembership(ptr::null_mut(), sid.as_mut_ptr().cast(), &mut member)
} != 0
&& member != 0,
"QUIESCENT_ADMIN_REQUIRED"
);
Ok(())
}
fn service(stop:bool) -> Result<Handle> {
let manager =
Handle(unsafe { OpenSCManagerW(ptr::null(), ptr::null(), SC_MANAGER_CONNECT) });
ensure!(!manager.0.is_null(), "QUIESCENT_SCM_MANAGER");
let h = Handle(unsafe {
OpenServiceW(
manager.0,
ipc::wide(rmm_agent_windows::SERVICE_NAME).as_ptr(),
SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG | if stop {SERVICE_STOP}else{0},
)
});
ensure!(!h.0.is_null(), "QUIESCENT_SCM_AGENT");
Ok(h)
}
fn status(h: &Handle) -> Result<SERVICE_STATUS_PROCESS> {
let mut s = unsafe { zeroed() };
let mut n = 0;
ensure!(
unsafe {
QueryServiceStatusEx(
h.0,
SC_STATUS_PROCESS_INFO,
(&mut s as *mut SERVICE_STATUS_PROCESS).cast(),
size_of::<SERVICE_STATUS_PROCESS>() as u32,
&mut n,
)
} != 0,
"QUIESCENT_SCM_STATUS"
);
Ok(s)
}
fn protected(path: &Path, readers: &[String], expected: &str) -> Result<(PinnedFile, Vec<u8>)> {
let mut file = PinnedFile::open(path, false, readers, &[], false)?;
ensure!(
file.file.metadata()?.len() <= 65536,
"QUIESCENT_PUBLIC_FILE_LIMIT"
);
let mut raw = Vec::new();
(&mut file.file).take(65537).read_to_end(&mut raw)?;
ensure!(
raw.len() <= 65536 && hash(&raw) == expected,
"QUIESCENT_PUBLIC_HASH"
);
file.check()?;
Ok((file, raw))
}
fn hold_agent(path: &Path) -> Result<File> {
native::private_path(path, false)?;
Ok(OpenOptions::new()
.read(true)
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)?)
}
fn check_id(file: &File, path: &Path) -> Result<()> {
let actual = hold_agent(path)?;
ensure!(
ipc::file_identity(file)? == ipc::file_identity(&actual)?,
"QUIESCENT_DATABASE_REPLACED"
);
Ok(())
}
fn receipt(dir: &Path, name: &str, value: &serde_json::Value) -> Result<()> {
let bytes = serde_json::to_vec(value)?;
ensure!(bytes.len() <= 16384, "QUIESCENT_RECEIPT_LIMIT");
let path = dir.join(name);
let mut f = OpenOptions::new()
.write(true)
.create_new(true)
.share_mode(FILE_SHARE_READ)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_WRITE_THROUGH)
.open(&path)?;
f.write_all(&bytes)?;
f.sync_all()?;
drop(f);
let mut read = PinnedFile::open(&path, false, &[], &[], false)?;
ensure!(read.sha256()? == hash(&bytes), "QUIESCENT_RECEIPT_READBACK");
Ok(())
}
struct Idle {
decision: Uuid,
checkpoint: u64,
helper_checkpoint: u64,
request_sha256: String,
response_sha256: String,
original_echo_job: Uuid,
pending_request:Option<String>,
pending_request_sha256:Option<String>,
}
fn idle(
db: &Connection,
consumption: &Connection,
helper: &Connection,
intents: &Connection,
binding: &Binding,
) -> Result<Idle> {
let (journal,checkpoint,generation,last,pending,helper_id,helper_cp,fault):(String,u64,u64,String,Option<String>,String,u64,Option<String>)=db.query_row("SELECT journal_id,checkpoint,generation,last_decision,pending_request,helper_id,helper_checkpoint,fault FROM reconcile_meta WHERE id=1",[],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?,r.get(5)?,r.get(6)?,r.get(7)?)))?;
ensure!(fault.is_none(),"QUIESCENT_AGENT_FAULT");
let (helper_journal, helper_last, helper_fault,helper_agent_cp): (String, String, Option<String>,u64) = helper
.query_row(
"SELECT journal_id,last_decision,fault,agent_checkpoint FROM helper_sync_meta WHERE id=1",
[],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?,r.get(3)?)),
)?;
ensure!(
helper_fault.is_none() && helper_last == last && helper_journal == helper_id,
"QUIESCENT_HELPER_HEAD_DIFFERS"
);
let (raw_response, raw_request, applied_cp): (Vec<u8>, Vec<u8>, u64) = helper.query_row(
"SELECT response,request,checkpoint FROM helper_sync_decisions WHERE decision_id=?1",
[&last],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
)?;
ensure!(
applied_cp == helper_cp,
"QUIESCENT_HELPER_APPLIED_CHECKPOINT"
);
let signed: SignedResponse = serde_json::from_slice(&raw_response)?;
let parsed: ReconcileDecisionPayload = serde_json::from_slice(&signed.decision_bytes)?;
let (agent_request, agent_response): (Vec<u8>, Vec<u8>) = db.query_row(
"SELECT request,response FROM reconcile_requests WHERE id=?1",
[parsed.request_id.to_string()],
|r| Ok((r.get(0)?, r.get(1)?)),
)?;
let response = SyncResponse::decode(agent_response.as_slice())?;
let request = SyncRequest::decode(agent_request.as_slice())?;
ensure!(
raw_request == agent_request
&& signed.decision_bytes == response.decision_bytes
&& signed.signature == response.signature,
"QUIESCENT_RAW_SIGNED_CONTROL_DIFFERS"
);
let verified = verify_response_with(
&DalekVerifier,
binding,
&request,
&Channel {
connection_generation: parsed.connection_generation,
boot_id: parsed.boot_id,
},
&response,
parsed.issued_at,
)?;
ensure!(
verified.decision_id.to_string() == last
&& verified.journal_id.to_string() == journal
&& verified.checkpoint == helper_agent_cp
&& verified.checkpoint<=checkpoint
&& verified.connection_generation<=generation
&& verified.helper_journal_id.map(|id| id.to_string()) == Some(helper_id.clone())
&& verified.helper_checkpoint == helper_cp
&& verified.ready
&& verified.helper_ready
&& verified.reason == "CONSISTENT",
"QUIESCENT_SIGNED_HEAD_BINDING"
);
let pending_request=if let Some(id)=pending.as_ref() {
let (request_raw,envelope_raw,row_generation,response):(Vec<u8>,Vec<u8>,u64,Option<Vec<u8>>)=db.query_row("SELECT request,envelope,generation,response FROM reconcile_requests WHERE id=?1",[id],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?)))?;
ensure!(response.is_none() && request_raw.len()<=rmm_domain::MAX_MESSAGE && envelope_raw.len()<=rmm_domain::MAX_MESSAGE,"QUIESCENT_ONLY_UNRESPONDED_CONTROL");
let request=SyncRequest::decode(request_raw.as_slice())?;
let envelope=Envelope::decode(envelope_raw.as_slice())?;
ensure!(request.encode_to_vec()==request_raw && envelope.encode_to_vec()==envelope_raw
&& request.request_id==*id && request.journal_id==journal && request.checkpoint==checkpoint
&& request.previous_decision_id==last && request.helper_previous_decision_id==last
&& request.helper_journal_id==helper_id && request.helper_checkpoint>=helper_cp
&& request.assignment_version==binding.assignment_version && request.journal_complete
&& request.durable_message_ids.is_empty() && request.attempts.len()==2
&& row_generation==generation && envelope.connection_generation==generation
&& envelope.agent_id==binding.agent_id.to_string() && envelope.enrollment_generation==binding.enrollment_generation
&& envelope.boot_id==verified.boot_id.to_string() && envelope.sequence==checkpoint
&& rmm_protocol::valid_envelope(&envelope,&binding.agent_id.to_string(),generation)
&& matches!(envelope.payload,Some(Payload::SyncRequest(ref body)) if body==&request),"QUIESCENT_PENDING_CONTROL_BINDING");
Some(request)
}else {
ensure!(verified.checkpoint==checkpoint && verified.connection_generation==generation,"QUIESCENT_WITHOUT_PENDING_EXACT_HEAD");
None
};
let busy:bool=db.query_row("SELECT EXISTS(SELECT 1 FROM job_attempts WHERE state IN ('requesting','running','verifying','unknown','awaiting_reboot'))",[],|r|r.get(0))?;
ensure!(!busy, "QUIESCENT_EFFECT_PENDING");
let (scope, original) = rmm_agent_windows::echo_probe::archive(db, binding)?
.context("QUIESCENT_ECHO_ARCHIVE_MISSING")?;
ensure!(
rmm_agent_windows::echo_completion::installed(db, binding, &scope, &original)?,
"QUIESCENT_ECHO_COMPLETION_MISSING"
);
let (total,echo,pending_new):(u64,u64,u64)=db.query_row("SELECT count(*),sum(job=?1 AND attempt=?2 AND state='succeeded'),sum(job=?3 AND attempt=?4 AND state IN ('accepted','expired') AND grant_id='') FROM job_attempts",rusqlite::params![scope.job_id.to_string(),scope.attempt_id.to_string(),JOB,ATTEMPT],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?)))?;
ensure!(
total == 2 && echo == 1 && pending_new == 1,
"QUIESCENT_EXPECTED_TWO_JOB_HISTORY"
);
if let Some(request)=&pending_request {
let echo=request.attempts.iter().filter(|r|r.job_id==scope.job_id.to_string() && r.attempt_id==scope.attempt_id.to_string()).collect::<Vec<_>>();
let new=request.attempts.iter().filter(|r|r.job_id==JOB && r.attempt_id==ATTEMPT).collect::<Vec<_>>();
ensure!(echo.len()==1 && new.len()==1,"QUIESCENT_PENDING_EXPECTED_ATTEMPTS");
let old=echo[0];let new=new[0];
let old_grant:String=db.query_row("SELECT grant_id FROM job_attempts WHERE job=?1 AND attempt=?2",rusqlite::params![scope.job_id.to_string(),scope.attempt_id.to_string()],|r|r.get(0))?;
ensure!(old.state=="succeeded" && old.consumption=="consumed" && old.grant_id==old_grant
&& !old.grant_id.is_empty() && old.job_payload_hash==scope.job_payload_hash && old.update_handoff_bytes.is_empty()
&& matches!(new.state.as_str(),"accepted"|"expired") && new.consumption=="unconsumed" && new.grant_id.is_empty()
&& new.update_handoff_bytes.is_empty(),"QUIESCENT_PENDING_NO_NEW_EFFECT");
}
let (total, new): (u64, u64) = consumption.query_row(
"SELECT count(*),COALESCE(sum(job=?1 OR attempt=?2),0) FROM consumed",
[JOB, ATTEMPT],
|r| Ok((r.get(0)?, r.get(1)?)),
)?;
ensure!(total == 1 && new == 0, "QUIESCENT_CONSUMPTION_CHANGED");
let (start,outcome,finished):(Vec<u8>,Vec<u8>,Vec<u8>)=consumption.query_row("SELECT e.start,e.outcome,c.result FROM consumed c JOIN execution_evidence e USING(grant_id) WHERE c.job=?1 AND c.attempt=?2",rusqlite::params![scope.job_id.to_string(),scope.attempt_id.to_string()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?)))?;
let start: serde_json::Value = serde_json::from_slice(&start)?;
let request: Request = serde_json::from_value(start["request"].clone())?;
let at = serde_json::from_value(start["reserved_at"].clone())?;
let (job, _) = binding.verify_with(&request, at, &DalekVerifier)?;
let o: Outcome = serde_json::from_slice(&outcome)?;
ensure!(
scope.matches_job(&job)
&& o.state == "succeeded"
&& o.evidence["postconditions_passed"] == true
&& outcome == finished,
"QUIESCENT_ORIGINAL_ECHO_EVIDENCE"
);
ensure!(
helper.query_row("SELECT count(*) FROM consumed", [], |r| r.get::<_, u64>(0))? == 0
&& intents.query_row("SELECT count(*) FROM system_intents", [], |r| r
.get::<_, u64>(0))?
== 0,
"QUIESCENT_HELPER_WORK_PRESENT"
);
Ok(Idle {
decision: verified.decision_id,
checkpoint,
helper_checkpoint: helper_cp,
request_sha256: hash(&raw_request),
response_sha256: hash(&raw_response),
original_echo_job: scope.job_id,
pending_request:pending,
pending_request_sha256:pending_request.as_ref().map(|r|hash(&r.encode_to_vec())),
})
}
fn safe_error(error:&anyhow::Error)->serde_json::Value {
for cause in error.chain() {
let text=cause.to_string();
if text.starts_with("QUIESCENT_") && text.bytes().all(|b|b.is_ascii_uppercase()||b==b'_') {return json!({"code":text});}
if let Some(sql)=cause.downcast_ref::<rusqlite::Error>() {
return match sql {
rusqlite::Error::SqliteFailure(code,_)=>json!({"code":"SQLITE_FAILURE","sqlite_code":format!("{:?}",code.code),"extended_code":code.extended_code}),
rusqlite::Error::QueryReturnedNoRows=>json!({"code":"SQLITE_NO_ROWS"}),
rusqlite::Error::InvalidColumnIndex(index)=>json!({"code":"SQLITE_COLUMN_INDEX","index":index}),
rusqlite::Error::InvalidColumnType(index,column,_)=>json!({"code":"SQLITE_COLUMN_TYPE","index":index,"column":column}),
_=>json!({"code":"SQLITE_READ_FAILED"}),
};
}
}
json!({"code":"SIGNED_OR_ARCHIVED_EVIDENCE_CHECK_FAILED"})
}
fn safe_metadata(db:&Connection,consumed:&Connection,helper:&Connection,intents:&Connection)->Result<serde_json::Value> {
let agent=db.query_row("SELECT checkpoint,generation,last_decision,pending_request,helper_checkpoint,fault IS NOT NULL FROM reconcile_meta WHERE id=1",[],|r|Ok(json!({
"checkpoint":r.get::<_,u64>(0)?,"generation":r.get::<_,u64>(1)?,"last_decision":r.get::<_,Option<String>>(2)?,"pending_request":r.get::<_,Option<String>>(3)?,"helper_checkpoint":r.get::<_,u64>(4)?,"fault_present":r.get::<_,bool>(5)?})))?;
let helper_meta=helper.query_row("SELECT checkpoint,generation,last_decision,fault IS NOT NULL,agent_checkpoint FROM helper_sync_meta WHERE id=1",[],|r|Ok(json!({
"current_capture_checkpoint":r.get::<_,u64>(0)?,"generation":r.get::<_,u64>(1)?,"last_decision":r.get::<_,Option<String>>(2)?,"fault_present":r.get::<_,bool>(3)?,"agent_checkpoint":r.get::<_,u64>(4)?})))?;
let mut q=db.prepare("SELECT job,attempt,state,grant_id<>'' FROM job_attempts ORDER BY job LIMIT 8")?;
let jobs=q.query_map([],|r|Ok(json!({"job_id":r.get::<_,String>(0)?,"attempt_id":r.get::<_,String>(1)?,"state":r.get::<_,String>(2)?,"grant_present":r.get::<_,bool>(3)?})))?.collect::<rusqlite::Result<Vec<_>>>()?;
let counts=json!({"events":db.query_row("SELECT count(*) FROM events",[],|r|r.get::<_,u64>(0))?,"job_events":db.query_row("SELECT count(*) FROM job_events",[],|r|r.get::<_,u64>(0))?,
"agent_consumed":consumed.query_row("SELECT count(*) FROM consumed",[],|r|r.get::<_,u64>(0))?,"agent_execution_evidence":consumed.query_row("SELECT count(*) FROM execution_evidence",[],|r|r.get::<_,u64>(0))?,
"helper_consumed":helper.query_row("SELECT count(*) FROM consumed",[],|r|r.get::<_,u64>(0))?,"helper_intents":intents.query_row("SELECT count(*) FROM system_intents",[],|r|r.get::<_,u64>(0))?});
Ok(json!({"agent":agent,"helper":helper_meta,"jobs":jobs,"counts":counts}))
}
pub fn run() -> Result<()> {
let args=std::env::args().skip(1).collect::<Vec<_>>();
let read_only=args==["--read-idle-check"];
ensure!(read_only || args==["--stop-known-idle-agent"],"QUIESCENT_ARGUMENTS");
admin()?;
let bootstrap = PinnedFile::open(
Path::new(r"C:\ProgramData\RustDiscoveryBootstrap"),
true,
&[],
&[],
false,
)?;
let dir = bootstrap.path.join(format!("quiescent-stop-{CASE}"));
let mut dir_guard=if read_only {None}else{
std::fs::create_dir(&dir)?;
Some(PinnedFile::open(&dir,true,&[],&[],false)?)
};
let readers = [
ipc::service_sid(rmm_agent_windows::SERVICE_NAME)?,
ipc::service_sid(ipc::HELPER_SERVICE)?,
];
let (mut pin_guard, raw) = protected(
Path::new(r"C:\ProgramData\RustDiscoverySystem\agent-pin.json"),
&readers,
PIN,
)?;
let pin: ipc::Pin = serde_json::from_slice(&raw)?;
pin.validate()?;
ensure!(
pin.agent.binary_sha256 == AGENT && pin.helper.binary_sha256 == HELPER,
"QUIESCENT_EXACT_PAIR"
);
let (mut settings_guard, _) = protected(
Path::new(r"C:\ProgramData\RustDiscoverySystem\helper.json"),
&readers,
SETTINGS,
)?;
let (mut config_guard, raw) = protected(
Path::new(r"C:\ProgramData\RustDiscovery\config.json"),
&[readers[0].clone()],
CONFIG,
)?;
let cfg: serde_json::Value = serde_json::from_slice(&raw)?;
ensure!(
cfg["enable_jobs"] == true
&& cfg.get("windows_echo_probe_only").is_none_or(|v|v==false)
&& cfg["state_directory"] == AGENT_STATE,
"QUIESCENT_EXACT_CONFIGURATION"
);
let agent_service = service(!read_only)?;
let before = status(&agent_service)?;
ensure!(
before.dwCurrentState == SERVICE_RUNNING,
"QUIESCENT_AGENT_NOT_RUNNING"
);
let mut peer = PeerProof::for_service(&pin.agent, before.dwProcessId)?;
let helper_manager=Handle(unsafe{OpenSCManagerW(ptr::null(),ptr::null(),SC_MANAGER_CONNECT)});
ensure!(!helper_manager.0.is_null(),"QUIESCENT_HELPER_SCM_MANAGER");
let helper_service=Handle(unsafe{OpenServiceW(helper_manager.0,ipc::wide(ipc::HELPER_SERVICE).as_ptr(),SERVICE_QUERY_STATUS|SERVICE_QUERY_CONFIG)});
ensure!(!helper_service.0.is_null(),"QUIESCENT_HELPER_SCM");
let helper_before=status(&helper_service)?;
ensure!(helper_before.dwCurrentState==SERVICE_RUNNING,"QUIESCENT_HELPER_NOT_RUNNING");
let mut helper_peer=PeerProof::for_service(&pin.helper,helper_before.dwProcessId)?;
// Keep original journal/sidecar names and ledger against replacement.
let journal_path = Path::new(AGENT_STATE).join("telemetry.sqlite");
let journal_file = hold_agent(&journal_path)?;
let _wal = hold_agent(&Path::new(AGENT_STATE).join("telemetry.sqlite-wal"))?;
let _shm = hold_agent(&Path::new(AGENT_STATE).join("telemetry.sqlite-shm"))?;
let consumption_path = Path::new(AGENT_STATE).join("consumption.sqlite");
let consumption_file = hold_agent(&consumption_path)?;
let helper_writer = ipc::service_sid(ipc::HELPER_SERVICE)?;
let mut helper_file = PinnedFile::open_read_shared(
&Path::new(HELPER_STATE).join("ledger.sqlite"),
false,
&[],
std::slice::from_ref(&helper_writer),
)?;
let mut intent_file = PinnedFile::open_read_shared(
Path::new(r"C:\ProgramData\RustDiscoverySystem\agent-intents\system-intents.sqlite"),
false,
&[],
&[readers[0].clone()],
)?;
let db = Connection::open_with_flags(&journal_path, if read_only {OpenFlags::SQLITE_OPEN_READ_ONLY}else{OpenFlags::SQLITE_OPEN_READ_WRITE})?;
db.busy_timeout(Duration::from_millis(20))?;
let consumed =
Connection::open_with_flags(&consumption_path, OpenFlags::SQLITE_OPEN_READ_ONLY)?;
let helper =
Connection::open_with_flags(&helper_file.path, OpenFlags::SQLITE_OPEN_READ_ONLY)?;
let intents =
Connection::open_with_flags(&intent_file.path, OpenFlags::SQLITE_OPEN_READ_ONLY)?;
if read_only {
let mut observations=Vec::new();
for _ in 0..10 {
db.execute_batch("BEGIN")?;helper.execute_batch("BEGIN")?;
let checked=idle(&db,&consumed,&helper,&intents,&pin.binding);
let metadata=safe_metadata(&db,&consumed,&helper,&intents)?;
let error=checked.as_ref().err().map(safe_error);
helper.execute_batch("ROLLBACK")?;db.execute_batch("ROLLBACK")?;
observations.push(json!({"observed_at":chrono::Utc::now(),"idle_check_passed":checked.is_ok(),"error":error,"metadata":metadata}));
std::thread::sleep(Duration::from_millis(100));
}
peer.check()?;helper_peer.check()?;
println!("{}",serde_json::to_string(&json!({"schema_version":1,"mode":"read_idle_check","read_only":true,"quiescence_reservation_held":false,"stop_requested":false,"case_created":false,"sql_data_changed":false,"samples":observations}))?);
return Ok(());
}
let until = Instant::now() + Duration::from_secs(30);
let locked = loop {
if Instant::now() >= until {
anyhow::bail!("QUIESCENT_HEAD_NOT_OBSERVED_NO_STOP");
}
if db.execute_batch("BEGIN IMMEDIATE").is_err() {
std::thread::sleep(Duration::from_millis(25));
continue;
}
helper.execute_batch("BEGIN")?;
let value = idle(&db, &consumed, &helper, &intents, &pin.binding);
helper.execute_batch("ROLLBACK")?;
match value {
Ok(value) => break value,
Err(_) => {
db.execute_batch("ROLLBACK")?;
std::thread::sleep(Duration::from_millis(25));
}
}
};
// All final observations occur while new agent writes remain excluded.
peer.check()?;
helper_peer.check()?;
pin_guard.check()?;
settings_guard.check()?;
config_guard.check()?;
dir_guard.as_mut().context("QUIESCENT_CASE_GUARD")?.check()?;
check_id(&journal_file, &journal_path)?;
check_id(&consumption_file, &consumption_path)?;
helper_file.check()?;
intent_file.check()?;
let current = status(&agent_service)?;
ensure!(
current.dwCurrentState == SERVICE_RUNNING && current.dwProcessId == before.dwProcessId,
"QUIESCENT_ORIGINAL_PROCESS_CHANGED"
);
receipt(
&dir,
"stop-intent.json",
&json!({"schema_version":1,"case_id":CASE,"observed_at":chrono::Utc::now(),"agent_sha256":AGENT,"helper_sha256":HELPER,"pin_sha256":PIN,"config_sha256":CONFIG,
"agent_pid":before.dwProcessId,"journal_file_id":ipc::file_identity(&journal_file)?,"consumption_file_id":ipc::file_identity(&consumption_file)?,"helper_ledger_file_id":helper_file.identity,"decision_id":locked.decision,
"checkpoint":locked.checkpoint,"helper_applied_checkpoint":locked.helper_checkpoint,"signed_request_sha256":locked.request_sha256,"signed_helper_response_sha256":locked.response_sha256,"original_echo_job":locked.original_echo_job,
"pending_job":JOB,"pending_control_request":locked.pending_request,"pending_control_request_sha256":locked.pending_request_sha256,"new_grants":0,"helper_consumptions":0,"helper_intents":0,"sql_data_changed":false,"agent_journal_immediate_reservation_held":true,"stop_service_only":rmm_agent_windows::SERVICE_NAME,"force_kill":false}),
)?;
let mut returned: SERVICE_STATUS = unsafe { zeroed() };
let stop_ok =
unsafe { ControlService(agent_service.0, SERVICE_CONTROL_STOP, &mut returned) } != 0;
let error = if stop_ok {
None
} else {
Some(unsafe { GetLastError() })
};
let wait = Instant::now() + Duration::from_secs(125);
let mut final_status = status(&agent_service)?;
while stop_ok && final_status.dwCurrentState != SERVICE_STOPPED && Instant::now() < wait {
std::thread::sleep(Duration::from_millis(50));
final_status = status(&agent_service)?;
}
let stopped = stop_ok && final_status.dwCurrentState == SERVICE_STOPPED;
helper_peer.check()?;
// Still held through the confirmed stop (or bounded honest failure).
check_id(&journal_file, &journal_path)?;
check_id(&consumption_file, &consumption_path)?;
receipt(
&dir,
"stop-result.json",
&json!({"schema_version":1,"case_id":CASE,"observed_at":chrono::Utc::now(),"normal_stop_requested_once":stop_ok,"native_error":error,"stopped":stopped,"state":final_status.dwCurrentState,"pid":final_status.dwProcessId,
"sql_data_changed":false,"job_executed":false,"helper_stopped":false,"reset":false,"force_kill":false,"reservation_held_until_observation":true}),
)?;
db.execute_batch("ROLLBACK")?;
ensure!(stopped, "QUIESCENT_STOP_UNCONFIRMED_NO_FORCE");
println!("{{\"case_id\":\"{CASE}\",\"stopped\":true,\"sql_data_changed\":false}}");
Ok(())
}
}
#[cfg(all(windows, feature = "system-helper"))]
fn main() {
if let Err(error) = platform::run() {
eprintln!("{}", error);
std::process::exit(1);
}
}
#[cfg(not(all(windows, feature = "system-helper")))]
fn main() {
eprintln!("Windows SYSTEM-helper SDK bootstrap only");
std::process::exit(1);
}
@@ -0,0 +1,47 @@
//! Administrator bootstrap metadata READ ONLY. Never stops a service, opens a
//! writable SQLite connection, repairs history, reads keys, or executes jobs.
#[cfg(windows)]
mod native {
use anyhow::{Result,ensure};
use prost::Message;
use rusqlite::{Connection,OpenFlags};
use serde_json::{Value,json};
use std::{path::Path,time::Duration};
use windows_sys::Win32::{Foundation::CloseHandle,Security::{GetTokenInformation,TOKEN_ELEVATION,TOKEN_QUERY,TokenElevation},System::Threading::{GetCurrentProcess,OpenProcessToken}};
fn db(path:&str)->Result<Connection>{ensure!(Path::new(path).is_file(),"SYNC_DIAGNOSTIC_FILE_MISSING");let db=Connection::open_with_flags(path,OpenFlags::SQLITE_OPEN_READ_ONLY|OpenFlags::SQLITE_OPEN_NO_MUTEX)?;db.busy_timeout(Duration::from_millis(500))?;Ok(db)}
fn requests(db:&Connection)->Result<Value>{
let mut stmt=db.prepare("SELECT id,generation,length(request),response IS NOT NULL,request FROM reconcile_requests ORDER BY rowid DESC LIMIT 2")?;
let rows=stmt.query_map([],|r|Ok((r.get::<_,String>(0)?,r.get::<_,u64>(1)?,r.get::<_,u64>(2)?,r.get::<_,bool>(3)?,r.get::<_,Vec<u8>>(4)?)))?.collect::<rusqlite::Result<Vec<_>>>()?;
Ok(json!(rows.into_iter().map(|(id,generation,bytes,response,raw)|{
let decoded=rmm_protocol::SyncRequest::decode(raw.as_slice()).ok();
json!({"request_id":id,"generation":generation,"request_bytes":bytes,"response_present":response,"decoded":decoded.map(|r|json!({"request_id":r.request_id,"checkpoint":r.checkpoint,"previous_decision_id":r.previous_decision_id,"helper_checkpoint":r.helper_checkpoint}))})
}).collect::<Vec<_>>()))
}
fn sample()->Result<Value>{
let agent=db(r"C:\ProgramData\RustDiscovery\state\telemetry.sqlite")?;
let helper=db(r"C:\ProgramData\RustDiscoverySystem\state\ledger.sqlite")?;
let meta=agent.query_row("SELECT checkpoint,generation,last_decision,pending_request,helper_checkpoint,fault FROM reconcile_meta WHERE id=1",[],|r|Ok(json!({"checkpoint":r.get::<_,u64>(0)?,"generation":r.get::<_,u64>(1)?,"last_decision":r.get::<_,Option<String>>(2)?,"pending_request":r.get::<_,Option<String>>(3)?,"helper_checkpoint":r.get::<_,u64>(4)?,"fault":r.get::<_,Option<String>>(5)?})))?;
let helper_meta=helper.query_row("SELECT checkpoint,generation,last_decision,agent_checkpoint,fault FROM helper_sync_meta WHERE id=1",[],|r|Ok(json!({"checkpoint":r.get::<_,u64>(0)?,"generation":r.get::<_,u64>(1)?,"last_decision":r.get::<_,Option<String>>(2)?,"agent_checkpoint":r.get::<_,u64>(3)?,"fault":r.get::<_,Option<String>>(4)?})))?;
let mut stmt=helper.prepare("SELECT decision_id,checkpoint,length(response),length(request) FROM helper_sync_decisions ORDER BY rowid DESC LIMIT 2")?;
let decisions=stmt.query_map([],|r|Ok(json!({"decision_id":r.get::<_,String>(0)?,"checkpoint":r.get::<_,u64>(1)?,"response_bytes":r.get::<_,u64>(2)?,"request_bytes":r.get::<_,u64>(3)?})))?.collect::<rusqlite::Result<Vec<_>>>()?;
let mut stmt=agent.prepare("SELECT job,attempt,state,grant_id<>'' FROM job_attempts ORDER BY job LIMIT 8")?;
let jobs=stmt.query_map([],|r|Ok(json!({"job_id":r.get::<_,String>(0)?,"attempt_id":r.get::<_,String>(1)?,"state":r.get::<_,String>(2)?,"grant_present":r.get::<_,bool>(3)?})))?.collect::<rusqlite::Result<Vec<_>>>()?;
Ok(json!({"agent":meta,"requests":requests(&agent)?,"helper":helper_meta,"helper_decisions":decisions,"jobs":jobs}))
}
fn error(e:&anyhow::Error)->Value {
for cause in e.chain(){if let Some(sql)=cause.downcast_ref::<rusqlite::Error>(){return match sql {rusqlite::Error::SqliteFailure(code,_)=>json!({"code":"SQLITE_FAILURE","sqlite_code":format!("{:?}",code.code),"extended_code":code.extended_code}),rusqlite::Error::InvalidColumnType(index,column,_)=>json!({"code":"SQLITE_COLUMN_TYPE","index":index,"column":column}),rusqlite::Error::QueryReturnedNoRows=>json!({"code":"SQLITE_NO_ROWS"}),_=>json!({"code":"SQLITE_READ_FAILED"})};}}
json!({"code":"READ_DIAGNOSTIC_FAILED"})
}
pub fn run()->Result<()> {
ensure!(std::env::args().count()==1,"SYNC_DIAGNOSTIC_NO_ARGUMENTS");
let mut token=std::ptr::null_mut();ensure!(unsafe{OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY,&mut token)}!=0,"SYNC_DIAGNOSTIC_TOKEN");
let mut elevation=TOKEN_ELEVATION{TokenIsElevated:0};let mut size=0;
let okay=unsafe{GetTokenInformation(token,TokenElevation,&mut elevation as *mut _ as *mut _,std::mem::size_of::<TOKEN_ELEVATION>() as u32,&mut size)};unsafe{CloseHandle(token)};
ensure!(okay!=0&&elevation.TokenIsElevated!=0,"SYNC_DIAGNOSTIC_ADMIN");
let mut samples=vec![];
for _ in 0..3 {samples.push(sample().unwrap_or_else(|e|json!({"error":error(&e)})));std::thread::sleep(Duration::from_millis(100));}
println!("{}",serde_json::to_string(&json!({"schema_version":1,"read_only":true,"utc":chrono::Utc::now(),"samples":samples}))?);Ok(())
}
}
#[cfg(windows)]fn main(){if native::run().is_err(){eprintln!("SYNC_DIAGNOSTIC_FAILED");std::process::exit(1);}}
#[cfg(not(windows))]fn main(){eprintln!("Windows only");std::process::exit(1);}
@@ -0,0 +1,245 @@
//! Administrative typed metadata only; no writes, effects, jobs, or readiness.
#[cfg(all(windows, feature = "system-helper"))]
mod sdk {
use anyhow::{Result, ensure};
use rmm_agent_windows::{helper_ipc as ipc, helper_system, signed_clock, update_state};
use rmm_domain::{
agent_update::{ReleaseEnvelope, ReleaseManifest, UpdateKeyringFile},
agent_update_provisioning::{HealthKeyPin, InstalledReleaseRecord, LocalUpdatePolicy},
jobs::hash,
};
use serde::Deserialize;
use std::io::Read;
#[derive(Deserialize)]
#[serde(tag = "operation", rename_all = "snake_case", deny_unknown_fields)]
enum Input {
ReadMetadata {
updater_sha256: Option<String>,
},
RenderPair {
settings: Vec<u8>,
agent_sha256: String,
helper_sha256: String,
},
RenderUpdaterClock {
pair_profile: Vec<u8>,
updater_sha256: String,
policy_sha256: String,
service_configuration_sha256: String,
qualification_sha256: String,
},
CanonicalRelease {
manifest: ReleaseManifest,
},
CanonicalRecord {
record: InstalledReleaseRecord,
},
CanonicalPolicy {
policy: Box<LocalUpdatePolicy>,
},
ValidatePublicBundle {
record: Vec<u8>,
policy: Vec<u8>,
keyring: Vec<u8>,
health_pin: Vec<u8>,
},
ValidateRelease {
envelope: ReleaseEnvelope,
},
}
fn bytes(raw: Vec<u8>) -> serde_json::Value {
serde_json::json!({"sha256":hash(&raw),"bytes":raw})
}
fn read_metadata(updater_sha256: Option<String>) -> Result<serde_json::Value> {
use rmm_agent_core::helper_reconcile::BootSource;
use rmm_agent_windows::update_native::{Budget, Role, files, services};
let boot = helper_system::WindowsBoot::capture()?;
let budget = Budget::new(
&boot,
boot.current_boot()?,
std::time::Duration::from_secs(30),
)?;
let (settings, _held) = helper_system::read_settings()?;
let mut running =
services::Running::observe([settings.agent.clone(), settings.helper.clone()], &budget)?;
let retained = update_state::RetainedSet::bootstrap_metadata()?;
let mut observed = Vec::new();
for role in [
Role::Agent,
Role::Helper,
Role::Settings,
Role::Pin,
Role::TimeProfile,
] {
observed.push(serde_json::json!({"role":role,"proof":files::observe(role,&budget)?}));
}
let updater = if let Some(sha) = updater_sha256 {
ensure!(ipc::digest(&sha), "BOOTSTRAP_UPDATER_IMAGE");
let pin = ipc::PeerPin {
service_name: rmm_agent_windows::update_ipc::SERVICE.into(),
service_sid: ipc::service_sid(rmm_agent_windows::update_ipc::SERVICE)?,
user_sid: "S-1-5-18".into(),
binary: rmm_agent_windows::update_ipc::BINARY.into(),
binary_sha256: sha,
};
let readers = [pin.service_sid.clone()];
let mut image = ipc::PinnedFile::open(&pin.binary, false, &readers, &[], false)?;
ensure!(
image.sha256()? == pin.binary_sha256,
"BOOTSTRAP_REGISTERED_UPDATER_IMAGE"
);
let definition = services::updater_bootstrap_definition(&pin)?;
image.check()?;
Some(
serde_json::json!({"pin":pin,"configuration_sha256":hash(&serde_json::to_vec(&definition)?),"configuration":definition,"running_not_qualified":true}),
)
} else {
None
};
running.check(&budget)?;
Ok(
serde_json::json!({"schema_version":1,"read_only":true,"boot_id":boot.current_boot()?,
"binding":settings.binding,"services":running.proofs(),"files":observed,"retained":retained,
"reader_contract_sha256":hash(update_state::READER_CONTRACT),"updater":updater,
"readiness_created":false,"target_mutated":false,"qualification_created":false}),
)
}
fn run(input: Input) -> Result<serde_json::Value> {
Ok(match input {
Input::ReadMetadata { updater_sha256 } => read_metadata(updater_sha256)?,
Input::RenderPair {
settings,
agent_sha256,
helper_sha256,
} => {
ensure!(
ipc::digest(&agent_sha256) && ipc::digest(&helper_sha256),
"BOOTSTRAP_PAIR_DIGESTS"
);
let mut s: helper_system::Settings = serde_json::from_slice(&settings)?;
s.validate()?;
s.agent.binary_sha256 = agent_sha256;
s.helper.binary_sha256 = helper_sha256;
s.validate()?;
let raw = serde_json::to_vec(&s)?;
let pin = s.pin()?;
ensure!(pin.policy_sha256 == hash(&raw), "BOOTSTRAP_CANONICAL_PAIR");
serde_json::json!({"settings":bytes(raw),"pin":bytes(serde_json::to_vec(&pin)?),"shape_only":true})
}
Input::RenderUpdaterClock {
pair_profile,
updater_sha256,
policy_sha256,
service_configuration_sha256,
qualification_sha256,
} => {
ensure!(
[
&updater_sha256,
&policy_sha256,
&service_configuration_sha256,
&qualification_sha256
]
.iter()
.all(|s| ipc::digest(s)),
"BOOTSTRAP_UPDATER_CLOCK_DIGESTS"
);
let profile: signed_clock::Configuration = serde_json::from_slice(&pair_profile)?;
let signed_clock::Configuration::TrustedOs(p) = profile else {
anyhow::bail!("BOOTSTRAP_EXPLICIT_ACTIVE_GUEST_PROFILE_REQUIRED")
};
ensure!(
p.schema_version == 2
&& p.trusted_os_active_guest.qualifications.len() == 2
&& p.trusted_os_active_guest.qualifications[0].role
== rmm_time_attestation::Role::Agent
&& p.trusted_os_active_guest.qualifications[1].role
== rmm_time_attestation::Role::SystemHelper,
"BOOTSTRAP_ORIGINAL_PAIR_PROFILE"
);
let mut guest = p.trusted_os_active_guest;
guest.qualifications = vec![signed_clock::RoleQualification {
role: rmm_time_attestation::Role::Updater,
binary_sha256: updater_sha256,
qualification_sha256,
}];
let new = signed_clock::UpdaterConfiguration {
schema_version: 3,
key_generation: p.key_generation,
server_instance: p.server_instance,
binding: p.binding,
public_keys_hex: p.public_keys_hex,
updater_policy_sha256: policy_sha256,
updater_service_configuration_sha256: service_configuration_sha256,
trusted_os_active_guest: guest,
};
serde_json::json!({"profile":bytes(serde_json::to_vec(&new)?),"shape_only":true,"qualification_created":false})
}
Input::CanonicalRelease { manifest } => {
ensure!(manifest.validate(), "BOOTSTRAP_RELEASE_SHAPE");
bytes(serde_json::to_vec(&manifest)?)
}
Input::CanonicalRecord { record } => bytes(record.bytes().map_err(anyhow::Error::msg)?),
Input::CanonicalPolicy { policy } => {
ensure!(
policy.validate() && policy.schema_version == 2,
"BOOTSTRAP_WINDOWS_POLICY_SHAPE"
);
bytes(serde_json::to_vec(&policy)?)
}
Input::ValidateRelease { envelope } => {
let decoded = envelope.decode().map_err(anyhow::Error::msg)?;
serde_json::json!({"manifest":decoded.manifest,"manifest_sha256":hash(&decoded.payload_bytes),"shape_only_not_signature_verified":true})
}
Input::ValidatePublicBundle {
record,
policy,
keyring,
health_pin,
} => {
let installed =
InstalledReleaseRecord::from_bytes(&record).map_err(anyhow::Error::msg)?;
let (policy, policy_sha256) =
LocalUpdatePolicy::from_bytes(&policy).map_err(anyhow::Error::msg)?;
let keys: UpdateKeyringFile = serde_json::from_slice(&keyring)?;
let health: HealthKeyPin = serde_json::from_slice(&health_pin)?;
ensure!(
keys.validate()
&& health.validate()
&& policy.schema_version == 2
&& policy.initial_record_sha256 == hash(&record)
&& policy.initial_activation_floor == installed.activation_floor,
"BOOTSTRAP_WINDOWS_PUBLIC_BUNDLE_SHAPE"
);
serde_json::json!({"record_sha256":hash(&record),"policy_sha256":policy_sha256,"keyring_sha256":hash(&keyring),"health_pin_sha256":hash(&health_pin),"shape_only_not_signature_verified":true})
}
})
}
pub fn main() -> Result<()> {
let mut raw = Vec::new();
std::io::stdin()
.take(512 * 1024 + 1)
.read_to_end(&mut raw)?;
ensure!(
!raw.is_empty() && raw.len() <= 512 * 1024,
"BOOTSTRAP_METADATA_FRAME_LIMIT"
);
println!(
"{}",
serde_json::to_string(&run(serde_json::from_slice(&raw)?)?)?
);
Ok(())
}
}
#[cfg(all(windows, feature = "system-helper"))]
fn main() {
if sdk::main().is_err() {
eprintln!("WINDOWS_BOOTSTRAP_METADATA_FAILED");
std::process::exit(1)
}
}
#[cfg(not(all(windows, feature = "system-helper")))]
fn main() {
eprintln!("Windows/system-helper required; no operation executed");
std::process::exit(2)
}
@@ -0,0 +1,25 @@
//! Stable updater is installed separately from the two mutable code roles.
#[cfg(windows)]
fn main() -> anyhow::Result<()> {
let mut args = std::env::args_os().skip(1);
match args.next().as_deref() {
None => rmm_agent_windows::update_worker::dispatch(),
Some(flag) if flag == "--release-service" && args.next().is_none() => {
rmm_agent_windows::release_service::dispatch()
}
Some(flag) if flag == "--verify-bootstrap" => {
let release = rmm_updater::verify_bootstrap_files(
rmm_agent_windows::release_platform::VERIFY,
&args.collect::<Vec<_>>(),
)?;
println!("{}", serde_json::to_string(release.manifest())?);
Ok(())
}
_ => anyhow::bail!("unrecognized Windows updater arguments"),
}
}
#[cfg(not(windows))]
fn main() {
eprintln!("Windows stable updater requires a Windows target");
std::process::exit(1);
}
@@ -1,6 +1,7 @@
//! Passive TLS renewal. SQLite commits only public CSR/certificate/version data;
//! private keys stay in immutable, protected files outside the telemetry WAL.
//! The caller must retain the existing exclusive agent-state journal lock.
//! Mutation/current callers retain the exclusive agent-state journal lock.
//! `read_only_current` is the bounded, snapshot-only stable-updater exception.
use anyhow::{Context, Result, ensure};
use rcgen::{CertificateParams, DnType, KeyPair};
use rusqlite::{Connection, OptionalExtension, params};
@@ -119,6 +120,48 @@ impl RotationStore {
private_key_pem: key,
})
}
/// Independent stable-updater mTLS read ONLY. This cannot initialize,
/// rotate, acknowledge, alter selectors, enroll or allocate a generation.
/// Concurrent rotation may make transport fail; it never selects a key
/// from another device or treats old TLS as an execution/sync lease.
pub fn read_only_current(
&self,
db: &Connection,
keys: &impl KeyFiles,
now: i64,
) -> Result<DeviceIdentity> {
ensure!(
unsafe { rusqlite::ffi::sqlite3_db_readonly(db.handle(), c"main".as_ptr()) } == 1
&& db.query_row("PRAGMA query_only", [], |r| r.get::<_, bool>(0))?
&& !db.query_row("PRAGMA trusted_schema", [], |r| r.get::<_, bool>(0))?,
"ROTATION_READ_ONLY_CONNECTION_REQUIRED"
);
let tx = db.unchecked_transaction()?;
for table in ["tls_rotation", "tls_versions"] {
ensure!(
tx.query_row(
"SELECT type FROM sqlite_master WHERE name=?1",
[table],
|r| r.get::<_, String>(0)
)? == "table",
"ROTATION_SELECTOR_MUST_BE_TABLE"
);
}
let (version, _) = self.selector(&tx)?;
let length: u64 = tx.query_row(
"SELECT length(certificate) FROM tls_versions WHERE version=?1",
[version.to_string()],
|r| r.get(0),
)?;
ensure!(length > 0 && length <= 32768, "ROTATION_CERTIFICATE_LIMIT");
let identity = self.current(&tx, keys, now)?;
ensure!(
self.selector(&tx)?.0 == version,
"ROTATION_READ_ONLY_SNAPSHOT_CHANGED"
);
tx.commit()?;
Ok(identity)
}
fn verify(&self, pem: &[u8], key: &[u8], now: i64) -> Result<(i64, i64)> {
ensure!(
pem.len() <= 32768 && key.len() <= 16384,
@@ -590,6 +633,29 @@ mod tests {
.unwrap()
}
#[test]
fn updater_tls_snapshot_requires_read_only_handle_and_preserves_selector() {
let (db, keys, store, _, cert) = setup();
db.execute_batch("PRAGMA trusted_schema=OFF;PRAGMA query_only=ON")
.unwrap();
assert!(store.read_only_current(&db, &keys, now()).is_err());
db.execute_batch("PRAGMA query_only=OFF").unwrap();
let path = std::env::temp_dir().join(format!("rmm-tls-read-{}.sqlite", Uuid::new_v4()));
db.execute("VACUUM INTO ?1", [path.to_str().unwrap()])
.unwrap();
let read =
Connection::open_with_flags(&path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY).unwrap();
assert!(store.read_only_current(&read, &keys, now()).is_err());
read.execute_batch("PRAGMA query_only=ON;PRAGMA trusted_schema=OFF")
.unwrap();
let before = store.selector(&read).unwrap();
let identity = store.read_only_current(&read, &keys, now()).unwrap();
assert_eq!(identity.certificate_pem, cert.as_bytes());
assert_eq!(identity.private_key_pem, keys.read(Uuid::nil()).unwrap());
assert_eq!(store.selector(&read).unwrap(), before);
drop(read);
std::fs::remove_file(path).unwrap();
}
#[test]
fn active_idle_admission_is_atomic_retained_and_cannot_adopt_legacy_pending() {
let (mut db, keys, store, _, _) = setup();
let witness = b"exact independently checked idle context";
+37 -22
View File
@@ -36,8 +36,8 @@ pub const PIPE_NAME: &str = r"\\.\pipe\RustDiscovery-System-v2";
pub const TIME_PIPE_NAME: &str = r"\\.\pipe\RustDiscovery-System-Time-v1";
const FRAME_TAG: [u8; 8] = *b"RDPIPC02";
const DRAIN_TAG: [u8; 8] = *b"RDPACK02";
const FRAME_HEADER_LEN: usize = 12;
const DRAIN_RECEIPT_LEN: usize = 56;
pub(crate) const FRAME_HEADER_LEN: usize = 12;
pub(crate) const DRAIN_RECEIPT_LEN: usize = 56;
pub const FRAME_LIMIT: usize = 1024 * 1024;
pub const CLIENT_PIPE_RIGHTS: u32 = 0x0012_0083; // data R/W, attributes R, RC, synchronize; no bit4
const READ_MASK: u32 = 0x0012_00a9;
@@ -302,6 +302,8 @@ pub enum Operation {
generation: u64,
},
Probe {},
UpdateObserve {request:crate::update_observer::Request},
UpdateHealth {request:rmm_agent_core::update_handoff::NativeControlRequest},
Snapshot {
generation: u64,
},
@@ -361,10 +363,17 @@ pub enum ReplyBody {
ready: bool,
ledger: FileIdentity,
lock: FileIdentity,
#[serde(default,skip_serializing_if="Option::is_none")]
reboot_privilege_available:Option<bool>,
/// Passive protocol negotiation only; no update capability/readiness.
#[serde(default,skip_serializing_if="Option::is_none")]
update_observer_configured:Option<bool>,
},
Snapshot {
snapshot: Snapshot,
},
UpdateObservation {response:Box<crate::update_observer::Response>},
UpdateHealth {reply:Box<rmm_agent_core::update_handoff::NativeControlReply>},
Applied {
snapshot: Snapshot,
unlocked_grants: Vec<Uuid>,
@@ -374,6 +383,9 @@ pub enum ReplyBody {
Executed {
outcome: Outcome,
},
UpdateAccepted {
accepted: crate::update_admission::Accepted,
},
Abandoned {
outcome: Outcome,
},
@@ -408,7 +420,7 @@ pub fn binding_hash(b: &Binding) -> Result<String> {
pub fn wide(s: impl AsRef<std::ffi::OsStr>) -> Vec<u16> {
s.as_ref().encode_wide().chain(Some(0)).collect()
}
fn owned(raw: HANDLE) -> Result<OwnedHandle> {
pub(crate) fn owned(raw: HANDLE) -> Result<OwnedHandle> {
if raw.is_null() || raw == INVALID_HANDLE_VALUE {
return Err(api_failure("HELPER_HANDLE"));
}
@@ -540,7 +552,7 @@ pub fn require_self(peer: &PeerPin) -> Result<()> {
let token = owned(token)?;
verify_token(token.as_raw_handle(), &peer.user_sid, &peer.service_sid)
}
fn check_acl(
pub(crate) fn check_acl(
handle: HANDLE,
readers: &[String],
writers: &[String],
@@ -801,7 +813,7 @@ impl Drop for ServiceHandle {
}
}
}
fn service_status(pin: &PeerPin) -> Result<u32> {
pub(crate) fn service_status(pin: &PeerPin) -> Result<u32> {
let manager =
ServiceHandle(unsafe { OpenSCManagerW(ptr::null(), ptr::null(), SC_MANAGER_CONNECT) });
ensure!(!manager.0.is_null(), "HELPER_SCM_MANAGER");
@@ -906,7 +918,7 @@ impl ProcessIdentity {
}
}
impl PeerProof {
fn capture(pipe: HANDLE, pin: &PeerPin, client: bool) -> Result<Self> {
pub(crate) fn capture(pipe: HANDLE, pin: &PeerPin, client: bool) -> Result<Self> {
let mut pid = 0;
ensure!(
unsafe {
@@ -923,7 +935,7 @@ impl PeerProof {
}
/// Internal fixture admission shares the exact same live-process proof as
/// both pipe peers. The caller supplies the PID read from its held SCM handle.
pub(crate) fn for_service(pin: &PeerPin, pid: u32) -> Result<Self> {
pub fn for_service(pin: &PeerPin, pid: u32) -> Result<Self> {
ensure!(pid == service_status(pin)?, "HELPER_PIPE_SCM_PID");
let process =
owned(unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, 0, pid) })?;
@@ -1040,9 +1052,9 @@ impl PeerProof {
}
}
struct Descriptor(*mut c_void);
pub(crate) struct Descriptor(pub(crate) *mut c_void);
impl Descriptor {
fn from(s: &str) -> Result<Self> {
pub(crate) fn from(s: &str) -> Result<Self> {
let mut descriptor = ptr::null_mut();
ensure!(
unsafe {
@@ -1106,18 +1118,18 @@ fn pipe_descriptor(agent: &str, helper: &str) -> Result<Descriptor> {
))
}
struct IoEvent {
pub(crate) struct IoEvent {
event: OwnedHandle,
overlapped: OVERLAPPED,
pub(crate) overlapped: OVERLAPPED,
}
impl IoEvent {
fn new() -> Result<Self> {
pub(crate) fn new() -> Result<Self> {
let event = owned(unsafe { CreateEventW(ptr::null(), 1, 0, ptr::null()) })?;
let mut overlapped: OVERLAPPED = unsafe { zeroed() };
overlapped.hEvent = event.as_raw_handle();
Ok(Self { event, overlapped })
}
fn wait(&mut self, pipe: HANDLE, deadline: Instant) -> Result<u32> {
pub(crate) fn wait(&mut self, pipe: HANDLE, deadline: Instant) -> Result<u32> {
let left = deadline.saturating_duration_since(Instant::now());
let milliseconds = u32::try_from(left.as_millis().max(1)).unwrap_or(u32::MAX - 1);
if unsafe { WaitForSingleObject(self.event.as_raw_handle(), milliseconds) } != WAIT_OBJECT_0
@@ -1167,7 +1179,7 @@ impl IoEvent {
Ok(count)
}
}
fn transfer(pipe: HANDLE, bytes: &mut [u8], write: bool, deadline: Instant) -> Result<()> {
pub(crate) fn transfer(pipe: HANDLE, bytes: &mut [u8], write: bool, deadline: Instant) -> Result<()> {
let mut offset = 0;
while offset < bytes.len() {
ensure!(Instant::now() < deadline, "HELPER_PIPE_TIMEOUT");
@@ -1222,7 +1234,7 @@ impl Write for LimitedJson {
Ok(())
}
}
fn encode(value: &impl Serialize) -> Result<Vec<u8>> {
pub(crate) fn encode(value: &impl Serialize) -> Result<Vec<u8>> {
let mut writer = LimitedJson(Vec::with_capacity(FRAME_LIMIT));
serde_json::to_writer(&mut writer, value)?;
ensure!(!writer.0.is_empty(), "HELPER_FRAME_EMPTY");
@@ -1235,12 +1247,12 @@ fn frame_header(len: usize) -> Result<[u8; FRAME_HEADER_LEN]> {
header[8..].copy_from_slice(&u32::try_from(len)?.to_be_bytes());
Ok(header)
}
fn send_bytes(pipe: HANDLE, bytes: &mut [u8], deadline: Instant) -> Result<()> {
pub(crate) fn send_bytes(pipe: HANDLE, bytes: &mut [u8], deadline: Instant) -> Result<()> {
let mut header = frame_header(bytes.len())?;
transfer(pipe, &mut header, true, deadline)?;
transfer(pipe, bytes, true, deadline)
}
fn send(pipe: HANDLE, value: &impl Serialize, deadline: Instant) -> Result<()> {
pub(crate) fn send(pipe: HANDLE, value: &impl Serialize, deadline: Instant) -> Result<()> {
send_bytes(pipe, &mut encode(value)?, deadline)
}
fn frame_length(header: [u8; FRAME_HEADER_LEN]) -> Result<usize> {
@@ -1249,30 +1261,30 @@ fn frame_length(header: [u8; FRAME_HEADER_LEN]) -> Result<usize> {
ensure!((1..=FRAME_LIMIT).contains(&len), "HELPER_FRAME_LENGTH");
Ok(len)
}
fn length(pipe: HANDLE, deadline: Instant) -> Result<usize> {
pub(crate) fn length(pipe: HANDLE, deadline: Instant) -> Result<usize> {
let mut header = [0u8; FRAME_HEADER_LEN];
transfer(pipe, &mut header, false, deadline)?;
frame_length(header)
}
fn body_bytes(pipe: HANDLE, len: usize, deadline: Instant) -> Result<Vec<u8>> {
pub(crate) fn body_bytes(pipe: HANDLE, len: usize, deadline: Instant) -> Result<Vec<u8>> {
ensure!((1..=FRAME_LIMIT).contains(&len), "HELPER_FRAME_LENGTH");
let mut bytes = vec![0u8; len];
transfer(pipe, &mut bytes, false, deadline)?;
Ok(bytes)
}
fn body<T: DeserializeOwned>(pipe: HANDLE, len: usize, deadline: Instant) -> Result<T> {
pub(crate) fn body<T: DeserializeOwned>(pipe: HANDLE, len: usize, deadline: Instant) -> Result<T> {
Ok(serde_json::from_slice(&body_bytes(pipe, len, deadline)?)?)
}
// This fixed-size receipt only acknowledges receipt of these transport bytes.
// It never acknowledges durable evidence, clears state, or permits an effect.
fn drain_receipt(challenge: Uuid, reply_bytes: &[u8]) -> [u8; DRAIN_RECEIPT_LEN] {
pub(crate) fn drain_receipt(challenge: Uuid, reply_bytes: &[u8]) -> [u8; DRAIN_RECEIPT_LEN] {
let mut receipt = [0; DRAIN_RECEIPT_LEN];
receipt[..8].copy_from_slice(&DRAIN_TAG);
receipt[8..24].copy_from_slice(challenge.as_bytes());
receipt[24..].copy_from_slice(&Sha256::digest(reply_bytes));
receipt
}
fn verify_drain_receipt(
pub(crate) fn verify_drain_receipt(
receipt: &[u8; DRAIN_RECEIPT_LEN],
challenge: Uuid,
reply_bytes: &[u8],
@@ -1470,8 +1482,11 @@ fn exchange_fixed(pin: &Pin, call: &Call, timeout: Duration, time_only: bool) ->
(_, ReplyBody::Denied { .. })
| (Operation::Probe { .. }, ReplyBody::Probe { .. })
| (Operation::Snapshot { .. }, ReplyBody::Snapshot { .. })
| (Operation::UpdateHealth {..},ReplyBody::UpdateHealth{..})
| (Operation::UpdateObserve {..},ReplyBody::UpdateObservation{..})
| (Operation::Apply { .. }, ReplyBody::Applied { .. })
| (Operation::Execute { .. }, ReplyBody::Executed { .. })
| (Operation::Execute { .. }, ReplyBody::UpdateAccepted { .. })
| (Operation::Abandon { .. }, ReplyBody::Abandoned { .. })
| (Operation::TimeBegin { .. }, ReplyBody::TimeChallenge { .. })
| (
+455 -26
View File
@@ -25,8 +25,11 @@ const PROBE_FILE: &str = "helper-probe.json";
#[derive(Clone)]
pub struct Client {
pin: ipc::Pin,
raw_pin_sha256: String,
raw_settings_sha256: String,
lane: Arc<Semaphore>,
qualified_capabilities: Vec<String>,
update_observer_configured:bool,
probed_at: Option<std::time::Instant>,
}
pub struct ControlSnapshot {
@@ -62,6 +65,28 @@ impl Client {
file.file.read_to_end(&mut bytes)?;
let pin: ipc::Pin = serde_json::from_slice(&bytes)?;
pin.validate()?;
let mut settings_file = ipc::PinnedFile::open(
Path::new(crate::helper_system::CONFIG_PATH),
false,
&readers,
&[],
false,
)?;
ensure!(
settings_file.file.metadata()?.len() <= 32768,
"HELPER_SETTINGS_LIMIT"
);
let mut settings_raw = Vec::new();
(&mut settings_file.file)
.take(32769)
.read_to_end(&mut settings_raw)?;
ensure!(settings_raw.len() <= 32768, "HELPER_SETTINGS_LIMIT");
let settings: crate::helper_system::Settings = serde_json::from_slice(&settings_raw)?;
ensure!(
serde_json::to_vec(&settings.pin()?)? == serde_json::to_vec(&pin)?,
"HELPER_CURRENT_SETTINGS_PIN_BINDING"
);
settings_file.check()?;
ensure!(
pin.binding.agent_id.to_string() == agent_id
&& pin.binding.asset_id.to_string() == asset_id
@@ -75,7 +100,15 @@ impl Client {
"HELPER_JOB_BINDING_MISMATCH"
);
}
Ok(Some(Self { pin, lane, qualified_capabilities:vec![], probed_at:None }))
Ok(Some(Self {
raw_pin_sha256: rmm_domain::jobs::hash(&bytes),
raw_settings_sha256: rmm_domain::jobs::hash(&settings_raw),
pin,
lane,
qualified_capabilities: vec![],
update_observer_configured:false,
probed_at: None,
}))
}
pub async fn refresh(
agent_id: String,
@@ -112,7 +145,9 @@ impl Client {
)?
.context("HELPER_PIN_REMOVED")?;
ensure!(
serde_json::to_vec(&current.pin)? == serde_json::to_vec(&self.pin)?,
serde_json::to_vec(&current.pin)? == serde_json::to_vec(&self.pin)?
&& current.raw_pin_sha256 == self.raw_pin_sha256
&& current.raw_settings_sha256 == self.raw_settings_sha256,
"HELPER_PIN_CHANGED"
);
Ok(())
@@ -123,6 +158,32 @@ impl Client {
pub fn helper_binary_hash(&self) -> &str {
&self.pin.helper.binary_sha256
}
fn retained_intent_context(&self, intent: &intent::Intent, job: &JobPayload) -> bool {
if intent.policy_sha256 == self.pin.policy_sha256
&& intent.helper_binary_sha256 == self.pin.helper.binary_sha256
{
return true;
}
let Action::UpdateAgent { update } = &job.action else {
return false;
};
let rmm_domain::agent_update::PeerPinTransition::WindowsCodePairV1 {
new_pin_sha256,
new_settings_sha256,
time_profile: Some(_),
..
} = &update.peer_pin_transition
else {
return false;
};
update.validate()
&& intent.helper_binary_sha256 == update.predecessor.helper_sha256
&& update
.manifest()
.is_ok_and(|manifest| manifest.artifacts[1].sha256 == self.pin.helper.binary_sha256)
&& *new_pin_sha256 == self.raw_pin_sha256
&& *new_settings_sha256 == self.raw_settings_sha256
}
/// Import only independently authenticated raw helper evidence. c+start is
/// atomic through the existing core API. A crash before outcome persistence
/// stays locked; the next fresh snapshot repairs that exact start idempotently.
@@ -159,9 +220,9 @@ impl Client {
let permit = intent.permit()?;
ensure!(
self.supports_system(&job)
&& intent.policy_sha256 == self.pin.policy_sha256
&& intent.helper_binary_sha256 == self.pin.helper.binary_sha256
&& snapshot.boot_id == intent.original_boot_id
&& self.retained_intent_context(&intent, &job)
&& (snapshot.boot_id == intent.original_boot_id
|| rmm_domain::windows_reboot::supported(&job))
&& snapshot.journal_id == intent.anchor.journal_id()
&& snapshot.checkpoint >= intent.anchor.checkpoint()
&& observed_at >= intent.recorded_at
@@ -176,8 +237,78 @@ impl Client {
.next()
.context("SYSTEM_DELEGATION_NO_HELPER_EVIDENCE")?;
ensure!(matches.next().is_none(), "SYSTEM_DUPLICATE_HELPER_ATTEMPT");
if matches!(job.action, Action::UpdateAgent { .. })
&& !row.update_handoff_bytes.is_empty()
{
let proof = rmm_domain::agent_update::UpdateInflightProof::from_bytes(
&row.update_handoff_bytes,
)
.map_err(anyhow::Error::msg)?;
let key = rmm_domain::agent_update::job_health_public_key(&job)
.map_err(anyhow::Error::msg)?;
let (handoff, _) = rmm_domain::agent_update::verify_inflight_proof(&proof, key)
.map_err(anyhow::Error::msg)?;
ensure!(
rmm_domain::agent_update::handoff_matches_job(&handoff, &job)
&& handoff.attempt.grant_id == permit.grant_id
&& row.job_id == job.job_id
&& row.attempt_id == job.attempt_id
&& row.job_payload_hash == permit.job_payload_hash
&& row.authorization_id == permit.authorization_id
&& row.plan_hash == permit.plan_hash
&& row.action == permit.action
&& row.execution_identity == "system"
&& row.grant_id == permit.grant_id
&& row.original_request_sha256
== rmm_domain::jobs::hash(&serde_json::to_vec(&intent.request)?)
&& row.original_boot_id == intent.original_boot_id
&& handoff.boot_id == intent.original_boot_id
&& row.state == "running"
&& row.consumption == "consumed"
&& row.outcome_bytes.is_empty()
&& row.outcome_sha256.is_empty()
&& snapshot.journal_id == handoff.helper_journal_id,
"UPDATE_MIRROR_ORIGINAL_INFLIGHT"
);
let start = core_ledger::start_witness_bytes(
&permit,
&intent.request,
handoff.boot_id,
proof.delegation.prepared_at,
)?;
ensure!(
rmm_domain::jobs::hash(&start) == handoff.attempt.original_start_witness_sha256,
"UPDATE_MIRROR_ORIGINAL_START"
);
let existing: Option<Vec<u8>> = ledger
.query_row(
"SELECT start FROM execution_evidence WHERE grant_id=?1",
[permit.grant_id.to_string()],
|r| r.get(0),
)
.optional()?;
if let Some(existing) = existing {
ensure!(existing == start, "UPDATE_MIRROR_LOCAL_START_CONFLICT");
} else {
core_ledger::begin_execution(
ledger,
&permit,
&intent.request,
handoff.boot_id,
proof.delegation.prepared_at,
)?;
}
continue;
}
let outcome =
verified_mirror_row(row, &job, &permit, &intent.request, intent.original_boot_id)?;
if rmm_domain::windows_reboot::supported(&job) && outcome.state == "succeeded" {
ensure!(
snapshot.boot_id != intent.original_boot_id
&& outcome.evidence["new_boot_id"] == snapshot.boot_id.to_string(),
"SYSTEM_REBOOT_MIRROR_NEW_BOOT"
);
}
let existing:Option<(String,u64,String,String,Vec<u8>)>=ledger.query_row("SELECT c.agent,c.generation,c.job,c.attempt,e.start FROM consumed c JOIN execution_evidence e USING(grant_id) WHERE c.grant_id=?1",[permit.grant_id.to_string()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?))).optional()?;
if let Some((agent, generation, j, a, start)) = existing {
let start: serde_json::Value = serde_json::from_slice(&start)?;
@@ -189,9 +320,16 @@ impl Client {
&& a == job.attempt_id.to_string()
&& serde_json::to_vec(&request)? == serde_json::to_vec(&intent.request)?
&& start["previous_boot_id"] == intent.original_boot_id.to_string()
&& serde_json::from_value::<chrono::DateTime<chrono::Utc>>(
start["reserved_at"].clone()
)? == intent.recorded_at,
&& {
let at = serde_json::from_value::<chrono::DateTime<chrono::Utc>>(
start["reserved_at"].clone(),
)?;
if matches!(job.action, Action::UpdateAgent { .. }) {
at >= permit.not_before && at < permit.start_before
} else {
at == intent.recorded_at
}
},
"SYSTEM_MIRROR_LOCAL_START_CONFLICT"
);
} else {
@@ -226,10 +364,9 @@ impl Client {
== Some(row.outcome_sha256.as_str());
ensure!(
self.supports_system(&job)
&& ((intent.policy_sha256 == self.pin.policy_sha256
&& intent.helper_binary_sha256 == self.pin.helper.binary_sha256)
|| mirrored)
&& snapshot.boot_id == intent.original_boot_id
&& (self.retained_intent_context(&intent, &job) || mirrored)
&& (snapshot.boot_id == intent.original_boot_id
|| rmm_domain::windows_reboot::supported(&job))
&& snapshot.journal_id == intent.anchor.journal_id()
&& snapshot.checkpoint >= intent.anchor.checkpoint(),
"SYSTEM_MIRROR_CONTEXT"
@@ -358,25 +495,48 @@ impl Client {
ready,
ledger,
lock,
reboot_privilege_available,
update_observer_configured,
} = reply.body
else {
anyhow::bail!("HELPER_PROBE_DENIED");
};
let value = json!({"schema_version":1,"source":"actual_local_service_runtime","agent_process_id":std::process::id(),"agent_service":crate::SERVICE_NAME,"agent_id":pin.binding.agent_id,"asset_id":pin.binding.asset_id,"challenge":reply.challenge,"observed_at":chrono::Utc::now(),"helper_service":ipc::HELPER_SERVICE,"verified_helper_user_sid":pin.helper.user_sid,"verified_helper_service_sid":pin.helper.service_sid,"helper_binary_sha256":reply.helper_binary_sha256,"policy_sha256":reply.policy_sha256,"authenticated_pipe_exchange":true,"client_service_pid_verified_by_helper":true,"ledger_file_id":ledger,"executor_lock_file_id":lock,"helper_clock_qualified":clock_qualified,"helper_ready":ready,"system_capability_advertised":false,"no_jobs":true});
self.check_pin()?;
// Advertise the static qualification independently of this connection's
// clock warm-up: a capability change forces a reconnect, which resets the
// per-generation clock again. Every start stays gated by helper readiness.
let _ = clock_qualified;
self.qualified_capabilities=crate::system_capabilities::qualified(pin,true)?;
self.probed_at=Some(std::time::Instant::now());
let mut value=value;
value["system_capability_advertised"]=json!(!self.qualified_capabilities.is_empty());
value["qualified_capabilities"]=json!(self.qualified_capabilities);
// Static qualification only; a per-connection clock warm-up must not flap
// advertised capabilities (each change forces a reconnect).
let qualification=crate::system_capabilities::qualified(pin,true,reboot_privilege_available);
let system_qualification_unavailable=qualification.is_err();
// Capability evidence is deny-only. A missing/stale optional record
// cannot remove the separately authenticated control/SignedSync lane.
self.qualified_capabilities=qualification.unwrap_or_default();
self.update_observer_configured=update_observer_configured==Some(true);
self.probed_at = Some(std::time::Instant::now());
let mut value = value;
if system_qualification_unavailable {
value["system_qualification_diagnostic"]="SYSTEM_QUALIFICATION_UNAVAILABLE".into();
}
value["system_capability_advertised"] = json!(!self.qualified_capabilities.is_empty());
value["qualified_capabilities"] = json!(self.qualified_capabilities);
if let Some(available) = reboot_privilege_available {
value["reboot_privilege_available"] = json!(available);
}
write_current_probe(state, &value).context(ipc::Stage::ClientReport)
}
/// An actual recent authenticated Probe negotiates the passive method.
/// Old helpers/missing local policy return false; never probe unknown IPC.
pub fn update_observer_configured(&self)->bool {
self.update_observer_configured && self.probed_at.is_some_and(|at|at.elapsed()<=Duration::from_secs(90))
}
pub fn qualified_capabilities(&self) -> Vec<String> {
if self.probed_at.is_some_and(|at|at.elapsed()<=Duration::from_secs(90)) {self.qualified_capabilities.clone()} else {vec![]}
if self
.probed_at
.is_some_and(|at| at.elapsed() <= Duration::from_secs(90))
{
self.qualified_capabilities.clone()
} else {
vec![]
}
}
/// Pure admission shape only; no capability or qualification is asserted.
pub fn supports_system(&self, job: &JobPayload) -> bool {
@@ -394,13 +554,17 @@ impl Client {
&self,
intent: intent::Intent,
admit: impl Fn() -> Result<()> + Send + 'static,
) -> Result<()> {
) -> Result<Option<crate::update_admission::Accepted>> {
let job = self.pin.binding.job(&intent.request.job_bytes)?;
ensure!(
intent.connection_generation > 0 && self.supports_system(&job),
"SYSTEM_TYPED_SERVICE_REQUIRED"
);
let timeout = execution_timeout(job.max_runtime_seconds)?;
let timeout = if matches!(job.action, Action::UpdateAgent { .. }) {
Duration::from_secs(60)
} else {
execution_timeout(job.max_runtime_seconds)?
};
let permit = self
.lane
.clone()
@@ -438,6 +602,14 @@ impl Client {
let call = ipc::Call::new(&client.pin, operation);
let reply = ipc::exchange(&client.pin, &call, timeout)?;
client.check_pin()?;
if let ipc::ReplyBody::UpdateAccepted { accepted } = &reply.body {
ensure!(
matches!(job.action, Action::UpdateAgent { .. }),
"UPDATE_ACK_FOR_NONUPDATE"
);
accepted.matches(&intent.request, intent.permit()?.grant_id)?;
return Ok(Some(accepted.clone()));
}
let outcome = match reply.body {
ipc::ReplyBody::Executed { outcome }
| ipc::ReplyBody::Abandoned { outcome } => outcome,
@@ -446,7 +618,7 @@ impl Client {
checked_outcome(&job, &outcome)?;
// A reply is never the consumption/mirror witness. Every outcome,
// including a successful reply, requires a fresh raw snapshot.
Ok::<_, anyhow::Error>(())
Ok::<_, anyhow::Error>(None)
}),
)
.await
@@ -476,6 +648,101 @@ impl Client {
);
Ok(())
}
/// Independent passive measurements only; returned records grant no job.
pub async fn observe_update(&self,request:crate::update_observer::Request)->Result<crate::update_observer::Response> {
let permit=tokio::time::timeout(Duration::from_secs(5),self.lane.clone().acquire_owned()).await.context("UPDATE_OBSERVER_LANE_BUSY")??;
let client=self.clone();
tokio::task::spawn_blocking(move||->Result<crate::update_observer::Response>{
let _permit=permit;client.check_pin()?;
let reply=ipc::exchange(&client.pin,&ipc::Call::new(&client.pin,ipc::Operation::UpdateObserve{request:request.clone()}),Duration::from_secs(15))?;
client.check_pin()?;
let ipc::ReplyBody::UpdateObservation{response}=reply.body else {anyhow::bail!("UPDATE_OBSERVER_HELPER_DENIED");};
response.validate(request.generation)?;
ensure!(response.observation.predecessor.as_ref().is_some_and(|p|p.agent_sha256==client.pin.agent.binary_sha256 && p.helper_sha256==client.pin.helper.binary_sha256),"UPDATE_OBSERVER_ACTUAL_PAIR");
Ok(*response)
}).await?
}
/// Evidence-only metadata for the already consumed original Update job.
/// No LocalService caller can claim Stop/Finalize through this route.
pub async fn submit_update_health(
&self,
handoff: &rmm_updater_handoff::Handoff,
key: [u8; 32],
receipt: rmm_updater_handoff::SignedHealth,
) -> Result<()> {
use rmm_agent_core::update_handoff::{NativeControlOperation, NativeControlRequest};
handoff.validate()?;
let request = NativeControlRequest {
operation: "agent_update_control_v1".into(),
schema_version: 1,
challenge: uuid::Uuid::new_v4(),
tenant_id: handoff.attempt.tenant_id,
asset_id: handoff.attempt.asset_id,
agent_id: handoff.attempt.agent_id,
enrollment_generation: handoff.attempt.enrollment_generation,
assignment_version: handoff.attempt.assignment_version,
grant_id: handoff.attempt.grant_id,
owner_nonce: handoff.owner_nonce,
handoff_sha256: rmm_domain::jobs::hash(&handoff.bytes()?),
method: NativeControlOperation::Health { receipt },
};
let permit =
tokio::time::timeout(Duration::from_secs(5), self.lane.clone().acquire_owned())
.await
.context("UPDATE_HEALTH_CONTROL_BUSY")??;
let client = self.clone();
tokio::task::spawn_blocking(move || -> Result<()> {
let _permit = permit;
client.check_pin()?;
let reply = ipc::exchange(
&client.pin,
&ipc::Call::new(
&client.pin,
ipc::Operation::UpdateHealth {
request: request.clone(),
},
),
Duration::from_secs(5),
)?;
client.check_pin()?;
let ipc::ReplyBody::UpdateHealth { reply } = reply.body else {
anyhow::bail!("UPDATE_HEALTH_HELPER_DENIED");
};
ensure!(
reply.schema_version == 1
&& reply.challenge == request.challenge
&& !reply.ready
&& reply.grant_id == request.grant_id
&& reply.owner_nonce == request.owner_nonce
&& reply.handoff_sha256 == request.handoff_sha256
&& reply.tenant_id == request.tenant_id
&& reply.asset_id == request.asset_id
&& reply.agent_id == request.agent_id
&& reply.enrollment_generation == request.enrollment_generation
&& reply.assignment_version == request.assignment_version
&& reply.original_start_base64url.is_none()
&& reply.pre_stop_sync_request_base64url.is_none()
&& reply.pre_stop_sync_response_base64url.is_none()
&& reply.claim.is_none()
&& reply.original_outcome_base64url.is_none(),
"UPDATE_HEALTH_REPLY_BINDING"
);
let proof = reply.proof.context("UPDATE_HEALTH_REPLY_PROOF")?;
let (actual, journal) = rmm_domain::agent_update::verify_inflight_proof(&proof, key)
.map_err(anyhow::Error::msg)?;
ensure!(
rmm_domain::jobs::hash(&actual.bytes()?) == request.handoff_sha256
&& matches!(
journal.phase(),
rmm_updater_handoff::Phase::HealthVerified
| rmm_updater_handoff::Phase::RollbackHealthVerified
),
"UPDATE_HEALTH_ORIGINAL_PROOF"
);
Ok(())
})
.await?
}
pub async fn snapshot(&self, generation: u64, boot: uuid::Uuid) -> Result<ControlSnapshot> {
let reply = self.call(ipc::Operation::Snapshot { generation }).await?;
let ipc::ReplyBody::Snapshot { snapshot } = reply.body else {
@@ -599,6 +866,18 @@ fn verified_mirror_row(
Ok(outcome)
}
fn system_shape(job: &JobPayload) -> bool {
if let Action::UpdateAgent { update } = &job.action {
return job.execution_identity == "system"
&& job.max_runtime_seconds == 600
&& update.validate()
&& update.execution_identity() == Some("system")
&& job
.action
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes);
}
if matches!(job.action, Action::Reboot { .. }) {
return rmm_domain::windows_reboot::supported(job);
}
if job.action.full_maintenance() {
return job.execution_identity == "system"
&& job.action.validate()
@@ -627,6 +906,123 @@ fn execution_timeout(seconds: u32) -> Result<Duration> {
Ok(Duration::from_secs(u64::from(seconds) + 5))
}
pub(super) fn checked_outcome(job: &JobPayload, outcome: &Outcome) -> Result<()> {
if let Action::UpdateAgent { update } = &job.action {
ensure!(
system_shape(job)
&& outcome.stdout.is_empty()
&& outcome.stderr.is_empty()
&& !outcome.output_truncated
&& !outcome.reboot_required,
"UPDATE_OUTCOME_SCOPE"
);
let evidence = &outcome.evidence;
let data = &evidence["agent_update"];
match outcome.state.as_str() {
"succeeded" => {
ensure!(
outcome.exit_code == Some(0)
&& outcome.error_code.is_empty()
&& evidence["postconditions_passed"] == true
&& data["schema_version"] == 1
&& data["manifest_sha256"] == update.manifest_sha256
&& data["predecessor_record_sha256"]
== update.predecessor.installed_record_sha256
&& data["rolled_back"] == false
&& [
"handoff_sha256",
"installed_record_sha256",
"signed_health_sha256"
]
.iter()
.all(|k| data[*k]
.as_str()
.is_some_and(rmm_domain::agent_update::digest))
&& data["activation_floor"]
== update
.manifest()
.map_err(anyhow::Error::msg)?
.release_sequence,
"UPDATE_SUCCESS_EVIDENCE"
);
}
"failed" if data["rolled_back"] == true => ensure!(
outcome.exit_code.is_none()
&& outcome.error_code == "AGENT_UPDATE_RETURNED_TO_PREDECESSOR"
&& evidence["postconditions_passed"] == false
&& data["schema_version"] == 2
&& data["manifest_sha256"] == update.manifest_sha256
&& data["predecessor_record_sha256"]
== update.predecessor.installed_record_sha256
&& data["installed_record_sha256"]
== update.predecessor.installed_record_sha256
&& ["handoff_sha256", "signed_health_sha256"]
.iter()
.all(|k| data[*k]
.as_str()
.is_some_and(rmm_domain::agent_update::digest)),
"UPDATE_ROLLBACK_EVIDENCE"
),
"failed" | "cancelled" | "expired" => ensure!(
evidence["not_started"] == true && !outcome.error_code.is_empty(),
"UPDATE_NO_START_EVIDENCE"
),
"unknown" => ensure!(
evidence["postconditions_passed"] != true && !outcome.error_code.is_empty(),
"UPDATE_UNKNOWN_EVIDENCE"
),
_ => anyhow::bail!("UPDATE_NONTERMINAL_IS_NOT_OUTCOME"),
}
return Ok(());
}
if matches!(job.action, Action::Reboot { .. }) {
ensure!(
rmm_domain::windows_reboot::supported(job)
&& outcome.stdout.is_empty()
&& outcome.stderr.is_empty()
&& outcome.exit_code.is_none()
&& !outcome.output_truncated
&& !outcome.reboot_required,
"SYSTEM_REBOOT_OUTCOME_SCOPE"
);
let e = &outcome.evidence;
match outcome.state.as_str() {
"awaiting_reboot" => ensure!(
e["provider"] == "windows.shutdown/1"
&& e["native_request_accepted"] == true
&& e["postconditions_passed"] == false
&& e["force_apps_closed"] == false
&& e["local_machine_only"] == true
&& e["announcement_seconds"]
== rmm_domain::windows_reboot::ANNOUNCEMENT_SECONDS
&& e["automatic_retry"] == false
&& e["previous_boot_id"]
.as_str()
.is_some_and(|s| uuid::Uuid::parse_str(s).is_ok_and(|id| !id.is_nil())),
"SYSTEM_REBOOT_ACCEPTANCE_EVIDENCE"
),
"succeeded" => ensure!(
e["postconditions_passed"] == true
&& e["reconciled_after_reboot"] == true
&& ["new_boot_id", "inventory_message_id"].iter().all(|k| e[k]
.as_str()
.is_some_and(|s| uuid::Uuid::parse_str(s).is_ok_and(|id| !id.is_nil()))),
"SYSTEM_REBOOT_NEW_BOOT_EVIDENCE"
),
"failed" => ensure!(
!outcome.error_code.is_empty() && e["not_started"] == true,
"SYSTEM_REBOOT_NONSTART_EVIDENCE"
),
"unknown" => ensure!(
!outcome.error_code.is_empty(),
"SYSTEM_REBOOT_UNKNOWN_REASON"
),
"cancelled" | "expired" => {
ensure!(e["not_started"] == true, "SYSTEM_REBOOT_NONSTART_EVIDENCE")
}
_ => anyhow::bail!("SYSTEM_REBOOT_OUTCOME_SCOPE"),
}
return Ok(());
}
ensure!(
matches!(
outcome.state.as_str(),
@@ -856,7 +1252,9 @@ pub fn record_verified_time(
rmm_time_attestation::Role::SystemHelper => {
("helper-time-sample.json", ".helper-time.pending")
}
rmm_time_attestation::Role::Updater => anyhow::bail!("TIME_UPDATER_OWN_PROFILE_REQUIRED"),
rmm_time_attestation::Role::Updater => {
anyhow::bail!("TIME_UPDATER_EVIDENCE_NOT_AGENT_OWNED")
}
};
let value = json!({
"schema_version": 1, "agent_pid": std::process::id(), "observed_at": observed_at,
@@ -906,6 +1304,37 @@ fn write_report(state: &Path, name: &str, pending: &str, value: &serde_json::Val
mod tests {
use super::*;
#[test]
fn reboot_acceptance_is_not_success_and_cannot_inherit_another_action() {
let mut job = msi_test_job();
job.action = Action::Reboot {
reason: "Windows-MVP".into(),
dependency_group: "windows-mvp".into(),
reconnect_timeout_seconds: 180,
};
job.max_runtime_seconds = 60;
let old = uuid::Uuid::new_v4();
let mut o = Outcome {
state: "awaiting_reboot".into(),
stdout: vec![],
stderr: vec![],
exit_code: None,
output_truncated: false,
reboot_required: false,
error_code: "EFFECT_REQUIRES_RECONCILIATION".into(),
evidence: json!({"provider":"windows.shutdown/1","native_request_accepted":true,"postconditions_passed":false,"force_apps_closed":false,"local_machine_only":true,"announcement_seconds":5,"automatic_retry":false,"previous_boot_id":old}),
};
checked_outcome(&job, &o).unwrap();
o.state = "succeeded".into();
assert!(checked_outcome(&job, &o).is_err());
o.evidence = json!({"postconditions_passed":true,"reconciled_after_reboot":true,"new_boot_id":uuid::Uuid::new_v4(),"inventory_message_id":uuid::Uuid::new_v4()});
checked_outcome(&job, &o).unwrap();
o.evidence["inventory_message_id"] = json!(null);
assert!(checked_outcome(&job, &o).is_err());
job.execution_identity = "agent_service".into();
assert!(!system_shape(&job));
assert!(checked_outcome(&job, &o).is_err());
}
#[test]
fn msi_scope_requires_bound_independent_postconditions_and_exact_noop_or_installer_exit() {
let job = msi_test_job();
assert!(system_shape(&job));
+257 -81
View File
@@ -105,7 +105,7 @@ impl Settings {
})
}
fn permits_script(&self, job: &JobPayload) -> bool {
self.schema_version == 3
self.schema_version >= 3
&& job.execution_identity == "system"
&& job.action.full_maintenance()
&& job.action.valid_execution_identity("system")
@@ -117,11 +117,17 @@ impl Settings {
&& self.allowed_script_profiles.as_deref()
== Some(&[rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1])
}
fn permits_reboot(&self, job: &JobPayload) -> bool {
self.schema_version == 4
&& self.allow_reboot
&& rmm_domain::windows_reboot::supported(job)
&& job.max_runtime_seconds <= self.max_runtime_seconds
}
pub fn validate(&self) -> Result<()> {
ensure!(
matches!(self.schema_version, 1..=3)
matches!(self.schema_version, 1..=4)
&& (self.schema_version >= 2 || self.allowed_msi_recipe_sha256.is_none())
&& (self.schema_version == 3 || self.allowed_script_profiles.is_none())
&& (self.schema_version >= 3 || self.allowed_script_profiles.is_none())
&& self
.allowed_msi_recipe_sha256
.as_ref()
@@ -137,7 +143,7 @@ impl Settings {
&& self.allowed_script_profiles.as_deref().is_none_or(
|v| v == [rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1]
)
&& !self.allow_reboot
&& (self.schema_version == 4 || !self.allow_reboot)
&& (1..=120).contains(&self.max_runtime_seconds)
&& self.allowed_services.len() <= 16,
"SYSTEM_POLICY_PROFILE"
@@ -228,14 +234,14 @@ pub fn read_settings() -> Result<(Settings, Vec<PinnedFile>)> {
settings.validate()?;
Ok((settings, vec![root, file]))
}
struct WindowsBoot(Uuid);
pub struct WindowsBoot(Uuid);
impl BootSource for WindowsBoot {
fn current_boot(&self) -> Result<Uuid> {
Ok(self.0)
}
}
impl WindowsBoot {
fn capture() -> Result<Self> {
pub fn capture() -> Result<Self> {
// The exact existing fixed read-only CIM getter, independently called here.
// No caller values, execution-policy flag, or supplied command are accepted.
let rt = tokio::runtime::Builder::new_current_thread()
@@ -306,6 +312,16 @@ impl LedgerGuard {
guard.check(&db)?;
Ok((guard, db))
}
pub(crate) fn update_identity(
&self,
db: &Connection,
) -> Result<crate::update_state::LedgerIdentity> {
self.check(db)?;
Ok(crate::update_state::LedgerIdentity {
ledger: self.ledger.identity,
lock: self.lock.identity,
})
}
fn check_files(&self) -> Result<()> {
for file in [&self.root, &self.lock, &self.ledger] {
ensure!(
@@ -833,6 +849,17 @@ struct UnsettledMsi {
request_sha256: String,
installer: Box<crate::package::Installer>,
}
/// Internal native-control adapter. No caller can construct readiness, choose
/// another database, or replace the real held executor through the wire.
pub(crate) struct UpdateContext<'a> {
pub db:&'a mut Connection,
pub guard:&'a LedgerGuard,
pub binding:&'a Binding,
pub clock:&'a BoundClock,
pub pin:&'a Pin,
pub boot:&'a WindowsBoot,
pub sync:Option<&'a mut HelperSync<DalekVerifier>>,
}
pub struct SystemHelper {
settings: Settings,
pin: Pin,
@@ -845,6 +872,7 @@ pub struct SystemHelper {
last_diagnostic: Option<Instant>,
last_apply_diagnostic: Option<Instant>,
unsettled_msi: Option<UnsettledMsi>,
pending_update_activation: Option<crate::update_admission::Activation>,
}
impl SystemHelper {
pub fn open() -> Result<Self> {
@@ -870,8 +898,13 @@ impl SystemHelper {
last_diagnostic: None,
last_apply_diagnostic: None,
unsettled_msi: None,
pending_update_activation: None,
})
}
pub(crate) fn update_context(&mut self)->UpdateContext<'_> {
UpdateContext{db:&mut self.db,guard:&self.guard,binding:&self.settings.binding,clock:&self.clock,
pin:&self.pin,boot:&self.boot,sync:self.sync.as_mut()}
}
pub fn pin(&self) -> &Pin {
&self.pin
}
@@ -922,54 +955,8 @@ impl SystemHelper {
);
Ok(())
}
// One authenticated control call, same original bytes/capture/deadline.
// Only a typed clock failure proven before BEGIN can be retried.
fn apply_control_with_clock(
&mut self,
response: &rmm_agent_core::helper_reconcile::SignedResponse,
request: &[u8],
issued: chrono::DateTime<chrono::Utc>,
until: chrono::DateTime<chrono::Utc>,
) -> Result<rmm_agent_core::helper_reconcile::Applied> {
let began = Instant::now();
loop {
ensure!(
began.elapsed() < Duration::from_secs(3),
"SYSTEM_APPLY_CLOCK_WAIT_EXPIRED"
);
match crate::job_readiness::response_window(
issued,
until,
began.elapsed(),
self.clock.reading().ok().map(|r| (r.own_wall, r.upper)),
) {
crate::job_readiness::ResponseWindow::WaitForClock => {
std::thread::sleep(Duration::from_millis(20));
continue;
}
crate::job_readiness::ResponseWindow::Expired => {
anyhow::bail!("SYSTEM_APPLY_ORIGINAL_DEADLINE_EXPIRED")
}
crate::job_readiness::ResponseWindow::WithinWindow => {}
}
self.sync()?;
match self.sync.as_mut().unwrap().apply(
&mut self.db,
&self.guard,
response,
request,
&self.clock,
&self.boot,
) {
Ok(value) => return Ok(value),
Err(error)
if rmm_agent_core::helper_reconcile::retryable_precommit_clock(&error) =>
{
std::thread::sleep(Duration::from_millis(20))
}
Err(error) => return Err(error),
}
}
fn wait_apply_clock(&self,issued:chrono::DateTime<chrono::Utc>,until:chrono::DateTime<chrono::Utc>)->Result<()> {
crate::job_readiness::wait_for_helper_apply_clock(&self.clock,issued,until)
}
/// Passive, bounded static denial metadata only. Never feeds a gate.
fn record_apply_error(&mut self,error:&anyhow::Error)->Result<()> {
@@ -1030,6 +1017,13 @@ impl SystemHelper {
| Operation::TimeClose { .. } => {
anyhow::bail!("SYSTEM_TIME_PIPE_REQUIRED")
}
Operation::UpdateObserve{request}=>{
Ok(ReplyBody::UpdateObservation{response:Box::new(crate::update_observer::collect(self.update_context(),request)?)})
}
Operation::UpdateHealth{request}=>{
ensure!(matches!(request.method,rmm_agent_core::update_handoff::NativeControlOperation::Health{..}),"UPDATE_AGENT_HEALTH_ONLY");
Ok(ReplyBody::UpdateHealth{reply:Box::new(crate::update_control::handle_agent_health(self.update_context(),peer,request)?)})
}
Operation::Probe {} => {
let ready = self.settings.enable_effects
&& self
@@ -1042,22 +1036,31 @@ impl SystemHelper {
})
.unwrap_or(false);
Ok(ReplyBody::Probe {
update_observer_configured:Some(crate::update_admission::configured(&self.settings.binding)),
clock_qualified: self.clock.now().is_ok(),
ready,
ledger: self.guard.ledger.identity,
lock: self.guard.lock.identity,
reboot_privilege_available: if self.settings.schema_version == 4
&& self.settings.allow_reboot
{
Some(crate::reboot::privilege_available()?)
} else {
None
},
})
}
Operation::Snapshot { generation } => {
self.clock = self.clock.for_generation(*generation);
self.sync()?;
let snapshot = self.sync.as_mut().unwrap().snapshot(
&mut self.db,
&self.guard,
*generation,
&self.clock,
&self.boot,
)?;
let snapshot = if let Some(grant)=crate::update_control::active_grant(&self.db)? {
let budget=crate::update_native::Budget::new(&self.boot,self.boot.current_boot()?,Duration::from_secs(5))?;
let guard=crate::update_control::Guard::open(&self.db,&self.guard,&self.settings.binding,
&self.clock,&self.pin,&budget,grant)?;
self.sync.as_mut().unwrap().snapshot(&mut self.db,&guard,*generation,&self.clock,&self.boot)?
} else {
self.sync.as_mut().unwrap().snapshot(&mut self.db,&self.guard,*generation,&self.clock,&self.boot)?
};
Ok(ReplyBody::Snapshot { snapshot })
}
Operation::Apply {
@@ -1068,16 +1071,20 @@ impl SystemHelper {
serde_json::from_slice(&response.decision_bytes)?;
self.clock
.require_generation(decision.connection_generation)?;
// Same authenticated original call, BEFORE any application.
// The independent time pipe continues on its own thread.
// No signature/deadline/lease is relaxed and no Execute retry.
let value = self.apply_control_with_clock(
response,
request_bytes,
decision.issued_at,
decision.valid_until,
)?;
let no_start_anchor = if value.ready && self.settings.enable_effects {
self.wait_apply_clock(decision.issued_at,decision.valid_until)?;
self.sync()?;
let value = if let Some(grant)=crate::update_control::active_grant(&self.db)? {
let budget=crate::update_native::Budget::new(&self.boot,self.boot.current_boot()?,Duration::from_secs(5))?;
let guard=crate::update_control::Guard::open(&self.db,&self.guard,&self.settings.binding,
&self.clock,&self.pin,&budget,grant)?;
self.sync.as_mut().unwrap().apply(&mut self.db,&guard,response,request_bytes,&self.clock,&self.boot)?
} else {
self.sync.as_mut().unwrap().apply(&mut self.db,&self.guard,response,request_bytes,&self.clock,&self.boot)?
};
let no_start_anchor = if value.ready
&& (self.settings.enable_effects
|| crate::update_admission::configured(&self.settings.binding))
{
let guard = DenialGuard {
ledger: &self.guard,
pin: &self.pin,
@@ -1109,9 +1116,41 @@ impl SystemHelper {
Operation::Execute {
generation,
request,
} => Ok(ReplyBody::Executed {
outcome: self.execute(*generation, request, peer)?,
}),
} => {
let job = self.settings.binding.job(&request.job_bytes)?;
if matches!(job.action, Action::UpdateAgent { .. }) {
ensure!(
self.pending_update_activation.is_none(),
"UPDATE_ACTIVATION_PENDING"
);
self.clock.require_generation(*generation)?;
self.sync()?;
let prepared = crate::update_admission::Prepared::new(
&self.db,
crate::update_admission::Local {
binding: &self.settings.binding,
guard: &self.guard,
clock: &self.clock,
boot: &self.boot,
pin: &self.pin,
generation: *generation,
},
self.sync.as_ref().context("SYSTEM_SYNC_REQUIRED")?,
request,
)?;
peer.check()?;
let accepted = prepared.consume(
&mut self.db,
self.sync.as_mut().context("SYSTEM_SYNC_REQUIRED")?,
)?;
self.pending_update_activation = Some(prepared.into_activation());
Ok(ReplyBody::UpdateAccepted { accepted })
} else {
Ok(ReplyBody::Executed {
outcome: self.execute(*generation, request, peer)?,
})
}
}
Operation::Abandon {
anchor,
request,
@@ -1125,10 +1164,15 @@ impl SystemHelper {
let job = self.settings.binding.job(&request.job_bytes)?;
ensure!(
job.execution_identity == "system"
&& job.max_runtime_seconds <= self.settings.max_runtime_seconds
&& (matches!(&job.action,Action::SetServiceState{unit,state} if matches!(state.as_str(),"running"|"stopped")&&self.settings.allowed_services.iter().any(|r|r.name==*unit))
|| self.settings.permits_msi(&job)
|| self.settings.permits_script(&job)),
&& ((job.max_runtime_seconds <= self.settings.max_runtime_seconds
&& (matches!(&job.action,Action::SetServiceState{unit,state} if matches!(state.as_str(),"running"|"stopped")&&self.settings.allowed_services.iter().any(|r|r.name==*unit))
|| self.settings.permits_msi(&job)
|| self.settings.permits_script(&job)
|| self.settings.permits_reboot(&job)))
|| crate::update_admission::permits_denial(
&self.settings.binding,
&job
)),
"SYSTEM_ABANDON_POLICY_DENIED"
);
self.sync()?;
@@ -1227,6 +1271,9 @@ impl SystemHelper {
if job.action.windows_msi().is_some() {
return self.execute_msi(generation, request, &job, &permit, peer);
}
if matches!(job.action, Action::Reboot { .. }) {
return self.execute_reboot(generation, request, &job, &permit, peer);
}
let mut provider = PreparedService::prepare(&self.settings, &job)?;
self.recheck()?;
peer.check()?;
@@ -1272,6 +1319,69 @@ impl SystemHelper {
ledger::finish(&self.db, &permit, &outcome)?;
Ok(outcome)
}
fn execute_reboot(
&mut self,
generation: u64,
request: &Request,
job: &JobPayload,
permit: &ExecutionPermitPayload,
peer: &mut ipc::PeerProof,
) -> Result<Outcome> {
ensure!(
self.settings.permits_reboot(job),
"SYSTEM_REBOOT_POLICY_DENIED"
);
self.observe_unsettled_msi()?;
ensure!(
self.unsettled_msi.is_none(),
"SYSTEM_MSI_PREVIOUS_PROCESS_UNSETTLED"
);
let provider = crate::reboot::Prepared::prepare(job)?;
self.recheck()?;
peer.check()?;
let (_, fresh, recorded_at) =
verified_window(&self.settings.binding, request, &self.clock)?;
ensure!(
&fresh == permit && !STOP.load(Ordering::SeqCst),
"SYSTEM_REBOOT_START_FENCED"
);
let boot = self.boot.current_boot()?;
crate::helper_runtime::intent::Store::require_not_denied(
request,
boot,
generation,
&self.pin.policy_sha256,
&self.pin.helper.binary_sha256,
)?;
ledger::begin_execution(&mut self.db, permit, request, boot, recorded_at)?;
self.sync.as_mut().unwrap().close();
let outcome = provider
.request(boot, || {
self.clock.require_generation(generation)?;
self.recheck()?;
peer.check()?;
ensure!(
!STOP.load(Ordering::SeqCst),
"SYSTEM_REBOOT_CANCELLED_BEFORE_REQUEST"
);
verified_window(&self.settings.binding, request, &self.clock)?;
crate::helper_runtime::intent::Store::require_not_denied(
request,
boot,
generation,
&self.pin.policy_sha256,
&self.pin.helper.binary_sha256,
)?;
Ok(())
})
.unwrap_or_else(|_| Outcome::unknown("WINDOWS_REBOOT_REQUEST_UNCONFIRMED"));
ledger::persist_outcome(&self.db, permit, &outcome)?;
self.guard.check(&self.db)?;
// Awaiting/Unknown deliberately keeps consumed.result NULL. Only the
// existing signed new-boot reconciliation may finish the same attempt.
ledger::finish(&self.db, permit, &outcome)?;
Ok(outcome)
}
fn execute_script(
&mut self,
generation: u64,
@@ -1650,30 +1760,76 @@ unsafe extern "system" fn service_main(_: u32, _: *mut *mut u16) {
let mut helper = SystemHelper::open()?;
let server = ipc::Server::bind(helper.pin().clone())?;
let time_server = ipc::Server::bind_time(helper.pin().clone())?;
let update_server=crate::update_control::server_pin(&helper.settings.binding,&helper.pin.helper)?
.map(crate::update_control_ipc::Server::bind).transpose()?;
let time_pin = helper.pin().clone();
let time_clock = helper.clock.source();
let time_worker = std::thread::Builder::new()
.name("rmm-helper-time-control".into())
.spawn(move || time_control(time_server, time_pin, time_clock))?;
scm_status(SERVICE_RUNNING, 0);
let mut next_update_unknown=Instant::now();
while !STOP.load(Ordering::SeqCst) {
if Instant::now()>=next_update_unknown {
next_update_unknown=Instant::now()+Duration::from_secs(2);
if let Err(error)=crate::update_control::observe_worker_unknown(helper.update_context()) {
let _diagnostic=helper.record_pipe_error(&error);
}
}
// A failed observation keeps the owned slot and its handles locked.
if helper.observe_unsettled_msi().is_err()
&& let Some(sync) = &mut helper.sync
{
sync.close();
}
if let Some(update_server)=&update_server {
match update_server.receive() {
Ok(Some(mut incoming))=> {
let reply=crate::update_control::handle_updater(helper.update_context(),&mut incoming.peer,&incoming.request);
let result=match reply {
Ok(reply)=>update_server.reply(&mut incoming,&reply),
Err(error)=>Err(error),
};
update_server.disconnect();
if let Err(error)=result {
if let Some(sync)=&mut helper.sync {sync.close();}
let _diagnostic=helper.record_pipe_error(&error);
}
}
Ok(None)=>{},
Err(error)=> {
update_server.disconnect();
if let Some(sync)=&mut helper.sync {sync.close();}
let _diagnostic=helper.record_pipe_error(&error);
}
}
}
match server.receive() {
Ok(Some(mut incoming)) => {
let reply = helper.handle(&incoming.call, &mut incoming.peer);
if let Err(error) = server.reply(&reply, &mut incoming.peer) {
let delivered = server.reply(&reply, &mut incoming.peer);
server.disconnect();
if let Err(error) = delivered {
if let Some(sync) = &mut helper.sync {
sync.close();
}
// Receipt loss cannot trigger an Activate or a retry.
helper.pending_update_activation = None;
let _diagnostic = helper.record_pipe_error(&error);
} else if matches!(reply.body, ReplyBody::UpdateAccepted { .. })
&& let Some(activation) = helper.pending_update_activation.take()
&& let Err(error) = activation.dispatch_after_reply(
&helper.db,
&helper.guard,
&helper.clock,
&helper.boot,
)
{
if let Some(sync) = &mut helper.sync {
sync.close();
}
server.disconnect();
let _diagnostic = helper.record_pipe_error(&error);
}
server.disconnect();
}
Ok(None) => {}
Err(error) => {
@@ -1862,6 +2018,26 @@ mod tests {
let mut null = legacy;
null["allowed_script_profiles"] = serde_json::Value::Null;
assert!(serde_json::from_value::<Settings>(null).is_err());
let mut reboot = job.clone();
reboot.action = Action::Reboot {
reason: "Windows-MVP".into(),
dependency_group: "windows-mvp".into(),
reconnect_timeout_seconds: 180,
};
reboot.max_runtime_seconds = 60;
settings.max_runtime_seconds = 120;
settings.allow_reboot = true;
for v in 1..=3 {
settings.schema_version = v;
assert!(!settings.permits_reboot(&reboot));
}
settings.schema_version = 4;
assert!(settings.permits_reboot(&reboot));
settings.allow_reboot = false;
assert!(!settings.permits_reboot(&reboot));
settings.allow_reboot = true;
reboot.execution_identity = "agent_service".into();
assert!(!settings.permits_reboot(&reboot));
}
#[test]
fn service_adapter_exposes_only_implemented_states() {
+45
View File
@@ -7,6 +7,8 @@ pub mod certificate_rotation;
pub mod clock;
pub mod echo_probe;
pub mod echo_completion;
#[cfg(feature = "system-helper")]
pub mod reboot;
#[cfg(all(windows, feature = "system-helper"))]
pub mod system_capabilities;
pub mod event_log;
@@ -28,6 +30,7 @@ pub mod msi_cache;
#[cfg(windows)]
pub mod native;
pub mod package;
pub mod release_platform;
#[cfg(windows)]
pub mod process;
#[cfg(windows)]
@@ -41,4 +44,46 @@ pub mod update_native;
pub const SERVICE_NAME: &str = "RmmDiscoveryWindows";
pub const CAPABILITIES: &[&str] = &["windows.base/1", "heartbeat/1"];
#[cfg(all(windows, feature = "system-helper"))]
pub mod update_ipc;
#[cfg(all(windows, feature = "system-helper"))]
pub mod update_cache;
#[cfg(all(windows, feature = "system-helper"))]
pub mod update_trust;
#[cfg(all(windows, feature = "system-helper"))]
pub mod update_state;
#[cfg(all(windows, feature = "system-helper"))]
pub mod release_service;
#[cfg(all(windows, feature = "system-helper"))]
pub mod update_admission;
pub mod job_readiness;
#[cfg(all(windows, feature = "system-helper"))]
pub mod update_original;
#[cfg(all(windows, feature = "system-helper"))]
pub mod update_control_ipc;
#[cfg(all(windows, feature = "system-helper"))]
pub mod update_owned;
#[cfg(all(windows, feature = "system-helper"))]
pub(crate) mod update_control;
#[cfg(all(windows, feature = "system-helper"))]
pub mod update_time_transport;
#[cfg(all(windows, feature = "system-helper"))]
pub mod update_worker;
#[cfg(all(windows, feature = "system-helper"))]
pub(crate) mod update_record;
#[cfg(all(windows, feature = "system-helper"))]
pub mod update_observer;
+7
View File
@@ -1,3 +1,10 @@
#[cfg(all(windows, feature = "system-helper"))]
mod update_observation_runtime;
#[cfg(all(windows, feature = "system-helper"))]
#[path = "../../agent/src/agent_update_health.rs"]
mod agent_update_health;
#[cfg(all(windows, feature = "system-helper"))]
mod update_download;
#[cfg(windows)]
#[path = "../../agent/src/https_channel.rs"]
mod https_channel;
+279
View File
@@ -0,0 +1,279 @@
//! Typed local reboot provider. The caller must durably consume the original
//! signed attempt and keep the independent helper gate before `request`.
#[cfg(any(windows, test))]
use rmm_agent_core::auth::Outcome;
#[cfg(any(windows, test))]
use uuid::Uuid;
#[cfg(any(windows, test))]
fn report(previous_boot: Uuid, accepted: bool, native_error: u32) -> Outcome {
Outcome {
state: if accepted {
"awaiting_reboot"
} else {
"failed"
}
.into(),
stdout: vec![],
stderr: vec![],
exit_code: None,
output_truncated: false,
reboot_required: false,
error_code: if accepted {
"EFFECT_REQUIRES_RECONCILIATION"
} else {
"WINDOWS_REBOOT_REQUEST_REJECTED"
}
.into(),
evidence: serde_json::json!({"provider":"windows.shutdown/1","previous_boot_id":previous_boot,"postconditions_passed":false,
"native_request_accepted":accepted,"native_error":native_error,"not_started":!accepted,"force_apps_closed":false,"local_machine_only":true,
"announcement_seconds":rmm_domain::windows_reboot::ANNOUNCEMENT_SECONDS,"reconnect_timeout_seconds":rmm_domain::windows_reboot::RECONNECT_SECONDS,
"automatic_retry":false,"success_requires_authenticated_new_boot":true}),
}
}
#[cfg(windows)]
mod native {
use super::*;
use anyhow::{Result, ensure};
use std::{
mem::{size_of, zeroed},
ptr,
};
use windows_sys::Win32::{
Foundation::{
CloseHandle, ERROR_INSUFFICIENT_BUFFER, GetLastError, HANDLE, LUID, SetLastError,
},
Security::{
AdjustTokenPrivileges, GetTokenInformation, LUID_AND_ATTRIBUTES, LookupPrivilegeValueW,
SE_PRIVILEGE_ENABLED, SE_SHUTDOWN_NAME, TOKEN_ADJUST_PRIVILEGES, TOKEN_PRIVILEGES,
TOKEN_QUERY, TokenPrivileges,
},
System::{
Shutdown::{
InitiateSystemShutdownExW, SHTDN_REASON_FLAG_PLANNED,
SHTDN_REASON_MAJOR_APPLICATION, SHTDN_REASON_MINOR_MAINTENANCE,
},
Threading::{GetCurrentProcess, OpenProcessToken},
},
};
struct Token(HANDLE);
impl Drop for Token {
fn drop(&mut self) {
unsafe {
CloseHandle(self.0);
}
}
}
fn open(access: u32) -> Result<Token> {
let mut raw = ptr::null_mut();
ensure!(
unsafe { OpenProcessToken(GetCurrentProcess(), access, &mut raw) } != 0,
"REBOOT_TOKEN_OPEN"
);
Ok(Token(raw))
}
fn luid() -> Result<LUID> {
let mut id = unsafe { zeroed() };
ensure!(
unsafe { LookupPrivilegeValueW(ptr::null(), SE_SHUTDOWN_NAME, &mut id) } != 0,
"REBOOT_PRIVILEGE_NAME"
);
Ok(id)
}
fn present(token: &Token, wanted: &LUID) -> Result<bool> {
let mut size = 0;
unsafe {
GetTokenInformation(token.0, TokenPrivileges, ptr::null_mut(), 0, &mut size);
}
ensure!(
unsafe { GetLastError() } == ERROR_INSUFFICIENT_BUFFER && (4..=65536).contains(&size),
"REBOOT_PRIVILEGE_SIZE"
);
let mut bytes = vec![0u64; (size as usize).div_ceil(8)];
ensure!(
unsafe {
GetTokenInformation(
token.0,
TokenPrivileges,
bytes.as_mut_ptr().cast(),
size,
&mut size,
)
} != 0,
"REBOOT_PRIVILEGE_READ"
);
let p = bytes.as_ptr().cast::<TOKEN_PRIVILEGES>();
let count = unsafe { (*p).PrivilegeCount } as usize;
let offset = std::mem::offset_of!(TOKEN_PRIVILEGES, Privileges);
ensure!(
offset
.checked_add(
count
.checked_mul(size_of::<LUID_AND_ATTRIBUTES>())
.ok_or_else(|| anyhow::anyhow!("REBOOT_PRIVILEGE_OVERFLOW"))?
)
.is_some_and(|v| v <= size as usize),
"REBOOT_PRIVILEGE_BOUNDS"
);
let entries = unsafe {
std::slice::from_raw_parts(
ptr::addr_of!((*p).Privileges).cast::<LUID_AND_ATTRIBUTES>(),
count,
)
};
Ok(entries
.iter()
.any(|x| x.Luid.LowPart == wanted.LowPart && x.Luid.HighPart == wanted.HighPart))
}
/// Read only; does not enable a privilege, call Shutdown or create a job.
pub fn privilege_available() -> Result<bool> {
present(&open(TOKEN_QUERY)?, &luid()?)
}
struct Privilege<'a> {
token: &'a Token,
previous: TOKEN_PRIVILEGES,
restore: bool,
}
impl<'a> Privilege<'a> {
fn enable(token: &'a Token, id: LUID) -> Result<Self> {
let change = TOKEN_PRIVILEGES {
PrivilegeCount: 1,
Privileges: [LUID_AND_ATTRIBUTES {
Luid: id,
Attributes: SE_PRIVILEGE_ENABLED,
}],
};
let mut previous = unsafe { zeroed() };
let mut len = 0;
unsafe {
SetLastError(0);
}
ensure!(
unsafe {
AdjustTokenPrivileges(
token.0,
0,
&change,
size_of::<TOKEN_PRIVILEGES>() as u32,
&mut previous,
&mut len,
)
} != 0
&& unsafe { GetLastError() } == 0,
"REBOOT_PRIVILEGE_ENABLE"
);
Ok(Self {
token,
previous,
restore: true,
})
}
fn restore(&mut self) -> Result<()> {
if self.restore {
ensure!(
unsafe {
AdjustTokenPrivileges(
self.token.0,
0,
&self.previous,
0,
ptr::null_mut(),
ptr::null_mut(),
)
} != 0,
"REBOOT_PRIVILEGE_RESTORE"
);
self.restore = false;
}
Ok(())
}
}
impl Drop for Privilege<'_> {
fn drop(&mut self) {
let _ = self.restore();
}
}
pub(crate) struct Prepared {
token: Token,
luid: LUID,
}
impl Prepared {
pub fn prepare(job: &rmm_domain::jobs::JobPayload) -> Result<Self> {
ensure!(
rmm_domain::windows_reboot::supported(job),
"WINDOWS_REBOOT_FIXED_PROFILE_REQUIRED"
);
let token = open(TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES)?;
let luid = luid()?;
ensure!(
present(&token, &luid)?,
"WINDOWS_REBOOT_PRIVILEGE_UNAVAILABLE"
);
Ok(Self { token, luid })
}
pub fn request(
self,
previous_boot: Uuid,
mut last_gate: impl FnMut() -> Result<()>,
) -> Result<Outcome> {
last_gate()?;
let mut privilege = Privilege::enable(&self.token, self.luid)?;
last_gate()?;
// No remote target, free command, force flag, clock setter or retry.
let message: Vec<u16> = "RustDiscovery: genehmigter Neustart"
.encode_utf16()
.chain(Some(0))
.collect();
let accepted = unsafe {
InitiateSystemShutdownExW(
ptr::null(),
message.as_ptr(),
rmm_domain::windows_reboot::ANNOUNCEMENT_SECONDS,
0,
1,
SHTDN_REASON_FLAG_PLANNED
| SHTDN_REASON_MAJOR_APPLICATION
| SHTDN_REASON_MINOR_MAINTENANCE,
)
} != 0;
let code = if accepted {
0
} else {
unsafe { GetLastError() }
};
let restored = privilege.restore();
if accepted && restored.is_err() {
return Ok(Outcome {
evidence: serde_json::json!({"provider":"windows.shutdown/1","previous_boot_id":previous_boot,"native_request_accepted":true,"postconditions_passed":false,"automatic_retry":false}),
..Outcome::unknown("WINDOWS_REBOOT_ACCEPTED_PRIVILEGE_RESTORE_UNCONFIRMED")
});
}
restored?;
Ok(report(previous_boot, accepted, code))
}
}
}
#[cfg(windows)]
pub(crate) use native::Prepared;
#[cfg(windows)]
pub use native::privilege_available;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn native_acceptance_requires_new_boot_instead_of_claiming_success_or_retry() {
let boot = Uuid::new_v4();
let accepted = report(boot, true, 0);
assert_eq!(accepted.state, "awaiting_reboot");
assert!(!accepted.reboot_required);
assert_eq!(accepted.evidence["previous_boot_id"], boot.to_string());
assert_eq!(accepted.evidence["postconditions_passed"], false);
assert_eq!(accepted.evidence["force_apps_closed"], false);
let denied = report(boot, false, 1314);
assert_eq!(denied.state, "failed");
assert_eq!(denied.evidence["not_started"], true);
assert_eq!(denied.evidence["automatic_retry"], false);
}
}
@@ -0,0 +1,14 @@
//! The release catalog distinguishes the two Windows ABIs even on the same CPU.
#[cfg(all(windows, target_env = "gnu"))]
pub const WIRE: rmm_domain::agent_update::Platform =
rmm_domain::agent_update::Platform::WindowsGnuX64;
#[cfg(not(all(windows, target_env = "gnu")))]
pub const WIRE: rmm_domain::agent_update::Platform = rmm_domain::agent_update::Platform::WindowsX64;
#[cfg(all(windows, target_env = "gnu"))]
pub const VERIFY: rmm_updater::Platform = rmm_updater::Platform::WindowsGnuX64;
#[cfg(not(all(windows, target_env = "gnu")))]
pub const VERIFY: rmm_updater::Platform = rmm_updater::Platform::WindowsX64;
#[cfg(all(windows, target_env = "gnu"))]
pub const TRIPLE: &str = "x86_64-pc-windows-gnu";
#[cfg(not(all(windows, target_env = "gnu")))]
pub const TRIPLE: &str = "x86_64-pc-windows-msvc";
+459
View File
@@ -0,0 +1,459 @@
//! Unattended, fixed-role releases for installations made by the HTTPS installer.
use crate::release_platform::{TRIPLE, VERIFY};
use crate::{
certificate_rotation::{ProtectedKeyFiles, RotationStore},
job_binding, native,
};
use anyhow::{Context, Result, ensure};
use reqwest::{Client, Response};
use rmm_domain::agent_update::ReleaseEnvelope;
use rmm_updater::ReleaseManifest;
use rusqlite::{Connection, OpenFlags};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::{
ffi::OsStr,
fs,
io::Write,
net::SocketAddr,
os::windows::ffi::OsStrExt,
path::{Path, PathBuf},
process::Command,
sync::atomic::{AtomicBool, Ordering},
time::Duration,
};
use uuid::Uuid;
pub const SERVICE: &str = "RmmDiscoveryReleasePull";
const AGENT: &str = "rmm-agent-windows.exe";
const HELPER: &str = "rmm-helper-windows.exe";
const ACTIVE: &str = "installed-release.json";
const INTENT: &str = "release-transition.json";
#[derive(Clone, Serialize, Deserialize)]
struct Installed {
schema_version: u32,
tenant_id: Uuid,
release_id: Uuid,
release_sequence: u64,
manifest_sha256: String,
}
#[derive(Serialize, Deserialize)]
struct Transition {
old: Installed,
new: Installed,
}
#[derive(Deserialize)]
struct Endpoint {
server_name: String,
connect_address: SocketAddr,
transport: String,
state_directory: PathBuf,
ca_file: PathBuf,
#[serde(default)]
enable_jobs: bool,
}
#[derive(Deserialize)]
struct Health {
agent_id: Uuid,
agent_version: Option<String>,
connection_generation: u64,
last_contact_at: Option<chrono::DateTime<chrono::Utc>>,
}
#[derive(Deserialize)]
struct Current {
status: String,
release: Option<Published>,
}
#[derive(Deserialize)]
struct Published {
release_envelope: ReleaseEnvelope,
manifest: ReleaseManifest,
}
fn data(name: &str) -> PathBuf {
PathBuf::from(std::env::var_os("ProgramData").unwrap_or_else(|| r"C:\ProgramData".into()))
.join("RustDiscovery")
.join(name)
}
fn releases() -> PathBuf {
PathBuf::from(std::env::var_os("ProgramFiles").unwrap_or_else(|| r"C:\Program Files".into()))
.join("RustDiscovery")
.join("releases")
}
fn generation(id: Uuid) -> PathBuf {
releases().join(id.to_string())
}
fn protected(path: &Path, limit: usize) -> Result<Vec<u8>> {
job_binding::check_admin_readonly(path)?;
ensure!(
fs::metadata(path)?.len() <= limit as u64,
"protected file size"
);
Ok(fs::read(path)?)
}
fn read_record<T: serde::de::DeserializeOwned>(name: &str) -> Result<T> {
Ok(serde_json::from_slice(&protected(&data(name), 8192)?)?)
}
fn write_new(path: &Path, bytes: &[u8]) -> Result<()> {
let mut file = fs::File::create_new(path)?;
file.write_all(bytes)?;
file.sync_all()?;
Ok(())
}
fn write_record<T: Serialize>(name: &str, value: &T) -> Result<()> {
use windows_sys::Win32::Storage::FileSystem::{
MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH, MoveFileExW,
};
let tmp = data(&format!(".release-{}", Uuid::new_v4()));
let wide = |p: &OsStr| p.encode_wide().chain(Some(0)).collect::<Vec<_>>();
let result = (|| -> Result<()> {
write_new(&tmp, &serde_json::to_vec(value)?)?;
let (from, to) = (wide(tmp.as_os_str()), wide(data(name).as_os_str()));
if unsafe {
MoveFileExW(
from.as_ptr(),
to.as_ptr(),
MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH,
)
} == 0
{
return Err(std::io::Error::last_os_error().into());
}
Ok(())
})();
let _ = fs::remove_file(tmp);
result
}
struct Device {
client: Client,
base: String,
id: Uuid,
}
impl Device {
fn open(config: &Endpoint) -> Result<Self> {
ensure!(
config.transport == "https"
&& config.ca_file == data("server-ca.pem")
&& config.state_directory == data("state"),
"installed HTTPS configuration"
);
let ca = protected(&config.ca_file, 32768)?;
let state = &config.state_directory;
let identity_path = state.join("identity.json");
native::private_path(&identity_path, false)?;
ensure!(
fs::metadata(&identity_path)?.len() <= 32768,
"identity size"
);
let identity: rmm_protocol::EnrollmentResponse =
serde_json::from_slice(&fs::read(identity_path)?)?;
let id = Uuid::parse_str(&identity.agent_id)?;
let db_path = state.join("telemetry.sqlite");
native::private_path(&db_path, false)?;
let db = Connection::open_with_flags(
db_path,
OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
)?;
db.execute_batch("PRAGMA trusted_schema=OFF;PRAGMA query_only=ON;")?;
let keys = ProtectedKeyFiles::open(state)?;
let rotation = RotationStore::new(id, 1, ca.clone())?;
let tls = rotation.read_only_current(&db, &keys, chrono::Utc::now().timestamp())?;
let mut pem = tls.certificate_pem;
pem.push(b'\n');
pem.extend_from_slice(&tls.private_key_pem);
let base = reqwest::Url::parse(&format!(
"https://{}:{}",
config.server_name,
config.connect_address.port()
))?;
ensure!(
base.domain() == Some(config.server_name.as_str()),
"invalid gateway hostname"
);
let client = Client::builder()
.https_only(true)
.tls_built_in_root_certs(false)
.add_root_certificate(reqwest::Certificate::from_pem(&ca)?)
.identity(reqwest::Identity::from_pem(&pem)?)
.resolve(&config.server_name, config.connect_address)
.no_proxy()
.redirect(reqwest::redirect::Policy::none())
.connect_timeout(Duration::from_secs(10))
.timeout(Duration::from_secs(180))
.build()?;
Ok(Self {
client,
base: base.origin().ascii_serialization(),
id,
})
}
async fn get(&self, path: &str, timeout: Duration) -> Result<Response> {
let r = self
.client
.get(format!("{}{path}", self.base))
.timeout(timeout)
.send()
.await?;
ensure!(
r.status() == 200,
"device release service returned {}",
r.status()
);
Ok(r)
}
async fn json<T: serde::de::DeserializeOwned>(&self, path: &str) -> Result<T> {
let mut r = self.get(path, Duration::from_secs(10)).await?;
let mut body = Vec::new();
while let Some(chunk) = r.chunk().await? {
ensure!(
body.len() + chunk.len() <= 131072,
"release response too large"
);
body.extend_from_slice(&chunk);
}
Ok(serde_json::from_slice(&body)?)
}
async fn health(&self) -> Result<Health> {
let value: Health = self.json("/agent/v1/releases/installed").await?;
ensure!(value.agent_id == self.id, "device release identity changed");
Ok(value)
}
async fn download(&self, path: &Path, url: &str, limit: u64) -> Result<()> {
ensure!(
(1..=rmm_updater::MAX_ARTIFACT_BYTES).contains(&limit),
"release size"
);
let mut r = self.get(url, Duration::from_secs(180)).await?;
ensure!(r.content_length() == Some(limit), "release length");
let mut file = fs::File::create_new(path)?;
let mut count = 0;
while let Some(chunk) = r.chunk().await? {
count += chunk.len() as u64;
ensure!(count <= limit, "release body too large");
file.write_all(&chunk)?;
}
ensure!(count == limit, "truncated release");
file.sync_all()?;
Ok(())
}
}
fn local_manifest(installed: &Installed) -> Result<ReleaseManifest> {
let root = generation(installed.release_id);
let raw = protected(&root.join("manifest.json"), rmm_updater::MAX_MANIFEST_BYTES)?;
ensure!(
hex::encode(Sha256::digest(&raw)) == installed.manifest_sha256,
"changed installed manifest"
);
let m: ReleaseManifest = serde_json::from_slice(&raw)?;
ensure!(
installed.schema_version == 1
&& m.platform == VERIFY
&& m.release_id == installed.release_id
&& m.release_sequence == installed.release_sequence,
"installed release identity"
);
for (expected, name) in m.artifacts.iter().zip([AGENT, HELPER]) {
let path = root.join(name);
job_binding::check_admin_readonly(&path)?;
let mut digest = Sha256::new();
let count = std::io::copy(&mut fs::File::open(path)?, &mut digest)?;
ensure!(
expected.bytes == count && expected.sha256 == hex::encode(digest.finalize()),
"installed release component changed"
);
}
Ok(m)
}
// Only typed release UUIDs enter the fixed SCM command. The actual service path,
// LocalService account and absence of an independently provisioned helper are checked again on the target.
fn select(from: Uuid, to: Uuid) -> Result<()> {
let script = include_str!("release_service_switch.ps1")
.replace("FROM_UUID", &from.to_string())
.replace("TO_UUID", &to.to_string());
let windows = std::env::var_os("SystemRoot").context("Windows directory")?;
let ps = Path::new(&windows).join(r"System32\WindowsPowerShell\v1.0\powershell.exe");
let result = Command::new(ps)
.args([
"-NoLogo",
"-NoProfile",
"-NonInteractive",
"-Command",
&script,
])
.output()?;
ensure!(result.status.success(), "SCM release selection failed");
Ok(())
}
async fn rollback(t: &Transition) -> Result<()> {
local_manifest(&t.old)?;
select(t.new.release_id, t.old.release_id)?;
write_record("rejected-release.json", &t.new)?;
fs::remove_file(data(INTENT))?;
Ok(())
}
async fn stage(device: &Device, release: &Published, active: &Installed) -> Result<Installed> {
let id = release.manifest.release_id;
let tmp = releases().join(format!(".stage-{}", Uuid::new_v4()));
fs::create_dir(&tmp)?;
let result = async {
let env_path = tmp.join("envelope.json");
write_new(&env_path, &serde_json::to_vec(&release.release_envelope)?)?;
for (entry, name) in release.manifest.artifacts.iter().zip([AGENT, HELPER]) {
device
.download(
&tmp.join(name),
&format!("/agent/v1/releases/{id}/artifacts/{}", entry.artifact_id),
entry.bytes,
)
.await?;
}
let paths = [
data("release-keyring.json"),
env_path,
tmp.join(AGENT),
tmp.join(HELPER),
]
.map(PathBuf::into_os_string);
let verified = rmm_updater::verify_bootstrap_files(VERIFY, &paths)?;
ensure!(
verified.manifest() == &release.manifest
&& verified.manifest().release_sequence > active.release_sequence,
"signed release identity"
);
let record = Installed {
schema_version: 1,
tenant_id: active.tenant_id,
release_id: id,
release_sequence: verified.manifest().release_sequence,
manifest_sha256: verified.manifest_sha256().into(),
};
write_new(
&tmp.join("manifest.json"),
&serde_json::to_vec(verified.manifest())?,
)?;
if !generation(id).try_exists()? {
fs::rename(&tmp, generation(id))?;
}
local_manifest(&record)?;
Ok::<_, anyhow::Error>(record)
}
.await;
if tmp.try_exists()? {
fs::remove_dir_all(tmp)?;
}
result
}
async fn cycle() -> Result<()> {
let active: Installed = read_record(ACTIVE)?;
let config: Endpoint = serde_json::from_slice(&protected(&data("config.json"), 32768)?)?;
// Installed passive pairs only. A separately provisioned SYSTEM helper and
// privileged time/profile pins need the existing coordinated handoff.
ensure!(
!config.enable_jobs,
"job-enabled pair requires coordinated helper handoff"
);
if data(INTENT).try_exists()? {
let t: Transition = read_record(INTENT)?;
if active.release_id == t.new.release_id {
fs::remove_file(data(INTENT))?;
} else {
ensure!(
active.release_id == t.old.release_id,
"unexpected activation floor"
);
rollback(&t).await?;
}
}
let device = Device::open(&config)?;
let catalog: Current = device
.json(&format!("/agent/v1/releases/current?platform={TRIPLE}"))
.await?;
let Some(release) = catalog.release else {
ensure!(
catalog.status == "not_configured",
"unexpected release response"
);
return Ok(());
};
let decoded = release
.release_envelope
.decode()
.map_err(|_| anyhow::anyhow!("invalid release envelope"))?;
let candidate = &release.manifest;
ensure!(
catalog.status == "available"
&& candidate.platform == VERIFY
&& candidate.release_sequence >= active.release_sequence,
"invalid release sequence or platform"
);
if candidate.release_sequence == active.release_sequence {
ensure!(
candidate.release_id == active.release_id
&& hex::encode(Sha256::digest(decoded.payload_bytes)) == active.manifest_sha256,
"conflicting equal release"
);
return Ok(());
}
if data("rejected-release.json").try_exists()? {
let rejected: Installed = read_record("rejected-release.json")?;
ensure!(
candidate.release_sequence > rejected.release_sequence,
"previously failed release sequence"
);
}
let old = local_manifest(&active)?;
let before = device.health().await?;
ensure!(
before.agent_version.as_deref() == Some(&old.version),
"current agent version not confirmed"
);
let new = stage(&device, &release, &active).await?;
let t = Transition { old: active, new };
write_record(INTENT, &t)?;
let start = chrono::Utc::now();
let selected = select(t.old.release_id, t.new.release_id);
if selected.is_ok() {
for _ in 0..18 {
if let Ok(h) = device.health().await
&& h.connection_generation > before.connection_generation
&& h.agent_version.as_deref() == Some(&candidate.version)
&& h.last_contact_at.is_some_and(|v| v >= start)
{
write_record(ACTIVE, &t.new)?;
fs::remove_file(data(INTENT))?;
return Ok(());
}
tokio::time::sleep(Duration::from_secs(5)).await;
}
}
rollback(&t).await?;
anyhow::bail!("new release did not reconnect; previous release selected")
}
pub fn dispatch() -> Result<()> {
crate::service::dispatch_named(SERVICE, run)
}
fn run(stop: &'static AtomicBool) -> Result<()> {
let runtime = tokio::runtime::Runtime::new()?;
while !stop.load(Ordering::SeqCst) {
let result = runtime.block_on(cycle());
write_record(
"release-status.json",
&serde_json::json!({"observed_at": chrono::Utc::now(),
"status": if result.is_ok() { "ok" } else { "error" }, "detail": result.err().map(|e| e.to_string())}),
)?;
for _ in 0..300 {
if stop.load(Ordering::SeqCst) {
break;
}
std::thread::sleep(Duration::from_secs(1));
}
}
Ok(())
}
@@ -0,0 +1,28 @@
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest
function Get-Image([string]$Id) {
$image = Join-Path ([Environment]::GetFolderPath('ProgramFiles')) ('RustDiscovery\releases\' + $Id + '\rmm-agent-windows.exe')
return '"' + $image + '" --service --config "' + $configPath + '"'
}
$configPath = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'RustDiscovery\config.json'
$from = Get-Image 'FROM_UUID'
$to = Get-Image 'TO_UUID'
$service = Get-CimInstance -ClassName Win32_Service -Filter "Name='RmmDiscoveryWindows'"
$config = Get-Content -LiteralPath $configPath -Raw | ConvertFrom-Json
if ($config.PSObject.Properties['enable_jobs'] -and $config.enable_jobs) { throw 'Job-enabled agent requires a coordinated handoff.' }
if (-not $service -or $service.StartName -ine 'NT AUTHORITY\LocalService' -or
$service.PathName -cnotin @($from,$to) -or (Get-Service 'RmmDiscoverySystemHelper' -ErrorAction SilentlyContinue)) { throw 'Unexpected service configuration.' }
if ($service.PathName -cne $to) {
$control = Get-Service 'RmmDiscoveryWindows'
if ($control.Status -ne 'Stopped') {
$control.Stop()
$control.WaitForStatus('Stopped', [TimeSpan]::FromSeconds(45))
}
$res = Invoke-CimMethod -InputObject $service -MethodName Change -Arguments @{PathName=$to}
if ($res.ReturnValue -ne 0) { throw 'SCM path change failed.' }
}
$control = Get-Service 'RmmDiscoveryWindows'
if ($control.Status -ne 'Running') {
$control.Start()
$control.WaitForStatus('Running',[TimeSpan]::FromSeconds(45))
}
+375 -48
View File
@@ -386,7 +386,26 @@ impl EffectFence {
})
}
}
type Completion = (JobOffer, ExecutionPermitPayload, Outcome);
enum ExecutorResult {
Outcome(Outcome),
#[cfg(feature = "system-helper")]
UpdatePending(Option<rmm_agent_windows::update_admission::Accepted>),
}
impl From<Outcome> for ExecutorResult {
fn from(value: Outcome) -> Self {
Self::Outcome(value)
}
}
fn interrupted_executor(grant: &ExecutionPermitPayload) -> ExecutorResult {
#[cfg(not(feature="system-helper"))]
let _=grant;
#[cfg(feature = "system-helper")]
if grant.action == "update_agent" {
return ExecutorResult::UpdatePending(None);
}
Outcome::unknown("EXECUTOR_THREAD_INTERRUPTED").into()
}
type Completion = (JobOffer, ExecutionPermitPayload, ExecutorResult);
#[cfg(feature = "system-helper")]
fn needs_bound_outcome(
db: &Connection,
@@ -573,6 +592,7 @@ impl HelperControl {
}
struct Agent {
config: Config,
reported_version: String,
identity: EnrollmentResponse,
ca: Vec<u8>,
journal: Journal,
@@ -591,6 +611,14 @@ struct Agent {
prepared: bool,
deferred_sync: Option<DeferredSync>,
#[cfg(feature = "system-helper")]
update_pending: bool,
#[cfg(feature="system-helper")]
update_observer:crate::update_observation_runtime::Observer,
#[cfg(feature = "system-helper")]
update_health: Option<tokio::task::JoinHandle<Result<()>>>,
#[cfg(feature = "system-helper")]
update_inventory_head: Option<(u64, String)>,
#[cfg(feature = "system-helper")]
prepared_request: Option<Vec<u8>>,
#[cfg(feature = "system-helper")]
helper_apply_unconfirmed: bool,
@@ -617,6 +645,10 @@ struct Agent {
running: Option<Running>,
deferred_permit: Option<(u64, ExecutionPermit)>,
readiness_worker: Option<tokio::task::JoinHandle<Result<()>>>,
#[cfg(feature = "system-helper")]
update_prefetch: Option<(u64, String, String, tokio::task::JoinHandle<Result<()>>)>,
#[cfg(feature = "system-helper")]
update_cached: Option<(u64, String, String)>,
}
impl Agent {
fn rotation_without_effects(&self) -> Result<()> {
@@ -1096,6 +1128,19 @@ impl Agent {
let (ledger, result) = task.await?;
self.ledger = Some(ledger);
let (snapshot, unknowns) = result?;
if Path::new(rmm_agent_windows::helper_runtime::intent::DB).is_file() {
self.update_pending =
rmm_agent_windows::helper_runtime::intent::Store::open(false)?
.pending()?
.iter()
.any(|intent| {
self.binding.as_ref().is_some_and(|binding| {
binding.job(&intent.request.job_bytes).is_ok_and(|job| {
matches!(job.action, Action::UpdateAgent { .. })
})
})
});
}
for bound in unknowns {
if needs_bound_outcome(self.journal.connection(), &bound)? {
let bytes: Vec<u8> = self.journal.connection().query_row(
@@ -1232,6 +1277,88 @@ impl Agent {
.is_some_and(|sync| sync.can_start(&channel, helper, &self.clock))
})
}
#[cfg(feature = "system-helper")]
async fn poll_update_health(&mut self, generation: u64) -> Result<bool> {
if self
.update_health
.as_ref()
.is_some_and(|task| task.is_finished())
{
let task = self.update_health.take().context("UPDATE_HEALTH_TASK")?;
task.await??;
return Ok(true);
}
if !self.update_pending
|| self.update_health.is_some()
|| self.prepared
|| self.helper_control_pending()
|| self.clock.reading().is_err()
{
return Ok(false);
}
let binding = self
.binding
.as_ref()
.context("UPDATE_BINDING_REQUIRED")?
.clone();
let Some(proof) = rmm_agent_core::update_health_inventory::current_proof(
self.journal.connection(),
&binding,
)?
else {
return Ok(true);
};
let decoded = proof.decode().map_err(anyhow::Error::msg)?;
let event = decoded
.events
.last()
.map(|raw| serde_json::from_slice::<rmm_updater_handoff::Event>(raw))
.transpose()?;
if !event.is_some_and(|event| {
matches!(
event.evidence,
rmm_updater_handoff::Evidence::ServicesStarted { .. }
| rmm_updater_handoff::Evidence::RollbackServicesStarted { .. }
)
}) {
return Ok(true);
}
let inventory_key = (generation, proof.head_sha256.clone());
if self.update_inventory_head.as_ref() != Some(&inventory_key)
&& self.queue_inventory(generation)?
{
self.update_inventory_head = Some(inventory_key);
}
let Some(context) = crate::agent_update_health::context(
self.journal.connection(),
&binding,
&proof,
self.clock.now()?,
)?
else {
return Ok(true);
};
let handoff = context.handoff().clone();
let key = context.health_public_key();
let identity = self.certificates.current(
self.journal.connection(),
&self.key_files,
Utc::now().timestamp(),
)?;
let client = crate::https_channel::mtls_client(
self.config.connect_address,
&self.ca,
&identity.certificate_pem,
&identity.private_key_pem,
)?;
let helper = self.helper.clone().context("UPDATE_HELPER_REQUIRED")?;
let address = self.config.connect_address;
self.update_health = Some(tokio::spawn(async move {
let receipt = crate::agent_update_health::request(&client, address, &context).await?;
helper.submit_update_health(&handoff, key, receipt).await
}));
Ok(false)
}
fn supported_job(&self, job: &rmm_domain::jobs::JobPayload) -> bool {
if self.config.windows_echo_probe_only
&& !self
@@ -1278,8 +1405,99 @@ impl Agent {
rmm_agent_windows::echo_probe::permits_offer(scope, offer, job)
})
}
#[cfg(feature = "system-helper")]
async fn prefetch_update(
&mut self,
generation: u64,
offer: &JobOffer,
job: &rmm_domain::jobs::JobPayload,
) -> Result<bool> {
let Action::UpdateAgent { update } = &job.action else {
return Ok(true);
};
ensure!(
update.validate()
&& update.manifest().map_err(anyhow::Error::msg)?.platform
== rmm_agent_windows::release_platform::WIRE,
"UPDATE_PREFETCH_JOB"
);
let key = (generation, offer.job_id.clone(), offer.attempt_id.clone());
if self.update_cached.as_ref() == Some(&key) {
return Ok(true);
}
if self.update_prefetch.as_ref().is_some_and(|(g, j, a, _)| {
(*g, j.as_str(), a.as_str())
!= (generation, offer.job_id.as_str(), offer.attempt_id.as_str())
}) && let Some((_, _, _, task)) = self.update_prefetch.take() {
task.abort();
}
if self
.update_prefetch
.as_ref()
.is_some_and(|(_, _, _, task)| task.is_finished())
{
let (_, _, _, task) = self
.update_prefetch
.take()
.context("UPDATE_PREFETCH_TASK")?;
task.await??;
self.update_cached = Some(key);
return Ok(true);
}
if self.update_prefetch.is_none() {
ensure!(
rmm_agent_windows::update_cache::configured(),
"UPDATE_PREFETCH_NOT_PROVISIONED"
);
let address = self.config.connect_address;
let identity = self.certificates.current(
self.journal.connection(),
&self.key_files,
Utc::now().timestamp(),
)?;
let client = crate::https_channel::mtls_client(
address,
&self.ca,
&identity.certificate_pem,
&identity.private_key_pem,
)?;
let base = format!(
"https://{}:{}",
crate::https_channel::server_name()?,
address.port()
);
let guard_job = job.clone();
let clock = self.clock.clone();
let fence = self.fence.clone();
let job = job.clone();
let manifest = update.manifest().map_err(anyhow::Error::msg)?;
let task = tokio::spawn(crate::update_download::prefetch(
client,
base,
job,
manifest,
move || {
ensure!(
fence.allows_identity(generation, true, &clock)
&& clock.now()? < guard_job.start_before,
"UPDATE_PREFETCH_FENCED"
);
Ok(())
},
));
self.update_prefetch = Some((
generation,
offer.job_id.clone(),
offer.attempt_id.clone(),
task,
));
}
Ok(false)
}
fn capabilities(&self) -> Vec<String> {
let mut caps: Vec<String> = CAPABILITIES.iter().map(|c| c.to_string()).collect();
#[cfg(target_env = "gnu")]
caps.push("agent.release.windows.gnu/1".into());
// queue_update_observation emits the passive update status in every profile.
caps.push("agent.update/1".into());
if self.config.windows_echo_probe_only {
@@ -1307,6 +1525,10 @@ impl Agent {
&& let Some(helper) = &self.helper
{
caps.extend(helper.qualified_capabilities());
if helper.update_observer_configured()
&& self.update_observer.cached().is_some_and(|r|r.observation.predecessor.as_ref().is_some_and(|p|p.helper_sha256==helper.helper_binary_hash())) {
for cap in self.update_observer.capabilities(){if !caps.contains(&cap){caps.push(cap);}}
}
}
}
caps
@@ -1338,6 +1560,13 @@ impl Agent {
let pending = intents.pending()?;
if let Some(intent) = pending.first() {
let p = intent.permit()?;
if matches!(
binding.job(&intent.request.job_bytes)?.action,
Action::UpdateAgent { .. }
) {
self.update_pending = true;
return Ok(());
}
let incompatible:bool=self.journal.connection().query_row("SELECT EXISTS(SELECT 1 FROM job_attempts WHERE state IN ('requesting','running','verifying','unknown','awaiting_reboot') AND NOT(job=?1 AND attempt=?2))",rusqlite::params![p.job_id.to_string(),p.attempt_id.to_string()],|r|r.get(0))?;
ensure!(!incompatible, "SYSTEM_PENDING_INTENT_CONFLICT");
binding.verify_historical_for_denial_with(
@@ -1496,37 +1725,13 @@ impl Agent {
helper: Option<&reconcile::HelperSnapshot>,
) -> Result<()> {
let context = self.channel(generation)?;
let closed_control_idle = {
#[cfg(feature = "system-helper")]
{
self.running.is_none()
&& !self.prepared
&& self.deferred_sync.is_none()
&& self.deferred_permit.is_none()
&& self.helper_control.is_none()
&& self.helper_probe.is_none()
&& helper.is_some()
&& (if Path::new(rmm_agent_windows::helper_runtime::intent::DB).exists() {
rmm_agent_windows::helper_runtime::intent::Store::open(false)
.and_then(|store| store.pending())
.is_ok_and(|pending| pending.is_empty())
} else {
helper.is_some_and(|snapshot| snapshot.attempts.is_empty())
})
}
#[cfg(not(feature = "system-helper"))]
{
false
}
};
let sync = self.sync.as_mut().context("SYNC_NOT_CONFIGURED")?;
let prepared = sync.prepare_with_closed_control_idle(
let prepared = sync.prepare(
self.journal.connection_mut(),
self.ledger.as_ref().context("LEDGER_REQUIRED")?,
context,
helper,
&self.clock,
closed_control_idle,
);
#[cfg(feature = "system-helper")]
if helper.is_some()
@@ -1708,7 +1913,7 @@ impl Agent {
}
Ok(())
}
fn completed(&mut self, generation: u64, (offer, grant, outcome): Completion) -> Result<()> {
fn completed(&mut self, generation: u64, (offer, grant, result): Completion) -> Result<()> {
let running = self
.running
.as_ref()
@@ -1719,6 +1924,48 @@ impl Agent {
&& running.grant == grant,
"EXECUTOR_COMPLETION_BINDING"
);
#[cfg(feature = "system-helper")]
if let ExecutorResult::UpdatePending(accepted) = result {
ensure!(
grant.execution_identity == "system" && grant.action == "update_agent",
"UPDATE_COMPLETION_SCOPE"
);
if let Some(accepted) = accepted {
let intent = rmm_agent_windows::helper_runtime::intent::Store::open(false)?
.by_grant(grant.grant_id)?;
accepted.matches(&intent.request, grant.grant_id)?;
let mut envelope = self.envelope(
generation,
Payload::JobStateChanged(JobStateChanged::default()),
)?;
let tx = self.journal.connection_mut().transaction()?;
let revision =
jobs::transition(&tx, &offer, "running", &grant.grant_id.to_string())?;
envelope.payload = Some(Payload::JobStateChanged(JobStateChanged {
job_id: offer.job_id.clone(),
attempt_id: offer.attempt_id.clone(),
revision,
state: "running".into(),
grant_id: grant.grant_id.to_string(),
}));
jobs::event(&tx, &envelope)?;
tx.commit()?;
}
// Neither a typed handoff ACK nor its loss is an Outcome. Import
// only actual original helper evidence in the next normal Sync.
self.update_pending = true;
self.running = None;
self.close_gate();
return Ok(());
}
#[cfg(not(feature="system-helper"))]
let ExecutorResult::Outcome(outcome)=result;
#[cfg(feature="system-helper")]
let outcome = match result {
ExecutorResult::Outcome(outcome) => outcome,
#[cfg(feature = "system-helper")]
ExecutorResult::UpdatePending(_) => unreachable!("handled update completion"),
};
if grant.execution_identity == "system" {
// No local consumption or definitive result from an IPC outcome.
// Import only a fresh raw helper snapshot before the next Sync.
@@ -1845,6 +2092,10 @@ impl Agent {
let completed = self.completed_tx.clone();
let work_offer = offer.clone();
let work_grant = grant.clone();
let is_update = matches!(job.action, Action::UpdateAgent { .. });
if is_update {
self.update_pending = true;
}
let msi = job.action.windows_msi().cloned();
let address = self.config.connect_address;
let ca = self.ca.clone();
@@ -1912,7 +2163,7 @@ impl Agent {
} else {
true
};
let _result = helper
let result = helper
.delegate(intent, move || {
ensure!(staged, "MSI_DOWNLOAD_NOT_READY");
ensure!(
@@ -1931,7 +2182,11 @@ impl Agent {
.send((
work_offer,
work_grant,
Outcome::unknown("SYSTEM_DELEGATION_REQUIRES_HELPER_SNAPSHOT"),
if is_update {
ExecutorResult::UpdatePending(result.ok().flatten())
} else {
Outcome::unknown("SYSTEM_DELEGATION_REQUIRES_HELPER_SNAPSHOT").into()
},
))
.await;
});
@@ -2054,7 +2309,7 @@ impl Agent {
outcome.error_code = "WINDOWS_FINAL_CLOCK_UNTRUSTED".into();
outcome.evidence["postconditions_passed"] = false.into();
}
let _ = completed.blocking_send((work_offer, work_grant, outcome));
let _ = completed.blocking_send((work_offer, work_grant, outcome.into()));
});
self.running = Some(Running {
offer,
@@ -2078,9 +2333,9 @@ impl Agent {
payload: Some(payload),
})
}
fn queue_inventory(&mut self, generation: u64) -> Result<()> {
fn queue_inventory(&mut self, generation: u64) -> Result<bool> {
if self.journal.count()? > 0 || !jobs::events(self.journal.connection())?.is_empty() {
return Ok(());
return Ok(false);
}
let data = serde_json::to_vec(&native::snapshot()?)?;
ensure!(data.len() <= 32768, "WINDOWS_INVENTORY_LIMIT");
@@ -2097,22 +2352,36 @@ impl Agent {
completeness: "partial".into(),
}),
)?;
if self.binding.is_some() {
jobs::event(self.journal.connection(), &envelope)
if let Some(binding) = &self.binding {
jobs::event(self.journal.connection(), &envelope)?;
let initialized:bool=self.journal.connection().query_row("SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name='reconcile_meta')",[],|r|r.get(0))?;
if initialized
&& self.journal.connection().query_row(
"SELECT generation FROM reconcile_meta WHERE id=1",
[],
|r| r.get::<_, u64>(0),
)? == generation
{
rmm_agent_core::update_health_inventory::retain_current(
self.journal.connection(),
&envelope,
binding,
)?;
}
} else {
self.journal.save(&envelope)
self.journal.save(&envelope)?;
}
Ok(true)
}
fn queue_update_observation(&mut self, generation: u64) -> Result<()> {
if self.journal.count()? > 0 || !jobs::events(self.journal.connection())?.is_empty() {
return Ok(());
}
// Schema support is passive only; no qualified updater/helper observer
// is configured by this source checkpoint, so apply remains closed.
#[cfg(feature="system-helper")]
let observation=self.update_observer.observation(generation);
#[cfg(not(feature="system-helper"))]
let observation = rmm_domain::agent_update::AgentUpdateObservation::not_configured(
rmm_domain::agent_update::Platform::WindowsX64,
Utc::now(),
);
rmm_agent_windows::release_platform::WIRE,Utc::now());
let data = serde_json::to_vec(&serde_json::json!({"agent_update":observation}))?;
let envelope = self.envelope(
generation,
@@ -2190,7 +2459,7 @@ impl Agent {
let hello = self.envelope(
0,
Payload::ClientHello(ClientHello {
agent_version: env!("CARGO_PKG_VERSION").into(),
agent_version: self.reported_version.clone(),
capabilities: advertised.clone(),
}),
)?;
@@ -2254,6 +2523,8 @@ impl Agent {
let mut tick = tokio::time::interval(Duration::from_millis(20));
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let mut readiness_at = Instant::now() - Duration::from_secs(5);
#[cfg(feature = "system-helper")]
let mut update_control_at = Instant::now() - Duration::from_secs(2);
while !stop.load(Ordering::SeqCst) || self.running.is_some() {
if stop.load(Ordering::SeqCst) {
self.close_gate();
@@ -2272,10 +2543,23 @@ impl Agent {
}
if self.running.as_ref().is_some_and(|r|r.worker.is_finished()) {
if let Ok(completion)=self.completed_rx.try_recv(){self.completed(generation,completion)?;}
else {let running=self.running.as_ref().context("RUNNING_REQUIRED")?;self.completed(generation,(running.offer.clone(),running.grant.clone(),Outcome::unknown("EXECUTOR_THREAD_INTERRUPTED")))?;}
else {let running=self.running.as_ref().context("RUNNING_REQUIRED")?;self.completed(generation,(running.offer.clone(),running.grant.clone(),interrupted_executor(&running.grant)))?;}
needs_sync=true;
}
#[cfg(feature="system-helper")]
if !stop.load(Ordering::SeqCst) && update_control_at.elapsed()>=Duration::from_secs(2) {
update_control_at=Instant::now();
if !self.update_pending && !self.prepared && !self.helper_control_pending() && self.running.is_none() && self.ready(generation) {
let transport=(||->Result<_>{let helper=self.helper.clone().filter(|h|h.update_observer_configured()).context("UPDATE_OBSERVER_NOT_CONFIGURED")?;
let identity=self.certificates.current(self.journal.connection(),&self.key_files,Utc::now().timestamp())?;
Ok((crate::https_channel::mtls_client(self.config.connect_address,&self.ca,&identity.certificate_pem,&identity.private_key_pem)?,self.config.connect_address,helper))})();
self.update_observer.poll(generation,||transport).await;
}
match self.poll_update_health(generation).await {Ok(refresh)=>{needs_sync|=refresh;},Err(_)=>{self.close_gate();needs_sync=true;}}
}
let busy=self.running.is_some() || self.journal.connection().query_row("SELECT EXISTS(SELECT 1 FROM job_attempts WHERE state IN ('requesting','running','verifying'))",[],|r|r.get::<_,bool>(0))?;
#[cfg(feature="system-helper")]
let busy=(busy && !(self.update_pending && self.running.is_none())) || self.update_health.is_some();
if !stop.load(Ordering::SeqCst) && !busy {
if capabilities_at.elapsed()>=Duration::from_secs(60) {capabilities_at=Instant::now();if advertised!=self.capabilities(){return Ok(());}}
if self.prepared && self.deferred_sync.is_none() && sync_at.elapsed()>=Duration::from_secs(20){self.close_gate();needs_sync=true;}
@@ -2289,9 +2573,15 @@ impl Agent {
ensure!(self.scope_permits(&offer,&job),"WINDOWS_ECHO_OFFER_OUT_OF_SCOPE");
if now>=job.start_before {self.record(generation,&offer,"",jobs::no_start("expired","START_DEADLINE_EXPIRED"))?;needs_sync=true;}
else if now-chrono::Duration::seconds(2)>=job.not_before && self.ready_identity(generation,job.execution_identity=="system") {
jobs::reserve_request(self.journal.connection(),&offer)?;
let request=self.envelope(generation,Payload::ExecutionPermitRequest(ExecutionPermitRequest{job_id:offer.job_id,attempt_id:offer.attempt_id,job_payload_hash:offer.job_payload_hash,assignment_version:job.assignment_version}))?;
channel.send(&request).await?;
#[cfg(feature="system-helper")]
let prefetched=self.prefetch_update(generation,&offer,&job).await?;
#[cfg(not(feature="system-helper"))]
let prefetched=true;
if prefetched {
jobs::reserve_request(self.journal.connection(),&offer)?;
let request=self.envelope(generation,Payload::ExecutionPermitRequest(ExecutionPermitRequest{job_id:offer.job_id,attempt_id:offer.attempt_id,job_payload_hash:offer.job_payload_hash,assignment_version:job.assignment_version}))?;
channel.send(&request).await?;
}
}
}
}
@@ -2484,6 +2774,29 @@ impl Agent {
)
}
}
fn installed_version() -> Result<String> {
let executable = std::env::current_exe()?;
let directory = executable.parent().context("AGENT_IMAGE_DIRECTORY")?;
let path = directory.join("manifest.json");
if !path.try_exists()? {
return Ok(env!("CARGO_PKG_VERSION").into());
}
rmm_agent_windows::job_binding::check_admin_readonly(&path)?;
let manifest: rmm_updater::ReleaseManifest =
serde_json::from_slice(&protected_read(&path, rmm_updater::MAX_MANIFEST_BYTES)?)?;
let expected = &manifest.artifacts[0];
let mut digest = Sha256::new();
let bytes = std::io::copy(&mut fs::File::open(executable)?, &mut digest)?;
ensure!(
manifest.platform == rmm_agent_windows::release_platform::VERIFY
&& expected.role == rmm_updater::ArtifactRole::Agent
&& expected.bytes == bytes
&& expected.sha256 == hex::encode(digest.finalize()),
"INSTALLED_AGENT_IMAGE_MISMATCH"
);
Ok(manifest.version)
}
fn service_run(stop: &'static AtomicBool) -> Result<()> {
let arguments: Vec<String> = std::env::args().skip(1).collect();
ensure!(
@@ -2550,6 +2863,7 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
let (completed_tx,completed_rx)=tokio::sync::mpsc::channel(1);
let mut agent = Agent {
config,
reported_version: installed_version()?,
identity,
ca,
journal,
@@ -2580,7 +2894,20 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
helper_checked:false,
#[cfg(feature="system-helper")]
helper_refused:false,
prepared:false,deferred_sync:None,fence:Arc::new(EffectFence::default()),completed_tx,completed_rx,running:None,deferred_permit:None,readiness_worker:None,
prepared:false,deferred_sync:None,
#[cfg(feature="system-helper")]
update_pending:false,
#[cfg(feature="system-helper")]
update_observer:crate::update_observation_runtime::Observer::default(),
#[cfg(feature="system-helper")]
update_health:None,
#[cfg(feature="system-helper")]
update_inventory_head:None,
fence:Arc::new(EffectFence::default()),completed_tx,completed_rx,running:None,deferred_permit:None,readiness_worker:None,
#[cfg(feature="system-helper")]
update_prefetch:None,
#[cfg(feature="system-helper")]
update_cached:None,
};
agent.recover_interrupted()?;
let mut backoff = 1;
@@ -2591,7 +2918,7 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
if let Ok(completion)=agent.completed_rx.try_recv(){agent.completed(0,completion)?;}
if agent.running.as_ref().is_some_and(|r|r.worker.is_finished()) {
let running=agent.running.as_ref().context("RUNNING_REQUIRED")?;
agent.completed(0,(running.offer.clone(),running.grant.clone(),Outcome::unknown("EXECUTOR_THREAD_INTERRUPTED")))?;
agent.completed(0,(running.offer.clone(),running.grant.clone(),interrupted_executor(&running.grant)))?;
}
if agent.running.is_some() {tokio::select!{Some(completion)=agent.completed_rx.recv()=>agent.completed(0,completion)?,_=tokio::time::sleep(Duration::from_millis(250))=>{}}}
continue;
@@ -2613,7 +2940,7 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
if let Ok(completion)=agent.completed_rx.try_recv(){agent.completed(0,completion)?;}
if agent.running.as_ref().is_some_and(|r|r.worker.is_finished()) {
let running=agent.running.as_ref().context("RUNNING_REQUIRED")?;
agent.completed(0,(running.offer.clone(),running.grant.clone(),Outcome::unknown("EXECUTOR_THREAD_INTERRUPTED")))?;
agent.completed(0,(running.offer.clone(),running.grant.clone(),interrupted_executor(&running.grant)))?;
}
tokio::time::sleep(Duration::from_millis(250)).await;
}
+7 -2
View File
@@ -12,6 +12,7 @@ static STOP: AtomicBool = AtomicBool::new(false);
static HANDLE: AtomicUsize = AtomicUsize::new(0);
type Runner = fn(&'static AtomicBool) -> Result<()>;
static RUN: OnceLock<Runner> = OnceLock::new();
static NAME: OnceLock<&'static str> = OnceLock::new();
fn status(state: u32, exit: u32) {
let handle = HANDLE.load(Ordering::SeqCst) as SERVICE_STATUS_HANDLE;
if handle.is_null() {
@@ -51,7 +52,7 @@ unsafe extern "system" fn control(
0
}
unsafe extern "system" fn service_main(_count: u32, _args: *mut *mut u16) {
let name = crate::native::wide(crate::SERVICE_NAME);
let name = crate::native::wide(NAME.get().copied().unwrap_or(crate::SERVICE_NAME));
let handle =
unsafe { RegisterServiceCtrlHandlerExW(name.as_ptr(), Some(control), ptr::null_mut()) };
if handle.is_null() {
@@ -64,8 +65,12 @@ unsafe extern "system" fn service_main(_count: u32, _args: *mut *mut u16) {
status(SERVICE_STOPPED, if result.is_ok() { 0 } else { 1066 });
}
pub fn dispatch(run: Runner) -> Result<()> {
dispatch_named(crate::SERVICE_NAME, run)
}
pub fn dispatch_named(name: &'static str, run: Runner) -> Result<()> {
ensure!(NAME.set(name).is_ok(), "SCM_ALREADY_INITIALIZED");
ensure!(RUN.set(run).is_ok(), "SCM_ALREADY_INITIALIZED");
let mut name = crate::native::wide(crate::SERVICE_NAME);
let mut name = crate::native::wide(name);
let table = [
SERVICE_TABLE_ENTRYW {
lpServiceName: name.as_mut_ptr(),
+262 -1
View File
@@ -113,6 +113,65 @@ pub struct RoleQualification {
pub binary_sha256: String,
pub qualification_sha256: String,
}
/// Separately protected stable-updater clock profile. It never loads a helper
/// calibration/qualification as its own image or process evidence.
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct UpdaterConfiguration {
pub schema_version: u32,
pub key_generation: u64,
pub server_instance: Uuid,
pub binding: rmm_agent_core::auth::Binding,
pub public_keys_hex: std::collections::BTreeMap<String, String>,
pub updater_policy_sha256: String,
pub updater_service_configuration_sha256: String,
pub trusted_os_active_guest: TrustedOsActiveGuest,
}
impl UpdaterConfiguration {
#[cfg(any(windows, test))]
fn validate(&self, image: &str) -> Result<()> {
let profile = &self.trusted_os_active_guest;
ensure!(
self.schema_version == 3
&& self.key_generation > 0
&& !self.server_instance.is_nil()
&& !self.binding.agent_id.is_nil()
&& !self.binding.asset_id.is_nil()
&& !self.binding.tenant_id.is_nil()
&& self.binding.enrollment_generation > 0
&& self.binding.assignment_version > 0
&& digest(&self.updater_policy_sha256)
&& digest(&self.updater_service_configuration_sha256)
&& matches!(
profile.operating_assumption,
ActiveGuestOperation::NoPauseSaveRestoreSnapshotMigrationHostSuspend
)
&& matches!(profile.platform, TrustedPlatform::KvmQemuHypervClock)
&& digest(&profile.platform_provenance_sha256)
&& profile.qualifications.len() == 1
&& profile.qualifications[0].role == rmm_time_attestation::Role::Updater
&& profile.qualifications[0].binary_sha256 == image
&& digest(&profile.qualifications[0].qualification_sha256),
"TIME_UPDATER_OWN_PROFILE"
);
ensure!(
!self.public_keys_hex.is_empty() && self.public_keys_hex.len() <= 8,
"TIME_UPDATER_KEYS"
);
for (id, public) in &self.public_keys_hex {
ensure!(
!id.is_empty()
&& id.len() <= 64
&& id
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"_-".contains(&b)),
"TIME_UPDATER_KEY_ID"
);
independent_time_key(public, &self.binding.public_key_hex)?;
}
Ok(())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum CaptureMode {
Physical { base_error_ns: u64 },
@@ -159,6 +218,10 @@ impl Configuration {
helper_image: &str,
) -> Result<CaptureMode> {
use rmm_time_attestation::Role;
ensure!(
own_role != Role::Updater,
"TIME_UPDATER_OWN_PROFILE_REQUIRED"
);
ensure!(self.key_generation() > 0, "TIME_NATIVE_CONFIG_PROFILE");
let images = [
(Role::Agent, agent_image),
@@ -663,6 +726,8 @@ mod installed {
};
pub const CONFIG_PATH: &str = r"C:\ProgramData\RustDiscoverySystem\time-attestation.json";
pub const UPDATER_CONFIG_PATH: &str =
r"C:\ProgramData\RustDiscoveryUpdater\time-attestation.json";
const PUBLIC_ROOT: &str = r"C:\ProgramData\RustDiscoverySystem";
const MAX_CONFIG_BYTES: usize = 16_384;
const MAX_REPLY_BYTES: usize = 16_384;
@@ -728,12 +793,16 @@ mod installed {
capture_mode: CaptureMode,
pending: Option<Pending>,
latest: Option<HeldEvidence>,
own_updater_configuration: Option<(ipc::PeerPin, String)>,
}
impl SignedClock {
/// Connection generation is later confirmed by the independently
/// signed server response. It is never itself a ready/sync flag.
pub async fn open(role: Role, connection_generation: u64) -> Result<Self> {
ensure!(connection_generation > 0, "TIME_NATIVE_CONNECTION");
if role == Role::Updater {
return Self::open_updater(connection_generation).await;
}
let mut failure_fence = ConstructorFailureFence { armed: true };
let (settings, mut files) = crate::helper_system::read_settings()?;
let own_pin = match role {
@@ -830,6 +899,127 @@ mod installed {
capture_mode,
pending: None,
latest: None,
own_updater_configuration: None,
};
value.recheck()?;
process()
.lock()
.map_err(|_| anyhow::anyhow!("TIME_NATIVE_STATE_POISONED"))?
.accept_connection(connection_generation)?;
observed(boot_id, capture_mode)?;
failure_fence.armed = false;
Ok(value)
}
/// Stable-updater-only process proof and separately protected profile.
/// It uses its OWN current SCM process/image/token and challenge.
pub async fn open_updater(connection_generation: u64) -> Result<Self> {
ensure!(connection_generation > 0, "TIME_NATIVE_CONNECTION");
let mut failure_fence = ConstructorFailureFence { armed: true };
let readers = vec![
ipc::service_sid(crate::update_ipc::SERVICE)?,
ipc::service_sid(crate::SERVICE_NAME)?,
ipc::service_sid(ipc::HELPER_SERVICE)?,
];
let root = PinnedFile::open_read_shared(
Path::new(r"C:\ProgramData\RustDiscoveryUpdater"),
true,
&readers,
&[],
)?;
let mut policy_file = PinnedFile::open(
Path::new(r"C:\ProgramData\RustDiscoveryUpdater\policy.json"),
false,
&readers,
&[],
false,
)?;
ensure!(
policy_file.file.metadata()?.len() <= 65536,
"TIME_UPDATER_POLICY_SIZE"
);
let mut policy_raw = Vec::new();
(&mut policy_file.file)
.take(65537)
.read_to_end(&mut policy_raw)?;
let (policy, policy_hash) =
rmm_domain::agent_update_provisioning::LocalUpdatePolicy::from_bytes(&policy_raw)
.map_err(anyhow::Error::msg)?;
let own_pin = crate::update_native::services::updater_pin(&policy)?;
ipc::require_self(&own_pin)?;
let own_process = PeerProof::for_service(&own_pin, unsafe {
windows_sys::Win32::System::Threading::GetCurrentProcessId()
})?;
let service_hash =
crate::update_native::services::updater_configuration_sha256(&own_pin)?;
ensure!(
service_hash == policy.updater_service.unit_sha256,
"TIME_UPDATER_SCM_POLICY"
);
let mut config_file =
PinnedFile::open(Path::new(UPDATER_CONFIG_PATH), false, &readers, &[], false)?;
ensure!(
config_file.file.metadata()?.len() <= MAX_CONFIG_BYTES as u64,
"TIME_NATIVE_CONFIG_SIZE"
);
let mut raw = Vec::new();
(&mut config_file.file)
.take(MAX_CONFIG_BYTES as u64 + 1)
.read_to_end(&mut raw)?;
ensure!(raw.len() <= MAX_CONFIG_BYTES, "TIME_NATIVE_CONFIG_SIZE");
let config: UpdaterConfiguration = serde_json::from_slice(&raw)?;
config.validate(&own_pin.binary_sha256)?;
ensure!(
config.updater_policy_sha256 == policy_hash
&& config.updater_service_configuration_sha256 == service_hash
&& config.binding.tenant_id == policy.tenant_id
&& config.binding.asset_id == policy.asset_id
&& config.binding.agent_id == policy.agent_id
&& config.binding.enrollment_generation == policy.enrollment_generation
&& config.binding.assignment_version == policy.assignment_version,
"TIME_UPDATER_POLICY_BINDING"
);
let keys = config
.public_keys_hex
.iter()
.map(|(id, key)| {
Ok((
id.clone(),
independent_time_key(key, &config.binding.public_key_hex)?,
))
})
.collect::<Result<BTreeMap<_, _>>>()?;
let pins = Pins::new(config.key_generation, config.server_instance, keys)?;
process()
.lock()
.map_err(|_| anyhow::anyhow!("TIME_NATIVE_STATE_POISONED"))?
.accept_configuration(config.key_generation, &hash(&raw))?;
let boot_id = Uuid::parse_str(&crate::native::boot_id().await?)?;
let context = Context {
tenant_id: config.binding.tenant_id,
asset_id: config.binding.asset_id,
agent_id: config.binding.agent_id,
enrollment_generation: config.binding.enrollment_generation,
assignment_generation: config.binding.assignment_version,
connection_generation,
windows_boot_id: boot_id,
verifier_incarnation: *INCARNATION.get_or_init(Uuid::new_v4),
role: Role::Updater,
helper_image_sha256: None,
binding_schema: 2,
updater_image_sha256: Some(own_pin.binary_sha256.clone()),
};
let capture_mode = CaptureMode::TrustedOsActiveGuest;
let mut value = Self {
verifier: Verifier::new(context, pins)?,
own_process,
files: vec![root, policy_file, config_file],
config_sha256: hash(&raw),
boot_id,
connection_generation,
capture_mode,
pending: None,
latest: None,
own_updater_configuration: Some((own_pin, service_hash)),
};
value.recheck()?;
process()
@@ -843,6 +1033,13 @@ mod installed {
fn recheck(&mut self) -> Result<()> {
let result = (|| {
self.own_process.check()?;
if let Some((pin, expected)) = &self.own_updater_configuration {
ensure!(
crate::update_native::services::updater_configuration_sha256(pin)?
== *expected,
"TIME_UPDATER_SCM_CHANGED"
);
}
for file in &mut self.files {
file.check()?;
}
@@ -1127,6 +1324,22 @@ mod installed {
fn now(&self) -> Result<chrono::DateTime<chrono::Utc>> {
Ok(self.reading()?.own_wall)
}
fn bounds(&self) -> Result<(chrono::DateTime<chrono::Utc>, chrono::DateTime<chrono::Utc>)> {
ensure!(self.generation > 0, "TIME_RUNTIME_NO_CONNECTION");
let mut state = self
.source
.state
.lock()
.map_err(|_| anyhow::anyhow!("TIME_RUNTIME_POISONED"))?;
let (held, clock) = state.as_mut().context("TIME_RUNTIME_NO_EVIDENCE")?;
ensure!(*held == self.generation, "TIME_RUNTIME_CONNECTION_CHANGED");
clock.with_current_comparison(|value| {
Ok((
chrono::DateTime::from_timestamp_nanos(value.interval().lower_utc_ns()),
chrono::DateTime::from_timestamp_nanos(value.interval().upper_utc_ns()),
))
})
}
fn reading(&self) -> Result<rmm_agent_core::reconcile::ClockReading> {
ensure!(self.generation > 0, "TIME_RUNTIME_NO_CONNECTION");
let mut state = self
@@ -1163,12 +1376,60 @@ mod installed {
}
}
#[cfg(all(windows, feature = "system-helper"))]
pub use installed::{BoundClock, CONFIG_PATH, Comparison, RuntimeClock, SignedClock};
pub use installed::{
BoundClock, CONFIG_PATH, Comparison, RuntimeClock, SignedClock, UPDATER_CONFIG_PATH,
};
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn updater_profile_binds_only_its_own_image_and_explicit_active_guest_assumption() {
use serde_json::json;
let job = ed25519_dalek::SigningKey::from_bytes(&[71; 32])
.verifying_key()
.to_bytes();
let time = ed25519_dalek::SigningKey::from_bytes(&[72; 32])
.verifying_key()
.to_bytes();
let hex = |raw: [u8; 32]| raw.iter().map(|b| format!("{b:02x}")).collect::<String>();
let value = json!({"schema_version":3,"key_generation":1,"server_instance":Uuid::new_v4(),
"binding":{"tenant_id":Uuid::new_v4(),"asset_id":Uuid::new_v4(),"agent_id":Uuid::new_v4(),"enrollment_generation":1,"assignment_version":1,"public_key_hex":hex(job)},
"public_keys_hex":{"updater-time":hex(time)},"updater_policy_sha256":"12".repeat(32),"updater_service_configuration_sha256":"13".repeat(32),
"trusted_os_active_guest":{"operating_assumption":"active_guest_no_pause_save_restore_snapshot_migration_host_suspend","platform":"kvm_qemu_hypervclock","platform_provenance_sha256":"14".repeat(32),
"qualifications":[{"role":"updater","binary_sha256":"15".repeat(32),"qualification_sha256":"16".repeat(32)}]}});
let config: UpdaterConfiguration = serde_json::from_value(value.clone()).unwrap();
config.validate(&"15".repeat(32)).unwrap();
assert!(config.validate(&"17".repeat(32)).is_err());
for mutation in ["helper", "second", "policy", "assumption"] {
let mut bad = value.clone();
match mutation {
"helper" => {
bad["trusted_os_active_guest"]["qualifications"][0]["role"] =
json!("system_helper")
}
"second" => {
let q = bad["trusted_os_active_guest"]["qualifications"][0].clone();
bad["trusted_os_active_guest"]["qualifications"]
.as_array_mut()
.unwrap()
.push(q);
}
"policy" => bad["updater_policy_sha256"] = json!("bad"),
_ => bad["trusted_os_active_guest"]["operating_assumption"] = json!(true),
}
let result = serde_json::from_value::<UpdaterConfiguration>(bad);
assert!(
match result {
Err(_) => true,
Ok(c) => c.validate(&"15".repeat(32)).is_err(),
},
"mutation {mutation}"
);
}
}
#[test]
fn passive_sampling_requires_a_profile_and_uses_heartbeat_cadence() {
let dir = std::env::temp_dir().join(Uuid::new_v4().to_string());
+268 -59
View File
@@ -6,7 +6,11 @@ use crate::{
};
use anyhow::{Result, ensure};
use serde::Deserialize;
use std::{collections::BTreeSet, io::Read, path::Path};
use std::{
collections::BTreeSet,
io::Read,
path::{Path, PathBuf},
};
use uuid::Uuid;
pub const PATH: &str = r"C:\ProgramData\RustDiscoverySystem\system-qualification.json";
@@ -27,65 +31,31 @@ struct Qualification {
qualification_reference: Uuid,
actions: Vec<String>,
}
pub fn qualified(pin: &Pin, clock_qualified: bool) -> Result<Vec<String>> {
if !clock_qualified || !Path::new(PATH).try_exists()? {
pub fn qualified(
pin: &Pin,
clock_qualified: bool,
reboot_privilege_available: Option<bool>,
) -> Result<Vec<String>> {
if !clock_qualified {
return Ok(vec![]);
}
let readers = [
ipc::service_sid(crate::SERVICE_NAME)?,
ipc::service_sid(ipc::HELPER_SERVICE)?,
];
let root = Path::new(PATH)
.parent()
.expect("fixed qualification parent");
let mut dir = PinnedFile::open_read_shared(root, true, &readers, &[])?;
let mut file = PinnedFile::open(Path::new(PATH), false, &readers, &[], false)?;
let mut bytes = vec![];
(&mut file.file).take(16385).read_to_end(&mut bytes)?;
ensure!(bytes.len() <= 16384, "system qualification size");
file.check()?;
dir.check()?;
let q: Qualification = serde_json::from_slice(&bytes)?;
ensure!(
q.schema_version == 1
&& (
q.tenant_id,
q.asset_id,
q.agent_id,
q.enrollment_generation,
q.assignment_version
) == (
pin.binding.tenant_id,
pin.binding.asset_id,
pin.binding.agent_id,
pin.binding.enrollment_generation,
pin.binding.assignment_version
)
&& q.agent_binary_sha256 == pin.agent.binary_sha256
&& q.helper_binary_sha256 == pin.helper.binary_sha256
&& q.policy_sha256 == pin.policy_sha256
&& ipc::digest(&q.native_result_sha256)
&& !q.qualification_reference.is_nil()
&& !q.actions.is_empty()
&& q.actions.len() <= 3
&& q.actions.iter().collect::<BTreeSet<_>>().len() == q.actions.len()
&& q.actions.iter().all(|a| matches!(
a.as_str(),
"run_script" | "set_service_state" | "ensure_package"
)),
"system qualification binding"
);
let mut result = PinnedFile::open(Path::new(RESULT_PATH), false, &readers, &[], false)?;
let mut result_bytes = vec![];
(&mut result.file)
.take(65537)
.read_to_end(&mut result_bytes)?;
ensure!(
result_bytes.len() <= 65536
&& rmm_domain::jobs::hash(&result_bytes) == q.native_result_sha256,
"system native qualification evidence hash"
);
result.check()?;
pin.validate()?;
let ordinary = load_ordinary(pin);
let (q, result_bytes) = match ordinary {
Ok(sources) => sources,
Err(error) => match load_catalog(pin) {
Ok(sources) => sources,
Err(catalog_error) => {
if !Path::new(PATH).try_exists()? && !catalog_directory(pin)?.try_exists()? {
return Ok(vec![]);
}
if catalog_directory(pin)?.try_exists()? {
return Err(catalog_error);
}
return Err(error);
}
},
};
let evidence: serde_json::Value = serde_json::from_slice(&result_bytes)?;
ensure!(
evidence["schema_version"] == 1
@@ -111,7 +81,7 @@ pub fn qualified(pin: &Pin, clock_qualified: bool) -> Result<Vec<String>> {
match action.as_str() {
"run_script" => {
ensure!(
settings.schema_version == 3
settings.schema_version >= 3
&& settings.allowed_script_profiles.as_deref()
== Some(&[
rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1
@@ -147,8 +117,247 @@ pub fn qualified(pin: &Pin, clock_qualified: bool) -> Result<Vec<String>> {
.map(str::to_string),
);
}
"reboot" => {
ensure!(
settings.schema_version == 4
&& settings.allow_reboot
&& reboot_privilege_available == Some(true),
"system reboot qualification policy or live token"
);
caps.extend(
[
"reboot",
"system:reboot",
rmm_domain::windows_reboot::CAPABILITY,
]
.map(str::to_string),
);
}
_ => unreachable!("validated qualification action"),
}
}
Ok(caps)
}
fn read(path: &Path, max: u64) -> Result<Vec<u8>> {
let readers = [
ipc::service_sid(crate::SERVICE_NAME)?,
ipc::service_sid(ipc::HELPER_SERVICE)?,
];
let mut dir = PinnedFile::open_read_shared(
path.parent().expect("fixed qualification parent"),
true,
&readers,
&[],
)?;
let mut file = PinnedFile::open(path, false, &readers, &[], false)?;
ensure!(
file.file.metadata()?.len() <= max,
"system qualification file limit"
);
let mut raw = vec![];
(&mut file.file).take(max + 1).read_to_end(&mut raw)?;
ensure!(raw.len() as u64 <= max, "system qualification file limit");
file.check()?;
dir.check()?;
Ok(raw)
}
fn validate(q: &Qualification, pin: &Pin) -> Result<()> {
ensure!(
q.schema_version == 1
&& (
q.tenant_id,
q.asset_id,
q.agent_id,
q.enrollment_generation,
q.assignment_version
) == (
pin.binding.tenant_id,
pin.binding.asset_id,
pin.binding.agent_id,
pin.binding.enrollment_generation,
pin.binding.assignment_version
)
&& q.agent_binary_sha256 == pin.agent.binary_sha256
&& q.helper_binary_sha256 == pin.helper.binary_sha256
&& q.policy_sha256 == pin.policy_sha256
&& ipc::digest(&q.native_result_sha256)
&& !q.qualification_reference.is_nil()
&& !q.actions.is_empty()
&& q.actions.len() <= 4
&& q.actions.iter().collect::<BTreeSet<_>>().len() == q.actions.len()
&& q.actions.iter().all(|a| matches!(
a.as_str(),
"run_script" | "set_service_state" | "ensure_package" | "reboot"
)),
"system qualification binding"
);
Ok(())
}
fn load_ordinary(pin: &Pin) -> Result<(Qualification, Vec<u8>)> {
let raw = read(Path::new(PATH), 16384)?;
let q: Qualification = serde_json::from_slice(&raw)?;
validate(&q, pin)?;
let result = read(Path::new(RESULT_PATH), 65536)?;
ensure!(
rmm_domain::jobs::hash(&result) == q.native_result_sha256,
"system native qualification evidence hash"
);
Ok((q, result))
}
/// Fixed per-device MVP catalog, provisioned only from actual qualification.
/// It is public metadata/deny-only capability evidence, never a job lease.
pub fn catalog_directory(pin: &Pin) -> Result<PathBuf> {
ensure!(
ipc::digest(&pin.agent.binary_sha256)
&& ipc::digest(&pin.helper.binary_sha256)
&& ipc::digest(&pin.policy_sha256),
"system catalog digest"
);
let key = rmm_domain::jobs::hash(&serde_json::to_vec(&(
&pin.agent.binary_sha256,
&pin.helper.binary_sha256,
&pin.policy_sha256,
))?);
Ok(Path::new(r"C:\ProgramData\RustDiscoverySystem\system-qualification-catalog").join(key))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct CatalogEvidence {
schema_version: u32,
source_manifest_sha256: String,
qualification_sha256: String,
native_result_sha256: String,
start_witness_sha256: String,
outcome_sha256: String,
approval_audit_sha256: String,
plan_id: Uuid,
plan_sha256: String,
job_id: Uuid,
attempt_id: Uuid,
grant_id: Uuid,
authorization_id: Uuid,
operation_id: Uuid,
approval_origin: String,
testsimulation: bool,
}
fn load_catalog(pin: &Pin) -> Result<(Qualification, Vec<u8>)> {
use rmm_domain::jobs::hash;
let directory = catalog_directory(pin)?;
let q_raw = read(&directory.join("qualification.json"), 16384)?;
let q: Qualification = serde_json::from_slice(&q_raw)?;
validate(&q, pin)?;
let result = read(&directory.join("native-result.json"), 65536)?;
let source_manifest = read(&directory.join("source-manifest.json"), 512 * 1024)?;
let source_document:serde_json::Value=serde_json::from_slice(&source_manifest)?;
ensure!(source_document.as_array().is_some_and(|a|!a.is_empty())
|| source_document.as_object().is_some_and(|a|!a.is_empty()),"system catalog source manifest");
let evidence_raw = read(&directory.join("prequalification.json"), 16384)?;
let e: CatalogEvidence = serde_json::from_slice(&evidence_raw)?;
ensure!(
e.schema_version == 1
&& e.source_manifest_sha256 == hash(&source_manifest)
&& e.qualification_sha256 == hash(&q_raw)
&& e.native_result_sha256 == hash(&result)
&& e.native_result_sha256 == q.native_result_sha256
&& [
e.plan_id,
e.job_id,
e.attempt_id,
e.grant_id,
e.authorization_id,
e.operation_id
]
.iter()
.all(|id| !id.is_nil())
&& ipc::digest(&e.plan_sha256)
&& matches!(
(e.testsimulation, e.approval_origin.as_str()),
(true, "dev_test_browser_simulation") | (false, "human_webui")
),
"system catalog qualification provenance"
);
let start = read(&directory.join("start-witness.json"), 512 * 1024)?;
let outcome = read(&directory.join("powershell-outcome.json"), 128 * 1024)?;
let audit = read(&directory.join("approval-audit.json"), 65536)?;
ensure!(
hash(&start) == e.start_witness_sha256
&& hash(&outcome) == e.outcome_sha256
&& hash(&audit) == e.approval_audit_sha256,
"system catalog actual evidence bytes"
);
let start_value: serde_json::Value = serde_json::from_slice(&start)?;
let request: rmm_agent_core::auth::Request =
serde_json::from_value(start_value["request"].clone())?;
let at: chrono::DateTime<chrono::Utc> =
serde_json::from_value(start_value["reserved_at"].clone())?;
let boot: Uuid = serde_json::from_value(start_value["previous_boot_id"].clone())?;
let (job, permit) = pin.binding.verify(&request, at)?;
ensure!(
rmm_agent_core::ledger::start_witness_bytes(&permit, &request, boot, at)? == start
&& (
job.job_id,
job.attempt_id,
permit.grant_id,
permit.authorization_id
) == (e.job_id, e.attempt_id, e.grant_id, e.authorization_id)
&& permit.plan_hash == e.plan_sha256
&& job.execution_identity == "system"
&& job.action.full_maintenance(),
"system catalog actual original SYSTEM job"
);
let rmm_domain::jobs::Action::RunScript {
interpreter,
script_utf8,
..
} = &job.action
else {
anyhow::bail!("system catalog PowerShell qualification required")
};
let parsed: rmm_domain::reconciliation::ReconciledOutcome = serde_json::from_slice(&outcome)?;
ensure!(
rmm_domain::reconciliation::canonical_outcome_bytes(&parsed)? == outcome
&& parsed.state == "succeeded"
&& parsed.exit_code == Some(0)
&& parsed.error_code.is_empty()
&& !parsed.output_truncated
&& !parsed.reboot_required
&& interpreter == "powershell"
&& parsed.evidence["postconditions_passed"] == true
&& parsed.evidence["execution_sid"] == "S-1-5-18"
&& parsed.evidence["privileged_script_profile"] == "full_maintenance_v1"
&& parsed.evidence["script_sha256"] == hash(script_utf8.as_bytes())
&& parsed.evidence["execution_context"]["schema_version"] == 1
&& parsed.evidence["execution_context"]["tenant_id"]
== pin.binding.tenant_id.to_string()
&& parsed.evidence["execution_context"]["asset_id"] == pin.binding.asset_id.to_string()
&& parsed.evidence["execution_context"]["agent_id"] == pin.binding.agent_id.to_string()
&& parsed.evidence["execution_context"]["agent_binary_sha256"]
== pin.agent.binary_sha256
&& parsed.evidence["execution_context"]["helper_binary_sha256"]
== pin.helper.binary_sha256
&& parsed.evidence["execution_context"]["policy_sha256"] == pin.policy_sha256
&& parsed.evidence["execution_context"]["binding_sha256"]
== ipc::binding_hash(&pin.binding)?
&& parsed.evidence["execution_context"]["rechecked_at_finish"] == true,
"system catalog actual PowerShell outcome"
);
let audit: serde_json::Value = serde_json::from_slice(&audit)?;
ensure!(
audit["tenant_id"] == pin.binding.tenant_id.to_string()
&& audit["event_type"] == "plan_authorization"
&& audit["event_id"]
.as_str()
.is_some_and(|s| Uuid::parse_str(s).is_ok_and(|id| !id.is_nil()))
&& audit["principal"]
.as_str()
.is_some_and(|s| !s.is_empty() && s.len() <= 256)
&& audit["data"]["plan_id"] == e.plan_id.to_string()
&& audit["data"]["plan_hash"] == e.plan_sha256
&& audit["data"]["operation_id"] == e.operation_id.to_string()
&& audit["data"]["decision"] == "approve"
&& audit["data"]["approval_origin"] == e.approval_origin
&& audit["data"]["testsimulation"] == e.testsimulation,
"system catalog actual WebUI approval audit"
);
Ok((q, result))
}
@@ -0,0 +1,670 @@
//! 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<DalekVerifier>,
request: &'a Request,
grant: Uuid,
nonce: Uuid,
trust: &'a TrustState,
pending: Option<String>,
}
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<services::Running>,
updater: RefCell<PeerProof>,
original: RefCell<PeerProof>,
stages: Vec<Staged>,
protected: Vec<Protected>,
sqlite: usize,
}
impl<'a> Prepared<'a> {
pub fn new(
db: &Connection,
local: Local<'a>,
sync: &HelperSync<DalekVerifier>,
request: &Request,
) -> Result<Self> {
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::<Vec<_>>();
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<u8>, Vec<u8>) = 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<DalekVerifier>,
) -> Result<Accepted> {
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<chrono::Utc>,
) -> 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<services::Running>,
updater: RefCell<PeerProof>,
original: RefCell<PeerProof>,
_stages: Vec<Staged>,
_protected: Vec<Protected>,
}
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<u8> = 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"))
}
+221
View File
@@ -0,0 +1,221 @@
//! Public signed artifact bytes only, before any startgrant is requested.
//! This cache grants no execution authority. SYSTEM reopens and hashes each
//! source independently; the writable LocalService source is never a trust pin.
use crate::helper_ipc::{self as ipc, PinnedFile};
use anyhow::{Context, Result, ensure};
use rmm_domain::agent_update::{ArtifactDescriptor, ReleaseManifest};
use sha2::{Digest, Sha256};
use std::{
fs::{File, OpenOptions},
io::{Read, Seek, SeekFrom, Write},
mem::zeroed,
os::windows::{
fs::OpenOptionsExt,
io::{AsRawHandle, FromRawHandle},
},
path::{Path, PathBuf},
ptr,
};
use windows_sys::Win32::{Foundation::*, Storage::FileSystem::*};
pub const ROOT: &str = r"C:\ProgramData\RustDiscovery\state\update-stage";
fn path(a: &ArtifactDescriptor, partial: bool) -> Result<PathBuf> {
ensure!(
!a.artifact_id.is_nil()
&& ipc::digest(&a.sha256)
&& a.bytes > 0
&& a.bytes <= rmm_domain::agent_update::MAX_ARTIFACT_BYTES,
"UPDATE_CACHE_DESCRIPTOR"
);
Ok(Path::new(ROOT).join(format!(
"{}.{}",
a.sha256,
if partial { "part" } else { "bin" }
)))
}
fn regular(f: &File, dir: bool) -> Result<()> {
let mut i: BY_HANDLE_FILE_INFORMATION = unsafe { zeroed() };
ensure!(
unsafe { GetFileInformationByHandle(f.as_raw_handle(), &mut i) } != 0
&& i.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT == 0
&& (i.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY != 0) == dir
&& (dir || i.nNumberOfLinks == 1),
"UPDATE_CACHE_FILE_TYPE"
);
Ok(())
}
fn parents(p: &Path) -> Result<Vec<File>> {
let mut guards = Vec::new();
for parent in p.ancestors().skip(1) {
let h = unsafe {
CreateFileW(
ipc::wide(parent).as_ptr(),
FILE_READ_ATTRIBUTES,
FILE_SHARE_READ | FILE_SHARE_WRITE,
ptr::null(),
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
ptr::null_mut(),
)
};
ensure!(h != INVALID_HANDLE_VALUE, "UPDATE_CACHE_NOT_PROVISIONED");
let file = unsafe { File::from_raw_handle(h) };
regular(&file, true)?;
guards.push(file);
}
Ok(guards)
}
fn verify(file: &mut File, a: &ArtifactDescriptor) -> Result<()> {
regular(file, false)?;
ensure!(file.metadata()?.len() == a.bytes, "UPDATE_CACHE_LENGTH");
file.seek(SeekFrom::Start(0))?;
let mut digest = Sha256::new();
let mut bytes = [0; 65536];
let mut length = 0u64;
loop {
let n = file.read(&mut bytes)?;
if n == 0 {
break;
}
length += n as u64;
ensure!(length <= a.bytes, "UPDATE_CACHE_LENGTH");
digest.update(&bytes[..n]);
}
ensure!(
length == a.bytes && format!("{:x}", digest.finalize()) == a.sha256,
"UPDATE_CACHE_DIGEST"
);
file.seek(SeekFrom::Start(0))?;
Ok(())
}
/// An already open independently hashed source. Parent and source handles deny
/// replacement and the source denies data writes until protected staging ends.
pub struct Source {
pub file: File,
_parents: Vec<File>,
identity: ipc::FileIdentity,
descriptor: ArtifactDescriptor,
}
impl Source {
pub fn open(a: &ArtifactDescriptor) -> Result<Self> {
let p = path(a, false)?;
let parents = parents(&p)?;
let mut file = OpenOptions::new()
.read(true)
.share_mode(FILE_SHARE_READ)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(&p)
.context("UPDATE_CACHE_MISSING")?;
verify(&mut file, a)?;
Ok(Self {
identity: ipc::file_identity(&file)?,
file,
_parents: parents,
descriptor: a.clone(),
})
}
pub fn check(&mut self) -> Result<()> {
ensure!(
ipc::file_identity(&self.file)? == self.identity,
"UPDATE_CACHE_IDENTITY"
);
verify(&mut self.file, &self.descriptor)
}
}
pub fn configured() -> bool {
crate::native::private_path(Path::new(ROOT), true).is_ok()
}
pub fn ready(m: &ReleaseManifest) -> Result<bool> {
ensure!(m.validate(), "UPDATE_CACHE_MANIFEST");
for a in &m.artifacts {
if !path(a, false)?.try_exists()? {
return Ok(false);
}
let _ = Source::open(a)?;
}
Ok(true)
}
/// The only resumable operation is a bounded public byte download. No journal,
/// request, consumption, handoff or effect is resumed by this cache.
pub struct Download {
file: File,
descriptor: ArtifactDescriptor,
received: u64,
_parents: Vec<File>,
_root: PinnedFile,
}
impl Download {
pub fn begin(a: &ArtifactDescriptor) -> Result<Self> {
crate::native::require_local_service()?;
let p = path(a, true)?;
let parents = parents(&p)?;
crate::native::private_path(Path::new(ROOT), true)?;
let root = PinnedFile::open(
Path::new(ROOT),
true,
&[crate::native::service_sid()?],
&[crate::native::service_sid()?],
false,
)?;
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.share_mode(FILE_SHARE_READ)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(&p)?;
regular(&file, false)?;
crate::native::private_path(&p, false)?;
let received = file.metadata()?.len();
ensure!(received <= a.bytes, "UPDATE_CACHE_PARTIAL_OVERSIZE");
file.seek(SeekFrom::Start(received))?;
Ok(Self {
file,
descriptor: a.clone(),
received,
_parents: parents,
_root: root,
})
}
pub fn offset(&self) -> u64 {
self.received
}
pub fn append(&mut self, offset: u64, bytes: &[u8]) -> Result<()> {
ensure!(
offset == self.received
&& !bytes.is_empty()
&& bytes.len() <= 512 * 1024
&& self.received + bytes.len() as u64 <= self.descriptor.bytes,
"UPDATE_CACHE_CHUNK"
);
self._root.check()?;
self.file.write_all(bytes)?;
self.received += bytes.len() as u64;
Ok(())
}
pub fn finish(mut self) -> Result<()> {
ensure!(
self.received == self.descriptor.bytes,
"UPDATE_CACHE_INCOMPLETE"
);
self.file.sync_all()?;
verify(&mut self.file, &self.descriptor)?;
self._root.check()?;
let src = path(&self.descriptor, true)?;
let dst = path(&self.descriptor, false)?;
drop(self.file);
// No replace, no delete of an existing source, and no shell invocation.
ensure!(
unsafe {
MoveFileExW(
ipc::wide(src).as_ptr(),
ipc::wide(dst).as_ptr(),
MOVEFILE_WRITE_THROUGH,
)
} != 0,
"UPDATE_CACHE_PUBLISH"
);
let _ = Source::open(&self.descriptor)?;
Ok(())
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,301 @@
//! Reverse stable-updater -> SYSTEM-helper control. A distinct fixed endpoint
//! never broadens the LocalService pipe into an updater effect API. Native
//! control still requires the ORIGINAL guarded journal and phase-specific proof.
use crate::{
helper_ipc::{self as ipc, PeerProof},
update_ipc::Pin,
};
use anyhow::{Result, ensure};
use rmm_agent_core::update_handoff::{
NativeControlOperation, NativeControlReply, NativeControlRequest, NativeService,
};
use std::{
mem::size_of,
os::windows::io::{AsRawHandle, OwnedHandle},
ptr,
time::{Duration, Instant},
};
use windows_sys::Win32::{
Foundation::*,
Security::*,
Storage::FileSystem::*,
System::{Pipes::*, Threading::*},
};
pub const PIPE: &str = r"\\.\pipe\RustDiscovery-System-Update-v1";
fn request_valid(pin: &Pin, r: &NativeControlRequest) -> Result<()> {
ensure!(
r.operation == "agent_update_control_v1"
&& r.schema_version == 1
&& !r.challenge.is_nil()
&& r.tenant_id == pin.binding.tenant_id
&& r.asset_id == pin.binding.asset_id
&& r.agent_id == pin.binding.agent_id
&& r.enrollment_generation == pin.binding.enrollment_generation
&& r.assignment_version == pin.binding.assignment_version
&& !r.grant_id.is_nil()
&& !r.owner_nonce.is_nil()
&& ipc::digest(&r.handoff_sha256),
"UPDATE_CONTROL_REQUEST_BINDING"
);
match &r.method {
NativeControlOperation::ClaimStop {
expected_head_sha256,
service,
} => ensure!(
ipc::digest(expected_head_sha256)
&& matches!(
service,
NativeService::WindowsAgent | NativeService::WindowsHelper
),
"UPDATE_CONTROL_WINDOWS_STOP_ONLY"
),
NativeControlOperation::Health { receipt } => ensure!(
!receipt.payload.is_empty()
&& receipt.payload.len() <= 4096
&& receipt.signature.len() == 64,
"UPDATE_CONTROL_HEALTH_LIMIT"
),
NativeControlOperation::ObserveStarts {
services,
observation_sha256,
} => ensure!(
services.len() == 2 && ipc::digest(observation_sha256),
"UPDATE_CONTROL_START_LIMIT"
),
NativeControlOperation::ReadOriginal | NativeControlOperation::Finalize => {}
}
Ok(())
}
fn reply_valid(r: &NativeControlRequest, v: &NativeControlReply) -> Result<()> {
ensure!(
v.schema_version == 1
&& v.challenge == r.challenge
&& v.tenant_id == r.tenant_id
&& v.asset_id == r.asset_id
&& v.agent_id == r.agent_id
&& v.enrollment_generation == r.enrollment_generation
&& v.assignment_version == r.assignment_version
&& v.grant_id == r.grant_id
&& v.owner_nonce == r.owner_nonce
&& v.handoff_sha256 == r.handoff_sha256
&& !v.ready,
"UPDATE_CONTROL_REPLY_BINDING"
);
if let Some(proof) = &v.proof {
ensure!(
proof.delegation.owner_nonce == r.owner_nonce
&& proof.delegation.handoff_sha256 == r.handoff_sha256,
"UPDATE_CONTROL_PROOF_BINDING"
);
}
ensure!(
v.original_start_base64url
.as_ref()
.is_none_or(|s| s.len() <= 699051)
&& v.original_outcome_base64url
.as_ref()
.is_none_or(|s| s.len() <= 699051),
"UPDATE_CONTROL_REPLY_LIMIT"
);
match (
&v.pre_stop_sync_request_base64url,
&v.pre_stop_sync_response_base64url,
) {
(None, None) => {}
(Some(request), Some(response)) => {
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
ensure!(
matches!(r.method, NativeControlOperation::ReadOriginal)
&& request.len() <= 699051
&& response.len() <= 699051,
"UPDATE_CONTROL_PRESTOP_SCOPE_LIMIT"
);
for raw in [request, response] {
let decoded = URL_SAFE_NO_PAD.decode(raw)?;
ensure!(
!decoded.is_empty()
&& decoded.len() <= 512 * 1024
&& URL_SAFE_NO_PAD.encode(&decoded) == *raw,
"UPDATE_CONTROL_PRESTOP_CANONICAL"
);
}
}
_ => anyhow::bail!("UPDATE_CONTROL_PRESTOP_PAIR_REQUIRED"),
}
match &r.method {
NativeControlOperation::ReadOriginal => ensure!(
v.original_start_base64url.is_some()
&& v.original_outcome_base64url.is_none()
&& v.claim.is_none(),
"UPDATE_CONTROL_READ_REPLY"
),
NativeControlOperation::ClaimStop { .. } => ensure!(
v.claim.is_some()
&& v.original_start_base64url.is_none()
&& v.original_outcome_base64url.is_none(),
"UPDATE_CONTROL_CLAIM_REPLY"
),
NativeControlOperation::ObserveStarts { .. } | NativeControlOperation::Health { .. } => {
ensure!(
v.original_start_base64url.is_none()
&& v.original_outcome_base64url.is_none()
&& v.claim.is_none(),
"UPDATE_CONTROL_PHASE_REPLY"
)
}
NativeControlOperation::Finalize => ensure!(
v.original_start_base64url.is_none() && v.claim.is_none(),
"UPDATE_CONTROL_FINAL_REPLY"
),
}
Ok(())
}
pub trait Engine {
fn handle(
&mut self,
peer: &mut PeerProof,
request: &NativeControlRequest,
) -> Result<NativeControlReply>;
}
pub struct Server {
pin: Pin,
pipe: OwnedHandle,
}
pub struct Received {
pub request: NativeControlRequest,
pub peer: PeerProof,
}
impl Server {
pub fn bind(pin: Pin) -> Result<Self> {
pin.validate()?;
ipc::require_self(&pin.helper)?;
let d = ipc::Descriptor::from(&format!(
"O:SYG:SYD:P(D;;GA;;;NU)(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;{})(A;;0x{:08x};;;{})",
pin.helper.service_sid,
ipc::CLIENT_PIPE_RIGHTS,
pin.updater.service_sid
))?;
let sa = SECURITY_ATTRIBUTES {
nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
lpSecurityDescriptor: d.0,
bInheritHandle: 0,
};
let pipe = ipc::owned(unsafe {
CreateNamedPipeW(
ipc::wide(PIPE).as_ptr(),
PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS,
1,
65536,
65536,
1000,
&sa,
)
})?;
Ok(Self { pin, pipe })
}
pub fn receive(&self) -> Result<Option<Received>> {
ipc::require_self(&self.pin.helper)?;
let pipe = self.pipe.as_raw_handle();
let mut event = ipc::IoEvent::new()?;
if unsafe { ConnectNamedPipe(pipe, &mut event.overlapped) } == 0 {
let error = unsafe { GetLastError() };
if error == ERROR_IO_PENDING {
if let Err(e) = event.wait(pipe, Instant::now() + Duration::from_millis(25)) {
if ipc::diagnostic(&e).code == "HELPER_PIPE_TIMEOUT" {
self.disconnect();
return Ok(None);
}
return Err(e);
}
} else {
ensure!(error == ERROR_PIPE_CONNECTED, "UPDATE_CONTROL_CONNECT");
}
}
let deadline = Instant::now() + Duration::from_secs(5);
let len = ipc::length(pipe, deadline)?;
let mut peer = PeerProof::capture(pipe, &self.pin.updater, true)?;
ensure!(
unsafe { ImpersonateNamedPipeClient(pipe) } != 0,
"UPDATE_CONTROL_IMPERSONATE"
);
let auth = (|| -> Result<()> {
let mut token = ptr::null_mut();
ensure!(
unsafe { OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, 1, &mut token) } != 0,
"UPDATE_CONTROL_THREAD_TOKEN"
);
let token = ipc::owned(token)?;
ipc::verify_token(
token.as_raw_handle(),
&self.pin.updater.user_sid,
&self.pin.updater.service_sid,
)
})();
if unsafe { RevertToSelf() } == 0 {
std::process::abort();
}
auth?;
ipc::require_self(&self.pin.helper)?;
let request: NativeControlRequest = ipc::body(pipe, len, deadline)?;
request_valid(&self.pin, &request)?;
peer.check()?;
Ok(Some(Received { request, peer }))
}
pub fn reply(&self, received: &mut Received, reply: &NativeControlReply) -> Result<()> {
reply_valid(&received.request, reply)?;
received.peer.check()?;
let mut raw = ipc::encode(reply)?;
let deadline = Instant::now() + Duration::from_secs(5);
ipc::send_bytes(self.pipe.as_raw_handle(), &mut raw, deadline)?;
let mut receipt = [0; ipc::DRAIN_RECEIPT_LEN];
ipc::transfer(self.pipe.as_raw_handle(), &mut receipt, false, deadline)?;
ipc::verify_drain_receipt(&receipt, received.request.challenge, &raw)?;
received.peer.check()
}
pub fn serve_one(&self, engine: &mut impl Engine) -> Result<bool> {
let result = (|| -> Result<bool> {
let Some(mut received) = self.receive()? else {
return Ok(false);
};
let reply = engine.handle(&mut received.peer, &received.request)?;
self.reply(&mut received, &reply)?;
Ok(true)
})();
self.disconnect();
result
}
pub fn disconnect(&self) {
unsafe {
DisconnectNamedPipe(self.pipe.as_raw_handle());
}
}
}
/// One original request, no reconnect/retry of a possibly committed claim.
pub fn exchange(pin: &Pin, request: &NativeControlRequest) -> Result<NativeControlReply> {
pin.validate()?;
request_valid(pin, request)?;
ipc::require_self(&pin.updater)?;
let pipe = ipc::owned(unsafe {
CreateFileW(
ipc::wide(PIPE).as_ptr(),
ipc::CLIENT_PIPE_RIGHTS,
0,
ptr::null(),
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED | SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION,
ptr::null_mut(),
)
})?;
let mut peer = PeerProof::capture(pipe.as_raw_handle(), &pin.helper, false)?;
let deadline = Instant::now() + Duration::from_secs(5);
ipc::send(pipe.as_raw_handle(), request, deadline)?;
let length = ipc::length(pipe.as_raw_handle(), deadline)?;
let raw = ipc::body_bytes(pipe.as_raw_handle(), length, deadline)?;
let reply: NativeControlReply = serde_json::from_slice(&raw)?;
reply_valid(request, &reply)?;
peer.check()?;
let mut receipt = ipc::drain_receipt(request.challenge, &raw);
ipc::transfer(pipe.as_raw_handle(), &mut receipt, true, deadline)?;
Ok(reply)
}
+111
View File
@@ -0,0 +1,111 @@
//! mTLS public artifact prefetch for an already approved JobOffer. This runs
//! before the sixty-second startgrant, on its own task and bounded disk lanes.
use anyhow::{Result, ensure};
use reqwest::{Client, StatusCode};
use rmm_agent_windows::update_cache::{self, Download};
use rmm_domain::{
agent_update::ReleaseManifest,
jobs::JobPayload,
};
use std::time::{Duration, Instant};
const CHUNK: u64 = 512 * 1024;
fn metadata(
response: &reqwest::Response,
a: &rmm_domain::agent_update::ArtifactDescriptor,
offset: u64,
length: u64,
) -> Result<()> {
let partial = offset != 0 || length != a.bytes;
ensure!(
response.status()
== if partial {
StatusCode::PARTIAL_CONTENT
} else {
StatusCode::OK
},
"UPDATE_DOWNLOAD_STATUS"
);
let h = response.headers();
ensure!(
h.get("x-artifact-sha256").and_then(|v| v.to_str().ok()) == Some(a.sha256.as_str())
&& h.get("content-type").and_then(|v| v.to_str().ok())
== Some("application/octet-stream")
&& !h.contains_key("content-encoding")
&& h.get("content-length")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse::<u64>().ok())
== Some(length),
"UPDATE_DOWNLOAD_METADATA"
);
if partial {
ensure!(
h.get("content-range").and_then(|v| v.to_str().ok())
== Some(format!("bytes {}-{}/{}", offset, offset + length - 1, a.bytes).as_str()),
"UPDATE_DOWNLOAD_RANGE"
);
} else {
ensure!(!h.contains_key("content-range"), "UPDATE_DOWNLOAD_RANGE");
}
Ok(())
}
pub async fn prefetch(
client: Client,
base: String,
job: JobPayload,
manifest: ReleaseManifest,
guard: impl Fn() -> Result<()> + Send + 'static,
) -> Result<()> {
ensure!(
manifest.validate() && manifest.platform == rmm_agent_windows::release_platform::WIRE,
"UPDATE_DOWNLOAD_MANIFEST"
);
let deadline = Instant::now() + Duration::from_secs(600);
for artifact in manifest.artifacts {
guard()?;
let descriptor = artifact.clone();
let exists = tokio::task::spawn_blocking(move || -> Result<bool> {
if update_cache::Source::open(&descriptor).is_ok() {
Ok(true)
} else {
Ok(false)
}
})
.await??;
if exists {
continue;
}
let descriptor = artifact.clone();
let mut stage = tokio::task::spawn_blocking(move || Download::begin(&descriptor)).await??;
while stage.offset() < artifact.bytes {
guard()?;
ensure!(Instant::now() < deadline, "UPDATE_DOWNLOAD_DEADLINE");
let offset = stage.offset();
let length = CHUNK.min(artifact.bytes - offset);
let mut response=client.get(format!("{base}/agent/v1/update-artifacts/{}?job_id={}&attempt_id={}&offset={offset}&length={length}",artifact.artifact_id,job.job_id,job.attempt_id)).send().await?;
metadata(&response, &artifact, offset, length)?;
let mut bytes = Vec::with_capacity(length as usize);
while let Some(chunk) = response.chunk().await? {
ensure!(
bytes.len() + chunk.len() <= length as usize,
"UPDATE_DOWNLOAD_BODY_LIMIT"
);
bytes.extend_from_slice(&chunk);
}
ensure!(
bytes.len() == length as usize,
"UPDATE_DOWNLOAD_BODY_LENGTH"
);
guard()?;
ensure!(Instant::now() < deadline, "UPDATE_DOWNLOAD_DEADLINE");
stage = tokio::task::spawn_blocking(move || -> Result<Download> {
stage.append(offset, &bytes)?;
Ok(stage)
})
.await??;
}
guard()?;
tokio::task::spawn_blocking(move || stage.finish()).await??;
}
guard()?;
Ok(())
}
+419
View File
@@ -0,0 +1,419 @@
//! Stable updater channel, separate from the LocalService agent channel.
//! Mutually pinned service identity is checked before decoding a bounded call.
//! An Activate is never retried by the transport. A response is not readiness.
use crate::helper_ipc::{self as ipc, PeerPin, PeerProof};
use anyhow::{Context, Result, ensure};
use rmm_agent_core::auth::Binding;
use rmm_domain::{
agent_update::{ParticipantIdentity, ParticipantRole},
jobs::hash,
};
use serde::{Deserialize, Serialize};
use std::{
mem::size_of,
os::windows::io::{AsRawHandle, OwnedHandle},
path::Path,
ptr,
time::{Duration, Instant},
};
use uuid::Uuid;
use windows_sys::Win32::{
Foundation::*,
Security::*,
Storage::FileSystem::*,
System::{Pipes::*, Threading::*},
};
pub const SERVICE: &str = "RmmDiscoveryUpdater";
pub const BINARY: &str = r"C:\Program Files\RustDiscovery\rmm-updater-windows.exe";
pub const PIPE: &str = r"\\.\pipe\RustDiscovery-Updater-v1";
const LIMIT: usize = 32768;
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Pin {
pub schema_version: u32,
pub binding: Binding,
pub policy_sha256: String,
pub helper: PeerPin,
pub updater: PeerPin,
}
impl Pin {
pub fn validate(&self) -> Result<()> {
ensure!(
self.schema_version == 1 && ipc::digest(&self.policy_sha256),
"UPDATE_IPC_PIN"
);
self.helper.validate(true)?;
ensure!(
self.updater.service_name == SERVICE
&& self.updater.service_sid == ipc::service_sid(SERVICE)?
&& self.updater.user_sid == "S-1-5-18"
&& self.updater.binary == Path::new(BINARY)
&& ipc::digest(&self.updater.binary_sha256),
"UPDATE_IPC_UPDATER_PIN"
);
ensure!(
!self.binding.agent_id.is_nil()
&& !self.binding.asset_id.is_nil()
&& !self.binding.tenant_id.is_nil()
&& self.binding.enrollment_generation > 0
&& self.binding.assignment_version > 0,
"UPDATE_IPC_BINDING"
);
Ok(())
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "method", rename_all = "snake_case", deny_unknown_fields)]
pub enum Request {
Describe {},
Activate {
grant_id: Uuid,
owner_nonce: Uuid,
handoff_sha256: String,
},
Read {
grant_id: Uuid,
owner_nonce: Uuid,
handoff_sha256: String,
},
Health {
grant_id: Uuid,
owner_nonce: Uuid,
handoff_sha256: String,
payload_base64url: String,
signature_base64url: String,
},
}
impl Request {
pub fn validate(&self) -> Result<()> {
match self {
Self::Describe {} => {}
Self::Activate {
grant_id,
owner_nonce,
handoff_sha256,
}
| Self::Read {
grant_id,
owner_nonce,
handoff_sha256,
}
| Self::Health {
grant_id,
owner_nonce,
handoff_sha256,
..
} => {
ensure!(
!grant_id.is_nil() && !owner_nonce.is_nil() && ipc::digest(handoff_sha256),
"UPDATE_IPC_ORIGINAL_BINDING"
);
if let Self::Health {
payload_base64url,
signature_base64url,
..
} = self
{
ensure!(
!payload_base64url.is_empty()
&& payload_base64url.len() <= 21846
&& signature_base64url.len() == 86
&& payload_base64url
.bytes()
.chain(signature_base64url.bytes())
.all(|b| b.is_ascii_alphanumeric() || b"-_".contains(&b)),
"UPDATE_IPC_HEALTH_LIMIT"
);
}
}
}
Ok(())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum State {
Described,
Inflight,
OutcomePersisted,
Unknown,
NotConfigured,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Response {
pub schema_version: u32,
pub state: State,
pub ready: bool,
pub updater: ParticipantIdentity,
pub head_sha256: Option<String>,
}
impl Response {
fn validate(&self) -> Result<()> {
ensure!(
self.schema_version == 1
&& !self.ready
&& self.updater.validate()
&& self.updater.role == ParticipantRole::WindowsUpdater
&& self.head_sha256.as_ref().is_none_or(|v| ipc::digest(v)),
"UPDATE_IPC_RESPONSE"
);
Ok(())
}
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Call {
schema_version: u32,
challenge: Uuid,
binding_sha256: String,
policy_sha256: String,
request: Request,
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Reply {
schema_version: u32,
challenge: Uuid,
binding_sha256: String,
policy_sha256: String,
response: Response,
}
/// The instance digest covers the pinned SCM command and held live process,
/// including image file identity and service SID, rather than PID alone.
pub fn participant(peer: &PeerProof, role: ParticipantRole) -> Result<ParticipantIdentity> {
ensure!(
matches!(
role,
ParticipantRole::WindowsHelper | ParticipantRole::WindowsUpdater
),
"UPDATE_IPC_PARTICIPANT_ROLE"
);
let p = peer.identity();
let expected = if role == ParticipantRole::WindowsHelper {
ipc::HELPER_SERVICE
} else {
SERVICE
};
ensure!(
p.user_sid == "S-1-5-18" && p.service_sid == ipc::service_sid(expected)?,
"UPDATE_IPC_PARTICIPANT_SID"
);
let value = ParticipantIdentity {
role,
pid: p.pid,
birth: p.creation_ticks,
image_sha256: p.image_sha256.clone(),
security_principal: p.user_sid.clone(),
service_instance_sha256: hash(&serde_json::to_vec(p)?),
};
ensure!(value.validate(), "UPDATE_IPC_PARTICIPANT");
Ok(value)
}
pub fn observe(pin: &PeerPin, role: ParticipantRole) -> Result<(PeerProof, ParticipantIdentity)> {
let mut proof = PeerProof::for_service(pin, ipc::service_status(pin)?)?;
proof.check()?;
let value = participant(&proof, role)?;
Ok((proof, value))
}
/// Caller implements all original-ledger, retained-state, clock and one-pass
/// checks. This transport has no default handler or automatic startup replay.
pub trait Engine {
fn handle(&mut self, peer: &ParticipantIdentity, request: Request) -> Result<Response>;
}
pub struct Server {
pipe: OwnedHandle,
pin: Pin,
}
impl Server {
pub fn bind(pin: Pin) -> Result<Self> {
pin.validate()?;
ipc::require_self(&pin.updater)?;
let descriptor = ipc::Descriptor::from(&format!(
"O:SYG:SYD:P(D;;GA;;;NU)(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;{})(A;;0x{:08x};;;{})",
pin.updater.service_sid,
ipc::CLIENT_PIPE_RIGHTS,
pin.helper.service_sid
))?;
let sa = SECURITY_ATTRIBUTES {
nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
lpSecurityDescriptor: descriptor.0,
bInheritHandle: 0,
};
let pipe = ipc::owned(unsafe {
CreateNamedPipeW(
ipc::wide(PIPE).as_ptr(),
PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS,
1,
LIMIT as u32,
LIMIT as u32,
1000,
&sa,
)
})?;
Ok(Self { pipe, pin })
}
pub fn serve_one(&self, engine: &mut impl Engine) -> Result<bool> {
let result = self.serve_connected(engine);
unsafe {
DisconnectNamedPipe(self.pipe.as_raw_handle());
}
result
}
fn serve_connected(&self, engine: &mut impl Engine) -> Result<bool> {
ipc::require_self(&self.pin.updater)?;
let pipe = self.pipe.as_raw_handle();
let mut event = ipc::IoEvent::new()?;
if unsafe { ConnectNamedPipe(pipe, &mut event.overlapped) } == 0 {
let error = unsafe { GetLastError() };
if error == ERROR_IO_PENDING {
if let Err(e) = event.wait(pipe, Instant::now() + Duration::from_millis(250)) {
if ipc::diagnostic(&e).code == "HELPER_PIPE_TIMEOUT" {
return Ok(false);
}
return Err(e);
}
} else {
ensure!(error == ERROR_PIPE_CONNECTED, "UPDATE_IPC_CONNECT");
}
}
let deadline = Instant::now() + Duration::from_secs(5);
let len = ipc::length(pipe, deadline)?;
ensure!(len <= LIMIT, "UPDATE_IPC_FRAME_LIMIT");
let mut peer = PeerProof::capture(pipe, &self.pin.helper, true)?;
ensure!(
unsafe { ImpersonateNamedPipeClient(pipe) } != 0,
"UPDATE_IPC_IMPERSONATE"
);
let auth = (|| -> Result<()> {
let mut token = ptr::null_mut();
ensure!(
unsafe { OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, 1, &mut token) } != 0,
"UPDATE_IPC_THREAD_TOKEN"
);
let token = ipc::owned(token)?;
ipc::verify_token(
token.as_raw_handle(),
&self.pin.helper.user_sid,
&self.pin.helper.service_sid,
)
})();
if unsafe { RevertToSelf() } == 0 {
std::process::abort();
}
auth?;
ipc::require_self(&self.pin.updater)?;
let call: Call = ipc::body(pipe, len, deadline)?;
ensure!(
call.schema_version == 1
&& !call.challenge.is_nil()
&& call.binding_sha256 == ipc::binding_hash(&self.pin.binding)?
&& call.policy_sha256 == self.pin.policy_sha256,
"UPDATE_IPC_CALL_BINDING"
);
call.request.validate()?;
peer.check()?;
let response = engine.handle(
&participant(&peer, ParticipantRole::WindowsHelper)?,
call.request,
)?;
response.validate()?;
let (_own, own) = observe(&self.pin.updater, ParticipantRole::WindowsUpdater)?;
ensure!(response.updater == own, "UPDATE_IPC_SELF_RESPONSE");
let reply = Reply {
schema_version: 1,
challenge: call.challenge,
binding_sha256: call.binding_sha256,
policy_sha256: call.policy_sha256,
response,
};
let mut bytes = ipc::encode(&reply)?;
ensure!(bytes.len() <= LIMIT, "UPDATE_IPC_REPLY_LIMIT");
peer.check()?;
let deadline = Instant::now() + Duration::from_secs(5);
ipc::send_bytes(pipe, &mut bytes, deadline)?;
let mut receipt = [0; ipc::DRAIN_RECEIPT_LEN];
ipc::transfer(pipe, &mut receipt, false, deadline)?;
ipc::verify_drain_receipt(&receipt, reply.challenge, &bytes)?;
peer.check()?;
Ok(true)
}
}
/// Bounded blocking lane only. Every failure propagates; no Activate retry.
pub fn exchange(pin: &Pin, request: &Request, timeout: Duration) -> Result<Response> {
pin.validate()?;
request.validate()?;
ipc::require_self(&pin.helper)?;
ensure!(
(Duration::from_secs(1)..=Duration::from_secs(30)).contains(&timeout),
"UPDATE_IPC_TIMEOUT"
);
let deadline = Instant::now() + timeout;
let pipe = ipc::owned(unsafe {
CreateFileW(
ipc::wide(PIPE).as_ptr(),
ipc::CLIENT_PIPE_RIGHTS,
0,
ptr::null(),
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED | SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION,
ptr::null_mut(),
)
})
.context("UPDATE_IPC_UNAVAILABLE")?;
let mut peer = PeerProof::capture(pipe.as_raw_handle(), &pin.updater, false)?;
let expected = participant(&peer, ParticipantRole::WindowsUpdater)?;
let call = Call {
schema_version: 1,
challenge: Uuid::new_v4(),
binding_sha256: ipc::binding_hash(&pin.binding)?,
policy_sha256: pin.policy_sha256.clone(),
request: request.clone(),
};
let raw = ipc::encode(&call)?;
ensure!(raw.len() <= LIMIT, "UPDATE_IPC_FRAME_LIMIT");
ipc::send(pipe.as_raw_handle(), &call, deadline)?;
let len = ipc::length(pipe.as_raw_handle(), deadline)?;
ensure!(len <= LIMIT, "UPDATE_IPC_FRAME_LIMIT");
let bytes = ipc::body_bytes(pipe.as_raw_handle(), len, deadline)?;
let reply: Reply = serde_json::from_slice(&bytes)?;
peer.check()?;
ensure!(
reply.schema_version == 1
&& reply.challenge == call.challenge
&& reply.binding_sha256 == call.binding_sha256
&& reply.policy_sha256 == call.policy_sha256
&& reply.response.updater == expected,
"UPDATE_IPC_REPLY_BINDING"
);
reply.response.validate()?;
let mut receipt = ipc::drain_receipt(call.challenge, &bytes);
ipc::transfer(pipe.as_raw_handle(), &mut receipt, true, deadline)?;
Ok(reply.response)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn request_cannot_select_a_path_command_service_or_weak_original_binding() {
for raw in [
r#"{"method":"activate","grant_id":"00000000-0000-0000-0000-000000000000","owner_nonce":"00000000-0000-0000-0000-000000000000","handoff_sha256":"00"}"#,
r#"{"method":"describe","path":"C:\\Windows\\cmd.exe"}"#,
r#"{"method":"prepare"}"#,
] {
assert!(
serde_json::from_str::<Request>(raw)
.and_then(|r| r.validate().map_err(serde::de::Error::custom))
.is_err()
);
}
assert!(
serde_json::from_str::<Request>(r#"{"method":"describe"}"#)
.unwrap()
.validate()
.is_ok()
);
}
}
@@ -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(())
}
}
+206 -11
View File
@@ -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()
@@ -0,0 +1,57 @@
//! One bounded passive mTLS catalog/read-only SYSTEM observation actor.
//! Its cache is evidence for planning, never an execution permit.
use anyhow::{Result,ensure};
use rmm_domain::agent_update::{AgentUpdateObservation,ReleaseEnvelope,ReleaseManifest};
use rmm_agent_windows::{helper_runtime::Client,update_observer::{Request,Response}};
use serde::Deserialize;
use std::{net::SocketAddr,time::{Duration,Instant}};
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Catalog {status:String,release:Option<CatalogRelease>,observed_at:chrono::DateTime<chrono::Utc>,server_time:chrono::DateTime<chrono::Utc>,job_created:bool}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct CatalogRelease {release_envelope:ReleaseEnvelope,manifest:ReleaseManifest}
async fn collect(client:reqwest::Client,address:SocketAddr,helper:Client,generation:u64)->Result<Response>{
let url=format!("https://{}:{}/agent/v1/releases/current?platform={}",crate::https_channel::server_name()?,address.port(),rmm_agent_windows::release_platform::TRIPLE);
let response=client.get(&url).send().await?;
ensure!(response.url().as_str()==url,"UPDATE_CATALOG_REDIRECT");
let raw=crate::https_channel::bounded_body(response,64*1024,"application/json").await?;
let catalog:Catalog=serde_json::from_slice(&raw)?;
ensure!(!catalog.job_created && catalog.observed_at.timestamp()>0 && catalog.server_time.timestamp()>0,"UPDATE_CATALOG_NOT_A_JOB");
let candidate=match (catalog.status.as_str(),catalog.release) {
("not_configured",None)=>None,
("available",Some(release))=>{
ensure!(release.release_envelope.decode().map_err(anyhow::Error::msg)?.manifest==release.manifest && release.manifest.platform==rmm_agent_windows::release_platform::WIRE,"UPDATE_CATALOG_UNSIGNED_VIEW");Some(release.release_envelope)
}
_=>anyhow::bail!("UPDATE_CATALOG_RESPONSE_SHAPE"),
};
helper.observe_update(Request{generation,candidate}).await
}
#[derive(Default)]
pub struct Observer {current:Option<Response>,pending:Option<tokio::task::JoinHandle<Result<Response>>>,started:Option<Instant>}
impl Observer {
pub async fn poll(&mut self,generation:u64,transport:impl FnOnce()->Result<(reqwest::Client,SocketAddr,Client)>){
if self.pending.as_ref().is_some_and(|task|task.is_finished()) {
let task=self.pending.take().expect("finished task");
self.current=match task.await {Ok(Ok(value)) if value.validate(generation).is_ok()=>Some(value),_=>None};
}
if self.pending.is_none() && self.started.is_none_or(|at|at.elapsed()>=Duration::from_secs(60)) {
self.started=Some(Instant::now());
if let Ok((client,address,helper))=transport(){self.pending=Some(tokio::spawn(async move{tokio::time::timeout(Duration::from_secs(50),collect(client,address,helper,generation)).await?}));}
else {self.current=None;}
}
}
pub fn cached(&self)->Option<&Response>{
let value=self.current.as_ref()?;
let age=chrono::Utc::now()-value.observation.observed_at;
(value.validate(value.generation).is_ok() && age>=chrono::Duration::zero() && age<=chrono::Duration::seconds(90)).then_some(value)
}
pub fn observation(&self,generation:u64)->AgentUpdateObservation{
self.cached().filter(|v|v.generation==generation).map(|v|v.observation.clone()).unwrap_or_else(||AgentUpdateObservation::not_configured(rmm_agent_windows::release_platform::WIRE,chrono::Utc::now()))
}
pub fn capabilities(&self)->Vec<String>{
let Some(value)=self.cached() else{return vec![];};
let(Some(updater),Some(predecessor))=(&value.observation.updater,&value.observation.predecessor) else{return vec![];};
vec![rmm_domain::agent_update::APPLY_CAPABILITY.into(),rmm_domain::agent_update::CHECK_CAPABILITY.into(),"update_agent".into(),"system:update_agent".into(),"helper.system.v1".into(),format!("updater.binary.sha256:{}",updater.binary_sha256),format!("updater.policy.sha256:{}",updater.policy_sha256),format!("helper.binary.sha256:{}",predecessor.helper_sha256)]
}
}
@@ -0,0 +1,89 @@
//! Passive SYSTEM measurements for the code-pair updater. No staging, journal
//! append, service mutation, approval, grant or repair occurs on this path.
use crate::{
helper_system::UpdateContext,
update_ipc,
update_native::{Budget,Role,services,transition},
update_state::QualifiedRegistry,
update_trust::{Protected,TrustState},
};
use anyhow::{Context,Result,ensure};
use rmm_agent_core::{helper_reconcile::{BootSource,ExecutorLedgerGuard},reconcile::SyncClock};
use rmm_domain::{agent_update::{AgentUpdateObservation,CandidatePreview,CatalogCandidate,CatalogCheckReport,CatalogCheckStatus,ObservationQuality,ReleaseEnvelope,ResolvedAgentUpdate,UpdateProfile,Recovery,HealthProfile},jobs::hash};
use serde::{Deserialize,Serialize};
use std::{path::Path,time::Duration};
use uuid::Uuid;
#[derive(Clone,Debug,Serialize,Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Request { pub generation:u64,pub candidate:Option<ReleaseEnvelope> }
#[derive(Clone,Debug,Serialize,Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Response {
pub generation:u64,
pub observation:AgentUpdateObservation,
pub catalog:CatalogCheckReport,
pub installed_record:Vec<u8>,
}
fn require_sync(ctx:&UpdateContext<'_>,generation:u64)->Result<Uuid>{
ctx.guard.check(ctx.db)?;
ctx.clock.require_generation(generation)?;
ensure!(crate::update_control::active_grant(ctx.db)?.is_none(),"UPDATE_OBSERVE_NO_ACTIVE_HANDOFF");
ensure!(ctx.sync.as_ref().is_some_and(|s|s.can_start(ctx.db,ctx.guard,generation,ctx.clock,ctx.boot)),"UPDATE_OBSERVE_CURRENT_SIGNED_SYNC_REQUIRED");
let decision:String=ctx.db.query_row("SELECT last_decision FROM helper_sync_meta WHERE id=1 AND generation=?1 AND fault IS NULL",[generation],|r|r.get(0))?;
Ok(Uuid::parse_str(&decision)?)
}
pub(crate) fn collect(ctx:UpdateContext<'_>,request:&Request)->Result<Response>{
let decision=require_sync(&ctx,request.generation)?;
let trust=TrustState::load_observed(ctx.binding,ctx.clock)?;
trust.qualify_history(ctx.db,ctx.guard,ctx.binding)?;
let budget=Budget::new(ctx.boot,ctx.boot.current_boot()?,Duration::from_secs(10))?;
let registry=QualifiedRegistry::load(&trust)?;
let mut running=services::Running::observe([ctx.pin.agent.clone(),ctx.pin.helper.clone()],&budget)?;
let(mut updater,updater_identity)=services::observe_updater(trust.policy(),&budget)?;
let pin=update_ipc::Pin{schema_version:1,binding:ctx.binding.clone(),policy_sha256:trust.updater_binding().policy_sha256.clone(),helper:ctx.pin.helper.clone(),updater:services::updater_pin(trust.policy())?};
let description=update_ipc::exchange(&pin,&update_ipc::Request::Describe{},Duration::from_secs(5))?;
ensure!(description.state==update_ipc::State::Described && !description.ready && description.head_sha256.is_none() && description.updater==updater_identity,"UPDATE_OBSERVE_LIVE_UPDATER");
registry.verify_observed(&running.proofs(),&services::updater_configuration_sha256(&pin.updater)?)?;
ensure!(ctx.pin.agent.binary_sha256==trust.predecessor().agent_sha256 && ctx.pin.helper.binary_sha256==trust.predecessor().helper_sha256,"UPDATE_OBSERVE_ACTUAL_PREDECESSOR");
let(_,helper)=update_ipc::observe(&ctx.pin.helper,rmm_domain::agent_update::ParticipantRole::WindowsHelper)?;
ensure!(helper.pid==std::process::id(),"UPDATE_OBSERVE_ACTUAL_SYSTEM_HELPER");
let mut protected=vec![];
let mut previews=vec![];
let mut catalog=CatalogCheckReport{schema_version:1,source_id:"mtls:release-catalog-v1".into(),checked_at:ctx.clock.now()?,status:CatalogCheckStatus::NotConfigured,candidate:None};
if let Some(candidate)=&request.candidate {
trust.verify_candidate(candidate,ctx.clock)?;
let decoded=candidate.decode().map_err(anyhow::Error::msg)?;
let manifest=&decoded.manifest;
catalog.status=if manifest.release_id==trust.predecessor().release_id {CatalogCheckStatus::Current} else {CatalogCheckStatus::Available};
catalog.candidate=Some(CatalogCandidate{release_id:manifest.release_id,release_sequence:manifest.release_sequence,version:manifest.version.clone(),manifest_sha256:hash(&decoded.payload_bytes),keyring_generation:trust.updater_binding().keyring_generation});
if manifest.release_id!=trust.predecessor().release_id {
let readers=[ctx.pin.agent.service_sid.clone(),ctx.pin.helper.service_sid.clone()];
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})?;
let update=ResolvedAgentUpdate{schema_version:1,profile:UpdateProfile::FixedCodePairV1,release_envelope:candidate.clone(),release_envelope_sha256:candidate.sha256().map_err(anyhow::Error::msg)?,manifest_sha256:hash(&decoded.payload_bytes),predecessor:trust.predecessor().clone(),updater:trust.updater_binding().clone(),peer_pin_transition:rendered.proof().clone(),recovery:Recovery::RestoreExactPredecessorOnce,health_profile:HealthProfile::MtlsInventorySyncV1,health_timeout_seconds:180,no_reboot:true};
ensure!(update.validate(),"UPDATE_OBSERVE_RENDERED_PLAN");
previews.push(CandidatePreview{release_id:manifest.release_id,manifest_sha256:update.manifest_sha256,peer_pin_transition:update.peer_pin_transition});
}
}
running.check(&budget)?;updater.check()?;registry.verify()?;trust.recheck_protected()?;
for file in protected {file.verify()?;}
ensure!(require_sync(&ctx,request.generation)?==decision,"UPDATE_OBSERVE_SIGNED_HEAD_CHANGED");
let observed_at=ctx.clock.now()?;
let observed_at=observed_at-chrono::Duration::nanoseconds(i64::from(observed_at.timestamp_subsec_nanos()%1_000_000));
let observation=AgentUpdateObservation{schema_version:1,platform:crate::release_platform::WIRE,observed_at,quality:ObservationQuality::Valid,predecessor:Some(trust.predecessor().clone()),updater:Some(trust.updater_binding().clone()),activation_floor:Some(trust.activation_floor()),rolled_back:false,helper_observation_sha256:Some(hash(&serde_json::to_vec(&(running.proofs(),updater_identity,decision,request.generation,&previews))?)),signed_sync_decision_id:Some(decision),candidate_previews:previews};
ensure!(observation.validate() && catalog.validate(observed_at,observed_at),"UPDATE_OBSERVE_OUTPUT_SHAPE");
Ok(Response{generation:request.generation,observation,catalog,installed_record:trust.installed_raw().to_vec()})
}
impl Response {
pub fn validate(&self,generation:u64)->Result<()> {
ensure!(self.generation==generation && self.observation.platform==crate::release_platform::WIRE && self.observation.quality==ObservationQuality::Valid && self.observation.validate() && self.catalog.validate(self.observation.observed_at,self.observation.observed_at),"UPDATE_OBSERVE_RESPONSE");
let record=rmm_domain::agent_update_provisioning::InstalledReleaseRecord::from_bytes(&self.installed_record).map_err(anyhow::Error::msg)?;
let predecessor=self.observation.predecessor.as_ref().context("UPDATE_OBSERVE_PREDECESSOR")?;
let manifest=record.release_envelope.decode().map_err(anyhow::Error::msg)?.manifest;
ensure!(hash(&self.installed_record)==predecessor.installed_record_sha256 && record.manifest_sha256==predecessor.manifest_sha256 && manifest.release_id==predecessor.release_id && manifest.release_sequence==predecessor.release_sequence && manifest.artifacts[0].sha256==predecessor.agent_sha256 && manifest.artifacts[1].sha256==predecessor.helper_sha256 && Some(record.activation_floor)==self.observation.activation_floor && record.rolled_back==self.observation.rolled_back,"UPDATE_OBSERVE_RECORD_BINDING");
Ok(())
}
}
+196
View File
@@ -0,0 +1,196 @@
//! Independently reverify the retained ORIGINAL request, never an IPC-supplied
//! approval bit, a replacement request or a renewed start window.
//! Windows SYSTEM/code-pair-clock profile only; no Linux or four-file fallback.
use crate::update_native::Budget;
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};
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> {
let result = Self::verify_retained(binding, start_bytes, record, delegation)?;
result.check_current(binding, clock, budget)?;
Ok(result)
}
/// Historical evidence ONLY. Never supplies current boot/time/owner trust,
/// health authority, a new lease or permission for any native effect.
pub fn verify_retained(
binding: &Binding,
start_bytes: &[u8],
record: &[u8],
delegation: UpdateDelegation,
) -> 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"
);
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::WindowsUpdater
&& 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,
"UPDATE_ORIGINAL_START_CHANGED"
);
ensure!(
job.execution_identity == "system"
&& 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::WindowsCodePairClockV1
)
&& handoff.stop_set == [Service::WindowsAgent, Service::WindowsHelper],
"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(),
};
Ok(result)
}
pub fn check_current(
&self,
binding: &Binding,
clock: &impl SyncClock,
budget: &Budget<'_>,
) -> Result<()> {
ensure!(
budget.boot_id()? == self.handoff.boot_id,
"UPDATE_ORIGINAL_BOOT_CHANGED"
);
// Budget independently pins the actual native boot and monotonic
// lifetime. The trusted clock must cover its entire signed interval,
// rather than treating the local wall clock as a lower bound.
let (lower, upper) = clock.bounds()?;
ensure!(
lower <= upper
&& lower >= self.delegation.prepared_at
&& u64::try_from(upper.timestamp())? < self.handoff.finish_before
&& upper
< 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
}
}
+830
View File
@@ -0,0 +1,830 @@
//! Stable updater ownership of the existing SYSTEM ledger. No CREATE, schema
//! initialization, replayed activation, replacement ledger or reset is allowed.
use crate::{
helper_ipc::{self as ipc, PeerProof, PinnedFile},
signed_clock::BoundClock,
update_ipc,
update_native::{
Budget, Role,
files::{self, Location},
services::Stopped,
},
update_original::Original,
update_state::{AgentStateFile, Bundle, QualifiedRegistry, RetainedSet},
update_trust::TrustState,
};
use anyhow::{Context, Result, ensure};
use fs2::FileExt;
use rmm_agent_core::{
auth::Binding,
helper_reconcile::ExecutorLedgerGuard,
reconcile::SyncClock,
update_handoff::{
self as core, NativeEffect, NativeEffectStage, NativeFileRole, NativeService, Participant,
UpdateParticipantGuard,
},
};
use rmm_domain::{
agent_update::{ParticipantRole, UpdateDelegation},
jobs::hash,
};
use rmm_updater_handoff::{Event, Evidence, Handoff, Phase};
use rusqlite::{Connection, OpenFlags};
use std::{cell::RefCell, path::Path, time::Duration};
const ROOT: &str = r"C:\ProgramData\RustDiscoverySystem\state";
const LEDGER: &str = r"C:\ProgramData\RustDiscoverySystem\state\ledger.sqlite";
const LOCK: &str = r"C:\ProgramData\RustDiscoverySystem\state\executor.lock";
const AGENT_LOCK: &str = r"C:\ProgramData\RustDiscovery\state\agent.lock";
/// These are the TWO original locks used by the registered helper and agent,
/// acquired only after their exact original instances have terminated.
pub struct ClosedFiles {
root: RefCell<PinnedFile>,
ledger: RefCell<PinnedFile>,
executor: RefCell<PinnedFile>,
agent: RefCell<AgentStateFile>,
}
impl ClosedFiles {
pub fn acquire(bundle: &Bundle, stopped: &Stopped, budget: &Budget<'_>) -> Result<Self> {
bundle.validate()?;
stopped.check(budget)?;
let helper = ipc::service_sid(ipc::HELPER_SERVICE)?;
let root = PinnedFile::open(
Path::new(ROOT),
true,
&[],
std::slice::from_ref(&helper),
true,
)?;
let executor = PinnedFile::open(
Path::new(LOCK),
false,
&[],
std::slice::from_ref(&helper),
true,
)?;
ensure!(
executor.identity == bundle.ledger.lock,
"UPDATE_ORIGINAL_LOCK_IDENTITY"
);
executor
.file
.try_lock_exclusive()
.context("UPDATE_ORIGINAL_EXECUTOR_BUSY")?;
let agent = AgentStateFile::lock()?;
let expected_agent = bundle
.retained
.iter()
.find(|p| p.spec.path == Path::new(AGENT_LOCK))
.context("UPDATE_ORIGINAL_AGENT_LOCK_REQUIRED")?;
ensure!(
agent.identity == expected_agent.spec.identity,
"UPDATE_ORIGINAL_AGENT_LOCK_IDENTITY"
);
agent
.file
.try_lock_exclusive()
.context("UPDATE_ORIGINAL_AGENT_BUSY")?;
let ledger = PinnedFile::open(Path::new(LEDGER), false, &[], &[helper], true)?;
ensure!(
ledger.identity == bundle.ledger.ledger,
"UPDATE_ORIGINAL_LEDGER_IDENTITY"
);
stopped.check(budget)?;
let value = Self {
root: RefCell::new(root),
ledger: RefCell::new(ledger),
executor: RefCell::new(executor),
agent: RefCell::new(agent),
};
value.verify(bundle, stopped, budget)?;
Ok(value)
}
fn verify(&self, bundle: &Bundle, stopped: &Stopped, budget: &Budget<'_>) -> Result<()> {
stopped.check(budget)?;
for file in [&self.root, &self.ledger, &self.executor] {
file.try_borrow_mut()?.check()?;
}
self.agent.try_borrow()?.check()?;
ensure!(
self.ledger.try_borrow()?.identity == bundle.ledger.ledger
&& self.executor.try_borrow()?.identity == bundle.ledger.lock,
"UPDATE_OWNED_LEDGER_REPLACED"
);
Ok(())
}
}
/// Produced by consuming both actually-held original locks after the SQLite
/// connection has closed; the retained handles continue to pin their names.
pub struct ReleasedFiles {
files: ClosedFiles,
}
impl ReleasedFiles {
pub(crate) fn check(&self, bundle: &Bundle) -> Result<()> {
for file in [&self.files.root, &self.files.ledger, &self.files.executor] {
file.try_borrow_mut()?.check()?;
}
self.files.agent.try_borrow()?.check()?;
ensure!(
self.files.ledger.try_borrow()?.identity == bundle.ledger.ledger
&& self.files.executor.try_borrow()?.identity == bundle.ledger.lock,
"UPDATE_RELEASED_FILES_CHANGED"
);
Ok(())
}
}
impl ClosedFiles {
pub fn release(
self,
bundle: &Bundle,
stopped: &Stopped,
budget: &Budget<'_>,
) -> Result<ReleasedFiles> {
self.verify(bundle, stopped, budget)?;
FileExt::unlock(&self.executor.try_borrow()?.file)?;
FileExt::unlock(&self.agent.try_borrow()?.file)?;
let result = ReleasedFiles { files: self };
result.check(bundle)?;
Ok(result)
}
}
pub struct Inputs<'a, 'b> {
pub closed: &'a ClosedFiles,
pub stopped: &'a Stopped,
pub bundle: &'a Bundle,
pub bundle_recheck: &'a dyn Fn() -> Result<()>,
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 registry: &'a QualifiedRegistry,
pub trust: &'a TrustState,
}
pub struct Guard<'a, 'b> {
input: Inputs<'a, 'b>,
sqlite: usize,
return_before: Option<u64>,
}
pub struct OwnedLedger<'a, 'b> {
db: Connection,
guard: Guard<'a, 'b>,
}
impl<'a, 'b> OwnedLedger<'a, 'b> {
pub fn open(input: Inputs<'a, 'b>) -> Result<Self> {
input
.closed
.verify(input.bundle, input.stopped, input.budget)?;
ensure!(
input.bundle.ledger.sha256()? == input.original.handoff().ledger_identity_sha256
&& input.retained.sha256()? == input.original.handoff().retained_state_sha256,
"UPDATE_ORIGINAL_STATE_BINDING"
);
let db = Connection::open_with_flags(
LEDGER,
OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_NO_MUTEX,
)?;
db.busy_timeout(Duration::ZERO)?;
ensure!(
db.query_row("PRAGMA journal_mode", [], |r| r.get::<_, String>(0))? == "delete"
&& db.query_row("PRAGMA synchronous", [], |r| r.get::<_, u32>(0))? >= 2,
"UPDATE_LEDGER_DURABILITY_REQUIRED"
);
let sqlite = unsafe { db.handle() } as usize;
let (count, max): (usize, Option<usize>) = db.query_row(
"SELECT count(*),max(length(event)) FROM agent_update_handoff_events WHERE grant_id=?1",
[input.original.permit().grant_id.to_string()],
|r| Ok((r.get(0)?, r.get(1)?)),
)?;
ensure!(
count <= rmm_updater_handoff::MAX_V2_EVENTS
&& max.is_none_or(|n| n <= rmm_updater_handoff::MAX_EVENT_BYTES),
"UPDATE_ORIGINAL_EVENT_LIMIT"
);
let mut query = db.prepare(
"SELECT event FROM agent_update_handoff_events WHERE grant_id=?1 ORDER BY sequence",
)?;
let rows = query
.query_map([input.original.permit().grant_id.to_string()], |r| {
r.get::<_, Vec<u8>>(0)
})?
.collect::<rusqlite::Result<Vec<_>>>()?;
drop(query);
let mut return_before = None;
for raw in rows {
let event: Event = serde_json::from_slice(&raw)?;
if matches!(event.evidence, Evidence::LedgerReturnIntent) {
ensure!(
return_before.is_none(),
"UPDATE_MULTIPLE_ORIGINAL_RETURN_EVENTS"
);
return_before = Some(
event
.observed_at
.checked_add(180)
.context("UPDATE_RETURN_DEADLINE_OVERFLOW")?,
);
}
}
let guard = Guard {
input,
sqlite,
return_before,
};
guard.check(&db)?;
core::read(&db, &guard, guard.input.original.permit().grant_id)?;
guard
.input
.trust
.qualify_history(&db, &guard, guard.input.binding)?;
db.execute_batch("PRAGMA foreign_keys=ON")?;
ensure!(
db.query_row("PRAGMA foreign_keys", [], |r| r.get::<_, bool>(0))?,
"UPDATE_LEDGER_FOREIGN_KEYS_REQUIRED"
);
rmm_agent_core::ledger::bounded_journal_capacity(&db)?;
Ok(Self { db, guard })
}
pub fn record_stops(
&mut self,
observations: crate::update_native::control_fence::StopObservations,
) -> Result<()> {
self.guard.effect_window()?;
ensure!(
self.guard.input.stopped.proofs() == observations.proofs,
"UPDATE_STOP_SOURCE_CHANGED"
);
for (claim, observed) in observations.claims.iter().zip(&observations.observations) {
core::observe_native_effect(
&mut self.db,
&self.guard,
claim,
observed,
self.guard.input.clock.reading()?.upper,
)?;
}
self.append(Evidence::AllStopped {
observation_sha256: hash(&serde_json::to_vec(self.guard.input.stopped.proofs())?),
})?;
let owner = &self.guard.input.original.delegation().updater;
self.append(Evidence::UpdaterOwnsLedger {
process: rmm_updater_handoff::Process {
pid: owner.pid,
birth: owner.birth,
image_sha256: owner.image_sha256.clone(),
},
ledger_identity_sha256: self.guard.input.bundle.ledger.sha256()?,
})
}
fn append(&mut self, evidence: Evidence) -> Result<()> {
let grant = self.guard.input.original.permit().grant_id;
let journal = core::read(&self.db, &self.guard, grant)?;
let event = journal.prepare(
u64::try_from(self.guard.input.clock.reading()?.upper.timestamp())?,
evidence,
)?;
core::append(
&mut self.db,
&self.guard,
grant,
journal.head_sha256(),
&event,
)
}
pub fn prepare_return_and_close(
mut self,
) -> Result<crate::update_native::control_fence::PreparedStart> {
self.guard.effect_window()?;
let grant = self.guard.input.original.permit().grant_id;
let journal = core::read(&self.db, &self.guard, grant)?;
ensure!(
journal.phase() == Phase::PairVerified,
"UPDATE_VERIFIED_PAIR_REQUIRED"
);
let now = self.guard.input.clock.reading()?.upper;
let event = journal.prepare(
u64::try_from(now.timestamp())?,
Evidence::LedgerReturnIntent,
)?;
let claims = core::prepare_windows_return_and_starts(
&mut self.db,
&self.guard,
grant,
journal.head_sha256(),
&event,
now,
)?;
let proof = core::current_proof(&self.db, &self.guard, grant)?
.context("UPDATE_RETURN_PREFIX_REQUIRED")?;
self.close()?;
Ok(
crate::update_native::control_fence::PreparedStart::after_closed_connection(
claims, proof,
),
)
}
pub fn parts(&mut self) -> (&mut Connection, &Guard<'a, 'b>) {
(&mut self.db, &self.guard)
}
pub fn close(self) -> Result<()> {
self.guard.check(&self.db)?;
self.db.close().map_err(|(_, error)| error)?;
self.guard.input.closed.verify(
self.guard.input.bundle,
self.guard.input.stopped,
self.guard.input.budget,
)
}
}
impl Guard<'_, '_> {
fn current(&self) -> Result<()> {
let i = &self.input;
(i.bundle_recheck)()?;
i.closed.verify(i.bundle, i.stopped, i.budget)?;
Original::verify_retained(
i.binding,
i.original.start_bytes(),
&i.original.handoff().bytes()?,
i.original.delegation().clone(),
)?;
i.trust.recheck_protected()?;
let updater_pin = crate::update_native::services::updater_pin(i.trust.policy())?;
let updater_configuration =
crate::update_native::services::updater_configuration_sha256(&updater_pin)?;
ensure!(
updater_configuration == i.trust.policy().updater_service.unit_sha256,
"UPDATE_UPDATER_CONFIGURATION_CHANGED"
);
i.registry
.verify_observed(i.stopped.proofs(), &updater_configuration)?;
i.retained.verify()?;
let mut updater = i.updater.try_borrow_mut()?;
updater.check()?;
ensure!(
update_ipc::participant(&updater, ParticipantRole::WindowsUpdater)?
== i.original.delegation().updater,
"UPDATE_ORIGINAL_UPDATER_PROCESS_CHANGED"
);
Ok(())
}
fn effect_window(&self) -> Result<()> {
self.current()?;
let i = &self.input;
i.original.check_current(i.binding, i.clock, i.budget)?;
if let Some(until) = self.return_before {
ensure!(
u64::try_from(i.clock.reading()?.upper.timestamp())? < until,
"UPDATE_ORIGINAL_HEALTH_WINDOW_EXPIRED"
);
}
i.trust.recheck_prepared(i.original.update(), i.clock)
}
fn same(&self, h: &Handoff, d: &UpdateDelegation) -> Result<()> {
ensure!(
h.bytes()? == self.input.original.handoff().bytes()?
&& d == self.input.original.delegation(),
"UPDATE_ORIGINAL_OWNER_CHANGED"
);
self.current()
}
fn file(&self, role: Role, location: Location, candidate: bool) -> Result<()> {
let bound = self
.input
.bundle
.files
.iter()
.find(|v| v.role == role)
.context("UPDATE_ORIGINAL_ROLE_REQUIRED")?;
let expected = if candidate {
&bound.staged
} else {
&bound.original
};
ensure!(
files::observe_bound(
role,
self.input.original.handoff().owner_nonce,
location,
self.input.budget
)? == *expected,
"UPDATE_OWNED_FILE_CHANGED"
);
Ok(())
}
fn pair(&self, candidate: bool) -> Result<()> {
for f in &self.input.bundle.files {
self.file(f.role, Location::Target, candidate)?;
self.file(
f.role,
if candidate {
Location::Previous
} else {
Location::Rejected
},
!candidate,
)?;
}
Ok(())
}
}
impl ExecutorLedgerGuard for Guard<'_, '_> {
fn check(&self, db: &Connection) -> Result<()> {
self.current()?;
self.input
.stopped
.verify_failure_claims(db, self.input.original.handoff())?;
ensure!(
unsafe { db.handle() } as usize == self.sqlite && db.path() == Some(LEDGER),
"UPDATE_OWNED_SQLITE_CONNECTION_CHANGED"
);
let start: Vec<u8> = db.query_row(
"SELECT start FROM execution_evidence WHERE grant_id=?1",
[self.input.original.permit().grant_id.to_string()],
|r| r.get(0),
)?;
ensure!(
start == self.input.original.start_bytes(),
"UPDATE_ORIGINAL_START_CHANGED"
);
let other: u64 = db.query_row(
"SELECT count(*) FROM consumed WHERE result IS NULL AND grant_id<>?1",
[self.input.original.permit().grant_id.to_string()],
|r| r.get(0),
)?;
ensure!(other == 0, "UPDATE_OTHER_UNRESOLVED_ATTEMPT");
Ok(())
}
fn check_update_owner(
&self,
h: &Handoff,
d: &UpdateDelegation,
phase: Phase,
_events: &[Event],
) -> Result<()> {
ensure!(
!matches!(
phase,
Phase::HandoffConsumed
| Phase::ServicesStarted
| Phase::HealthVerified
| Phase::RollbackServicesStarted
| Phase::RollbackHealthVerified
| Phase::OutcomePersisted
),
"UPDATE_STABLE_WRITER_PHASE"
);
self.same(h, d)?;
self.effect_window()
}
}
fn role(r: NativeFileRole) -> Result<Role> {
Ok(match r {
NativeFileRole::AgentBinary => Role::Agent,
NativeFileRole::HelperBinary => Role::Helper,
NativeFileRole::WindowsSettings => Role::Settings,
NativeFileRole::WindowsPin => Role::Pin,
NativeFileRole::WindowsTimeProfile => Role::TimeProfile,
_ => anyhow::bail!("UPDATE_WINDOWS_FILE_ROLE_REQUIRED"),
})
}
impl UpdateParticipantGuard for Guard<'_, '_> {
fn participant(&self) -> Participant {
Participant::StableUpdater
}
fn verify_native_effect(
&self,
h: &Handoff,
d: &UpdateDelegation,
effect: &NativeEffect,
stage: NativeEffectStage,
) -> Result<()> {
self.same(h, d)?;
self.effect_window()?;
match (effect, stage) {
(
NativeEffect::StartService { .. } | NativeEffect::RollbackStopService { .. },
NativeEffectStage::ObserveNonstart,
) => self
.input
.stopped
.failure_observation(h, d, effect, self.input.budget)
.map(|_| ()),
(NativeEffect::StopService { service }, NativeEffectStage::Observe) => {
let expected = match service {
NativeService::WindowsAgent => super::update_native::Service::Agent,
NativeService::WindowsHelper => super::update_native::Service::Helper,
_ => anyhow::bail!("UPDATE_WINDOWS_SERVICE_REQUIRED"),
};
ensure!(
self.input
.stopped
.proofs()
.iter()
.any(|p| p.configuration.service == expected),
"UPDATE_STOPPED_ORIGINAL_SERVICE_REQUIRED"
);
self.input.stopped.check(self.input.budget)
}
(NativeEffect::SavePredecessor { role: r }, NativeEffectStage::Claim) => {
self.file(role(*r)?, Location::Target, false)?;
self.file(role(*r)?, Location::Stage, true)
}
(NativeEffect::SavePredecessor { role: r }, NativeEffectStage::Observe) => {
self.file(role(*r)?, Location::Previous, false)
}
(NativeEffect::PublishReplacement { role: r }, NativeEffectStage::Claim) => {
self.file(role(*r)?, Location::Previous, false)?;
self.file(role(*r)?, Location::Stage, true)
}
(NativeEffect::PublishReplacement { role: r }, NativeEffectStage::Observe) => {
self.file(role(*r)?, Location::Target, true)
}
(NativeEffect::SaveRejectedCandidate { role: r }, NativeEffectStage::Claim) => {
self.file(role(*r)?, Location::Target, true)?;
self.file(role(*r)?, Location::Previous, false)
}
(NativeEffect::SaveRejectedCandidate { role: r }, NativeEffectStage::Observe) => {
self.file(role(*r)?, Location::Rejected, true)
}
(NativeEffect::RestorePredecessor { role: r }, NativeEffectStage::Claim) => {
self.file(role(*r)?, Location::Previous, false)?;
self.file(role(*r)?, Location::Rejected, true)
}
(NativeEffect::RestorePredecessor { role: r }, NativeEffectStage::Observe) => {
self.file(role(*r)?, Location::Target, false)
}
(NativeEffect::ReturnLedger, NativeEffectStage::Claim) => self.pair(true),
(NativeEffect::RollbackReturnLedger, NativeEffectStage::Claim) => self.pair(false),
(
NativeEffect::StartService {
service: NativeService::WindowsHelper | NativeService::WindowsAgent,
},
NativeEffectStage::ReserveFutureStart,
) => self.pair(true),
(
NativeEffect::RollbackStartService {
service: NativeService::WindowsHelper | NativeService::WindowsAgent,
},
NativeEffectStage::ReserveFutureStart,
) => self.pair(false),
_ => anyhow::bail!("UPDATE_WINDOWS_OWNED_EFFECT_NOT_QUALIFIED"),
}
}
fn native_observation_sha256(
&self,
h: &Handoff,
d: &UpdateDelegation,
effect: &NativeEffect,
stage: NativeEffectStage,
) -> Result<String> {
self.same(h, d)?;
self.effect_window()?;
ensure!(
stage == NativeEffectStage::ObserveNonstart,
"UPDATE_KNOWN_NONSTART_STAGE_REQUIRED"
);
self.input
.stopped
.failure_observation(h, d, effect, self.input.budget)
}
fn verify_update_event(&self, h: &Handoff, d: &UpdateDelegation, event: &Event) -> Result<()> {
self.same(h, d)?;
if matches!(event.evidence, Evidence::Unknown { .. }) {
return Ok(());
}
self.effect_window()?;
match &event.evidence {
Evidence::AllStopped { observation_sha256 } => ensure!(
*observation_sha256 == hash(&serde_json::to_vec(self.input.stopped.proofs())?),
"UPDATE_STOPPED_OBSERVATION_CHANGED"
),
Evidence::UpdaterOwnsLedger {
process,
ledger_identity_sha256,
} => ensure!(
process.pid == d.updater.pid
&& process.birth == d.updater.birth
&& process.image_sha256 == d.updater.image_sha256
&& *ledger_identity_sha256 == self.input.bundle.ledger.sha256()?,
"UPDATE_UPDATER_OWNER_OBSERVATION_CHANGED"
),
Evidence::ReplaceIntent { role: r } => {
let r = self
.input
.bundle
.files
.iter()
.find(|v| v.role.handoff_role() == *r)
.context("UPDATE_ORIGINAL_ROLE_REQUIRED")?
.role;
self.file(r, Location::Target, false)?;
self.file(r, Location::Stage, true)?;
}
Evidence::Replaced {
role: r,
observed_sha256,
} => {
let f = self
.input
.bundle
.files
.iter()
.find(|v| v.role.handoff_role() == *r)
.context("UPDATE_ORIGINAL_ROLE_REQUIRED")?;
ensure!(
*observed_sha256 == f.staged.sha256,
"UPDATE_REPLACED_HASH_CHANGED"
);
self.file(f.role, Location::Target, true)?;
self.file(f.role, Location::Previous, false)?;
}
Evidence::PairVerified {
pair,
retained_state_sha256,
} => {
ensure!(
*pair == h.target && *retained_state_sha256 == self.input.retained.sha256()?,
"UPDATE_PAIR_OBSERVATION_CHANGED"
);
self.pair(true)?;
}
Evidence::LedgerReturnIntent => self.pair(true)?,
Evidence::RollbackIntent {
cause:
rmm_updater_handoff::RollbackCause::StartupFailed {
service: rmm_updater_handoff::Service::WindowsHelper,
},
failure_observation_sha256,
} => {
let failed = self
.input
.stopped
.failed_start()
.context("UPDATE_KNOWN_HELPER_FAILURE_REQUIRED")?;
ensure!(
*failure_observation_sha256 == failed.sha256()?,
"UPDATE_ACTUAL_HELPER_FAILURE_CHANGED"
);
self.input.stopped.failure_observation(
h,
d,
&NativeEffect::StartService {
service: NativeService::WindowsHelper,
},
self.input.budget,
)?;
self.pair(true)?;
}
Evidence::RollbackStopped {
process,
ledger_identity_sha256,
observation_sha256,
} => {
let failed = self
.input
.stopped
.failed_start()
.context("UPDATE_KNOWN_HELPER_FAILURE_REQUIRED")?;
ensure!(
process.pid == d.updater.pid
&& process.birth == d.updater.birth
&& process.image_sha256 == d.updater.image_sha256
&& *ledger_identity_sha256 == self.input.bundle.ledger.sha256()?
&& *observation_sha256
== hash(&serde_json::to_vec(&(failed, self.input.stopped.proofs()))?),
"UPDATE_ACTUAL_ROLLBACK_STOPPED_CHANGED"
);
self.input.stopped.check(self.input.budget)?;
}
Evidence::RestoreIntent { role: r }
| Evidence::CandidatePreserved { role: r, .. }
| Evidence::PredecessorRestored { role: r, .. } => {
let bound = self
.input
.bundle
.files
.iter()
.find(|f| f.role.handoff_role() == *r)
.context("UPDATE_ORIGINAL_RESTORE_ROLE_REQUIRED")?;
match &event.evidence {
Evidence::RestoreIntent { .. } => {
self.file(bound.role, Location::Target, true)?;
self.file(bound.role, Location::Previous, false)?;
}
Evidence::CandidatePreserved {
observation_sha256, ..
} => {
self.file(bound.role, Location::Rejected, true)?;
self.file(bound.role, Location::Previous, false)?;
ensure!(
*observation_sha256 == hash(&serde_json::to_vec(&bound.staged)?),
"UPDATE_ACTUAL_PRESERVED_CANDIDATE_CHANGED"
);
}
Evidence::PredecessorRestored {
observed_sha256, ..
} => {
self.file(bound.role, Location::Target, false)?;
self.file(bound.role, Location::Rejected, true)?;
ensure!(
*observed_sha256 == bound.original.sha256,
"UPDATE_ACTUAL_RESTORED_PREDECESSOR_CHANGED"
);
}
_ => unreachable!(),
}
}
Evidence::PredecessorVerified {
pair,
retained_state_sha256,
predecessor_record_sha256,
} => {
ensure!(
*pair == h.predecessor
&& *retained_state_sha256 == self.input.retained.sha256()?
&& *predecessor_record_sha256 == hash(self.input.trust.installed_raw()),
"UPDATE_PREDECESSOR_OBSERVATION_CHANGED"
);
self.pair(false)?;
}
Evidence::RollbackLedgerReturnIntent => self.pair(false)?,
// Failed-start/rollback events require a retained native failure
// source; a caller-provided reason or hash is never sufficient.
_ => anyhow::bail!("UPDATE_WINDOWS_OWNED_EVENT_NOT_QUALIFIED"),
}
Ok(())
}
}
impl OwnedLedger<'_, '_> {
pub fn begin_failed_helper_rollback(&mut self) -> Result<()> {
self.guard.effect_window()?;
let failed = self
.guard
.input
.stopped
.failed_start()
.context("UPDATE_KNOWN_HELPER_FAILURE_REQUIRED")?;
ensure!(
failed.service() == crate::update_native::Service::Helper,
"UPDATE_HELPER_FAILURE_REQUIRED"
);
let grant = self.guard.input.original.permit().grant_id;
let journal = core::read(&self.db, &self.guard, grant)?;
core::begin_rollback(
&mut self.db,
&self.guard,
grant,
journal.head_sha256(),
&rmm_updater_handoff::RollbackCause::StartupFailed {
service: rmm_updater_handoff::Service::WindowsHelper,
},
&failed.sha256()?,
self.guard.input.clock.reading()?.upper,
)?;
let owner = &self.guard.input.original.delegation().updater;
self.append(Evidence::RollbackStopped {
process: rmm_updater_handoff::Process {
pid: owner.pid,
birth: owner.birth,
image_sha256: owner.image_sha256.clone(),
},
ledger_identity_sha256: self.guard.input.bundle.ledger.sha256()?,
observation_sha256: hash(&serde_json::to_vec(&(
failed,
self.guard.input.stopped.proofs(),
))?),
})
}
pub fn prepare_rollback_return_and_close(
mut self,
) -> Result<crate::update_native::control_fence::PreparedStart> {
self.guard.effect_window()?;
let grant = self.guard.input.original.permit().grant_id;
let journal = core::read(&self.db, &self.guard, grant)?;
ensure!(
journal.phase() == Phase::PredecessorVerified,
"UPDATE_VERIFIED_PREDECESSOR_REQUIRED"
);
let now = self.guard.input.clock.reading()?.upper;
let event = journal.prepare(
u64::try_from(now.timestamp())?,
Evidence::RollbackLedgerReturnIntent,
)?;
let claims = core::prepare_windows_rollback_return_and_starts(
&mut self.db,
&self.guard,
grant,
journal.head_sha256(),
&event,
now,
)?;
let proof = core::current_proof(&self.db, &self.guard, grant)?
.context("UPDATE_ROLLBACK_RETURN_PREFIX_REQUIRED")?;
self.close()?;
Ok(
crate::update_native::control_fence::PreparedStart::after_closed_connection(
claims, proof,
),
)
}
}
+354
View File
@@ -0,0 +1,354 @@
//! Private Windows installed-record builder and fixed handle-based namespace.
//! Public metadata assembly is never permission to publish a record/floor.
use crate::{
helper_ipc::PinnedFile,
update_native::files::{self, Proof},
update_original::Original,
};
use anyhow::{Result, ensure};
use ed25519_dalek::{Signature, VerifyingKey};
use rmm_agent_core::update_handoff::{NativeEffect, NativeEffectClaim};
use rmm_domain::{
agent_update::ResolvedAgentUpdate,
agent_update_provisioning::{InstalledReleaseRecord, MAX_RECORD_BYTES},
jobs::hash,
};
use rmm_updater_handoff::{
Event, Evidence, HEALTH_DOMAIN, HealthReceipt, Journal, Phase, SignedHealth,
};
use std::{
fs::{File, OpenOptions},
io::Write,
os::windows::fs::OpenOptionsExt,
path::{Path, PathBuf},
};
use uuid::Uuid;
use windows_sys::Win32::Storage::FileSystem::*;
const ROOT: &str = r"C:\ProgramData\RustDiscoveryUpdater";
const CURRENT: &str = r"C:\ProgramData\RustDiscoveryUpdater\installed-record.json";
const RECORDS: &str = r"C:\ProgramData\RustDiscoveryUpdater\records";
pub(crate) struct BuiltRecord {
record: InstalledReleaseRecord,
raw: Vec<u8>,
prior_raw: Vec<u8>,
old_sha256: String,
sha256: String,
grant_id: Uuid,
owner_nonce: Uuid,
}
impl BuiltRecord {
pub(crate) fn build(
original: &Original,
prior_raw: &[u8],
journal: &Journal,
health_event_raw: &[u8],
) -> Result<Self> {
let header = original.handoff();
let handoff_sha256 = hash(&header.bytes()?);
ensure!(
journal.phase() == Phase::HealthVerified
&& journal.handoff_sha256() == handoff_sha256
&& !health_event_raw.is_empty()
&& health_event_raw.len() <= rmm_updater_handoff::MAX_EVENT_BYTES
&& hash(health_event_raw) == journal.head_sha256(),
"UPDATE_RECORD_HEALTH_HEAD"
);
let event: Event = serde_json::from_slice(health_event_raw)?;
ensure!(
serde_json::to_vec(&event)? == health_event_raw
&& event.handoff_sha256 == handoff_sha256
&& event.boot_id == header.boot_id,
"UPDATE_RECORD_HEALTH_EVENT"
);
let Evidence::HealthVerified { receipt: signed } = &event.evidence else {
anyhow::bail!("UPDATE_RECORD_HEALTH_REQUIRED")
};
ensure!(
!signed.payload.is_empty()
&& signed.payload.len() <= 4096
&& signed.signature.len() == 64,
"UPDATE_RECORD_HEALTH_LIMIT"
);
let receipt: HealthReceipt = serde_json::from_slice(&signed.payload)?;
ensure!(
serde_json::to_vec(&receipt)? == signed.payload,
"UPDATE_RECORD_HEALTH_NONCANONICAL"
);
// Journal possession is not independent key trust. Authenticate the
// exact receipt again with the ORIGINAL signed job's external key pin.
let raw: [u8; 32] = hex::decode(&original.update().updater.health_public_key_hex)?
.try_into()
.map_err(|_| anyhow::anyhow!("UPDATE_RECORD_HEALTH_KEY"))?;
let public = VerifyingKey::from_bytes(&raw)?;
ensure!(!public.is_weak(), "UPDATE_RECORD_HEALTH_KEY");
let mut message = HEALTH_DOMAIN.to_vec();
message.extend_from_slice(&signed.payload);
public.verify_strict(&message, &Signature::from_slice(&signed.signature)?)?;
ensure!(
receipt.schema_version == 1
&& receipt.handoff_sha256 == handoff_sha256
&& receipt.owner_nonce == header.owner_nonce
&& receipt.boot_id == header.boot_id
&& receipt.helper_journal_id == header.helper_journal_id
&& receipt.agent_journal_id == header.agent_journal_id
&& receipt.connection_generation > header.connection_generation
&& !receipt.ready
&& receipt.issued_at >= header.consumed_at
&& receipt.issued_at <= event.observed_at
&& event.observed_at < receipt.valid_until
&& receipt.valid_until <= header.finish_before,
"UPDATE_RECORD_HEALTH_BINDING"
);
Self::assemble(
original.update(),
prior_raw,
&handoff_sha256,
signed,
&receipt,
header.attempt.grant_id,
header.owner_nonce,
)
}
fn assemble(
update: &ResolvedAgentUpdate,
prior_raw: &[u8],
handoff_sha256: &str,
signed: &SignedHealth,
receipt: &HealthReceipt,
grant_id: Uuid,
owner_nonce: Uuid,
) -> Result<Self> {
ensure!(
update.validate() && !grant_id.is_nil() && !owner_nonce.is_nil(),
"UPDATE_RECORD_INPUT"
);
let record = rmm_domain::agent_update_provisioning::assemble_updated_record(
update,
prior_raw,
handoff_sha256,
signed,
receipt,
)
.map_err(anyhow::Error::msg)?;
let old_sha256 = hash(prior_raw);
let raw = record.bytes().map_err(anyhow::Error::msg)?;
let sha256 = hash(&raw);
ensure!(sha256 != old_sha256, "UPDATE_RECORD_SAME_BYTES");
Ok(Self {
record,
raw,
prior_raw: prior_raw.to_vec(),
old_sha256,
sha256,
grant_id,
owner_nonce,
})
}
pub(crate) fn record(&self) -> &InstalledReleaseRecord {
&self.record
}
pub(crate) fn sha256(&self) -> &str {
&self.sha256
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
enum State {
Staged,
Archived,
Published,
}
pub(crate) struct Transition {
built: BuiltRecord,
root: std::cell::RefCell<PinnedFile>,
records: std::cell::RefCell<PinnedFile>,
old_proof: Proof,
new_proof: Proof,
new: File,
old: Option<File>,
stage: PathBuf,
archive: PathBuf,
state: State,
}
fn open(path: &Path, delete: bool) -> Result<File> {
let mut options = OpenOptions::new();
options
.read(true)
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_WRITE_THROUGH);
if delete {
options
.access_mode(FILE_GENERIC_READ | FILE_GENERIC_WRITE | DELETE)
.share_mode(FILE_SHARE_READ);
}
Ok(options.open(path)?)
}
fn read(path: &Path) -> Result<Proof> {
files::proof(&mut open(path, false)?, path, MAX_RECORD_BYTES as u64)
}
impl Transition {
pub(crate) fn prepare(built: BuiltRecord) -> Result<Self> {
let root = PinnedFile::open(Path::new(ROOT), true, &[], &[], false)?;
let records = PinnedFile::open(Path::new(RECORDS), true, &[], &[], false)?;
let mut original = open(Path::new(CURRENT), false)?;
let old_proof = files::proof(&mut original, Path::new(CURRENT), MAX_RECORD_BYTES as u64)?;
ensure!(
old_proof.sha256 == built.old_sha256,
"UPDATE_RECORD_ORIGINAL_FILE_REQUIRED"
);
let stage = Path::new(ROOT).join(format!(".rmm-record-{}.stage", built.owner_nonce));
let archive = Path::new(RECORDS).join(format!("{}.json", built.old_sha256));
ensure!(
!archive.try_exists()?,
"UPDATE_RECORD_ARCHIVE_ALREADY_PRESENT"
);
let mut new = files::create_record_stage(&original, &stage)?;
new.write_all(&built.raw)?;
new.sync_all()?;
let new_proof = files::proof(&mut new, &stage, MAX_RECORD_BYTES as u64)?;
ensure!(
new_proof.sha256 == built.sha256
&& new_proof.security_sha256 == old_proof.security_sha256
&& new_proof.identity != old_proof.identity,
"UPDATE_RECORD_STAGE_BINDING"
);
let result = Self {
built,
root: std::cell::RefCell::new(root),
records: std::cell::RefCell::new(records),
old_proof,
new_proof,
new,
old: None,
stage,
archive,
state: State::Staged,
};
result.verify()?;
Ok(result)
}
pub(crate) fn verify(&self) -> Result<()> {
self.root.try_borrow_mut()?.check()?;
self.records.try_borrow_mut()?.check()?;
match self.state {
State::Staged => ensure!(
read(Path::new(CURRENT))? == self.old_proof
&& read(&self.stage)? == self.new_proof
&& !self.archive.try_exists()?,
"UPDATE_RECORD_STAGED_NAMESPACE_CHANGED"
),
State::Archived => ensure!(
read(&self.archive)? == self.old_proof
&& read(&self.stage)? == self.new_proof
&& !Path::new(CURRENT).try_exists()?,
"UPDATE_RECORD_ARCHIVED_NAMESPACE_CHANGED"
),
State::Published => ensure!(
read(&self.archive)? == self.old_proof
&& read(Path::new(CURRENT))? == self.new_proof
&& !self.stage.try_exists()?,
"UPDATE_RECORD_PUBLISHED_NAMESPACE_CHANGED"
),
}
Ok(())
}
pub(crate) fn verify_original(&self, raw: &[u8]) -> Result<()> {
ensure!(
self.built.prior_raw == raw && hash(raw) == self.old_proof.sha256,
"UPDATE_RECORD_PREDECESSOR_CHANGED"
);
self.verify()
}
pub(crate) fn effect(&self) -> Result<NativeEffect> {
let old_sha256 = self.built.old_sha256.clone();
let new_sha256 = self.built.sha256.clone();
Ok(match self.state {
State::Staged => NativeEffect::SaveInstalledRecord {
old_sha256,
new_sha256,
},
State::Archived => NativeEffect::PublishInstalledRecord {
old_sha256,
new_sha256,
},
State::Published => anyhow::bail!("UPDATE_RECORD_ALREADY_PUBLISHED"),
})
}
pub(crate) fn verify_effect(&self, effect: &NativeEffect, observed: bool) -> Result<()> {
self.verify()?;
let expected = match (self.state, observed) {
(State::Staged, false) | (State::Archived, true) => NativeEffect::SaveInstalledRecord {
old_sha256: self.built.old_sha256.clone(),
new_sha256: self.built.sha256.clone(),
},
(State::Archived, false) | (State::Published, true) => {
NativeEffect::PublishInstalledRecord {
old_sha256: self.built.old_sha256.clone(),
new_sha256: self.built.sha256.clone(),
}
}
_ => anyhow::bail!("UPDATE_RECORD_EFFECT_PHASE"),
};
ensure!(
*effect == expected,
"UPDATE_RECORD_EXACT_NATIVE_EFFECT_REQUIRED"
);
Ok(())
}
pub(crate) fn apply(&mut self, claim: &NativeEffectClaim) -> Result<()> {
self.verify_effect(claim.effect(), false)?;
ensure!(
claim.grant_id() == self.built.grant_id
&& claim.owner_nonce() == self.built.owner_nonce,
"UPDATE_RECORD_ORIGINAL_CLAIM_REQUIRED"
);
match self.state {
State::Staged => {
let mut old = open(Path::new(CURRENT), true)?;
ensure!(
files::proof(&mut old, Path::new(CURRENT), MAX_RECORD_BYTES as u64)?
== self.old_proof,
"UPDATE_RECORD_OLD_HANDLE_CHANGED"
);
files::rename_record(&old, &self.archive)?;
ensure!(
files::proof(&mut old, &self.archive, MAX_RECORD_BYTES as u64)?
== self.old_proof,
"UPDATE_RECORD_ARCHIVE_READBACK"
);
self.old = Some(old);
self.state = State::Archived;
}
State::Archived => {
files::rename_record(&self.new, Path::new(CURRENT))?;
ensure!(
files::proof(&mut self.new, Path::new(CURRENT), MAX_RECORD_BYTES as u64)?
== self.new_proof,
"UPDATE_RECORD_PUBLISH_READBACK"
);
self.state = State::Published;
}
State::Published => anyhow::bail!("UPDATE_RECORD_NO_RETRY"),
}
self.verify()
}
pub(crate) fn observation(&self) -> Result<String> {
self.verify()?;
Ok(hash(&serde_json::to_vec(&(
self.state,
&self.old_proof,
&self.new_proof,
))?))
}
pub(crate) fn built(&self) -> &BuiltRecord {
&self.built
}
pub(crate) fn published(&self) -> Result<()> {
ensure!(
self.state == State::Published,
"UPDATE_RECORD_PUBLICATION_REQUIRED"
);
self.verify()
}
}
+727
View File
@@ -0,0 +1,727 @@
//! Original update state witnesses, never key contents or recovery authority.
//! The local retained list and compatible-reader registry are protected files;
//! none of their paths, identities or qualification hashes come from a job.
use crate::{
helper_ipc::{self as ipc, FileIdentity, PinnedFile},
update_native::{Role, files},
update_trust::{Protected, TrustState},
};
use anyhow::{Result, ensure};
use rmm_agent_core::auth::Request;
use rmm_domain::{
agent_update::UpdateDelegation, agent_update_provisioning::ActivationEvidence, jobs::hash,
};
use rmm_updater_handoff::Handoff;
use serde::{Deserialize, Serialize};
use std::{
fs::{File, OpenOptions},
io::Write,
mem::zeroed,
os::windows::{
fs::OpenOptionsExt,
io::{AsRawHandle, FromRawHandle},
},
path::{Path, PathBuf},
ptr,
};
use uuid::Uuid;
use windows_sys::Win32::{Foundation::*, Storage::FileSystem::*};
pub const ROOT: &str = r"C:\ProgramData\RustDiscoveryUpdater";
const RETAINED: &str = r"C:\ProgramData\RustDiscoveryUpdater\retained-files.json";
const ATTEMPTS: &str = r"C:\ProgramData\RustDiscoveryUpdater\attempts";
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Retention {
MutableDatabase,
ImmutableMetadata,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Spec {
pub path: PathBuf,
pub identity: FileIdentity,
pub retention: Retention,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Metadata {
pub bytes: u64,
pub created: u64,
pub modified: u64,
pub attributes: u32,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RetainedProof {
pub spec: Spec,
pub security_sha256: String,
pub immutable_metadata: Option<Metadata>,
}
struct Held {
file: File,
parents: Vec<File>,
proof: RetainedProof,
}
fn info(file: &File, dir: bool) -> Result<Metadata> {
let mut v: BY_HANDLE_FILE_INFORMATION = unsafe { zeroed() };
ensure!(
unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut v) } != 0
&& v.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT == 0
&& (v.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY != 0) == dir
&& (dir || v.nNumberOfLinks == 1),
"UPDATE_RETAINED_FILE_TYPE"
);
Ok(Metadata {
bytes: (u64::from(v.nFileSizeHigh) << 32) | u64::from(v.nFileSizeLow),
created: (u64::from(v.ftCreationTime.dwHighDateTime) << 32)
| u64::from(v.ftCreationTime.dwLowDateTime),
modified: (u64::from(v.ftLastWriteTime.dwHighDateTime) << 32)
| u64::from(v.ftLastWriteTime.dwLowDateTime),
attributes: v.dwFileAttributes,
})
}
fn open_meta(path: &Path, dir: bool) -> Result<File> {
// Do not request FILE_READ_DATA, even for the retained private TLS key.
let h = unsafe {
CreateFileW(
ipc::wide(path).as_ptr(),
FILE_READ_ATTRIBUTES | READ_CONTROL,
FILE_SHARE_READ | FILE_SHARE_WRITE,
ptr::null(),
OPEN_EXISTING,
FILE_FLAG_OPEN_REPARSE_POINT | if dir { FILE_FLAG_BACKUP_SEMANTICS } else { 0 },
ptr::null_mut(),
)
};
ensure!(h != INVALID_HANDLE_VALUE, "UPDATE_RETAINED_OPEN");
let file = unsafe { File::from_raw_handle(h) };
info(&file, dir)?;
Ok(file)
}
fn fixed_namespace(path: &Path) -> bool {
path.is_absolute()
&& !path.to_string_lossy().starts_with(r"\\")
&& !path.to_string_lossy().contains("..")
&& [
r"C:\ProgramData\RustDiscovery\state",
r"C:\ProgramData\RustDiscoverySystem\state",
r"C:\ProgramData\RustDiscoverySystem\agent-intents",
]
.iter()
.any(|root| path.starts_with(root))
&& !path.as_os_str().to_string_lossy().contains('\0')
}
fn protected_metadata(file: &File, path: &Path) -> Result<()> {
if path.starts_with(r"C:\ProgramData\RustDiscovery\state") {
crate::native::private_path(path, false)
} else {
let writer = if path.starts_with(r"C:\ProgramData\RustDiscoverySystem\agent-intents") {
crate::SERVICE_NAME
} else {
ipc::HELPER_SERVICE
};
ipc::check_acl(
file.as_raw_handle(),
&[],
&[ipc::service_sid(writer)?],
None,
)
}
}
impl Held {
fn open(spec: Spec) -> Result<Self> {
ensure!(
fixed_namespace(&spec.path),
"UPDATE_RETAINED_FIXED_NAMESPACE"
);
let mut parents = Vec::new();
for parent in spec.path.ancestors().skip(1) {
parents.push(open_meta(parent, true)?);
}
let file = open_meta(&spec.path, false)?;
ensure!(
ipc::file_identity(&file)? == spec.identity,
"UPDATE_RETAINED_FILE_IDENTITY"
);
protected_metadata(&file, &spec.path)?;
let metadata = info(&file, false)?;
let proof = RetainedProof {
security_sha256: files::security_sha256(&file)?,
immutable_metadata: (spec.retention == Retention::ImmutableMetadata)
.then_some(metadata),
spec,
};
let held = Self {
file,
parents,
proof,
};
held.verify()?;
Ok(held)
}
fn verify(&self) -> Result<()> {
for parent in &self.parents {
info(parent, true)?;
}
let named = open_meta(&self.proof.spec.path, false)?;
protected_metadata(&named, &self.proof.spec.path)?;
ensure!(
ipc::file_identity(&named)? == self.proof.spec.identity
&& ipc::file_identity(&self.file)? == self.proof.spec.identity
&& files::security_sha256(&named)? == self.proof.security_sha256
&& self
.proof
.immutable_metadata
.as_ref()
.is_none_or(|v| info(&named, false).is_ok_and(|actual| &actual == v)),
"UPDATE_RETAINED_CHANGED"
);
Ok(())
}
}
/// Held access to the two fixed, LocalService-created agent state files.
/// The agent's existing private ACL contract permits its LocalService file
/// owner; SYSTEM helper policy files continue to use the stricter PinnedFile.
/// This pins names and security, and does not grant an executor/update effect.
pub(crate) struct AgentStateFile {
pub(crate) file: File,
pub(crate) identity: FileIdentity,
held: Held,
}
impl AgentStateFile {
pub(crate) fn journal() -> Result<Self> {
Self::open(
Path::new(r"C:\ProgramData\RustDiscovery\state\telemetry.sqlite"),
false,
)
}
pub(crate) fn lock() -> Result<Self> {
Self::open(
Path::new(r"C:\ProgramData\RustDiscovery\state\agent.lock"),
true,
)
}
fn open(path: &Path, write: bool) -> Result<Self> {
crate::native::private_path(Path::new(r"C:\ProgramData\RustDiscovery\state"), true)?;
let file = OpenOptions::new()
.read(true)
.write(write)
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)?;
info(&file, false)?;
let identity = ipc::file_identity(&file)?;
let held = Held::open(Spec {
path: path.into(),
identity,
retention: Retention::MutableDatabase,
})?;
let result = Self {
file,
identity,
held,
};
result.check()?;
Ok(result)
}
pub(crate) fn check(&self) -> Result<()> {
self.held.verify()?;
info(&self.file, false)?;
ensure!(
ipc::file_identity(&self.file)? == self.identity
&& files::security_sha256(&self.file)? == self.held.proof.security_sha256,
"UPDATE_AGENT_STATE_CHANGED"
);
Ok(())
}
}
fn key_paths() -> Result<std::collections::BTreeSet<PathBuf>> {
let mut keys = std::collections::BTreeSet::new();
for entry in std::fs::read_dir(r"C:\ProgramData\RustDiscovery\state")? {
let entry = entry?;
let path = entry.path();
if path.extension().is_some_and(|v| v == "key") {
let name = path
.file_name()
.and_then(|v| v.to_str())
.ok_or_else(|| anyhow::anyhow!("UPDATE_RETAINED_KEY_NAME"))?;
ensure!(
name == "device.key"
|| name
.strip_prefix("device-")
.and_then(|v| v.strip_suffix(".key"))
.is_some_and(|v| Uuid::parse_str(v).is_ok_and(|id| id.to_string() == v)),
"UPDATE_RETAINED_KEY_NAME"
);
ensure!(
keys.len() < 64 && keys.insert(path),
"UPDATE_RETAINED_KEY_LIMIT"
);
}
}
ensure!(!keys.is_empty(), "UPDATE_RETAINED_KEYS_MISSING");
Ok(keys)
}
const MANDATORY: [(&str, Retention); 9] = [
(
r"C:\ProgramData\RustDiscovery\state\telemetry.sqlite",
Retention::MutableDatabase,
),
(
r"C:\ProgramData\RustDiscovery\state\consumption.sqlite",
Retention::MutableDatabase,
),
(
r"C:\ProgramData\RustDiscovery\state\agent.lock",
Retention::ImmutableMetadata,
),
(
r"C:\ProgramData\RustDiscovery\state\identity.json",
Retention::ImmutableMetadata,
),
(
r"C:\ProgramData\RustDiscovery\state\device.key",
Retention::ImmutableMetadata,
),
(
r"C:\ProgramData\RustDiscovery\state\device.pem",
Retention::ImmutableMetadata,
),
(
r"C:\ProgramData\RustDiscoverySystem\state\ledger.sqlite",
Retention::MutableDatabase,
),
(
r"C:\ProgramData\RustDiscoverySystem\state\executor.lock",
Retention::ImmutableMetadata,
),
(
r"C:\ProgramData\RustDiscoverySystem\agent-intents\system-intents.sqlite",
Retention::MutableDatabase,
),
];
pub struct RetainedSet {
config: Protected,
files: Vec<Held>,
proofs: Vec<RetainedProof>,
}
impl RetainedSet {
/// Administrative read-only metadata, not an admitted retained set or lease.
/// The original key data and mutable SQLite contents are never read here.
pub fn bootstrap_metadata() -> Result<Vec<RetainedProof>> {
let mut specs = MANDATORY
.iter()
.map(|(p, r)| (PathBuf::from(p), *r))
.collect::<std::collections::BTreeMap<_, _>>();
for key in key_paths()? {
specs.insert(key, Retention::ImmutableMetadata);
}
ensure!(specs.len() <= 64, "UPDATE_RETAINED_LIMIT");
let mut held = Vec::new();
for (path, retention) in specs {
let file = open_meta(&path, false)?;
held.push(Held::open(Spec {
identity: ipc::file_identity(&file)?,
path,
retention,
})?);
}
for file in &held {
file.verify()?;
}
Ok(held.iter().map(|file| file.proof.clone()).collect())
}
pub fn capture() -> Result<Self> {
let (config, raw) = Protected::read(Path::new(RETAINED), 65536)?;
let specs: Vec<Spec> = serde_json::from_slice(&raw)?;
ensure!(
!specs.is_empty() && specs.len() <= 64,
"UPDATE_RETAINED_LIMIT"
);
let mut files = Vec::new();
for spec in specs {
ensure!(
!files.iter().any(|h: &Held| h.proof.spec.path == spec.path),
"UPDATE_RETAINED_DUPLICATE"
);
files.push(Held::open(spec)?);
}
for (path, retention) in MANDATORY {
ensure!(
files
.iter()
.any(|h| h.proof.spec.path == Path::new(path)
&& h.proof.spec.retention == retention),
"UPDATE_RETAINED_MANDATORY"
);
}
// Read only names/metadata, never another role's SQLite or key data.
// Include EVERY immutable private key namespace member, so the current
// selector cannot name an unretained key; accepted jobs prevent normal
// TLS rotation and verify() rejects an added/removed key meanwhile.
for key in key_paths()? {
ensure!(
files.iter().any(|h| h.proof.spec.path == key
&& h.proof.spec.retention == Retention::ImmutableMetadata),
"UPDATE_RETAINED_TLS_KEYS"
);
}
let proofs = files.iter().map(|h| h.proof.clone()).collect();
let value = Self {
config,
files,
proofs,
};
value.verify()?;
Ok(value)
}
/// Reopen exactly the original public metadata set; no local JSON edit can
/// substitute a new key, journal inode or immutable identity after consume.
pub fn reopen(proofs: &[RetainedProof]) -> Result<Self> {
let result = Self::capture()?;
ensure!(
result.proofs == proofs,
"UPDATE_RETAINED_ORIGINAL_SET_CHANGED"
);
Ok(result)
}
pub fn verify(&self) -> Result<()> {
self.config.verify()?;
for f in &self.files {
f.verify()?;
}
let actual = key_paths()?;
let expected = self
.files
.iter()
.filter(|f| {
f.proof.spec.path.parent() == Some(Path::new(r"C:\ProgramData\RustDiscovery\state"))
&& f.proof.spec.path.extension().is_some_and(|v| v == "key")
})
.map(|f| f.proof.spec.path.clone())
.collect::<std::collections::BTreeSet<_>>();
ensure!(actual == expected, "UPDATE_RETAINED_TLS_NAMESPACE_CHANGED");
Ok(())
}
pub fn proofs(&self) -> &[RetainedProof] {
&self.proofs
}
pub fn sha256(&self) -> Result<String> {
Ok(hash(&serde_json::to_vec(&self.proofs)?))
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BoundFile {
pub role: Role,
pub original: files::Proof,
pub staged: files::Proof,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LedgerIdentity {
pub ledger: FileIdentity,
pub lock: FileIdentity,
}
impl LedgerIdentity {
pub fn sha256(&self) -> Result<String> {
Ok(hash(&serde_json::to_vec(self)?))
}
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Bundle {
pub schema_version: u32,
pub original: Request,
pub handoff_record: Vec<u8>,
pub delegation: UpdateDelegation,
pub files: Vec<BoundFile>,
pub retained: Vec<RetainedProof>,
pub ledger: LedgerIdentity,
/// ORIGINAL retained signed decision and request, not a claimed ready bit.
pub signed_sync_response: Vec<u8>,
pub signed_sync_request: Vec<u8>,
}
impl Bundle {
pub fn validate(&self) -> Result<Handoff> {
ensure!(
self.schema_version == 1 && self.handoff_record.len() <= 65536,
"UPDATE_BUNDLE_SCHEMA"
);
let h: Handoff = serde_json::from_slice(&self.handoff_record)?;
h.validate()?;
ensure!(
h.bytes()? == self.handoff_record
&& h.pin_transition == rmm_updater_handoff::PinTransition::WindowsCodePairClockV1
&& self.delegation.validate()
&& self.delegation.handoff_sha256 == hash(&self.handoff_record)
&& self.delegation.owner_nonce == h.owner_nonce
&& self.delegation.boot_id == h.boot_id
&& hash(&serde_json::to_vec(&self.original)?) == h.attempt.original_request_sha256
&& hash(&serde_json::to_vec(&self.files)?) == h.staged_files_sha256
&& hash(&serde_json::to_vec(&self.retained)?) == h.retained_state_sha256
&& self.ledger.sha256()? == h.ledger_identity_sha256
&& self.files.iter().map(|f| f.role).collect::<Vec<_>>()
== [
Role::Agent,
Role::Helper,
Role::Settings,
Role::Pin,
Role::TimeProfile
]
&& self.signed_sync_response.len() <= 1048576
&& self.signed_sync_request.len() <= 1048576,
"UPDATE_BUNDLE_BINDING"
);
for (f, t) in self.files.iter().zip(&h.files) {
ensure!(
f.role.handoff_role() == t.role
&& f.original.sha256 == t.old_sha256
&& f.staged.sha256 == t.new_sha256,
"UPDATE_BUNDLE_FILE_BINDING"
);
}
Ok(h)
}
pub fn write_before_consume(&self) -> Result<()> {
let h = self.validate()?;
let raw = serde_json::to_vec(self)?;
ensure!(raw.len() <= 3 * 1024 * 1024, "UPDATE_BUNDLE_SIZE");
let mut root = PinnedFile::open(Path::new(ATTEMPTS), true, &[], &[], false)?;
let directory = Path::new(ATTEMPTS).join(h.attempt.grant_id.to_string());
// Inherit only the separately provisioned SYS/Admin private ACL.
// No pre-existing/partial directory is reused or repaired.
std::fs::create_dir(&directory)?;
let mut dir = PinnedFile::open(&directory, true, &[], &[], false)?;
let path = directory.join("bundle.json");
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.share_mode(FILE_SHARE_READ)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_WRITE_THROUGH)
.open(&path)?;
file.write_all(&raw)?;
file.sync_all()?;
drop(file);
let mut published = PinnedFile::open(&path, false, &[], &[], false)?;
ensure!(
published.sha256()? == hash(&raw),
"UPDATE_BUNDLE_WRITE_CHANGED"
);
published.check()?;
dir.check()?;
root.check()
}
pub fn load(grant: Uuid) -> Result<(Self, impl Fn() -> Result<()>)> {
ensure!(!grant.is_nil(), "UPDATE_BUNDLE_GRANT");
let path = Path::new(ATTEMPTS)
.join(grant.to_string())
.join("bundle.json");
let (file, raw) = Protected::read(&path, 3 * 1024 * 1024)?;
let value: Self = serde_json::from_slice(&raw)?;
let handoff = value.validate()?;
ensure!(
handoff.attempt.grant_id == grant,
"UPDATE_BUNDLE_WRONG_GRANT"
);
Ok((value, move || file.verify()))
}
}
/// Every registered reader is an explicit decoder-compatible baseline service.
/// This protected registry is not a claim of global future process absence.
/// Worker additionally proves all registered original instances have stopped
/// and holds BOTH original executor/journal locks before opening mutable state.
pub const READER_CONTRACT:&[u8]=b"rmm.windows-shared-readers.v2\0agent:existing-agent.lock-before-agent-sqlite-and-held-for-process-lifetime;helper:existing-executor.lock-before-helper-sqlite-and-every-sql-or-effect;all-registered-readers:original-update-handoff-v2-inflight-decoder-compatible;updater:both-original-locks-only-after-registered-instances-stopped;scope:no-global-future-exec-absence-promise\n";
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Reader {
pub service: String,
pub binary_sha256: String,
pub configuration_sha256: String,
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct RegistryFile {
schema_version: u32,
profile: String,
bootstrap_receipt_sha256: String,
reader_contract_sha256: String,
readers: Vec<Reader>,
}
pub struct QualifiedRegistry {
file: Protected,
qualification: Protected,
readers: Vec<Reader>,
}
impl QualifiedRegistry {
pub fn load(trust: &TrustState) -> Result<Self> {
let p = trust.policy();
ensure!(
p.schema_version == 2 && p.profile == "windows_code_pair_clock_v1",
"UPDATE_READER_POLICY"
);
let (file, raw) = Protected::read(Path::new(&p.registry_path), 65536)?;
ensure!(
hash(&raw) == p.reader_registry_sha256,
"UPDATE_READER_REGISTRY_HASH"
);
let r: RegistryFile = serde_json::from_slice(&raw)?;
let baseline = p.initial_baseline.decode().map_err(anyhow::Error::msg)?;
let ActivationEvidence::Bootstrap {
qualification_receipt_sha256,
} = baseline.record.activation_evidence
else {
anyhow::bail!("UPDATE_READER_BASELINE_REQUIRED");
};
let initial = baseline
.record
.release_envelope
.decode()
.map_err(anyhow::Error::msg)?;
ensure!(
r.schema_version == 1
&& r.profile == "windows_compatible_readers_v2"
&& r.bootstrap_receipt_sha256 == qualification_receipt_sha256
&& r.reader_contract_sha256 == hash(READER_CONTRACT)
&& r.readers
.iter()
.map(|v| v.service.as_str())
.collect::<Vec<_>>()
== [
crate::SERVICE_NAME,
ipc::HELPER_SERVICE,
crate::update_ipc::SERVICE
]
&& r.readers[0].binary_sha256 == initial.manifest.artifacts[0].sha256
&& r.readers[1].binary_sha256 == initial.manifest.artifacts[1].sha256
&& r.readers[2].binary_sha256 == p.updater_binary_sha256
&& r.readers
.iter()
.all(|v| ipc::digest(&v.binary_sha256) && ipc::digest(&v.configuration_sha256))
&& r.readers[0].configuration_sha256 == p.services[0].unit_sha256
&& r.readers[1].configuration_sha256 == p.services[1].unit_sha256
&& r.readers[2].configuration_sha256 == p.updater_service.unit_sha256,
"UPDATE_READER_REGISTRY_BINDING"
);
let (qualification, qraw) = Protected::read(
Path::new(r"C:\ProgramData\RustDiscoveryUpdater\bootstrap-qualification.json"),
65536,
)?;
ensure!(
hash(&qraw) == qualification_receipt_sha256,
"UPDATE_READER_QUALIFICATION_PIN"
);
// Raw real native evidence is covered by the separately signed baseline
// receipt hash; parsing a label here never creates native qualification.
Ok(Self {
file,
qualification,
readers: r.readers,
})
}
pub fn verify(&self) -> Result<()> {
self.file.verify()?;
self.qualification.verify()
}
pub fn verify_observed(
&self,
pair: &[crate::update_native::services::Proof],
updater_configuration_sha256: &str,
) -> Result<()> {
self.verify()?;
ensure!(pair.len() == 2, "UPDATE_READER_PAIR");
for (proof, reader) in pair.iter().zip(&self.readers) {
ensure!(
proof.configuration.service.name() == reader.service
&& hash(&serde_json::to_vec(&proof.configuration)?)
== reader.configuration_sha256,
"UPDATE_READER_SCM_CONFIGURATION"
);
// For later releases the signed installed record/approved exact
// predecessor supplies current binary pins. This is the original
// compatible reader contract, not a permanent initial image pin.
}
ensure!(
self.readers[2].configuration_sha256 == updater_configuration_sha256,
"UPDATE_READER_STABLE_UPDATER_CONFIGURATION"
);
self.verify()
}
}
/// One-way uncertainty report from the actual original stable worker. It never
/// asserts readiness, missing effects, a new start window or recovery rights.
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct Uncertain {
schema_version: u32,
grant_id: Uuid,
owner_nonce: Uuid,
handoff_sha256: String,
delegation_sha256: String,
worker: rmm_domain::agent_update::ParticipantIdentity,
}
impl Uncertain {
pub(crate) fn write(
grant: Uuid,
worker: &rmm_domain::agent_update::ParticipantIdentity,
) -> Result<()> {
let (bundle, recheck) = Bundle::load(grant)?;
let h = bundle.validate()?;
ensure!(
&bundle.delegation.updater == worker,
"UPDATE_UNKNOWN_ORIGINAL_WORKER_REQUIRED"
);
let value = Self {
schema_version: 1,
grant_id: grant,
owner_nonce: h.owner_nonce,
handoff_sha256: hash(&h.bytes()?),
delegation_sha256: hash(&serde_json::to_vec(&bundle.delegation)?),
worker: worker.clone(),
};
let raw = serde_json::to_vec(&value)?;
ensure!(raw.len() <= 4096, "UPDATE_UNKNOWN_REPORT_LIMIT");
let directory = Path::new(ATTEMPTS).join(grant.to_string());
let mut root = PinnedFile::open(&directory, true, &[], &[], false)?;
let path = directory.join("uncertain.json");
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create_new(true)
.share_mode(FILE_SHARE_READ)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_WRITE_THROUGH)
.open(&path)?;
ipc::check_acl(file.as_raw_handle(), &[], &[], None)?;
file.write_all(&raw)?;
file.sync_all()?;
drop(file);
let (published, bytes) = Protected::read(&path, 4096)?;
ensure!(bytes == raw, "UPDATE_UNKNOWN_REPORT_WRITE_CHANGED");
published.verify()?;
root.check()?;
recheck()
}
pub(crate) fn read(header: &Handoff, delegation: &UpdateDelegation) -> Result<bool> {
let path = Path::new(ATTEMPTS)
.join(header.attempt.grant_id.to_string())
.join("uncertain.json");
if !path.try_exists()? {
return Ok(false);
}
let (file, raw) = Protected::read(&path, 4096)?;
let value: Self = serde_json::from_slice(&raw)?;
ensure!(
serde_json::to_vec(&value)? == raw
&& value.schema_version == 1
&& value.grant_id == header.attempt.grant_id
&& value.owner_nonce == header.owner_nonce
&& value.handoff_sha256 == hash(&header.bytes()?)
&& value.delegation_sha256 == hash(&serde_json::to_vec(delegation)?)
&& value.worker == delegation.updater,
"UPDATE_UNKNOWN_REPORT_ORIGINAL_CONTEXT_REQUIRED"
);
file.verify()?;
Ok(true)
}
}
@@ -0,0 +1,164 @@
//! Stable-updater-only time transport. Reuses the enrolled device's selected
//! certificate without enrollment, rotation, ClientHello, or inventory changes.
//! SignedClock still independently verifies its OWN role/image/nonce/context.
use crate::{
certificate_rotation::{ProtectedKeyFiles, RotationStore},
helper_ipc as ipc,
update_trust::Protected,
};
use anyhow::{Context, Result, ensure};
use rmm_agent_core::auth::Binding;
use rusqlite::{Connection, OpenFlags};
use std::{
net::{IpAddr, Ipv4Addr, SocketAddr},
path::Path,
time::Duration,
};
const STATE: &str = r"C:\ProgramData\RustDiscovery\state";
const CONFIG: &str = r"C:\ProgramData\RustDiscovery\config.json";
const CA: &str = r"C:\ProgramData\RustDiscovery\server-ca.pem";
const JOURNAL: &str = r"C:\ProgramData\RustDiscovery\state\telemetry.sqlite";
const DOMAIN: &str = "discovery.ease-technologies.de";
pub struct Transport {
client: reqwest::Client,
configuration: Protected,
ca: Protected,
address: SocketAddr,
}
impl Transport {
pub fn open(binding: &Binding) -> Result<Self> {
let readers = vec![
ipc::service_sid(crate::SERVICE_NAME)?,
ipc::service_sid(ipc::HELPER_SERVICE)?,
ipc::service_sid(crate::update_ipc::SERVICE)?,
];
let (configuration, raw) = Protected::read_shared(Path::new(CONFIG), 16384, &readers)?;
let value: serde_json::Value = serde_json::from_slice(&raw)?;
let fields = value.as_object().context("UPDATE_TIME_CONFIG_OBJECT")?;
ensure!(
fields.keys().all(|key| matches!(
key.as_str(),
"server_name"
| "connect_address"
| "ca_file"
| "state_directory"
| "enrollment_token_file"
| "transport"
| "job_binding_file"
| "enable_jobs"
| "windows_echo_probe_only"
| "windows_execution_profile"
)),
"UPDATE_TIME_CONFIG_UNKNOWN_FIELD"
);
ensure!(
value["server_name"].as_str() == Some(DOMAIN)
&& value["ca_file"].as_str() == Some(CA)
&& value["state_directory"].as_str() == Some(STATE)
&& matches!(value["transport"].as_str(), Some("auto" | "https")),
"UPDATE_TIME_FIXED_ENDPOINT"
);
let address: SocketAddr = value["connect_address"]
.as_str()
.context("UPDATE_TIME_ADDRESS")?
.parse()?;
ensure!(
address.ip() == IpAddr::V4(Ipv4Addr::new(88, 99, 80, 202)) && address.port() == 443,
"UPDATE_TIME_FIXED_ADDRESS"
);
let (ca, ca_bytes) = Protected::read_shared(Path::new(CA), 65536, &readers)?;
crate::native::private_path(Path::new(STATE), true)?;
crate::native::private_path(Path::new(JOURNAL), false)?;
let journal_pin = crate::update_state::AgentStateFile::journal()?;
let db = Connection::open_with_flags(
JOURNAL,
OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
)?;
db.busy_timeout(Duration::ZERO)?;
unsafe {
rusqlite::ffi::sqlite3_limit(db.handle(), rusqlite::ffi::SQLITE_LIMIT_LENGTH, 65536);
}
db.execute_batch("PRAGMA trusted_schema=OFF;PRAGMA query_only=ON;")?;
let keys = ProtectedKeyFiles::open(Path::new(STATE))?;
let rotation = RotationStore::new(
binding.agent_id,
binding.enrollment_generation,
ca_bytes.clone(),
)?;
let identity = rotation.read_only_current(&db, &keys, chrono::Utc::now().timestamp())?;
let mut pem = identity.certificate_pem;
pem.push(b'\n');
pem.extend_from_slice(&identity.private_key_pem);
let client = reqwest::Client::builder()
.https_only(true)
.tls_built_in_root_certs(false)
.add_root_certificate(reqwest::Certificate::from_pem(&ca_bytes)?)
.identity(reqwest::Identity::from_pem(&pem)?)
.resolve(DOMAIN, address)
.no_proxy()
.redirect(reqwest::redirect::Policy::none())
.connect_timeout(Duration::from_millis(650))
.timeout(Duration::from_millis(650))
.pool_max_idle_per_host(1)
.build()?;
db.close().map_err(|(_, error)| error)?;
journal_pin.check()?;
configuration.verify()?;
ca.verify()?;
Ok(Self {
client,
configuration,
ca,
address,
})
}
pub async fn compare(&mut self, request: &rmm_time_attestation::Request) -> Result<Vec<u8>> {
request.validate()?;
ensure!(
request.context.role == rmm_time_attestation::Role::Updater,
"UPDATE_TIME_OWN_ROLE_REQUIRED"
);
self.configuration.verify()?;
self.ca.verify()?;
let client = self.client.clone();
let address = self.address;
let body = tokio::time::timeout(Duration::from_millis(650), async move {
let mut response = client
.post(format!(
"https://{DOMAIN}:{}/agent/v1/time-attestation",
address.port()
))
.json(request)
.send()
.await?;
ensure!(
response.status() == reqwest::StatusCode::OK
&& response
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|h| h.to_str().ok())
== Some("application/json")
&& !response
.headers()
.contains_key(reqwest::header::CONTENT_ENCODING)
&& response.content_length().is_none_or(|n| n <= 16384),
"UPDATE_TIME_HTTP_PROFILE"
);
let mut body = vec![];
while let Some(chunk) = response.chunk().await? {
ensure!(
chunk.len() <= 16384usize.saturating_sub(body.len()),
"UPDATE_TIME_BODY_LIMIT"
);
body.extend_from_slice(&chunk);
}
ensure!(!body.is_empty(), "UPDATE_TIME_EMPTY_RESPONSE");
Ok::<Vec<u8>, anyhow::Error>(body)
})
.await
.context("UPDATE_TIME_HTTP_DEADLINE")??;
self.configuration.verify()?;
self.ca.verify()?;
Ok(body)
}
}
+627
View File
@@ -0,0 +1,627 @@
//! 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<PinnedFile>,
root: RefCell<PinnedFile>,
sha256: String,
}
impl Protected {
pub(crate) fn read(path: &Path, max: u64) -> Result<(Self, Vec<u8>)> {
Self::read_shared(path, max, &[])
}
pub(crate) fn read_shared(
path: &Path,
max: u64,
readers: &[String],
) -> Result<(Self, Vec<u8>)> {
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<Protected>,
policy: LocalUpdatePolicy,
installed: InstalledReleaseRecord,
installed_raw: Vec<u8>,
installed_pin: RefCell<Option<Protected>>,
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<Self> {
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<chrono::Utc>,
) -> Result<Self> {
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<Self> {
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<chrono::Utc>,
) -> Result<Self> {
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<ReleasedRecordReadPin> {
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 })
}
}
+799
View File
@@ -0,0 +1,799 @@
//! Stable, separately provisioned SCM updater. Activation is one live pass:
//! only a successfully drained reply releases the queued original; no startup
//! scan resumes effects, and a duplicate activation is always denied.
use crate::{
helper_ipc::{self as ipc, PeerProof},
helper_system::{self, WindowsBoot},
signed_clock::{BoundClock, RuntimeClock, UpdaterConfiguration},
update_ipc::{self, Pin, Request, Response, State},
update_native::{
self as native, Budget, control_fence,
files::{BoundStage, Staged},
services,
},
update_original::Original,
update_owned,
update_state::{Bundle, QualifiedRegistry, RetainedSet},
update_time_transport::Transport,
update_trust::{Protected, TrustState},
};
use anyhow::{Context, Result, ensure};
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use rmm_agent_core::{
auth::Binding,
helper_reconcile::BootSource,
reconcile::SyncClock,
update_handoff::{
NativeControlOperation, NativeControlReply, NativeControlRequest, NativeService,
},
};
use rmm_domain::{
agent_update::{ParticipantIdentity, ParticipantRole, verify_inflight_proof},
jobs::hash,
};
use rmm_updater_handoff::Phase;
use std::{
cell::RefCell,
collections::BTreeMap,
path::Path,
sync::{
Arc,
atomic::{AtomicBool, AtomicU64, Ordering},
},
time::Duration,
};
use uuid::Uuid;
struct Worker {
binding: Binding,
policy: rmm_domain::agent_update_provisioning::LocalUpdatePolicy,
policy_file: Protected,
profile_file: Protected,
pin: Pin,
own: RefCell<PeerProof>,
identity: ParticipantIdentity,
clock: RuntimeClock,
generation: Arc<AtomicU64>,
pending: Option<Uuid>,
current: Option<Uuid>,
seen: BTreeMap<Uuid, (Uuid, String)>,
state: State,
}
impl Worker {
fn open(clock: RuntimeClock, generation: Arc<AtomicU64>) -> Result<Self> {
let (policy_file, raw) = Protected::read(
Path::new(r"C:\ProgramData\RustDiscoveryUpdater\policy.json"),
65536,
)?;
let (policy, policy_sha256) =
rmm_domain::agent_update_provisioning::LocalUpdatePolicy::from_bytes(&raw)
.map_err(anyhow::Error::msg)?;
let (profile_file, raw) =
Protected::read(Path::new(crate::signed_clock::UPDATER_CONFIG_PATH), 16384)?;
let profile: UpdaterConfiguration = serde_json::from_slice(&raw)?;
ensure!(
policy.schema_version == 2
&& profile.schema_version == 3
&& profile.updater_policy_sha256 == policy_sha256
&& policy.tenant_id == profile.binding.tenant_id
&& policy.asset_id == profile.binding.asset_id
&& policy.agent_id == profile.binding.agent_id
&& policy.enrollment_generation == profile.binding.enrollment_generation
&& policy.assignment_version == profile.binding.assignment_version,
"UPDATE_WORKER_PROTECTED_BINDING"
);
let boot = WindowsBoot::capture()?;
let budget = Budget::new(&boot, boot.current_boot()?, Duration::from_secs(5))?;
let (own, identity) = services::observe_updater(&policy, &budget)?;
let (settings, _) = helper_system::read_settings()?;
ensure!(
serde_json::to_vec(&settings.binding)? == serde_json::to_vec(&profile.binding)?,
"UPDATE_WORKER_HELPER_BINDING"
);
let pin = Pin {
schema_version: 1,
binding: profile.binding.clone(),
policy_sha256,
helper: settings.helper,
updater: services::updater_pin(&policy)?,
};
pin.validate()?;
Ok(Self {
binding: profile.binding,
policy,
policy_file,
profile_file,
pin,
own: RefCell::new(own),
identity,
clock,
generation,
pending: None,
current: None,
seen: BTreeMap::new(),
state: State::NotConfigured,
})
}
fn check(&self) -> Result<()> {
self.policy_file.verify()?;
self.profile_file.verify()?;
let mut own = self.own.try_borrow_mut()?;
own.check()?;
ensure!(
update_ipc::participant(&own, ParticipantRole::WindowsUpdater)? == self.identity
&& services::updater_configuration_sha256(&self.pin.updater)?
== self.policy.updater_service.unit_sha256,
"UPDATE_WORKER_OWN_INSTANCE_CHANGED"
);
Ok(())
}
fn bound_clock(&self) -> BoundClock {
self.clock
.for_generation(self.generation.load(Ordering::SeqCst))
}
fn request(
&self,
h: &rmm_updater_handoff::Handoff,
method: NativeControlOperation,
) -> Result<NativeControlReply> {
self.check()?;
let r = NativeControlRequest {
operation: "agent_update_control_v1".into(),
schema_version: 1,
challenge: Uuid::new_v4(),
tenant_id: self.binding.tenant_id,
asset_id: self.binding.asset_id,
agent_id: self.binding.agent_id,
enrollment_generation: self.binding.enrollment_generation,
assignment_version: self.binding.assignment_version,
grant_id: h.attempt.grant_id,
owner_nonce: h.owner_nonce,
handoff_sha256: hash(&h.bytes()?),
method,
};
crate::update_control_ipc::exchange(&self.pin, &r)
}
fn drive(&mut self, grant: Uuid) -> Result<()> {
self.check()?;
let (bundle, bundle_recheck) = Bundle::load(grant)?;
let h = bundle.validate()?;
ensure!(
h.schema_version == 2 && bundle.delegation.updater == self.identity,
"UPDATE_WORKER_ORIGINAL_OWNER_REQUIRED"
);
let mut reply = self.request(&h, NativeControlOperation::ReadOriginal)?;
let start = URL_SAFE_NO_PAD.decode(
reply
.original_start_base64url
.as_ref()
.context("UPDATE_ORIGINAL_START_REQUIRED")?,
)?;
let boot = WindowsBoot::capture()?;
let budget = Budget::new(&boot, h.boot_id, Duration::from_secs(600))?;
let clock = self.bound_clock();
clock.require_generation(h.connection_generation)?;
let original = Original::verify(
&self.binding,
&start,
&bundle.handoff_record,
bundle.delegation.clone(),
&clock,
&budget,
)?;
let trust = TrustState::load_prepared(original.update(), &self.binding, &clock)?;
let retained = RetainedSet::reopen(&bundle.retained)?;
let registry = QualifiedRegistry::load(&trust)?;
let (settings, _) = helper_system::read_settings()?;
let mut running =
services::Running::observe([settings.agent.clone(), settings.helper.clone()], &budget)?;
registry.verify_observed(
&running.proofs(),
&services::updater_configuration_sha256(&self.pin.updater)?,
)?;
running.check(&budget)?;
while !pre_stop_context(&self.binding, &original, &trust, &clock, &reply)? {
original.check_current(&self.binding, &clock, &budget)?;
std::thread::sleep(Duration::from_millis(100));
reply = self.request(&h, NativeControlOperation::ReadOriginal)?;
}
let proof = reply
.proof
.as_ref()
.context("UPDATE_ORIGINAL_PREFIX_REQUIRED")?;
let (_, journal) =
verify_inflight_proof(proof, trust.health_public_key()).map_err(anyhow::Error::msg)?;
ensure!(
journal.phase() == Phase::StopIntent,
"UPDATE_NO_REENTER_OR_RESUME"
);
let mut claims = vec![];
for service in [NativeService::WindowsAgent, NativeService::WindowsHelper] {
claims.push(
self.request(
&h,
NativeControlOperation::ClaimStop {
expected_head_sha256: journal.head_sha256().into(),
service,
},
)?
.claim
.context("UPDATE_ORIGINAL_STOP_CLAIM_REQUIRED")?,
);
}
let context = || control_fence::Context {
original: &original,
binding: &self.binding,
clock: &clock,
budget: &budget,
updater: &self.own,
retained: &retained,
trust: &trust,
};
let proofs = running
.proofs()
.try_into()
.map_err(|_| anyhow::anyhow!("UPDATE_TWO_ORIGINAL_SERVICES_REQUIRED"))?;
let mut stop = control_fence::StopFence::new(
context(),
claims
.try_into()
.map_err(|_| anyhow::anyhow!("UPDATE_TWO_STOP_CLAIMS_REQUIRED"))?,
proofs,
proof,
)?;
let stopped = running.stop(&budget, &mut stop)?;
let observations = stop.finish(&stopped)?;
let closed = update_owned::ClosedFiles::acquire(&bundle, &stopped, &budget)?;
let mut ledger = update_owned::OwnedLedger::open(update_owned::Inputs {
closed: &closed,
stopped: &stopped,
bundle: &bundle,
bundle_recheck: &bundle_recheck,
original: &original,
binding: &self.binding,
clock: &clock,
budget: &budget,
updater: &self.own,
retained: &retained,
registry: &registry,
trust: &trust,
})?;
ledger.record_stops(observations)?;
let originals = bundle
.files
.iter()
.map(|f| f.original.clone())
.collect::<Vec<_>>()
.try_into()
.map_err(|_| anyhow::anyhow!("UPDATE_FIVE_FILES_REQUIRED"))?;
let stages = bundle
.files
.iter()
.map(|f| f.staged.clone())
.collect::<Vec<_>>()
.try_into()
.map_err(|_| anyhow::anyhow!("UPDATE_FIVE_FILES_REQUIRED"))?;
let (db, guard) = ledger.parts();
let mut fence = native::fence::LedgerFence::new(native::fence::Inputs {
db,
guard,
clock: &clock,
budget: &budget,
original: &h,
originals: &originals,
staged: &stages,
})?;
let mut published = vec![];
for f in &bundle.files {
let stage = Staged::reopen_bound(
BoundStage {
role: f.role,
owner_nonce: h.owner_nonce,
original: &f.original,
staged: &f.staged,
},
&budget,
)?;
published.push(stage.publish(&stopped, &budget, &mut fence)?);
}
fence.finish()?;
for file in published {
file.release(&budget)?;
}
let prepared = ledger.prepare_return_and_close()?;
let released = closed.release(&bundle, &stopped, &budget)?;
let mut start_fence = prepared.bind(context(), released, &bundle)?;
let (settings, _) = helper_system::read_settings()?;
let result = stopped.start_observed(
[settings.agent, settings.helper.clone()],
&budget,
&mut start_fence,
)?;
let (mut started, rolled_back) = match result {
services::StartResult::Running(mut running) => {
start_fence.finish(&mut running)?;
(running, false)
}
services::StartResult::KnownFailure(failed) => {
// Only first-helper failure has no started candidate reader.
// Partial starts require separately authorized stops; this
// branch cannot infer those from a caller reason or timeout.
let stopped = start_fence.helper_failed(*failed)?;
let closed = update_owned::ClosedFiles::acquire(&bundle, &stopped, &budget)?;
let mut ledger = update_owned::OwnedLedger::open(update_owned::Inputs {
closed: &closed,
stopped: &stopped,
bundle: &bundle,
bundle_recheck: &bundle_recheck,
original: &original,
binding: &self.binding,
clock: &clock,
budget: &budget,
updater: &self.own,
retained: &retained,
registry: &registry,
trust: &trust,
})?;
ledger.begin_failed_helper_rollback()?;
let (db, guard) = ledger.parts();
let mut fence = native::fence::RestoreFence::new(native::fence::Inputs {
db,
guard,
clock: &clock,
budget: &budget,
original: &h,
originals: &originals,
staged: &stages,
})?;
for f in bundle.files.iter().rev() {
native::files::Published::reopen_bound(
BoundStage {
role: f.role,
owner_nonce: h.owner_nonce,
original: &f.original,
staged: &f.staged,
},
&stopped,
&budget,
)?
.restore(&stopped, &budget, &mut fence)?;
}
fence.finish()?;
let prepared = ledger.prepare_rollback_return_and_close()?;
let released = closed.release(&bundle, &stopped, &budget)?;
let mut fence = prepared.bind(context(), released, &bundle)?;
let (settings, _) = helper_system::read_settings()?;
let result = stopped.start_observed(
[settings.agent, settings.helper],
&budget,
&mut fence,
)?;
let services::StartResult::Running(mut running) = result else {
anyhow::bail!("UPDATE_PREDECESSOR_START_FAILED_NO_SECOND_RETURN")
};
fence.finish(&mut running)?;
(running, true)
}
};
self.pin.helper = helper_system::read_settings()?.0.helper;
let health_key = trust.health_public_key();
let proof = started.proofs();
self.request(
&h,
NativeControlOperation::ObserveStarts {
services: proof.iter().map(|p| p.started()).collect(),
observation_sha256: hash(&serde_json::to_vec(&proof)?),
},
)?;
loop {
original.check_current(&self.binding, &clock, &budget)?;
started.check(&budget)?;
let reply = self.request(&h, NativeControlOperation::ReadOriginal)?;
let proof = reply.proof.context("UPDATE_ACTIVE_PREFIX_REQUIRED")?;
let (_, journal) =
verify_inflight_proof(&proof, health_key).map_err(anyhow::Error::msg)?;
if journal.phase()
== if rolled_back {
Phase::RollbackHealthVerified
} else {
Phase::HealthVerified
}
{
trust.recheck_prepared(original.update(), &clock)?;
let released = if rolled_back {
None
} else {
Some(trust.release_worker_record_pin_after_health(&h, &proof)?)
};
let reply = self.request(&h, NativeControlOperation::Finalize)?;
if rolled_back {
verify_rollback_outcome(&original, &trust, &proof, &reply)?;
trust.recheck_protected()?;
} else {
verify_final_record(&original, &trust, &proof, &reply)?;
released
.context("UPDATE_WORKER_READ_PIN_RELEASE_REQUIRED")?
.verify_archive()?;
trust.recheck_other_protected()?;
}
self.state = State::OutcomePersisted;
return Ok(());
}
ensure!(
journal.phase()
== if rolled_back {
Phase::RollbackServicesStarted
} else {
Phase::ServicesStarted
},
"UPDATE_UNEXPECTED_POST_START_PHASE"
);
std::thread::sleep(Duration::from_millis(100));
}
}
}
// This is evidence of one already applied original control context, not a new
// grant/approval/start window. Absent witness means bounded no-effect waiting.
fn pre_stop_context(
binding: &Binding,
original: &Original,
trust: &TrustState,
clock: &BoundClock,
reply: &NativeControlReply,
) -> Result<bool> {
use prost::Message;
let (Some(raw), Some(signed)) = (
&reply.pre_stop_sync_request_base64url,
&reply.pre_stop_sync_response_base64url,
) else {
return Ok(false);
};
let raw = URL_SAFE_NO_PAD.decode(raw)?;
let signed = URL_SAFE_NO_PAD.decode(signed)?;
ensure!(
raw.len() <= 512 * 1024 && signed.len() <= 512 * 1024,
"UPDATE_PRE_STOP_SYNC_LIMIT"
);
let request = rmm_protocol::SyncRequest::decode(raw.as_slice())?;
let signed: rmm_agent_core::helper_reconcile::SignedResponse = serde_json::from_slice(&signed)?;
let response = rmm_protocol::SyncResponse {
decision_bytes: signed.decision_bytes,
signature: signed.signature,
};
let decision: rmm_domain::reconciliation::ReconcileDecisionPayload =
serde_json::from_slice(&response.decision_bytes)?;
clock.require_generation(decision.connection_generation)?;
let (lower, upper) = clock.bounds()?;
ensure!(
request.encode_to_vec() == raw
&& decision.issued_at <= lower
&& upper < decision.valid_until
&& !request.previous_decision_id.is_empty()
&& request.previous_decision_id == request.helper_previous_decision_id,
"UPDATE_PRE_STOP_CURRENT_CONFIRMED_CONTEXT_REQUIRED"
);
let verified = rmm_agent_core::reconcile::verify_response(
binding,
&request,
&rmm_agent_core::reconcile::Channel {
connection_generation: decision.connection_generation,
boot_id: original.handoff().boot_id,
},
&response,
lower,
)?;
let proof = reply
.proof
.as_ref()
.context("UPDATE_PRE_STOP_PREFIX_REQUIRED")?;
let expected = rmm_domain::agent_update::inflight_decision(proof, trust.health_public_key())
.map_err(anyhow::Error::msg)?;
let (header, journal) =
verify_inflight_proof(proof, trust.health_public_key()).map_err(anyhow::Error::msg)?;
ensure!(
header.bytes()? == original.handoff().bytes()?
&& journal.phase() == Phase::StopIntent
&& verified
.attempts
.iter()
.any(|a| a.job_id == original.permit().job_id
&& a.attempt_id == original.permit().attempt_id
&& a.update_inflight.as_ref() == Some(&expected)
&& !a.unlock),
"UPDATE_PRE_STOP_EXACT_ORIGINAL_ACK_REQUIRED"
);
let proof_bytes = proof.bytes().map_err(anyhow::Error::msg)?;
ensure!(
request
.attempts
.iter()
.any(|a| a.job_id == original.permit().job_id.to_string()
&& a.attempt_id == original.permit().attempt_id.to_string()
&& a.update_handoff_bytes == proof_bytes),
"UPDATE_PRE_STOP_EXACT_ORIGINAL_REQUEST_REQUIRED"
);
Ok(true)
}
impl update_ipc::Engine for Worker {
fn handle(&mut self, peer: &ParticipantIdentity, request: Request) -> Result<Response> {
self.check()?;
match request {
Request::Describe {} => {
if self.pending.is_none()
&& self.state != State::Unknown
&& self.state != State::OutcomePersisted
{
self.state = if self.bound_clock().now().is_ok() {
State::Described
} else {
State::NotConfigured
};
}
}
Request::Activate {
grant_id,
owner_nonce,
handoff_sha256,
} => {
ensure!(
self.pending.is_none() && !self.seen.contains_key(&grant_id),
"UPDATE_ACTIVATION_NO_REPLAY"
);
let (bundle, recheck) = Bundle::load(grant_id)?;
let h = bundle.validate()?;
ensure!(
h.schema_version == 2
&& h.owner_nonce == owner_nonce
&& hash(&h.bytes()?) == handoff_sha256
&& bundle.delegation.original_helper == *peer
&& bundle.delegation.updater == self.identity,
"UPDATE_ACTIVATION_ORIGINAL_BINDING"
);
self.bound_clock()
.require_generation(h.connection_generation)?;
self.bound_clock().now()?;
recheck()?;
ensure!(
matches!(self.state, State::Described | State::OutcomePersisted)
&& self.seen.len() < 64,
"UPDATE_WORKER_NOT_AVAILABLE_FOR_NEW_ATTEMPT"
);
self.seen.insert(grant_id, (owner_nonce, handoff_sha256));
self.pending = Some(grant_id);
self.current = Some(grant_id);
self.state = State::Inflight;
}
Request::Read {
grant_id,
owner_nonce,
handoff_sha256,
} => ensure!(
self.current == Some(grant_id)
&& self.seen.get(&grant_id) == Some(&(owner_nonce, handoff_sha256)),
"UPDATE_NO_ACTIVE_ORIGINAL"
),
Request::Health { .. } => anyhow::bail!("UPDATE_AGENT_HEALTH_USES_SYSTEM_CONTROL"),
}
Ok(Response {
schema_version: 1,
state: self.state,
ready: false,
updater: self.identity.clone(),
head_sha256: None,
})
}
}
fn current_generation_hint() -> Result<u64> {
const LEDGER: &str = r"C:\ProgramData\RustDiscoverySystem\state\ledger.sqlite";
let file = ipc::PinnedFile::open(
Path::new(LEDGER),
false,
&[],
&[ipc::service_sid(ipc::HELPER_SERVICE)?],
true,
)?;
let db = rusqlite::Connection::open_with_flags(
LEDGER,
rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
)?;
db.busy_timeout(Duration::ZERO)?;
db.execute_batch("PRAGMA query_only=ON;PRAGMA trusted_schema=OFF")?;
let generation: u64 = db.query_row(
"SELECT generation FROM helper_sync_meta WHERE id=1 AND fault IS NULL",
[],
|r| r.get(0),
)?;
ensure!(generation > 0, "UPDATE_TIME_GENERATION_HINT_MISSING");
db.close().map_err(|(_, error)| error)?;
ensure!(
ipc::file_identity(&file.file)? == file.identity,
"UPDATE_TIME_HINT_FILE_CHANGED"
);
// Hint only: independent server context/signature/nonce validates it.
Ok(generation)
}
pub fn dispatch() -> Result<()> {
crate::service::dispatch_named(update_ipc::SERVICE, run)
}
fn run(stop: &'static AtomicBool) -> Result<()> {
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()?;
let clock = RuntimeClock::new(rmm_time_attestation::Role::Updater);
let generation = Arc::new(AtomicU64::new(current_generation_hint()?));
let mut worker = Worker::open(clock.clone(), generation.clone())?;
let binding = worker.binding.clone();
let time_clock = clock.clone();
let time_generation = generation.clone();
let time_task = runtime.spawn(async move {
loop {
if stop.load(Ordering::SeqCst) {
break;
}
let generation = time_generation.load(Ordering::SeqCst);
let result = async {
if !time_clock.configured_for(generation) {
time_clock.open_connection(generation).await?;
}
let mut transport = Transport::open(&binding)?;
let request = time_clock.begin(generation)?;
let response = transport.compare(&request).await?;
time_clock.complete(generation, &response)
}
.await;
if result.is_err() {
let _ = time_clock.close_generation(generation);
}
tokio::time::sleep(Duration::from_millis(if result.is_ok() {
250
} else {
1000
}))
.await;
}
});
let mut server = update_ipc::Server::bind(worker.pin.clone())?;
while !stop.load(Ordering::SeqCst) {
let delivered = server.serve_one(&mut worker);
match delivered {
Ok(true) => {
if let Some(grant) = worker.pending.take() {
// Only this successful drain receipt allows a live pass.
let result = worker.drive(grant);
if result.is_err() {
worker.state = State::Unknown;
let _report =
crate::update_state::Uncertain::write(grant, &worker.identity);
}
drop(server);
let (settings, _) = helper_system::read_settings()?;
worker.pin.helper = settings.helper;
server = update_ipc::Server::bind(worker.pin.clone())?;
generation.store(current_generation_hint()?, Ordering::SeqCst);
}
}
Ok(false) => {}
Err(_) => {
// Lost reply/receipt can never execute the queued original.
if let Some(grant) = worker.pending.take() {
worker.state = State::Unknown;
let _report = crate::update_state::Uncertain::write(grant, &worker.identity);
}
}
}
}
time_task.abort();
clock.close()?;
Ok(())
}
fn verify_final_record(
original: &Original,
trust: &TrustState,
proof: &rmm_domain::agent_update::UpdateInflightProof,
reply: &NativeControlReply,
) -> Result<()> {
let encoded = reply
.original_outcome_base64url
.as_ref()
.context("UPDATE_ORIGINAL_FINAL_OUTCOME_REQUIRED")?;
let raw = URL_SAFE_NO_PAD.decode(encoded)?;
let outcome: rmm_domain::reconciliation::ReconciledOutcome = serde_json::from_slice(&raw)?;
ensure!(
rmm_domain::reconciliation::canonical_outcome_bytes(&outcome)? == raw
&& outcome.state == "succeeded"
&& !outcome.reboot_required
&& outcome.error_code.is_empty()
&& outcome.exit_code == Some(0)
&& outcome.evidence["postconditions_passed"] == true,
"UPDATE_ORIGINAL_FINAL_OUTCOME_CHANGED"
);
let event_raw = URL_SAFE_NO_PAD.decode(
proof
.events
.last()
.context("UPDATE_ORIGINAL_HEALTH_EVENT_REQUIRED")?,
)?;
let event: rmm_updater_handoff::Event = serde_json::from_slice(&event_raw)?;
let rmm_updater_handoff::Evidence::HealthVerified { receipt: signed } = event.evidence else {
anyhow::bail!("UPDATE_ORIGINAL_HEALTH_EVENT_REQUIRED")
};
let receipt: rmm_updater_handoff::HealthReceipt = serde_json::from_slice(&signed.payload)?;
let expected = rmm_domain::agent_update_provisioning::assemble_updated_record(
original.update(),
trust.installed_raw(),
&hash(&original.handoff().bytes()?),
&signed,
&receipt,
)
.map_err(anyhow::Error::msg)?
.bytes()
.map_err(anyhow::Error::msg)?;
let (file, actual) = Protected::read(
Path::new(r"C:\ProgramData\RustDiscoveryUpdater\installed-record.json"),
32768,
)?;
let evidence = &outcome.evidence["agent_update"];
ensure!(
actual == expected
&& evidence["handoff_sha256"] == hash(&original.handoff().bytes()?)
&& evidence["installed_record_sha256"] == hash(&actual)
&& evidence["manifest_sha256"] == original.handoff().target.manifest_sha256
&& evidence["predecessor_record_sha256"]
== original.handoff().predecessor_record_sha256
&& evidence["signed_health_sha256"] == hash(&serde_json::to_vec(&signed)?)
&& evidence["rolled_back"] == false,
"UPDATE_ORIGINAL_RECORD_AND_OUTCOME_CHANGED"
);
file.verify()
}
fn verify_rollback_outcome(
original: &Original,
trust: &TrustState,
proof: &rmm_domain::agent_update::UpdateInflightProof,
reply: &NativeControlReply,
) -> Result<()> {
let raw = URL_SAFE_NO_PAD.decode(
reply
.original_outcome_base64url
.as_ref()
.context("UPDATE_ORIGINAL_ROLLBACK_OUTCOME_REQUIRED")?,
)?;
let outcome: rmm_domain::reconciliation::ReconciledOutcome = serde_json::from_slice(&raw)?;
let event_raw = URL_SAFE_NO_PAD.decode(
proof
.events
.last()
.context("UPDATE_ROLLBACK_HEALTH_EVENT_REQUIRED")?,
)?;
let event: rmm_updater_handoff::Event = serde_json::from_slice(&event_raw)?;
let rmm_updater_handoff::Evidence::RollbackHealthVerified { receipt: signed } = event.evidence
else {
anyhow::bail!("UPDATE_ROLLBACK_HEALTH_EVENT_REQUIRED")
};
let evidence = &outcome.evidence["agent_update"];
ensure!(
rmm_domain::reconciliation::canonical_outcome_bytes(&outcome)? == raw
&& outcome.state == "failed"
&& outcome.error_code == "AGENT_UPDATE_RETURNED_TO_PREDECESSOR"
&& !outcome.reboot_required
&& outcome.evidence["postconditions_passed"] == false
&& evidence["rolled_back"] == true
&& evidence["handoff_sha256"] == hash(&original.handoff().bytes()?)
&& evidence["predecessor_record_sha256"]
== original.handoff().predecessor_record_sha256
&& evidence["installed_record_sha256"] == original.handoff().predecessor_record_sha256
&& evidence["signed_health_sha256"] == hash(&serde_json::to_vec(&signed)?),
"UPDATE_ROLLBACK_OUTCOME_CHANGED"
);
let (file, raw) = Protected::read(
Path::new(r"C:\ProgramData\RustDiscoveryUpdater\installed-record.json"),
32768,
)?;
ensure!(
raw == trust.installed_raw(),
"UPDATE_ROLLBACK_CHANGED_RECORD_OR_FLOOR"
);
file.verify()
}