Add reviewed Windows scope completion and idle certificate renewal; deploy completion API
Rust development slice / linux (push) Failing after 7s

This commit is contained in:
2026-11-16 10:25:25 +01:00
parent ebcad08731
commit bb4ffe518d
43 changed files with 5146 additions and 50 deletions
@@ -3,7 +3,7 @@
//! The caller must retain the existing exclusive agent-state journal lock.
use anyhow::{Context, Result, ensure};
use rcgen::{CertificateParams, DnType, KeyPair};
use rusqlite::{Connection, params};
use rusqlite::{Connection, OptionalExtension, params};
use rustls::{RootCertStore, pki_types::UnixTime, sign::CertifiedKey};
use serde::Deserialize;
use std::{io::Cursor, sync::Arc, time::Duration};
@@ -61,7 +61,10 @@ impl RotationStore {
) -> Result<()> {
let tx = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
tx.execute_batch("CREATE TABLE IF NOT EXISTS tls_versions(version TEXT PRIMARY KEY,certificate BLOB,csr TEXT);
CREATE TABLE IF NOT EXISTS tls_rotation(id INTEGER PRIMARY KEY CHECK(id=1),schema_version INTEGER NOT NULL,agent TEXT NOT NULL,enrollment INTEGER NOT NULL,current_version TEXT NOT NULL REFERENCES tls_versions(version),pending_version TEXT REFERENCES tls_versions(version));")?;
CREATE TABLE IF NOT EXISTS tls_rotation(id INTEGER PRIMARY KEY CHECK(id=1),schema_version INTEGER NOT NULL,agent TEXT NOT NULL,enrollment INTEGER NOT NULL,current_version TEXT NOT NULL REFERENCES tls_versions(version),pending_version TEXT REFERENCES tls_versions(version));
CREATE TABLE IF NOT EXISTS tls_idle_admission(version TEXT PRIMARY KEY REFERENCES tls_versions(version),witness BLOB NOT NULL CHECK(length(witness) BETWEEN 1 AND 32768));
CREATE TRIGGER IF NOT EXISTS tls_idle_no_update BEFORE UPDATE ON tls_idle_admission BEGIN SELECT RAISE(ABORT,'ROTATION_IDLE_IMMUTABLE');END;
CREATE TRIGGER IF NOT EXISTS tls_idle_no_delete BEFORE DELETE ON tls_idle_admission BEGIN SELECT RAISE(ABORT,'ROTATION_IDLE_IMMUTABLE');END;")?;
let present: bool = tx.query_row("SELECT EXISTS(SELECT 1 FROM tls_rotation)", [], |r| {
r.get(0)
})?;
@@ -173,6 +176,20 @@ impl RotationStore {
pub fn has_pending(&self, db: &Connection) -> Result<bool> {
Ok(self.selector(db)?.1.is_some())
}
/// Retained local maintenance context, never readiness or job authority.
/// Legacy passive requests deliberately have no active-idle admission.
pub fn pending_idle_admission(&self, db: &Connection) -> Result<Option<Vec<u8>>> {
let Some(version) = self.selector(db)?.1 else {
return Ok(None);
};
Ok(db
.query_row(
"SELECT witness FROM tls_idle_admission WHERE version=?1",
[version.to_string()],
|r| r.get(0),
)
.optional()?)
}
/// A crash before the transaction leaves only an unselected key file. A
/// response loss reuses the committed CSR/key and still-valid old mTLS leaf.
pub fn prepare(
@@ -181,9 +198,37 @@ impl RotationStore {
keys: &impl KeyFiles,
now: i64,
) -> Result<PendingRequest> {
self.prepare_with_idle_admission(db, keys, now, None)
}
/// Commit a caller-verified idle witness in the SAME transaction as the
/// pending CSR/selector. A resumed active request must retain exact bytes.
pub fn prepare_with_idle_admission(
&self,
db: &mut Connection,
keys: &impl KeyFiles,
now: i64,
admission: Option<&[u8]>,
) -> Result<PendingRequest> {
ensure!(
admission.is_none_or(|bytes| !bytes.is_empty() && bytes.len() <= 32768),
"ROTATION_IDLE_ADMISSION_LIMIT"
);
let identity = self.current(db, keys, now)?;
let tx = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
let (base, pending) = self.selector(&tx)?;
if let (Some(version), Some(expected)) = (pending, admission) {
let saved: Option<Vec<u8>> = tx
.query_row(
"SELECT witness FROM tls_idle_admission WHERE version=?1",
[version.to_string()],
|r| r.get(0),
)
.optional()?;
ensure!(
saved.as_deref() == Some(expected),
"ROTATION_IDLE_ADMISSION_CHANGED"
);
}
let (version, csr_pem) = if let Some(version) = pending {
ensure!(
!version.is_nil() && version != base,
@@ -231,6 +276,12 @@ impl RotationStore {
"UPDATE tls_rotation SET pending_version=?1 WHERE id=1",
[version.to_string()],
)?;
if let Some(witness) = admission {
tx.execute(
"INSERT INTO tls_idle_admission VALUES(?1,?2)",
params![version.to_string(), witness],
)?;
}
(version, csr)
};
tx.commit()?;
@@ -299,6 +350,71 @@ impl RotationStore {
}
}
/// A local idle witness for certificate maintenance, not an execution grant.
/// All accepted/unknown work and missing effect evidence block rotation. The
/// caller retains both existing database guards while computing this digest.
pub fn idle_history_sha256(journal: &Connection, ledger: &Connection) -> Result<String> {
use rusqlite::types::ValueRef;
use sha2::{Digest, Sha256};
let safe: bool = journal.query_row("SELECT count(*)=1 AND min(last_decision IS NOT NULL AND pending_request IS NULL AND fault IS NULL AND generation>0) FROM reconcile_meta WHERE id=1", [], |r| r.get(0))?;
let idle: bool = journal.query_row("SELECT NOT EXISTS(SELECT 1 FROM job_attempts WHERE state NOT IN ('succeeded','failed','cancelled','expired')) AND NOT EXISTS(SELECT 1 FROM job_events) AND NOT EXISTS(SELECT 1 FROM events)", [], |r| r.get(0))?;
let resolved: bool = ledger.query_row("SELECT NOT EXISTS(SELECT 1 FROM consumed c LEFT JOIN execution_evidence e USING(grant_id) WHERE c.result IS NULL OR e.start IS NULL OR e.outcome IS NULL) AND NOT EXISTS(SELECT 1 FROM execution_evidence e LEFT JOIN consumed c USING(grant_id) WHERE c.grant_id IS NULL)", [], |r| r.get(0))?;
ensure!(
safe && idle && resolved,
"ROTATION_EFFECT_OR_CONTROL_UNRESOLVED"
);
let mut hash = Sha256::new();
hash.update(b"rmm.windows.tls-idle.v1\0");
for (db, sql) in [
(journal, "SELECT seq FROM counter WHERE id=1"),
(
journal,
"SELECT journal_id,checkpoint,high_sequence,generation,last_decision,pending_request,helper_id,helper_checkpoint,fault FROM reconcile_meta WHERE id=1",
),
(
journal,
"SELECT job,attempt,offer,state,revision,grant_id,cancel_requested FROM job_attempts ORDER BY job,attempt",
),
(
ledger,
"SELECT c.grant_id,c.agent,c.generation,c.job,c.attempt,c.result,e.start,e.outcome FROM consumed c JOIN execution_evidence e USING(grant_id) ORDER BY c.grant_id",
),
] {
hash.update(sql.as_bytes());
let mut query = db.prepare(sql)?;
let columns = query.column_count();
let mut rows = query.query([])?;
let mut count = 0u64;
while let Some(row) = rows.next()? {
count += 1;
ensure!(count <= 256, "ROTATION_HISTORY_LIMIT");
hash.update([0xff]);
for column in 0..columns {
match row.get_ref(column)? {
ValueRef::Null => hash.update([0]),
ValueRef::Integer(value) => {
hash.update([1]);
hash.update(value.to_be_bytes());
}
ValueRef::Text(bytes) | ValueRef::Blob(bytes) => {
ensure!(bytes.len() <= 1048576, "ROTATION_HISTORY_BLOB_LIMIT");
hash.update([if matches!(row.get_ref(column)?, ValueRef::Text(_)) {
2
} else {
3
}]);
hash.update((bytes.len() as u64).to_be_bytes());
hash.update(bytes);
}
ValueRef::Real(_) => anyhow::bail!("ROTATION_HISTORY_TYPE"),
}
}
}
hash.update(count.to_be_bytes());
}
Ok(format!("{:x}", hash.finalize()))
}
#[cfg(windows)]
pub struct ProtectedKeyFiles {
root: std::path::PathBuf,
@@ -474,6 +590,146 @@ mod tests {
.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";
db.execute_batch("CREATE TEMP TRIGGER deny_idle BEFORE INSERT ON tls_idle_admission BEGIN SELECT RAISE(ABORT,'TEST_IDLE_COMMIT_DENIED');END;").unwrap();
assert!(
store
.prepare_with_idle_admission(&mut db, &keys, now(), Some(witness))
.is_err()
);
assert_eq!(store.selector(&db).unwrap(), (Uuid::nil(), None));
assert_eq!(
db.query_row("SELECT count(*) FROM tls_versions", [], |r| r
.get::<_, u64>(0))
.unwrap(),
1
);
db.execute_batch("DROP TRIGGER deny_idle").unwrap();
let original = store
.prepare_with_idle_admission(&mut db, &keys, now(), Some(witness))
.unwrap();
assert_eq!(
store.pending_idle_admission(&db).unwrap().as_deref(),
Some(witness.as_slice())
);
assert!(
store
.prepare_with_idle_admission(&mut db, &keys, now(), Some(b"changed context"))
.is_err()
);
let retained = store
.prepare_with_idle_admission(&mut db, &keys, now(), Some(witness))
.unwrap();
assert_eq!(original.version, retained.version);
assert_eq!(original.csr_pem, retained.csr_pem);
assert!(
db.execute(
"UPDATE tls_idle_admission SET witness=?1",
[b"replacement".as_slice()]
)
.is_err()
);
assert!(db.execute("DELETE FROM tls_idle_admission", []).is_err());
let (mut legacy, legacy_keys, legacy_store, _, _) = setup();
legacy_store
.prepare(&mut legacy, &legacy_keys, now())
.unwrap();
assert!(
legacy_store
.pending_idle_admission(&legacy)
.unwrap()
.is_none()
);
assert!(
legacy_store
.prepare_with_idle_admission(&mut legacy, &legacy_keys, now(), Some(witness))
.is_err()
);
}
#[test]
fn idle_history_rejects_unfinished_jobs_missing_effect_evidence_and_changed_heads() {
let root = std::env::temp_dir().join(format!("rmm-rotation-idle-{}", Uuid::new_v4()));
std::fs::create_dir(&root).unwrap();
let journal = crate::journal::Journal::open(&root).unwrap();
let ledger = Connection::open_in_memory().unwrap();
rmm_agent_core::ledger::initialize_ledger(&ledger).unwrap();
assert!(idle_history_sha256(journal.connection(), &ledger).is_err());
journal
.connection()
.execute(
"UPDATE reconcile_meta SET generation=1,last_decision=?1 WHERE id=1",
[Uuid::new_v4().to_string()],
)
.unwrap();
let clean = idle_history_sha256(journal.connection(), &ledger).unwrap();
journal.connection().execute("INSERT INTO job_attempts(job,attempt,offer,state) VALUES('fixture','attempt',x'01','accepted')",[]).unwrap();
for state in [
"queued",
"accepted",
"requesting",
"running",
"verifying",
"unknown",
"awaiting_reboot",
] {
journal
.connection()
.execute("UPDATE job_attempts SET state=?1", [state])
.unwrap();
assert!(
idle_history_sha256(journal.connection(), &ledger).is_err(),
"{state}"
);
}
journal
.connection()
.execute("UPDATE job_attempts SET state='succeeded'", [])
.unwrap();
let finished = idle_history_sha256(journal.connection(), &ledger).unwrap();
assert_ne!(clean, finished);
ledger
.execute(
"INSERT INTO consumed VALUES('grant','agent',1,'fixture','attempt',NULL)",
[],
)
.unwrap();
assert!(idle_history_sha256(journal.connection(), &ledger).is_err());
ledger
.execute("UPDATE consumed SET result=x'02'", [])
.unwrap();
assert!(idle_history_sha256(journal.connection(), &ledger).is_err());
ledger
.execute(
"INSERT INTO execution_evidence VALUES('grant',x'01',x'02')",
[],
)
.unwrap();
let resolved = idle_history_sha256(journal.connection(), &ledger).unwrap();
journal
.connection()
.execute(
"UPDATE reconcile_meta SET checkpoint=checkpoint+1 WHERE id=1",
[],
)
.unwrap();
assert_ne!(
resolved,
idle_history_sha256(journal.connection(), &ledger).unwrap()
);
journal
.connection()
.execute(
"UPDATE reconcile_meta SET pending_request='pending' WHERE id=1",
[],
)
.unwrap();
assert!(idle_history_sha256(journal.connection(), &ledger).is_err());
drop(journal);
std::fs::remove_dir_all(root).unwrap();
}
#[test]
fn response_loss_reuses_exact_pending_csr_and_private_key_stays_outside_sqlite() {
let (mut db, keys, store, issuer, old) = setup();
assert!(store.due(&db, &keys, now()).unwrap());
+463
View File
@@ -0,0 +1,463 @@
//! Append-only retirement of the additional development echo restriction.
//! Preserves all original scope, journal, fault history and consumption bytes.
use anyhow::{Context, Result, ensure};
use chrono::{DateTime, Utc};
use prost::Message;
use rmm_agent_core::{
auth::{Binding, Request},
crypto::{DalekVerifier, Ed25519Verifier},
};
use rmm_domain::{
checkpoint_repair::{SignedReceipt, inventory_sha256},
jobs::{ExecutionPermitPayload, JobPayload, hash},
windows_echo_completion::{Receipt, Witness, successful_outcome},
windows_echo_probe::{ProbeReceipt, ProbeScope},
};
use rmm_protocol::JobOffer;
use rusqlite::{Connection, TransactionBehavior, params};
use serde_json::Value;
const TABLE: &str = "windows_echo_scope_completion";
const DDL: &str = "CREATE TABLE windows_echo_scope_completion(id INTEGER PRIMARY KEY CHECK(id=1),original_receipt BLOB NOT NULL,witness_sha256 TEXT NOT NULL,applied_at TEXT NOT NULL)";
fn schema() -> [String; 4] {
[DDL.into(),
"CREATE TRIGGER windows_echo_completion_no_replace BEFORE INSERT ON windows_echo_scope_completion WHEN EXISTS(SELECT 1 FROM windows_echo_scope_completion) BEGIN SELECT RAISE(ABORT,'WINDOWS_ECHO_COMPLETION_IMMUTABLE'); END".into(),
"CREATE TRIGGER windows_echo_completion_no_change BEFORE UPDATE ON windows_echo_scope_completion BEGIN SELECT RAISE(ABORT,'WINDOWS_ECHO_COMPLETION_IMMUTABLE'); END".into(),
"CREATE TRIGGER windows_echo_completion_no_delete BEFORE DELETE ON windows_echo_scope_completion BEGIN SELECT RAISE(ABORT,'WINDOWS_ECHO_COMPLETION_IMMUTABLE'); END".into()]
}
fn verify(binding: &Binding, bytes: &[u8], signature: &[u8]) -> Result<()> {
let b = &binding.public_key_hex;
ensure!(
b.len() == 64 && b.is_ascii() && bytes.len() <= 65536 && signature.len() == 64,
"completion pin/size"
);
let key = (0..64)
.step_by(2)
.map(|i| u8::from_str_radix(&b[i..i + 2], 16))
.collect::<std::result::Result<Vec<_>, _>>()?;
ensure!(
DalekVerifier.verify(&key, bytes, signature)?,
"completion original signature"
);
Ok(())
}
fn receipt(raw: &[u8], binding: &Binding) -> Result<Receipt> {
ensure!(raw.len() <= 131072, "completion envelope size");
let signed: SignedReceipt = serde_json::from_slice(raw)?;
verify(binding, &signed.payload, &signed.signature)?;
let r: Receipt = serde_json::from_slice(&signed.payload)?;
ensure!(r.valid(r.issued_at), "completion historical profile");
let key = (0..64)
.step_by(2)
.map(|i| u8::from_str_radix(&binding.public_key_hex[i..i + 2], 16))
.collect::<std::result::Result<Vec<_>, _>>()?;
ensure!(r.key_id == hash(&key), "completion signing key");
Ok(r)
}
fn matches_original(r: &Receipt, scope: &ProbeScope, original: &[u8]) -> Result<()> {
let old: SignedReceipt = serde_json::from_slice(original)?;
let p: ProbeReceipt = serde_json::from_slice(&old.payload)?;
ensure!(
&r.witness.scope == scope
&& r.witness.probe_receipt_id == p.receipt_id
&& r.witness.probe_receipt_sha256 == hash(&old.payload)
&& r.witness.probe_signature_sha256 == hash(&old.signature),
"completion retained scope"
);
Ok(())
}
pub fn installed(
db: &Connection,
binding: &Binding,
scope: &ProbeScope,
original: &[u8],
) -> Result<bool> {
let exists: bool = db.query_row(
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE name=?)",
[TABLE],
|r| r.get(0),
)?;
if !exists {
return Ok(false);
}
let names = [
TABLE,
"windows_echo_completion_no_replace",
"windows_echo_completion_no_change",
"windows_echo_completion_no_delete",
];
for (name, expected) in names.iter().zip(schema()) {
let actual: String =
db.query_row("SELECT sql FROM sqlite_schema WHERE name=?", [name], |r| {
r.get(0)
})?;
ensure!(actual == expected, "completion schema");
}
let (raw, digest): (Vec<u8>, String) = db.query_row(
"SELECT original_receipt,witness_sha256 FROM windows_echo_scope_completion WHERE id=1",
[],
|r| Ok((r.get(0)?, r.get(1)?)),
)?;
let r = receipt(&raw, binding)?;
matches_original(&r, scope, original)?;
ensure!(digest == r.witness_sha256, "completion archive digest");
Ok(true)
}
/// Independent read of original native start, signatures and exact successful outcome.
pub fn witness(
db: &Connection,
consumption: &Connection,
helper: &Connection,
binding: &Binding,
helper_binding: &Binding,
) -> Result<Witness> {
let (scope, original) =
crate::echo_probe::archive(db, binding)?.context("original echo scope missing")?;
let old: SignedReceipt = serde_json::from_slice(&original)?;
verify(helper_binding, &old.payload, &old.signature)?;
let probe: ProbeReceipt = serde_json::from_slice(&old.payload)?;
ensure!(
(
helper_binding.tenant_id,
helper_binding.asset_id,
helper_binding.agent_id,
helper_binding.enrollment_generation,
helper_binding.assignment_version
) == (
binding.tenant_id,
binding.asset_id,
binding.agent_id,
binding.enrollment_generation,
binding.assignment_version
),
"completion independent helper identity"
);
for journal in [db, consumption, helper] {
let check: String = journal.query_row("PRAGMA integrity_check", [], |r| r.get(0))?;
ensure!(check == "ok", "completion journal integrity");
}
let fault: Option<String> =
db.query_row("SELECT fault FROM reconcile_meta WHERE id=1", [], |r| {
r.get(0)
})?;
ensure!(fault.is_none(), "current reconciliation fault");
let jobs: u64 = db.query_row("SELECT count(*) FROM job_attempts", [], |r| r.get(0))?;
ensure!(jobs == 1, "completion requires exact native single probe");
let (offer, state, grant): (Vec<u8>, String, String) = db.query_row(
"SELECT offer,state,grant_id FROM job_attempts WHERE job=? AND attempt=?",
params![scope.job_id.to_string(), scope.attempt_id.to_string()],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
)?;
let offer = JobOffer::decode(offer.as_slice())?;
let job: JobPayload = serde_json::from_slice(&offer.payload_bytes)?;
ensure!(
state == "succeeded" && crate::echo_probe::permits_offer(&scope, &offer, &job),
"native completed echo offer"
);
let count: u64 = consumption.query_row("SELECT count(*) FROM consumed", [], |r| r.get(0))?;
let evidence: u64 =
consumption.query_row("SELECT count(*) FROM execution_evidence", [], |r| r.get(0))?;
let helper_count: u64 = helper.query_row("SELECT count(*) FROM consumed", [], |r| r.get(0))?;
ensure!(
count == 1 && evidence == 1 && helper_count == 0,
"completion original consumption inventory"
);
let (start,outcome,result):(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.grant_id=? AND c.agent=? AND c.generation=? AND c.job=? AND c.attempt=?",params![grant,binding.agent_id.to_string(),binding.enrollment_generation,scope.job_id.to_string(),scope.attempt_id.to_string()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?)))?;
let start: Value = serde_json::from_slice(&start)?;
let request: Request = serde_json::from_value(start["request"].clone())?;
verify(binding, &request.permit_bytes, &request.signature)?;
verify(helper_binding, &request.permit_bytes, &request.signature)?;
let g: ExecutionPermitPayload = serde_json::from_slice(&request.permit_bytes)?;
ensure!(
g.domain == "rmm.execution-permit"
&& g.schema_version == 1
&& g.agent_update_plan_id.is_none()
&& g.start_before - g.not_before <= chrono::Duration::seconds(60)
&& request.job_bytes == offer.payload_bytes
&& request.authorization_id.to_string() == offer.authorization_id
&& request.plan_hash == scope.plan_hash
&& g.grant_id.to_string() == grant
&& g.plan_hash == scope.plan_hash
&& g.authorization_id == request.authorization_id
&& g.job_payload_hash == scope.job_payload_hash
&& (g.tenant_id, g.asset_id, g.agent_id, g.job_id, g.attempt_id)
== (
scope.tenant_id,
scope.asset_id,
scope.agent_id,
scope.job_id,
scope.attempt_id
)
&& (g.enrollment_generation, g.assignment_version)
== (scope.enrollment_generation, scope.assignment_version)
&& g.execution_identity == "agent_service"
&& g.action == "run_script"
&& g.not_before >= scope.not_before
&& g.start_before <= scope.start_before
&& g.not_before < g.start_before
&& g.max_runtime_seconds == scope.max_runtime_seconds,
"completion retained signed grant"
);
let outcome: Value = serde_json::from_slice(&outcome)?;
let result: Value = serde_json::from_slice(&result)?;
ensure!(
outcome == result && successful_outcome(&outcome),
"completion exact native outcome"
);
let boot_id = serde_json::from_value(start["previous_boot_id"].clone())?;
let w = Witness {
scope,
probe_receipt_id: probe.receipt_id,
probe_receipt_sha256: hash(&old.payload),
probe_signature_sha256: hash(&old.signature),
grant_id: g.grant_id,
grant_payload_sha256: hash(&request.permit_bytes),
grant_signature_sha256: hash(&request.signature),
outcome_sha256: inventory_sha256(&outcome)?,
boot_id,
};
ensure!(w.valid(), "completion witness profile");
Ok(w)
}
pub struct LocalPair<'a> {
pub consumption: &'a Connection,
pub helper: &'a Connection,
pub binding: &'a Binding,
pub helper_binding: &'a Binding,
}
pub fn apply(
db: &mut Connection,
pair: LocalPair<'_>,
raw: &[u8],
boot: uuid::Uuid,
now: DateTime<Utc>,
) -> Result<()> {
let LocalPair {
consumption,
helper,
binding,
helper_binding,
} = pair;
let r = receipt(raw, binding)?;
let signed: SignedReceipt = serde_json::from_slice(raw)?;
verify(helper_binding, &signed.payload, &signed.signature)?;
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
let expected = witness(&tx, consumption, helper, binding, helper_binding)?;
ensure!(
r.witness == expected && expected.boot_id == boot,
"completion differs from native evidence"
);
let (scope, original) = crate::echo_probe::archive(&tx, binding)?.context("original scope")?;
if installed(&tx, binding, &scope, &original)? {
let prior: Vec<u8> = tx.query_row(
"SELECT original_receipt FROM windows_echo_scope_completion WHERE id=1",
[],
|r| r.get(0),
)?;
ensure!(prior == raw, "different completion already applied");
return Ok(());
}
ensure!(r.valid(now), "completion expired or premature");
for sql in schema() {
tx.execute_batch(&sql)?;
}
tx.execute(
"INSERT INTO windows_echo_scope_completion VALUES(1,?,?,?)",
params![raw, r.witness_sha256, now.to_rfc3339()],
)?;
crate::echo_probe::retire_triggers(&tx)?;
ensure!(
crate::echo_probe::installed(&tx, binding)?.is_none(),
"completion did not retire additional scope"
);
tx.commit()?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use ed25519_dalek::{Signer, SigningKey};
use rmm_domain::{
jobs::{Action, PlanPayload, PlannedJob, WindowsExecutionProfile},
windows_echo_probe as echo,
};
use uuid::Uuid;
#[test]
fn scope_retirement_is_append_only_and_does_not_rewrite_history() -> Result<()> {
let key = SigningKey::from_bytes(&[24; 32]);
let now = Utc::now();
let binding = Binding {
tenant_id: echo::TENANT,
asset_id: echo::ASSET,
agent_id: echo::AGENT,
enrollment_generation: 1,
assignment_version: 1,
public_key_hex: key
.verifying_key()
.to_bytes()
.iter()
.map(|b| format!("{b:02x}"))
.collect(),
};
let job = JobPayload {
schema_version: 1,
tenant_id: echo::TENANT,
asset_id: echo::ASSET,
agent_id: echo::AGENT,
enrollment_generation: 1,
assignment_version: 1,
job_id: Uuid::new_v4(),
attempt_id: Uuid::new_v4(),
action: Action::RunScript {
interpreter: "powershell".into(),
script_utf8: echo::SCRIPT.into(),
arguments: vec![],
expected_stdout: Some(echo::OUTPUT.into()),
windows_execution_profile: Some(WindowsExecutionProfile::PowerShell51RemoteSigned),
privileged_script_profile: None,
},
execution_identity: "agent_service".into(),
not_before: now,
start_before: now + chrono::Duration::minutes(15),
max_runtime_seconds: 60,
max_output_bytes: 65536,
};
let job_bytes = serde_json::to_vec(&job)?;
let plan = PlanPayload {
schema_version: 1,
tenant_id: echo::TENANT,
plan_id: Uuid::new_v4(),
principal: format!("automation:{}", echo::TENANT),
reason: "fixture".into(),
jobs: vec![PlannedJob {
payload: job.clone(),
job_payload_hash: hash(&job_bytes),
script_sha256: Some(hash(echo::SCRIPT.as_bytes())),
}],
max_parallel: 1,
halt_after_failures: 1,
recipe_references: vec![],
artifact_references: vec![],
};
let scope = ProbeScope::from_plan(&plan, Uuid::new_v4()).context("fixture fixed scope")?;
let probe = ProbeReceipt {
domain: echo::DOMAIN.into(),
schema_version: 1,
request_id: Uuid::new_v4(),
receipt_id: Uuid::new_v4(),
witness: Value::Null,
witness_sha256: "0".repeat(64),
scope: scope.clone(),
scope_sha256: scope.digest().unwrap(),
job_payload_bytes: job_bytes.clone(),
key_id: hash(&key.verifying_key().to_bytes()),
issued_at: now,
valid_until: now + chrono::Duration::minutes(10),
confirmed_by: echo::TEST_PRINCIPAL.into(),
approval_origin: "dev_test_browser_simulation".into(),
testsimulation: true,
};
let probe_payload = serde_json::to_vec(&probe)?;
let old = SignedReceipt {
signature: key.sign(&probe_payload).to_bytes().to_vec(),
payload: probe_payload,
};
let original = serde_json::to_vec(&old)?;
let mut db = Connection::open_in_memory()?;
db.execute_batch("CREATE TABLE job_attempts(job TEXT,attempt TEXT,offer BLOB,state TEXT);CREATE TABLE original_history(raw BLOB);INSERT INTO original_history VALUES(x'00ff2a')")?;
let tx = db.transaction()?;
crate::echo_probe::install(&tx, &scope, &job_bytes, &original)?;
tx.commit()?;
let w = Witness {
scope: scope.clone(),
probe_receipt_id: probe.receipt_id,
probe_receipt_sha256: hash(&old.payload),
probe_signature_sha256: hash(&old.signature),
grant_id: Uuid::new_v4(),
grant_payload_sha256: "1".repeat(64),
grant_signature_sha256: "2".repeat(64),
outcome_sha256: "3".repeat(64),
boot_id: Uuid::new_v4(),
};
let r = Receipt {
domain: rmm_domain::windows_echo_completion::DOMAIN.into(),
schema_version: 1,
receipt_id: Uuid::new_v4(),
witness_sha256: w.digest().unwrap(),
witness: w,
key_id: hash(&key.verifying_key().to_bytes()),
issued_at: now,
valid_until: now + chrono::Duration::minutes(10),
confirmed_by: echo::TEST_PRINCIPAL.into(),
approval_origin: "dev_test_browser_simulation".into(),
testsimulation: true,
ready: false,
helper_ready: false,
unlock: false,
};
let seal = |r: &Receipt| -> Result<Vec<u8>> {
let payload = serde_json::to_vec(r)?;
Ok(serde_json::to_vec(&SignedReceipt {
signature: key.sign(&payload).to_bytes().to_vec(),
payload,
})?)
};
let raw = seal(&r)?;
for field in 0..4 {
let mut bad = r.clone();
match field {
0 => bad.ready = true,
1 => bad.helper_ready = true,
2 => bad.unlock = true,
_ => bad.testsimulation = false,
};
assert!(receipt(&seal(&bad)?, &binding).is_err());
}
assert!(
receipt(
&raw,
&Binding {
public_key_hex: "00".repeat(32),
..binding.clone()
}
)
.is_err()
);
assert!(!installed(&db, &binding, &scope, &original)?);
let tx = db.transaction()?;
for sql in schema() {
tx.execute_batch(&sql)?;
}
tx.execute(
"INSERT INTO windows_echo_scope_completion VALUES(1,?,?,?)",
params![raw, r.witness_sha256, now.to_rfc3339()],
)?;
crate::echo_probe::retire_triggers(&tx)?;
tx.commit()?;
assert!(installed(&db, &binding, &scope, &original)?);
crate::echo_probe::check(&db, &scope, &job_bytes, &original)?;
assert_eq!(
db.query_row("SELECT raw FROM original_history", [], |r| r
.get::<_, Vec<u8>>(0))?,
vec![0, 255, 42]
);
for sql in [
"DELETE FROM windows_echo_scope_completion",
"UPDATE windows_echo_scope_completion SET applied_at='other'",
"INSERT OR REPLACE INTO windows_echo_scope_completion SELECT * FROM windows_echo_scope_completion",
"DELETE FROM windows_echo_probe_scope",
] {
assert!(db.execute(sql, []).is_err());
}
let tx = db.transaction()?;
tx.execute_batch("DROP TRIGGER windows_echo_completion_no_change")?;
assert!(installed(&tx, &binding, &scope, &original).is_err());
tx.rollback()?;
let mut changed = scope.clone();
changed.attempt_id = Uuid::new_v4();
assert!(installed(&db, &binding, &changed, &original).is_err());
Ok(())
}
}
+44 -6
View File
@@ -24,17 +24,26 @@ const IMMUTABLE: &str = "CREATE TRIGGER windows_echo_probe_no_change BEFORE UPDA
const RETAIN: &str = "CREATE TRIGGER windows_echo_probe_no_delete BEFORE DELETE ON windows_echo_probe_scope BEGIN SELECT RAISE(ABORT,'WINDOWS_ECHO_SCOPE_IMMUTABLE'); END";
const BOUND: &str = "WHEN NOT EXISTS(SELECT 1 FROM windows_echo_probe_scope s WHERE s.id=1 AND s.job=NEW.job AND s.attempt=NEW.attempt AND typeof(NEW.offer)='blob' AND length(NEW.offer)=length(s.prefix)+36+length(s.suffix) AND substr(NEW.offer,1,length(s.prefix))=s.prefix AND substr(NEW.offer,-length(s.suffix))=s.suffix) BEGIN SELECT RAISE(ABORT,'WINDOWS_ECHO_OFFER_OUT_OF_SCOPE'); END";
fn schema() -> [String; 6] {
fn schema(completed: bool) -> [String; 6] {
let bound = if completed {
BOUND.replacen(
"WHEN ",
"WHEN NOT EXISTS(SELECT 1 FROM windows_echo_scope_completion WHERE id=1) AND ",
1,
)
} else {
BOUND.to_owned()
};
[
POLICY.to_owned(),
"CREATE TRIGGER windows_echo_probe_no_replace BEFORE INSERT ON windows_echo_probe_scope WHEN EXISTS(SELECT 1 FROM windows_echo_probe_scope) BEGIN SELECT RAISE(ABORT,'WINDOWS_ECHO_SCOPE_IMMUTABLE'); END".to_owned(),
IMMUTABLE.to_owned(),
RETAIN.to_owned(),
format!(
"CREATE TRIGGER windows_echo_probe_offer_insert BEFORE INSERT ON job_attempts {BOUND}"
"CREATE TRIGGER windows_echo_probe_offer_insert BEFORE INSERT ON job_attempts {bound}"
),
format!(
"CREATE TRIGGER windows_echo_probe_offer_update BEFORE UPDATE OF job,attempt,offer ON job_attempts {BOUND}"
"CREATE TRIGGER windows_echo_probe_offer_update BEFORE UPDATE OF job,attempt,offer ON job_attempts {bound}"
),
]
}
@@ -82,7 +91,7 @@ pub fn install(
review: &[u8],
) -> Result<()> {
let (prefix, suffix) = blobs(scope, payload)?;
for sql in schema() {
for sql in schema(false) {
tx.execute_batch(&sql)?;
}
tx.execute(
@@ -100,7 +109,12 @@ pub fn install(
}
pub fn check(db: &Connection, scope: &ProbeScope, payload: &[u8], review: &[u8]) -> Result<()> {
let (prefix, suffix) = blobs(scope, payload)?;
for (name, expected) in OBJECTS.iter().zip(schema()) {
let completed: bool = db.query_row(
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE name='windows_echo_scope_completion')",
[],
|r| r.get(0),
)?;
for (name, expected) in OBJECTS.iter().zip(schema(completed)) {
let actual: String =
db.query_row("SELECT sql FROM sqlite_schema WHERE name=?", [name], |r| {
r.get(0)
@@ -115,6 +129,20 @@ pub fn installed(
db: &Connection,
binding: &rmm_agent_core::auth::Binding,
) -> Result<Option<ProbeScope>> {
let Some((scope, raw)) = archive(db, binding)? else {
return Ok(None);
};
if crate::echo_completion::installed(db, binding, &scope, &raw)? {
return Ok(None);
}
Ok(Some(scope))
}
/// Verify the retained original, including after the separately reviewed completion.
pub fn archive(
db: &Connection,
binding: &rmm_agent_core::auth::Binding,
) -> Result<Option<(ProbeScope, Vec<u8>)>> {
use rmm_agent_core::crypto::{DalekVerifier, Ed25519Verifier};
use rmm_domain::{
checkpoint_repair::SignedReceipt, windows_echo_probe::ProbeReceipt,
@@ -141,7 +169,17 @@ pub fn installed(
"Echo archive signature"
);
check(db, &r.scope, &r.job_payload_bytes, &raw)?;
Ok(Some(r.scope))
Ok(Some((r.scope, raw)))
}
pub(crate) fn retire_triggers(tx: &Transaction<'_>) -> Result<()> {
for name in &OBJECTS[4..] {
tx.execute_batch(&format!("DROP TRIGGER {name}"))?;
}
for ddl in &schema(true)[4..] {
tx.execute_batch(ddl)?;
}
Ok(())
}
pub fn permits_offer(scope: &ProbeScope, offer: &JobOffer, job: &JobPayload) -> bool {
scope.matches_job(job)
+14 -4
View File
@@ -26,6 +26,8 @@ const PROBE_FILE: &str = "helper-probe.json";
pub struct Client {
pin: ipc::Pin,
lane: Arc<Semaphore>,
qualified_capabilities: Vec<String>,
probed_at: Option<std::time::Instant>,
}
pub struct ControlSnapshot {
pub raw: Snapshot,
@@ -73,7 +75,7 @@ impl Client {
"HELPER_JOB_BINDING_MISMATCH"
);
}
Ok(Some(Self { pin, lane }))
Ok(Some(Self { pin, lane, qualified_capabilities:vec![], probed_at:None }))
}
pub async fn refresh(
agent_id: String,
@@ -89,8 +91,8 @@ impl Client {
tokio::task::spawn_blocking(move || {
let _permit = permit;
let result=(|| {
let client=Self::discover(&agent_id,&asset_id,binding.as_ref(),lane).context(ipc::Stage::DiscoverPin)?;
if let Some(client)=&client {client.probe_blocking(&state)?;}
let mut client=Self::discover(&agent_id,&asset_id,binding.as_ref(),lane).context(ipc::Stage::DiscoverPin)?;
if let Some(client)=&mut client {client.probe_blocking(&state)?;}
Ok(client)
})();
if result.is_err() || matches!(&result,Ok(None)) && state.join(PROBE_FILE).try_exists()? {
@@ -338,7 +340,7 @@ impl Client {
})
.await?
}
fn probe_blocking(&self, state: &Path) -> Result<()> {
fn probe_blocking(&mut self, state: &Path) -> Result<()> {
self.check_pin().context(ipc::Stage::DiscoverPin)?;
let pin = &self.pin;
let call = ipc::Call::new(pin, ipc::Operation::Probe {});
@@ -357,8 +359,16 @@ impl Client {
};
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()?;
self.qualified_capabilities=crate::system_capabilities::qualified(pin,clock_qualified)?;
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);
write_current_probe(state, &value).context(ipc::Stage::ClientReport)
}
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![]}
}
/// Pure admission shape only; no capability or qualification is asserted.
pub fn supports_system(&self, job: &JobPayload) -> bool {
system_shape(job)
+5
View File
@@ -6,6 +6,9 @@ pub mod certificate_rotation;
#[cfg(windows)]
pub mod clock;
pub mod echo_probe;
pub mod echo_completion;
#[cfg(all(windows, feature = "system-helper"))]
pub mod system_capabilities;
pub mod event_log;
#[cfg(windows)]
pub mod event_log_job;
@@ -32,6 +35,8 @@ pub mod service;
pub mod signed_clock;
#[cfg(all(windows, feature = "system-helper"))]
mod system_script;
#[cfg(feature = "system-helper")]
pub mod update_native;
pub const SERVICE_NAME: &str = "RmmDiscoveryWindows";
pub const CAPABILITIES: &[&str] = &["windows.base/1", "heartbeat/1"];
+217 -15
View File
@@ -49,6 +49,42 @@ struct Config {
)]
windows_execution_profile: Option<rmm_domain::jobs::WindowsExecutionProfile>,
}
/// Local TLS maintenance evidence only. It never restores readiness; after
/// renewal both roles must pass their ordinary fresh signed synchronization.
#[derive(serde::Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
struct RotationIdleAdmission {
schema_version: u32,
agent_id: String,
binding_sha256: String,
boot_id: String,
journal_file_id: [u32; 3],
ledger_file_id: [u32; 3],
history_sha256: String,
helper_pin_sha256: Option<String>,
helper_anchor_sha256: Option<String>,
intent_file_id: Option<[u32; 3]>,
}
fn rotation_file_id(path: &Path) -> Result<[u32; 3]> {
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Storage::FileSystem::{
BY_HANDLE_FILE_INFORMATION, GetFileInformationByHandle,
};
native::private_path(path, false)?;
let file = fs::File::open(path)?;
let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
// SAFETY: live file handle and correctly sized writable native structure.
ensure!(
unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } != 0
&& info.nNumberOfLinks == 1,
"ROTATION_FILE_IDENTITY"
);
Ok([
info.dwVolumeSerialNumber,
info.nFileIndexHigh,
info.nFileIndexLow,
])
}
impl Config {
fn profile_enabled(&self, profile: rmm_domain::jobs::WindowsExecutionProfile) -> bool {
self.enable_jobs
@@ -536,6 +572,137 @@ struct Agent {
deferred_permit: Option<(u64, ExecutionPermit)>,
}
impl Agent {
fn rotation_without_effects(&self) -> Result<()> {
ensure!(
self.running.is_none() && self.deferred_permit.is_none() && !self.prepared,
"ROTATION_BUSY"
);
let idle: bool = self.journal.connection().query_row("SELECT NOT EXISTS(SELECT 1 FROM job_attempts WHERE state NOT IN ('succeeded','failed','cancelled','expired'))", [], |r| r.get(0))?;
ensure!(idle, "ROTATION_EFFECT_UNRESOLVED");
if let Some(ledger) = &self.ledger {
let resolved: bool = ledger.query_row("SELECT NOT EXISTS(SELECT 1 FROM consumed c LEFT JOIN execution_evidence e USING(grant_id) WHERE c.result IS NULL OR e.start IS NULL OR e.outcome IS NULL)", [], |r| r.get(0))?;
ensure!(resolved, "ROTATION_CONSUMPTION_UNRESOLVED");
}
#[cfg(feature = "system-helper")]
{
ensure!(
self.helper_control.is_none()
&& self.helper_probe.is_none()
&& !self.helper_apply_unconfirmed,
"ROTATION_HELPER_CONTROL_PENDING"
);
if Path::new(rmm_agent_windows::helper_runtime::intent::DB).try_exists()? {
let intents = rmm_agent_windows::helper_runtime::intent::Store::open(false)?;
ensure!(
intents.pending()?.is_empty(),
"ROTATION_SYSTEM_DELEGATION_PENDING"
);
}
}
Ok(())
}
fn rotation_admission(
&self,
generation: Option<u64>,
retained: Option<&[u8]>,
) -> Result<Vec<u8>> {
self.rotation_without_effects()?;
let old: Option<RotationIdleAdmission> =
retained.map(serde_json::from_slice).transpose()?;
if let Some(generation) = generation {
#[cfg(feature = "system-helper")]
let helper_present = self.helper.is_some();
#[cfg(not(feature = "system-helper"))]
let helper_present = false;
ensure!(
self.ready_identity(generation, helper_present),
"ROTATION_SIGNED_IDLE_REQUIRED"
);
} else {
ensure!(
self.fence.generation.load(Ordering::SeqCst) == 0 && old.is_some(),
"ROTATION_PENDING_IDLE_ADMISSION_REQUIRED"
);
}
#[cfg(feature = "system-helper")]
let (helper_pin_sha256, helper_anchor_sha256, intent_file_id) = {
use rmm_agent_windows::helper_runtime::{Client, intent};
let helper = Client::discover(
&self.identity.agent_id,
&self.identity.asset_id,
self.binding.as_ref(),
self.helper_lane.clone(),
)?;
let pin = helper.as_ref().map(|h| {
format!(
"{:x}",
Sha256::digest(
format!("{}:{}", h.pin_hash(), h.helper_binary_hash()).as_bytes()
)
)
});
let anchor = if helper.is_some() {
if generation.is_some() {
Some(format!(
"{:x}",
Sha256::digest(serde_json::to_vec(
self.helper_anchor
.as_ref()
.context("ROTATION_HELPER_ANCHOR_REQUIRED")?
)?)
))
} else {
let saved = old
.as_ref()
.and_then(|a| a.helper_anchor_sha256.clone())
.context("ROTATION_RETAINED_HELPER_ANCHOR_REQUIRED")?;
ensure!(
saved.len() == 64 && saved.bytes().all(|b| b.is_ascii_hexdigit()),
"ROTATION_RETAINED_HELPER_ANCHOR_INVALID"
);
Some(saved)
}
} else {
None
};
let file = Path::new(intent::DB)
.try_exists()?
.then(|| rotation_file_id(Path::new(intent::DB)))
.transpose()?;
(pin, anchor, file)
};
#[cfg(not(feature = "system-helper"))]
let (helper_pin_sha256, helper_anchor_sha256, intent_file_id) = (None, None, None);
let admission = RotationIdleAdmission {
schema_version: 1,
agent_id: self.identity.agent_id.clone(),
binding_sha256: format!(
"{:x}",
Sha256::digest(serde_json::to_vec(
self.binding.as_ref().context("ROTATION_BINDING_REQUIRED")?
)?)
),
boot_id: self.boot.clone(),
journal_file_id: rotation_file_id(
&self.config.state_directory.join("telemetry.sqlite"),
)?,
ledger_file_id: rotation_file_id(
&self.config.state_directory.join("consumption.sqlite"),
)?,
history_sha256: rmm_agent_windows::certificate_rotation::idle_history_sha256(
self.journal.connection(),
self.ledger.as_ref().context("ROTATION_LEDGER_REQUIRED")?,
)?,
helper_pin_sha256,
helper_anchor_sha256,
intent_file_id,
};
ensure!(
old.as_ref().is_none_or(|saved| saved == &admission),
"ROTATION_IDLE_STATE_CHANGED"
);
Ok(serde_json::to_vec(&admission)?)
}
#[cfg(feature = "system-helper")]
fn start_time_refresh(
&mut self,
@@ -958,6 +1125,12 @@ impl Agent {
caps.push(rmm_agent_windows::actions::REMOTE_SIGNED_PROFILE_CAPABILITY.into());
}
}
#[cfg(feature = "system-helper")]
if !self.config.windows_echo_probe_only
&& let Some(helper) = &self.helper
{
caps.extend(helper.qualified_capabilities());
}
}
caps
}
@@ -1679,11 +1852,16 @@ impl Agent {
// Server commit may have fenced Hello even if its HTTP response was
// lost. Recover the durable original CSR before requiring any channel.
if self.certificates.has_pending(self.journal.connection())? {
ensure!(
!self.config.enable_jobs,
"ROTATION_PENDING_REQUIRES_PASSIVE_RECOVERY"
);
self.renew_certificate().await?;
let admission = if self.config.enable_jobs {
let retained = self
.certificates
.pending_idle_admission(self.journal.connection())?
.context("ROTATION_PENDING_REQUIRES_PASSIVE_RECOVERY")?;
Some(self.rotation_admission(None, Some(&retained))?)
} else {
None
};
self.renew_certificate(admission.as_deref()).await?;
}
self.boot = native::boot_id().await?;
let advertised = self.capabilities();
@@ -1747,6 +1925,7 @@ impl Agent {
let mut inventory = Instant::now();
let mut update_at = Instant::now();
let mut rotation_at = Instant::now();
let mut rotation_after = Duration::from_secs(30);
let mut heartbeat = Instant::now() - Duration::from_secs(60);
let mut heartbeat_after = Duration::from_secs(30);
let mut tick = tokio::time::interval(Duration::from_secs(1));
@@ -1834,19 +2013,32 @@ impl Agent {
if stop.load(Ordering::SeqCst) {
continue;
}
// This slice renews only passive clients. Job admission and helper
// lifecycle are not extended by certificate maintenance.
if !self.config.enable_jobs && rotation_at.elapsed() >= Duration::from_secs(30) {
// Certificate maintenance cannot interrupt accepted, ambiguous or
// live work. Active rotation also retains its exact signed-idle
// context for a closed, effect-free retry after response loss.
if rotation_at.elapsed() >= rotation_after {
rotation_at = Instant::now();
rotation_after = Duration::from_secs(30);
let now = Utc::now().timestamp();
if self
.certificates
.due(self.journal.connection(), &self.key_files, now)?
{
self.renew_certificate().await?;
// The server fences the previous connection generation.
// A new Hello/Sync uses the newly selected pair.
return Ok(());
let admission = if self.config.enable_jobs {
self.rotation_admission(Some(generation), None).map(Some)
} else {
self.rotation_without_effects().map(|()| None)
};
if let Ok(admission) = admission {
self.renew_certificate(admission.as_deref()).await?;
// No offers are processed during renewal. The server
// fences this channel; fresh Hello/Sync must qualify
// both roles again before any subsequent job starts.
return Ok(());
}
// Avoid phase-locking a due renewal to the 30s helper
// probe cadence. Busy work keeps its guard and continues.
rotation_after = Duration::from_secs(1);
}
}
if heartbeat.elapsed() >= heartbeat_after {
@@ -1901,13 +2093,23 @@ impl Agent {
}
Ok(())
}
async fn renew_certificate(&mut self) -> Result<()> {
ensure!(!self.config.enable_jobs, "PASSIVE_RENEWAL_ONLY");
async fn renew_certificate(&mut self, admission: Option<&[u8]>) -> Result<()> {
self.rotation_without_effects()?;
ensure!(
!self.config.enable_jobs || admission.is_some(),
"ROTATION_ACTIVE_IDLE_REQUIRED"
);
self.close_gate();
let request = self.certificates.prepare(
#[cfg(feature = "system-helper")]
self.stop_time_refresh().await;
if self.config.enable_jobs {
self.rotation_admission(None, admission)?;
}
let request = self.certificates.prepare_with_idle_admission(
self.journal.connection_mut(),
&self.key_files,
Utc::now().timestamp(),
admission,
)?;
let client = crate::https_channel::mtls_client(
self.config.connect_address,
@@ -0,0 +1,154 @@
//! Operator-provisioned native qualification intersected with a live authenticated helper.
//! A source build or a permissive policy by itself cannot publish SYSTEM capabilities.
use crate::{
helper_ipc::{self as ipc, Pin, PinnedFile},
helper_system,
};
use anyhow::{Result, ensure};
use serde::Deserialize;
use std::{collections::BTreeSet, io::Read, path::Path};
use uuid::Uuid;
pub const PATH: &str = r"C:\ProgramData\RustDiscoverySystem\system-qualification.json";
pub const RESULT_PATH: &str = r"C:\ProgramData\RustDiscoverySystem\system-native-result.json";
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Qualification {
schema_version: u32,
tenant_id: Uuid,
asset_id: Uuid,
agent_id: Uuid,
enrollment_generation: u64,
assignment_version: u64,
agent_binary_sha256: String,
helper_binary_sha256: String,
policy_sha256: String,
native_result_sha256: String,
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()? {
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()?;
let evidence: serde_json::Value = serde_json::from_slice(&result_bytes)?;
ensure!(
evidence["schema_version"] == 1
&& evidence["platform"] == "windows-x86_64"
&& evidence["qualification_reference"] == q.qualification_reference.to_string()
&& evidence["helper_binary_sha256"] == q.helper_binary_sha256
&& evidence["validated_actions"] == serde_json::to_value(&q.actions)?
&& evidence["status"] == "passed",
"system native qualification evidence profile"
);
let (settings, _handles) = helper_system::read_settings()?;
ensure!(
serde_json::to_vec(&settings.pin()?)? == serde_json::to_vec(pin)?
&& settings.enable_effects,
"system qualification effective policy"
);
let mut caps = vec![
"helper.system.v1".into(),
format!("helper.binary.sha256:{}", pin.helper.binary_sha256),
format!("helper.policy.sha256:{}", pin.policy_sha256),
];
for action in q.actions {
match action.as_str() {
"run_script" => {
ensure!(
settings.schema_version == 3
&& settings.allowed_script_profiles.as_deref()
== Some(&[
rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1
])
&& crate::actions::powershell().is_ok(),
"system script qualification policy"
);
caps.extend(["system:run_script", "script.full_maintenance/1"].map(str::to_string));
}
"set_service_state" => {
ensure!(
!settings.allowed_services.is_empty(),
"system SCM qualification policy"
);
caps.extend(["set_service_state", "system:set_service_state"].map(str::to_string));
}
"ensure_package" => {
ensure!(
settings.schema_version >= 2
&& settings
.allowed_msi_recipe_sha256
.as_ref()
.is_some_and(|v| !v.is_empty())
&& crate::msi_cache::stage_configured(),
"system MSI qualification policy"
);
caps.extend(
[
"ensure_package",
"system:ensure_package",
rmm_domain::windows_execution::MSI_CAPABILITY,
]
.map(str::to_string),
);
}
_ => unreachable!("validated qualification action"),
}
}
Ok(caps)
}
@@ -0,0 +1,278 @@
//! File-swap fence against the SAME original guarded SYSTEM helper ledger.
//! Construction never re-enters a partial replacement or creates a handoff.
use super::{
Budget, DurableEffectFence, Effect, Role, digest,
files::{self, Location, Proof},
};
use anyhow::{Result, ensure};
use rmm_agent_core::{
reconcile::SyncClock,
update_handoff::{
self as core, NativeEffect, NativeEffectClaim, NativeFileRole, Participant,
UpdateParticipantGuard,
},
};
use rmm_updater_handoff::{Evidence, Handoff, Phase, PinTransition};
use rusqlite::Connection;
const ROLES: [Role; 5] = [
Role::Agent,
Role::Helper,
Role::Settings,
Role::Pin,
Role::TimeProfile,
];
fn native(role: Role) -> NativeFileRole {
match role {
Role::Agent => NativeFileRole::AgentBinary,
Role::Helper => NativeFileRole::HelperBinary,
Role::Settings => NativeFileRole::WindowsSettings,
Role::Pin => NativeFileRole::WindowsPin,
Role::TimeProfile => NativeFileRole::WindowsTimeProfile,
}
}
pub struct LedgerFence<'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,
}
/// Bindings are independently re-read before effects; parsed/transferred Proof
/// records never substitute for actual protected file identities/bytes.
pub struct Inputs<'a, 'b, G, C> {
pub db: &'a mut Connection,
pub guard: &'a G,
pub clock: &'a C,
pub budget: &'a Budget<'b>,
pub original: &'a Handoff,
pub originals: &'a [Proof; 5],
pub staged: &'a [Proof; 5],
}
impl<'a, 'b, G: UpdateParticipantGuard, C: SyncClock> LedgerFence<'a, 'b, G, C> {
pub fn new(input: Inputs<'a, 'b, G, C>) -> Result<Self> {
input.budget.check()?;
input.original.validate()?;
ensure!(
input.original.pin_transition == PinTransition::WindowsCodePairClockV1
&& input.guard.participant() == Participant::StableUpdater,
"UPDATE_WINDOWS_FENCE_ROLE"
);
let grant = input.original.attempt.grant_id;
let journal = core::read(input.db, input.guard, grant)?;
ensure!(
journal.phase() == Phase::UpdaterOwnsLedger,
"UPDATE_NO_FENCE_RESUME"
);
// Retained Handoff is immutable and read through the actual executor
// guard. No separately supplied record may stand in for those bytes.
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() {
let original = &input.original.files[i];
ensure!(
original.role == role.handoff_role()
&& original.old_sha256 == input.originals[i].sha256
&& original.new_sha256 == input.staged[i].sha256
&& input.originals[i].identity.volume_serial
== input.staged[i].identity.volume_serial
&& input.originals[i].identity != input.staged[i].identity
&& input.originals[i].security_sha256 == input.staged[i].security_sha256
&& files::observe_bound(
role,
input.original.owner_nonce,
Location::Target,
input.budget
)? == input.originals[i]
&& files::observe_bound(
role,
input.original.owner_nonce,
Location::Stage,
input.budget
)? == input.staged[i],
"UPDATE_WINDOWS_SWAP_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 now = self.clock.reading()?.upper;
ensure!(
u64::try_from(now.timestamp())? < self.original.finish_before,
"UPDATE_WINDOWS_DEADLINE"
);
let bytes = journal.prepare(u64::try_from(now.timestamp())?, evidence)?;
core::append(self.db, self.guard, grant, journal.head_sha256(), &bytes)
}
pub fn finish(mut self) -> Result<()> {
ensure!(
!self.poisoned && self.pending.is_none() && self.next == ROLES.len() && !self.saved,
"UPDATE_WINDOWS_FENCE_INCOMPLETE"
);
for (i, role) in ROLES.iter().copied().enumerate() {
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_FINAL_PAIR_CHANGED"
);
}
self.append(Evidence::PairVerified {
pair: self.original.target.clone(),
retained_state_sha256: self.original.retained_state_sha256.clone(),
})
}
}
impl<G: UpdateParticipantGuard, C: SyncClock> DurableEffectFence for LedgerFence<'_, '_, G, C> {
fn before_effect(&mut self, effect: &Effect) -> Result<()> {
ensure!(
!self.poisoned && self.pending.is_none() && self.next < ROLES.len(),
"UPDATE_WINDOWS_FENCE_REENTRY"
);
self.poisoned = true;
self.budget.check()?;
let role = ROLES[self.next];
let native = match *effect {
Effect::SavePredecessor { role: r } if r == role && !self.saved => {
ensure!(
files::observe_bound(
role,
self.original.owner_nonce,
Location::Target,
self.budget
)? == self.originals[self.next]
&& files::observe_bound(
role,
self.original.owner_nonce,
Location::Stage,
self.budget
)? == self.staged[self.next],
"UPDATE_WINDOWS_FILES_CHANGED"
);
self.append(Evidence::ReplaceIntent {
role: role.handoff_role(),
})?;
NativeEffect::SavePredecessor { role: native(role) }
}
Effect::PublishReplacement { role: r } if r == role && self.saved => {
ensure!(
files::observe_bound(
role,
self.original.owner_nonce,
Location::Previous,
self.budget
)? == self.originals[self.next]
&& files::observe_bound(
role,
self.original.owner_nonce,
Location::Stage,
self.budget
)? == self.staged[self.next],
"UPDATE_WINDOWS_FILES_CHANGED"
);
NativeEffect::PublishReplacement { role: native(role) }
}
_ => anyhow::bail!("UPDATE_WINDOWS_SWAP_FENCE_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(),
&native,
self.clock.reading()?.upper,
)?;
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_EFFECT_NOT_CLAIMED"))?;
ensure!(
self.poisoned && *effect == expected,
"UPDATE_WINDOWS_EFFECT_CALLBACK_CHANGED"
);
self.budget.check()?;
let role = ROLES[self.next];
let replaced = matches!(effect, Effect::PublishReplacement { .. });
let proof = files::observe_bound(
role,
self.original.owner_nonce,
if replaced {
Location::Target
} else {
Location::Previous
},
self.budget,
)?;
ensure!(
proof
== if replaced {
self.staged[self.next].clone()
} else {
self.originals[self.next].clone()
}
&& digest(&serde_json::to_vec(&proof)?) == observation,
"UPDATE_WINDOWS_EFFECT_READBACK_CHANGED"
);
core::observe_native_effect(
self.db,
self.guard,
&claim,
observation,
self.clock.reading()?.upper,
)?;
if replaced {
self.append(Evidence::Replaced {
role: role.handoff_role(),
observed_sha256: proof.sha256,
})?;
self.next += 1;
self.saved = false;
} else {
self.saved = true;
}
self.poisoned = false;
Ok(())
}
}
@@ -0,0 +1,576 @@
//! Fixed-file, same-volume native staging and one-step-at-a-time publication.
//! 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 anyhow::{Context, Result, ensure};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::{
fs::File,
io::{Read, Seek, SeekFrom, Write},
mem::{offset_of, size_of, zeroed},
os::windows::{
ffi::OsStrExt,
io::{AsRawHandle, FromRawHandle},
},
path::{Path, PathBuf},
ptr,
};
use uuid::Uuid;
use windows_sys::Win32::{
Foundation::{INVALID_HANDLE_VALUE, LocalFree},
Security::{
self,
Authorization::{GetSecurityInfo, SE_FILE_OBJECT},
SECURITY_ATTRIBUTES,
},
Storage::FileSystem::*,
};
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Proof {
pub identity: FileIdentity,
pub bytes: u64,
pub sha256: String,
pub security_sha256: String,
}
/// All ancestors remain open without DELETE sharing. The protected immediate
/// directory also remains pinned by file identity/owner/DACL throughout effects.
struct Directory {
root: PinnedFile,
ancestors: Vec<File>,
}
fn regular(file: &File, directory: bool) -> Result<()> {
let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { zeroed() };
ensure!(
unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } != 0
&& info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT == 0
&& (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY != 0) == directory
&& (directory || info.nNumberOfLinks == 1),
"UPDATE_NONREGULAR_FILE"
);
Ok(())
}
fn open(
path: &Path,
desired: u32,
creation: u32,
security: *const SECURITY_ATTRIBUTES,
) -> Result<File> {
let handle = unsafe {
CreateFileW(
ipc::wide(path).as_ptr(),
desired,
FILE_SHARE_READ,
security,
creation,
FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_WRITE_THROUGH,
ptr::null_mut(),
)
};
ensure!(
handle != INVALID_HANDLE_VALUE,
"UPDATE_NATIVE_FILE_OPEN: {}",
std::io::Error::last_os_error()
);
let file = unsafe { File::from_raw_handle(handle) };
regular(&file, false)?;
Ok(file)
}
impl Directory {
fn open(role: Role) -> Result<Self> {
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 mut ancestors = Vec::new();
for ancestor in path.ancestors().skip(1) {
let raw = unsafe {
CreateFileW(
ipc::wide(ancestor).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!(raw != INVALID_HANDLE_VALUE, "UPDATE_ANCESTOR_OPEN");
let file = unsafe { File::from_raw_handle(raw) };
regular(&file, true)?;
ancestors.push(file);
}
Ok(Self { root, ancestors })
}
fn check(&mut self) -> Result<()> {
self.root.check()?;
for ancestor in &self.ancestors {
regular(ancestor, true)?;
}
Ok(())
}
fn child(&self, name: &str) -> PathBuf {
self.root.path.join(name)
}
}
struct SecurityDescriptor(*mut core::ffi::c_void);
impl Drop for SecurityDescriptor {
fn drop(&mut self) {
unsafe {
LocalFree(self.0);
}
}
}
impl SecurityDescriptor {
fn read(file: &File) -> Result<Self> {
let mut descriptor = ptr::null_mut();
ensure!(
unsafe {
GetSecurityInfo(
file.as_raw_handle(),
SE_FILE_OBJECT,
Security::OWNER_SECURITY_INFORMATION
| Security::GROUP_SECURITY_INFORMATION
| Security::DACL_SECURITY_INFORMATION,
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
&mut descriptor,
)
} == 0
&& !descriptor.is_null(),
"UPDATE_FILE_SECURITY"
);
Ok(Self(descriptor))
}
fn hash(&self) -> Result<String> {
let mut owner = ptr::null_mut();
let mut group = ptr::null_mut();
let mut defaulted = 0;
let mut present = 0;
let mut acl = ptr::null_mut();
let mut control = 0;
let mut revision = 0;
ensure!(
unsafe {
Security::GetSecurityDescriptorOwner(self.0, &mut owner, &mut defaulted) != 0
&& Security::GetSecurityDescriptorGroup(self.0, &mut group, &mut defaulted) != 0
&& Security::GetSecurityDescriptorDacl(
self.0,
&mut present,
&mut acl,
&mut defaulted,
) != 0
&& Security::GetSecurityDescriptorControl(self.0, &mut control, &mut revision)
!= 0
} && !owner.is_null()
&& !group.is_null()
&& present != 0
&& !acl.is_null(),
"UPDATE_FILE_SECURITY_PARTS"
);
// Only actual owner, group, ACL bytes and inheritance protection are
// hashed. Windows may clear the informational AUTO_INHERITED bit when
// creating an explicitly protected object; that bit grants no rights.
let mut bytes = Vec::new();
for sid in [owner, group] {
let len = unsafe { Security::GetLengthSid(sid) };
ensure!((8..=256).contains(&len), "UPDATE_SECURITY_SID_SIZE");
bytes.extend_from_slice(&len.to_le_bytes());
bytes.extend_from_slice(unsafe {
std::slice::from_raw_parts(sid.cast::<u8>(), len as usize)
});
}
let len = unsafe { (*acl).AclSize };
ensure!(
(size_of::<Security::ACL>() as u16..=32768).contains(&len),
"UPDATE_SECURITY_ACL_SIZE"
);
bytes.extend_from_slice(&(control & Security::SE_DACL_PROTECTED).to_le_bytes());
bytes.extend_from_slice(unsafe {
std::slice::from_raw_parts(acl.cast::<u8>(), len as usize)
});
Ok(digest(&bytes))
}
fn attributes(&self) -> SECURITY_ATTRIBUTES {
SECURITY_ATTRIBUTES {
nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
lpSecurityDescriptor: self.0,
bInheritHandle: 0,
}
}
}
fn hash_file(file: &mut File, max: u64) -> Result<String> {
ensure!((1..=256 * 1024 * 1024).contains(&max), "UPDATE_FILE_LIMIT");
file.seek(SeekFrom::Start(0))?;
let mut hash = Sha256::new();
let mut count = 0u64;
let mut buf = [0u8; 65536];
loop {
let read = file.read(&mut buf)?;
if read == 0 {
break;
}
count = count
.checked_add(read as u64)
.context("UPDATE_FILE_LIMIT")?;
ensure!(count <= max, "UPDATE_FILE_LIMIT");
hash.update(&buf[..read]);
}
Ok(format!("{:x}", hash.finalize()))
}
fn proof(file: &mut File, path: &Path, max: u64) -> Result<Proof> {
regular(file, false)?;
job_binding::check_admin_readonly(path)?;
let identity = ipc::file_identity(file)?;
let bytes = file.metadata()?.len();
ensure!(bytes > 0 && bytes <= max, "UPDATE_FILE_SIZE");
let security_sha256 = SecurityDescriptor::read(file)?.hash()?;
let sha256 = hash_file(file, max)?;
regular(file, false)?;
ensure!(
ipc::file_identity(file)? == identity
&& file.metadata()?.len() == bytes
&& SecurityDescriptor::read(file)?.hash()? == security_sha256,
"UPDATE_FILE_CHANGED_DURING_READ"
);
let named = unsafe {
CreateFileW(
ipc::wide(path).as_ptr(),
FILE_READ_ATTRIBUTES,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
ptr::null(),
OPEN_EXISTING,
FILE_FLAG_OPEN_REPARSE_POINT,
ptr::null_mut(),
)
};
ensure!(named != INVALID_HANDLE_VALUE, "UPDATE_FILE_NAME_READBACK");
let named = unsafe { File::from_raw_handle(named) };
regular(&named, false)?;
ensure!(
ipc::file_identity(&named)? == identity,
"UPDATE_FILE_NAME_REPLACED"
);
Ok(Proof {
identity,
bytes,
sha256,
security_sha256,
})
}
/// Read-only predecessor capture while the original services may still run.
/// This is an observation, not an authenticated InstalledRecord or baseline.
pub fn observe(role: Role, budget: &Budget<'_>) -> Result<Proof> {
budget.check()?;
let mut directory = Directory::open(role)?;
let mut file = open(
Path::new(role.target()),
FILE_GENERIC_READ,
OPEN_EXISTING,
ptr::null(),
)?;
let value = proof(&mut file, Path::new(role.target()), role.max_bytes())?;
directory.check()?;
budget.check()?;
Ok(value)
}
#[derive(Clone, Copy)]
pub(crate) enum Location {
Target,
Stage,
Previous,
}
/// Independent readback while the actual swap retains DELETE/write handles.
/// Opening this read-only observer grants no write/delete access or authority.
pub(crate) fn observe_bound(
role: Role,
nonce: Uuid,
location: Location,
budget: &Budget<'_>,
) -> Result<Proof> {
ensure!(!nonce.is_nil(), "UPDATE_READBACK_NONCE");
budget.check()?;
let mut directory = Directory::open(role)?;
let path = match location {
Location::Target => PathBuf::from(role.target()),
Location::Stage => directory.child(&format!(".rmm-update-{nonce}-{}.stage", role.label())),
Location::Previous => {
directory.child(&format!(".rmm-update-{nonce}-{}.previous", role.label()))
}
};
let raw = unsafe {
CreateFileW(
ipc::wide(&path).as_ptr(),
FILE_GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
ptr::null(),
OPEN_EXISTING,
FILE_FLAG_OPEN_REPARSE_POINT,
ptr::null_mut(),
)
};
ensure!(raw != INVALID_HANDLE_VALUE, "UPDATE_READBACK_OPEN");
let mut file = unsafe { File::from_raw_handle(raw) };
let result = proof(&mut file, &path, role.max_bytes())?;
directory.check()?;
budget.check()?;
Ok(result)
}
pub struct StageDescriptor<'a> {
pub role: Role,
pub owner_nonce: Uuid,
pub original: &'a Proof,
pub replacement_sha256: &'a str,
pub replacement_bytes: u64,
}
pub struct Staged {
role: Role,
nonce: Uuid,
directory: Directory,
path: PathBuf,
file: File,
original: Proof,
staged: Proof,
}
impl Staged {
/// 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.
pub fn create(
descriptor: StageDescriptor<'_>,
source: &mut impl Read,
budget: &Budget<'_>,
fence: &mut impl DurableEffectFence,
) -> Result<Self> {
let StageDescriptor {
role,
owner_nonce: nonce,
original,
replacement_sha256,
replacement_bytes,
} = descriptor;
ensure!(
!nonce.is_nil()
&& valid_digest(&original.sha256)
&& valid_digest(replacement_sha256)
&& replacement_bytes > 0
&& replacement_bytes <= role.max_bytes(),
"UPDATE_STAGE_DESCRIPTOR"
);
budget.check()?;
let mut directory = Directory::open(role)?;
let mut predecessor = open(
Path::new(role.target()),
FILE_GENERIC_READ,
OPEN_EXISTING,
ptr::null(),
)?;
ensure!(
proof(&mut predecessor, Path::new(role.target()), role.max_bytes())? == *original,
"UPDATE_PREDECESSOR_CHANGED"
);
let security = SecurityDescriptor::read(&predecessor)?;
let attributes = security.attributes();
let path = directory.child(&format!(".rmm-update-{nonce}-{}.stage", role.label()));
let effect = Effect::StageFile { role };
fence.before_effect(&effect)?;
budget.check()?;
directory.check()?;
let mut file = open(
&path,
FILE_GENERIC_READ | FILE_GENERIC_WRITE | DELETE,
CREATE_NEW,
&attributes,
)?;
let mut total = 0u64;
let mut buffer = [0u8; 65536];
loop {
budget.check()?;
let read = source.read(&mut buffer)?;
if read == 0 {
break;
}
total = total
.checked_add(read as u64)
.context("UPDATE_STAGE_LENGTH")?;
ensure!(total <= replacement_bytes, "UPDATE_STAGE_EXTRA_BYTES");
file.write_all(&buffer[..read])?;
}
ensure!(total == replacement_bytes, "UPDATE_STAGE_TRUNCATED");
file.sync_all()?;
let staged = proof(&mut file, &path, role.max_bytes())?;
ensure!(
staged.bytes == replacement_bytes
&& staged.sha256 == replacement_sha256
&& staged.identity != original.identity
&& staged.identity.volume_serial == original.identity.volume_serial
&& staged.security_sha256 == original.security_sha256,
"UPDATE_STAGE_VERIFICATION"
);
directory.check()?;
budget.check()?;
fence.after_effect(&effect, &digest(&serde_json::to_vec(&staged)?))?;
Ok(Self {
role,
nonce,
directory,
path,
file,
original: original.clone(),
staged,
})
}
pub fn original(&self) -> &Proof {
&self.original
}
pub fn staged(&self) -> &Proof {
&self.staged
}
/// Publication consists of TWO separately fenced native renames. This is
/// explicitly not an atomic pair swap. Any missing reply/readback requires
/// retained-namespace adjudication, never automatic re-entry/replacement.
pub fn publish(
mut self,
stopped: &super::services::Stopped,
budget: &Budget<'_>,
fence: &mut impl DurableEffectFence,
) -> Result<Published> {
stopped.check(budget)?;
self.directory.check()?;
ensure!(
proof(&mut self.file, &self.path, self.role.max_bytes())? == self.staged,
"UPDATE_STAGED_FILE_CHANGED"
);
let target = Path::new(self.role.target());
let mut original = open(
target,
FILE_GENERIC_READ | FILE_GENERIC_WRITE | DELETE,
OPEN_EXISTING,
ptr::null(),
)?;
ensure!(
proof(&mut original, target, self.role.max_bytes())? == self.original,
"UPDATE_PREDECESSOR_CHANGED"
);
let previous = self.directory.child(&format!(
".rmm-update-{}-{}.previous",
self.nonce,
self.role.label()
));
let save = Effect::SavePredecessor { role: self.role };
fence.before_effect(&save)?;
budget.check()?;
stopped.check(budget)?;
self.directory.check()?;
rename_new(&original, &previous)?;
let saved = proof(&mut original, &previous, self.role.max_bytes())?;
ensure!(saved == self.original, "UPDATE_SAVED_PREDECESSOR_CHANGED");
fence.after_effect(&save, &digest(&serde_json::to_vec(&saved)?))?;
let publish = Effect::PublishReplacement { role: self.role };
fence.before_effect(&publish)?;
budget.check()?;
stopped.check(budget)?;
self.directory.check()?;
rename_new(&self.file, target)?;
let published = proof(&mut self.file, target, self.role.max_bytes())?;
ensure!(published == self.staged, "UPDATE_PUBLISHED_FILE_CHANGED");
fence.after_effect(&publish, &digest(&serde_json::to_vec(&published)?))?;
Ok(Published {
role: self.role,
directory: self.directory,
original,
predecessor: previous,
original_proof: saved,
replacement: self.file,
replacement_proof: published,
})
}
}
fn rename_new(file: &File, target: &Path) -> Result<()> {
let name: Vec<u16> = target.as_os_str().encode_wide().collect();
ensure!(
target.is_absolute() && name.len() <= 32767 && !name.contains(&0),
"UPDATE_RENAME_TARGET"
);
let length = offset_of!(FILE_RENAME_INFO, FileName) + name.len() * 2;
let mut bytes = vec![0usize; length.div_ceil(size_of::<usize>())];
let info = bytes.as_mut_ptr().cast::<FILE_RENAME_INFO>();
// SAFETY: aligned, zeroed buffer with exact capacity for the fixed header
// and full UTF16 name. The native call is handle-relative to the already
// held SOURCE; ReplaceIfExists=false refuses files, links or a raced target.
unsafe {
(*info).Anonymous.ReplaceIfExists = false;
(*info).RootDirectory = ptr::null_mut();
(*info).FileNameLength = (name.len() * 2) as u32;
ptr::copy_nonoverlapping(
name.as_ptr(),
ptr::addr_of_mut!((*info).FileName).cast::<u16>(),
name.len(),
);
}
ensure!(
unsafe {
SetFileInformationByHandle(
file.as_raw_handle(),
FileRenameInfo,
info.cast(),
length as u32,
)
} != 0,
"UPDATE_RENAME_UNCERTAIN: {}",
std::io::Error::last_os_error()
);
// Flush the held write-through file after the rename; a power loss or
// failed metadata observation still remains uncertain in the durable ledger.
file.sync_all()?;
Ok(())
}
pub struct Published {
role: Role,
directory: Directory,
original: File,
predecessor: PathBuf,
original_proof: Proof,
replacement: File,
replacement_proof: Proof,
}
impl Published {
pub fn proof(&self) -> &Proof {
&self.replacement_proof
}
pub fn verify(&mut self, budget: &Budget<'_>) -> Result<()> {
budget.check()?;
self.directory.check()?;
ensure!(
proof(&mut self.original, &self.predecessor, self.role.max_bytes())?
== self.original_proof
&& proof(
&mut self.replacement,
Path::new(self.role.target()),
self.role.max_bytes()
)? == self.replacement_proof,
"UPDATE_PUBLISHED_PAIR_CHANGED"
);
Ok(())
}
/// Close replacement/delete handles before SCM startup. The caller retains
/// the proofs and must independently reopen/recheck them during Health.
/// No predecessor is removed; this module contains no cleanup primitive.
pub fn release(mut self, budget: &Budget<'_>) -> Result<(Proof, Proof)> {
self.verify(budget)?;
Ok((self.original_proof, self.replacement_proof))
}
}
@@ -0,0 +1,198 @@
//! Native Windows primitives for the separately provisioned stable updater.
//!
//! This module neither approves an update nor activates a worker. The caller
//! authenticates the approved original admission and (after staging) consumed
//! handoff, owns the existing ledger guard, and supplies a durable effect fence.
//! No default/permissive fence, resume,
//! reset, shell, reboot, or arbitrary service/path operation is provided.
use anyhow::{Result, ensure};
use rmm_agent_core::helper_reconcile::BootSource;
use serde::{Deserialize, Serialize};
use std::time::{Duration, Instant};
use uuid::Uuid;
#[cfg(windows)]
pub mod fence;
#[cfg(windows)]
pub mod files;
#[cfg(windows)]
pub mod services;
pub mod transition;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Service {
Agent,
Helper,
}
impl Service {
pub fn name(self) -> &'static str {
match self {
Self::Agent => "RmmDiscoveryWindows",
Self::Helper => "RmmDiscoverySystemHelper",
}
}
pub fn handoff_service(self) -> rmm_updater_handoff::Service {
match self {
Self::Agent => rmm_updater_handoff::Service::WindowsAgent,
Self::Helper => rmm_updater_handoff::Service::WindowsHelper,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Role {
Agent,
Helper,
Settings,
Pin,
TimeProfile,
}
impl Role {
pub fn target(self) -> &'static str {
match self {
Self::Agent => r"C:\Program Files\RustDiscovery\rmm-agent-windows.exe",
Self::Helper => r"C:\Program Files\RustDiscovery\rmm-helper-windows.exe",
Self::Settings => r"C:\ProgramData\RustDiscoverySystem\helper.json",
Self::Pin => r"C:\ProgramData\RustDiscoverySystem\agent-pin.json",
Self::TimeProfile => r"C:\ProgramData\RustDiscoverySystem\time-attestation.json",
}
}
pub fn handoff_role(self) -> rmm_updater_handoff::FileRole {
match self {
Self::Agent => rmm_updater_handoff::FileRole::AgentBinary,
Self::Helper => rmm_updater_handoff::FileRole::HelperBinary,
Self::Settings => rmm_updater_handoff::FileRole::WindowsSettings,
Self::Pin => rmm_updater_handoff::FileRole::WindowsPin,
Self::TimeProfile => rmm_updater_handoff::FileRole::WindowsTimeProfile,
}
}
#[cfg(windows)]
fn label(self) -> &'static str {
match self {
Self::Agent => "agent",
Self::Helper => "helper",
Self::Settings => "settings",
Self::Pin => "pin",
Self::TimeProfile => "time-profile",
}
}
pub fn max_bytes(self) -> u64 {
match self {
Self::Agent | Self::Helper => 256 * 1024 * 1024,
Self::Settings | Self::Pin | Self::TimeProfile => 64 * 1024,
}
}
}
/// The embedding worker must additionally check its original trusted-clock
/// interval and signed deadline at each effect. This budget cannot extend it.
pub struct Budget<'a> {
boot: &'a dyn BootSource,
boot_id: Uuid,
until: Instant,
}
impl<'a> Budget<'a> {
pub fn new(boot: &'a dyn BootSource, expected: Uuid, remaining: Duration) -> Result<Self> {
ensure!(
!expected.is_nil() && !remaining.is_zero() && remaining <= Duration::from_secs(600),
"UPDATE_BUDGET"
);
let value = Self {
boot,
boot_id: expected,
until: Instant::now()
.checked_add(remaining)
.ok_or_else(|| anyhow::anyhow!("UPDATE_BUDGET"))?,
};
value.check()?;
Ok(value)
}
pub fn check(&self) -> Result<()> {
ensure!(Instant::now() < self.until, "UPDATE_DEADLINE");
ensure!(
self.boot.current_boot()? == self.boot_id,
"UPDATE_BOOT_CHANGED"
);
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "effect", rename_all = "snake_case", deny_unknown_fields)]
pub enum Effect {
StopService { service: Service },
StageFile { role: Role },
SavePredecessor { role: Role },
PublishReplacement { role: Role },
RestorePredecessor { role: Role },
StartService { service: Service },
}
/// Implementations MUST independently check the original approved admission
/// for StageFile; every later effect additionally needs the consumed original
/// handoff. Retained owner/process/boot/clock/ledger witnesses and a COMMITTED
/// create-once intent are required. Observation failure never allows a retry.
pub trait DurableEffectFence {
fn before_effect(&mut self, effect: &Effect) -> Result<()>;
fn after_effect(&mut self, effect: &Effect, observation_sha256: &str) -> Result<()>;
}
fn valid_digest(value: &str) -> bool {
value.len() == 64
&& value
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
#[cfg(windows)]
fn digest(bytes: &[u8]) -> String {
use sha2::{Digest, Sha256};
Sha256::digest(bytes)
.iter()
.map(|b| format!("{b:02x}"))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicBool, Ordering};
struct Boot(AtomicBool, Uuid);
impl BootSource for Boot {
fn current_boot(&self) -> Result<Uuid> {
Ok(if self.0.load(Ordering::SeqCst) {
Uuid::nil()
} else {
self.1
})
}
}
#[test]
fn budget_is_original_boot_bound_and_never_has_an_unbounded_window() {
let boot = Boot(AtomicBool::new(false), Uuid::new_v4());
assert!(Budget::new(&boot, boot.1, Duration::ZERO).is_err());
assert!(Budget::new(&boot, boot.1, Duration::from_secs(601)).is_err());
assert!(Budget::new(&boot, Uuid::nil(), Duration::from_secs(1)).is_err());
let bound = Budget::new(&boot, boot.1, Duration::from_secs(1)).unwrap();
bound.check().unwrap();
boot.0.store(true, Ordering::SeqCst);
assert!(bound.check().is_err());
}
#[test]
fn windows_roles_are_closed_and_effects_reject_unknown_fields() {
assert_eq!(Service::Agent.name(), crate::SERVICE_NAME);
assert_eq!(
Role::Pin.handoff_role(),
rmm_updater_handoff::FileRole::WindowsPin
);
for raw in [
r#"{"effect":"stop_service","service":"updater"}"#,
r#"{"effect":"publish_replacement","role":"arbitrary"}"#,
r#"{"effect":"stop_service","service":"helper","command":"extra"}"#,
] {
assert!(serde_json::from_str::<Effect>(raw).is_err());
}
assert!(valid_digest(&"ab".repeat(32)));
assert!(!valid_digest(&"AB".repeat(32)));
}
}
@@ -0,0 +1,393 @@
//! Closed native SCM stop/start with held original process witnesses.
//! Service recovery actions, triggers and dependencies are refused rather than
//! modified. Every native request is issued once after a durable caller intent.
use super::{Budget, DurableEffectFence, Effect, Service, digest};
use crate::helper_ipc::{PeerPin, PeerProof, utf16_pointer, wide};
use anyhow::{Result, ensure};
use rmm_updater_handoff::{Process, StartedService};
use serde::{Deserialize, Serialize};
use std::{
mem::{size_of, zeroed},
ptr, thread,
time::Duration,
};
use windows_sys::Win32::System::Services::*;
struct Handle(SC_HANDLE);
impl Drop for Handle {
fn drop(&mut self) {
unsafe {
CloseServiceHandle(self.0);
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Configuration {
pub service: Service,
pub command: String,
pub account: String,
pub start_type: u32,
pub error_control: u32,
pub sid_type: u32,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Proof {
pub configuration: Configuration,
pub process: Process,
}
struct HeldService {
service: Service,
handle: Handle,
peer: PeerProof,
proof: Proof,
}
fn handle(service: Service, rights: u32) -> Result<Handle> {
let manager = Handle(unsafe { OpenSCManagerW(ptr::null(), ptr::null(), SC_MANAGER_CONNECT) });
ensure!(!manager.0.is_null(), "UPDATE_SCM_MANAGER");
let value = Handle(unsafe { OpenServiceW(manager.0, wide(service.name()).as_ptr(), rights) });
ensure!(!value.0.is_null(), "UPDATE_SCM_SERVICE");
Ok(value)
}
fn status(handle: &Handle) -> Result<SERVICE_STATUS_PROCESS> {
let mut value = unsafe { zeroed() };
let mut needed = 0;
ensure!(
unsafe {
QueryServiceStatusEx(
handle.0,
SC_STATUS_PROCESS_INFO,
(&mut value as *mut SERVICE_STATUS_PROCESS).cast(),
size_of::<SERVICE_STATUS_PROCESS>() as u32,
&mut needed,
)
} != 0,
"UPDATE_SCM_STATUS"
);
Ok(value)
}
fn config2(handle: &Handle, kind: u32) -> Result<Vec<usize>> {
let mut needed = 0;
unsafe {
QueryServiceConfig2W(handle.0, kind, 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 {
QueryServiceConfig2W(
handle.0,
kind,
bytes.as_mut_ptr().cast(),
needed,
&mut needed,
)
} != 0,
"UPDATE_SCM_CONFIG"
);
Ok(bytes)
}
fn configuration(handle: &Handle, service: Service, pin: &PeerPin) -> Result<Configuration> {
pin.validate(service == Service::Helper)?;
let mut needed = 0;
unsafe {
QueryServiceConfigW(handle.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(handle.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) }?;
let expected = if service == Service::Agent {
format!(
"\"{}\" --service --config \"C:\\ProgramData\\RustDiscovery\\config.json\"",
pin.binary.display()
)
} else {
format!("\"{}\" --service", pin.binary.display())
};
ensure!(
cfg.dwServiceType == SERVICE_WIN32_OWN_PROCESS
&& command == expected
&& cfg.dwStartType
== if service == Service::Agent {
SERVICE_AUTO_START
} else {
SERVICE_DEMAND_START
}
&& (cfg.lpDependencies.is_null() || unsafe { *cfg.lpDependencies } == 0)
&& (cfg.lpLoadOrderGroup.is_null() || unsafe { *cfg.lpLoadOrderGroup } == 0),
"UPDATE_SCM_UNEXPECTED_CONFIGURATION"
);
let recovery = config2(handle, SERVICE_CONFIG_FAILURE_ACTIONS)?;
let recovery = unsafe { &*recovery.as_ptr().cast::<SERVICE_FAILURE_ACTIONSW>() };
ensure!(recovery.cActions == 0, "UPDATE_SCM_RECOVERY_ACTIONS");
let triggers = config2(handle, SERVICE_CONFIG_TRIGGER_INFO)?;
let triggers = unsafe { &*triggers.as_ptr().cast::<SERVICE_TRIGGER_INFO>() };
ensure!(triggers.cTriggers == 0, "UPDATE_SCM_TRIGGERS");
let sid = config2(handle, SERVICE_CONFIG_SERVICE_SID_INFO)?;
let sid = unsafe { &*sid.as_ptr().cast::<SERVICE_SID_INFO>() };
ensure!(
sid.dwServiceSidType == SERVICE_SID_TYPE_UNRESTRICTED,
"UPDATE_SCM_SERVICE_SID"
);
// Refuse active dependent services; stopping this pair cannot stop another
// product or cause StartService's implicit dependency side effects.
let mut dependent_bytes = 0;
let mut dependent_count = 0;
let no_dependents = unsafe {
EnumDependentServicesW(
handle.0,
SERVICE_ACTIVE,
ptr::null_mut(),
0,
&mut dependent_bytes,
&mut dependent_count,
)
};
ensure!(
no_dependents != 0 && dependent_count == 0 && dependent_bytes == 0,
"UPDATE_SCM_ACTIVE_DEPENDENTS"
);
Ok(Configuration {
service,
command,
account,
start_type: cfg.dwStartType,
error_control: cfg.dwErrorControl,
sid_type: sid.dwServiceSidType,
})
}
fn observe(service: Service, pin: &PeerPin, budget: &Budget<'_>) -> Result<HeldService> {
budget.check()?;
let handle = handle(
service,
SERVICE_QUERY_STATUS
| SERVICE_QUERY_CONFIG
| SERVICE_ENUMERATE_DEPENDENTS
| SERVICE_STOP
| SERVICE_START,
)?;
let before = configuration(&handle, service, pin)?;
let state = status(&handle)?;
ensure!(
state.dwCurrentState == SERVICE_RUNNING && state.dwProcessId > 0,
"UPDATE_SERVICE_NOT_RUNNING"
);
let mut peer = PeerProof::for_service(pin, state.dwProcessId)?;
peer.check()?;
let id = peer.identity();
let proof = Proof {
configuration: before.clone(),
process: Process {
pid: id.pid,
birth: id.creation_ticks,
image_sha256: id.image_sha256.clone(),
},
};
ensure!(
configuration(&handle, service, pin)? == before
&& status(&handle)?.dwProcessId == proof.process.pid,
"UPDATE_SERVICE_OBSERVATION_CHANGED"
);
budget.check()?;
Ok(HeldService {
service,
handle,
peer,
proof,
})
}
/// Observation holds both original processes/images, not a freely constructible
/// Running flag. Drop these witnesses only after confirmed process termination.
pub struct Running {
pins: [PeerPin; 2],
held: Vec<HeldService>,
}
impl Running {
pub fn observe(pins: [PeerPin; 2], budget: &Budget<'_>) -> Result<Self> {
let held = vec![
observe(Service::Agent, &pins[0], budget)?,
observe(Service::Helper, &pins[1], budget)?,
];
Ok(Self { pins, held })
}
pub fn proofs(&self) -> Vec<Proof> {
self.held.iter().map(|s| s.proof.clone()).collect()
}
pub fn check(&mut self, budget: &Budget<'_>) -> Result<()> {
budget.check()?;
for (i, service) in self.held.iter_mut().enumerate() {
service.peer.check()?;
ensure!(
configuration(&service.handle, service.service, &self.pins[i])?
== service.proof.configuration,
"UPDATE_SERVICE_CONFIG_CHANGED"
);
}
Ok(())
}
pub fn stop(
mut self,
budget: &Budget<'_>,
fence: &mut impl DurableEffectFence,
) -> Result<Stopped> {
self.check(budget)?;
for (i, service) in self.held.iter_mut().enumerate() {
service.peer.check()?;
ensure!(
configuration(&service.handle, service.service, &self.pins[i])?
== service.proof.configuration,
"UPDATE_SERVICE_CONFIG_CHANGED"
);
let effect = Effect::StopService {
service: service.service,
};
fence.before_effect(&effect)?;
budget.check()?;
service.peer.check()?;
let mut stopped = unsafe { zeroed() };
ensure!(
unsafe { ControlService(service.handle.0, SERVICE_CONTROL_STOP, &mut stopped) }
!= 0,
"UPDATE_STOP_REQUEST_UNCERTAIN"
);
loop {
budget.check()?;
let state = status(&service.handle)?;
if state.dwCurrentState == SERVICE_STOPPED
&& state.dwProcessId == 0
&& service.peer.exited()?
{
break;
}
ensure!(
matches!(state.dwCurrentState, SERVICE_STOP_PENDING | SERVICE_STOPPED),
"UPDATE_STOP_STATE_UNCERTAIN"
);
thread::sleep(Duration::from_millis(20));
}
fence.after_effect(&effect, &digest(&serde_json::to_vec(&service.proof)?))?;
}
let proofs = self.proofs();
let stopped = Stopped {
pins: self.pins,
configurations: [
proofs[0].configuration.clone(),
proofs[1].configuration.clone(),
],
};
// Held image handles intentionally close here, after BOTH exact original
// processes have terminated. Neither PID reuse nor SCM state suffices.
drop(self.held);
stopped.check(budget)?;
Ok(stopped)
}
}
/// Only the actual completed stop sequence constructs this token. It is not a
/// closed-reader census or a helper-ledger lock; those remain separate gates.
pub struct Stopped {
pins: [PeerPin; 2],
configurations: [Configuration; 2],
}
impl Stopped {
pub fn check(&self, budget: &Budget<'_>) -> Result<()> {
budget.check()?;
for (i, service) in [Service::Agent, Service::Helper].into_iter().enumerate() {
let handle = handle(
service,
SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG | SERVICE_ENUMERATE_DEPENDENTS,
)?;
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"
);
}
Ok(())
}
/// Caller MUST commit the original ledger-return/start-reservation before
/// dropping its guard and calling this. Helper starts before agent. This
/// function never retries a failed or uncertain native start request.
pub fn start(
self,
replacement_pins: [PeerPin; 2],
budget: &Budget<'_>,
fence: &mut impl DurableEffectFence,
) -> Result<Running> {
self.check(budget)?;
let mut started = Vec::with_capacity(2);
for (i, service) in [(1, Service::Helper), (0, Service::Agent)] {
replacement_pins[i].validate(service == Service::Helper)?;
ensure!(
replacement_pins[i].binary == self.pins[i].binary
&& replacement_pins[i].service_name == self.pins[i].service_name
&& replacement_pins[i].service_sid == self.pins[i].service_sid
&& replacement_pins[i].user_sid == self.pins[i].user_sid,
"UPDATE_REPLACEMENT_SERVICE_IDENTITY"
);
let handle = handle(
service,
SERVICE_QUERY_STATUS
| SERVICE_QUERY_CONFIG
| SERVICE_ENUMERATE_DEPENDENTS
| SERVICE_START,
)?;
ensure!(
configuration(&handle, service, &replacement_pins[i])? == self.configurations[i],
"UPDATE_SERVICE_CONFIG_CHANGED"
);
let effect = Effect::StartService { service };
fence.before_effect(&effect)?;
budget.check()?;
ensure!(
status(&handle)?.dwCurrentState == SERVICE_STOPPED,
"UPDATE_START_ALREADY_RUNNING"
);
ensure!(
unsafe { StartServiceW(handle.0, 0, ptr::null()) } != 0,
"UPDATE_START_REQUEST_UNCERTAIN"
);
loop {
budget.check()?;
let state = status(&handle)?;
if state.dwCurrentState == SERVICE_RUNNING {
break;
}
ensure!(
state.dwCurrentState == SERVICE_START_PENDING,
"UPDATE_START_STATE_UNCERTAIN"
);
thread::sleep(Duration::from_millis(20));
}
let held = observe(service, &replacement_pins[i], budget)?;
fence.after_effect(&effect, &digest(&serde_json::to_vec(&held.proof)?))?;
started.push(held);
}
started.reverse();
let mut running = Running {
pins: replacement_pins,
held: started,
};
running.check(budget)?;
Ok(running)
}
}
impl Proof {
pub fn started(&self) -> StartedService {
StartedService {
service: self.configuration.service.handoff_service(),
process: self.process.clone(),
}
}
}
@@ -0,0 +1,540 @@
//! Closed Windows code/pin/time-profile rendering, without OS effects.
//!
//! Input bytes must come from protected, independently authenticated original
//! files. Candidate time qualifications must be independently verified by the
//! embedding admission worker BEFORE offering a release. This pure renderer
//! binds their exact bytes/hashes; parsing a receipt hash does not qualify code.
use super::valid_digest;
use crate::signed_clock::{ActiveGuestOperation, TrustedOsConfiguration, TrustedPlatform};
use anyhow::{Result, ensure};
use rmm_agent_core::{
auth::Binding,
crypto::{DalekVerifier, Ed25519Verifier},
};
use rmm_domain::{
agent_update::{PeerPinTransition, WindowsTimeProfileTransition},
jobs::{PrivilegedScriptProfile, hash},
};
use serde::{Deserialize, Serialize};
use serde_json::value::RawValue;
use std::path::PathBuf;
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Peer {
service_name: String,
service_sid: String,
user_sid: String,
binary: PathBuf,
binary_sha256: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Rule {
name: String,
binary: PathBuf,
binary_sha256: String,
}
/// Versioned snapshot of Settings' SERIALIZATION field order. No new rights,
/// service rules, reboot setting or interpreter policy can be introduced here.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Settings {
schema_version: u32,
binding: Binding,
agent: Peer,
helper: Peer,
allowed_services: Vec<Rule>,
max_runtime_seconds: u32,
enable_effects: bool,
allow_reboot: bool,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "strict_hashes"
)]
allowed_msi_recipe_sha256: Option<Vec<String>>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "rmm_domain::jobs::deserialize_script_profiles"
)]
allowed_script_profiles: Option<Vec<PrivilegedScriptProfile>>,
}
fn strict_hashes<'de, D: serde::Deserializer<'de>>(
d: D,
) -> std::result::Result<Option<Vec<String>>, D::Error> {
Vec::<String>::deserialize(d).map(Some)
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Pin {
schema_version: u32,
binding: Binding,
policy_sha256: String,
agent: Peer,
helper: Peer,
}
#[derive(Deserialize)]
struct PeerSpan<'a> {
#[serde(borrow)]
binary_sha256: &'a RawValue,
}
#[derive(Deserialize)]
struct Spans<'a> {
#[serde(borrow)]
agent: PeerSpan<'a>,
#[serde(borrow)]
helper: PeerSpan<'a>,
#[serde(default, borrow)]
policy_sha256: Option<&'a RawValue>,
}
pub struct CodePairTransition {
proof: PeerPinTransition,
settings: Vec<u8>,
pin: Vec<u8>,
time_profile: Vec<u8>,
}
impl CodePairTransition {
pub fn proof(&self) -> &PeerPinTransition {
&self.proof
}
pub fn settings_bytes(&self) -> &[u8] {
&self.settings
}
pub fn pin_bytes(&self) -> &[u8] {
&self.pin
}
pub fn time_profile_bytes(&self) -> &[u8] {
&self.time_profile
}
}
pub struct Inputs<'a> {
pub settings: &'a [u8],
pub pin: &'a [u8],
pub time_profile: &'a [u8],
pub qualified_candidate_time_profile: &'a [u8],
pub target_agent_sha256: &'a str,
pub target_helper_sha256: &'a str,
}
fn bound_peer(peer: &Peer, helper: bool) -> bool {
let service = if helper {
super::Service::Helper
} else {
super::Service::Agent
};
let role = if helper {
super::Role::Helper
} else {
super::Role::Agent
};
peer.service_name == service.name()
&& peer.user_sid == if helper { "S-1-5-18" } else { "S-1-5-19" }
&& peer.service_sid.starts_with("S-1-5-80-")
&& peer.binary.to_str() == Some(role.target())
&& valid_digest(&peer.binary_sha256)
}
fn time_configuration(
bytes: &[u8],
binding: &Binding,
agent: &str,
helper: &str,
) -> Result<TrustedOsConfiguration> {
let value: TrustedOsConfiguration = serde_json::from_slice(bytes)?;
let profile = &value.trusted_os_active_guest;
ensure!(
value.schema_version == 2
&& value.key_generation > 0
&& !value.server_instance.is_nil()
&& serde_json::to_value(&value.binding)? == serde_json::to_value(binding)?
&& !value.public_keys_hex.is_empty()
&& value.public_keys_hex.len() <= 8
&& matches!(
profile.operating_assumption,
ActiveGuestOperation::NoPauseSaveRestoreSnapshotMigrationHostSuspend
)
&& matches!(profile.platform, TrustedPlatform::KvmQemuHypervClock)
&& valid_digest(&profile.platform_provenance_sha256)
&& profile.qualifications.len() == 2,
"UPDATE_TIME_PROFILE_BINDING"
);
for (id, public) in &value.public_keys_hex {
ensure!(
!id.is_empty()
&& id.len() <= 64
&& id
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"_-".contains(&b))
&& valid_digest(public)
&& public != &binding.public_key_hex,
"UPDATE_TIME_PROFILE_KEY"
);
let key = (0..32)
.map(|i| u8::from_str_radix(&public[i * 2..i * 2 + 2], 16))
.collect::<std::result::Result<Vec<_>, _>>()?;
ensure!(DalekVerifier.validate_key(&key)?, "UPDATE_TIME_PROFILE_KEY");
}
for (role, image) in [
(rmm_time_attestation::Role::Agent, agent),
(rmm_time_attestation::Role::SystemHelper, helper),
] {
let found: Vec<_> = profile
.qualifications
.iter()
.filter(|q| q.role == role)
.collect();
ensure!(
found.len() == 1
&& found[0].binary_sha256 == image
&& valid_digest(&found[0].qualification_sha256),
"UPDATE_TIME_PROFILE_QUALIFICATION"
);
}
Ok(value)
}
pub fn render(input: Inputs<'_>) -> Result<CodePairTransition> {
for raw in [
input.settings,
input.pin,
input.time_profile,
input.qualified_candidate_time_profile,
] {
ensure!(
!raw.is_empty() && raw.len() <= 32768,
"UPDATE_WINDOWS_RENDER_LIMIT"
);
}
ensure!(
valid_digest(input.target_agent_sha256) && valid_digest(input.target_helper_sha256),
"UPDATE_WINDOWS_IMAGE"
);
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
&& (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())
&& bound_peer(&settings.agent, false)
&& bound_peer(&settings.helper, true)
&& !settings.binding.tenant_id.is_nil()
&& !settings.binding.asset_id.is_nil()
&& !settings.binding.agent_id.is_nil()
&& settings.binding.enrollment_generation > 0
&& settings.binding.assignment_version > 0
&& pin.schema_version == 1
&& pin.policy_sha256 == hash(&serde_json::to_vec(&settings)?)
&& serde_json::to_value(&pin.binding)? == serde_json::to_value(&settings.binding)?
&& serde_json::to_value(&pin.agent)? == serde_json::to_value(&settings.agent)?
&& serde_json::to_value(&pin.helper)? == serde_json::to_value(&settings.helper)?,
"UPDATE_WINDOWS_ORIGINAL_PAIR"
);
let old_agent = settings.agent.binary_sha256.clone();
let old_helper = settings.helper.binary_sha256.clone();
let old_time = time_configuration(
input.time_profile,
&settings.binding,
&old_agent,
&old_helper,
)?;
let candidate = time_configuration(
input.qualified_candidate_time_profile,
&settings.binding,
input.target_agent_sha256,
input.target_helper_sha256,
)?;
let mut unchanged_candidate = serde_json::to_value(&candidate)?;
unchanged_candidate["trusted_os_active_guest"]["qualifications"] =
serde_json::to_value(&old_time.trusted_os_active_guest.qualifications)?;
ensure!(
unchanged_candidate == serde_json::to_value(&old_time)?,
"UPDATE_TIME_TRUST_OR_PLATFORM_CHANGE"
);
for new in &candidate.trusted_os_active_guest.qualifications {
let old = old_time
.trusted_os_active_guest
.qualifications
.iter()
.find(|q| q.role == new.role)
.ok_or_else(|| anyhow::anyhow!("UPDATE_TIME_ROLE"))?;
ensure!(
new.binary_sha256 == old.binary_sha256
|| new.qualification_sha256 != old.qualification_sha256,
"UPDATE_TIME_OLD_QUALIFICATION_REUSED"
);
}
settings.agent.binary_sha256 = input.target_agent_sha256.into();
settings.helper.binary_sha256 = input.target_helper_sha256.into();
pin.agent.binary_sha256 = input.target_agent_sha256.into();
pin.helper.binary_sha256 = input.target_helper_sha256.into();
pin.policy_sha256 = hash(&serde_json::to_vec(&settings)?);
let settings_spans: Spans<'_> = serde_json::from_slice(input.settings)?;
let pin_spans: Spans<'_> = serde_json::from_slice(input.pin)?;
let settings_bytes = replace(
input.settings,
vec![
(
settings_spans.agent.binary_sha256,
input.target_agent_sha256,
),
(
settings_spans.helper.binary_sha256,
input.target_helper_sha256,
),
],
)?;
let pin_bytes = replace(
input.pin,
vec![
(pin_spans.agent.binary_sha256, input.target_agent_sha256),
(pin_spans.helper.binary_sha256, input.target_helper_sha256),
(
pin_spans
.policy_sha256
.ok_or_else(|| anyhow::anyhow!("UPDATE_PIN_POLICY_HASH"))?,
&pin.policy_sha256,
),
],
)?;
// Confirm the span edits exactly equal the typed, closed intended objects.
ensure!(
serde_json::to_value(serde_json::from_slice::<Settings>(&settings_bytes)?)?
== serde_json::to_value(&settings)?
&& serde_json::to_value(serde_json::from_slice::<Pin>(&pin_bytes)?)?
== serde_json::to_value(&pin)?,
"UPDATE_WINDOWS_RENDER_CHANGED"
);
let quals = &candidate.trusted_os_active_guest.qualifications;
let agent = quals
.iter()
.find(|q| q.role == rmm_time_attestation::Role::Agent)
.unwrap();
let helper = quals
.iter()
.find(|q| q.role == rmm_time_attestation::Role::SystemHelper)
.unwrap();
let transition = PeerPinTransition::WindowsCodePairV1 {
old_settings_sha256: hash(input.settings),
new_settings_sha256: hash(&settings_bytes),
old_pin_sha256: hash(input.pin),
new_pin_sha256: hash(&pin_bytes),
time_profile: Some(WindowsTimeProfileTransition {
schema_version: 1,
old_time_profile_sha256: hash(input.time_profile),
new_time_profile_sha256: hash(input.qualified_candidate_time_profile),
agent_qualification_sha256: agent.qualification_sha256.clone(),
helper_qualification_sha256: helper.qualification_sha256.clone(),
}),
};
Ok(CodePairTransition {
proof: transition,
settings: settings_bytes,
pin: pin_bytes,
time_profile: input.qualified_candidate_time_profile.to_vec(),
})
}
fn replace(bytes: &[u8], values: Vec<(&RawValue, &str)>) -> Result<Vec<u8>> {
let mut spans = Vec::new();
for (raw, replacement) in values {
let raw = raw.get();
let start = (raw.as_ptr() as usize)
.checked_sub(bytes.as_ptr() as usize)
.ok_or_else(|| anyhow::anyhow!("UPDATE_RENDER_SPAN"))?;
let end = start
.checked_add(raw.len())
.ok_or_else(|| anyhow::anyhow!("UPDATE_RENDER_SPAN"))?;
ensure!(
bytes.get(start..end) == Some(raw.as_bytes())
&& raw.len() == 66
&& raw.starts_with('"')
&& raw.ends_with('"')
&& valid_digest(&raw[1..65])
&& valid_digest(replacement),
"UPDATE_RENDER_HASH_ENCODING"
);
spans.push((start, end, format!("\"{replacement}\"")));
}
spans.sort_by_key(|s| s.0);
ensure!(
spans.windows(2).all(|p| p[0].1 <= p[1].0),
"UPDATE_RENDER_OVERLAP"
);
let mut result = Vec::with_capacity(bytes.len());
let mut cursor = 0;
for (start, end, value) in spans {
result.extend_from_slice(&bytes[cursor..start]);
result.extend_from_slice(value.as_bytes());
cursor = end;
}
result.extend_from_slice(&bytes[cursor..]);
Ok(result)
}
#[cfg(test)]
mod tests {
use super::*;
use ed25519_dalek::SigningKey;
use serde_json::{Value, json};
struct Fixture {
settings: Vec<u8>,
pin: Vec<u8>,
time: Vec<u8>,
candidate: Vec<u8>,
}
fn fixture() -> Fixture {
let public = |byte| {
SigningKey::from_bytes(&[byte; 32])
.verifying_key()
.to_bytes()
.iter()
.map(|b| format!("{b:02x}"))
.collect::<String>()
};
let binding = json!({"tenant_id":uuid::Uuid::from_u128(1),"asset_id":uuid::Uuid::from_u128(2),
"agent_id":uuid::Uuid::from_u128(3),"enrollment_generation":1,"assignment_version":1,"public_key_hex":public(17)});
let peer = |helper: bool| {
json!({"service_name":if helper {super::super::Service::Helper.name()}else{super::super::Service::Agent.name()},
"service_sid":if helper {"S-1-5-80-1-2-3-4-5"}else{"S-1-5-80-6-7-8-9-10"},
"user_sid":if helper{"S-1-5-18"}else{"S-1-5-19"},
"binary":if helper {super::super::Role::Helper.target()}else{super::super::Role::Agent.target()},
"binary_sha256":if helper{"cd".repeat(32)}else{"ab".repeat(32)}})
};
let settings = json!({"schema_version":3,"binding":binding,"agent":peer(false),"helper":peer(true),
"allowed_services":[{"name":"RmmDiscoveryFixtureUpdater","binary":"C:\\Program Files\\RustDiscoveryFixtures\\fixture.exe","binary_sha256":"ab".repeat(32)}],
"max_runtime_seconds":120,"enable_effects":true,"allow_reboot":false,
"allowed_msi_recipe_sha256":[],"allowed_script_profiles":["full_maintenance_v1"]});
let typed: Settings = serde_json::from_value(settings.clone()).unwrap();
let pin = json!({"schema_version":1,"binding":binding,"policy_sha256":hash(&serde_json::to_vec(&typed).unwrap()),"agent":peer(false),"helper":peer(true)});
let time = json!({"schema_version":2,"key_generation":1,"server_instance":uuid::Uuid::from_u128(4),"binding":binding,
"public_keys_hex":{"development_time_v1":public(19)},"trusted_os_active_guest":{
"operating_assumption":"active_guest_no_pause_save_restore_snapshot_migration_host_suspend","platform":"kvm_qemu_hypervclock",
"platform_provenance_sha256":"01".repeat(32),"qualifications":[
{"role":"agent","binary_sha256":"ab".repeat(32),"qualification_sha256":"02".repeat(32)},
{"role":"system_helper","binary_sha256":"cd".repeat(32),"qualification_sha256":"03".repeat(32)}]}});
let mut candidate = time.clone();
candidate["trusted_os_active_guest"]["qualifications"][0]["binary_sha256"] =
json!("ef".repeat(32));
candidate["trusted_os_active_guest"]["qualifications"][0]["qualification_sha256"] =
json!("04".repeat(32));
candidate["trusted_os_active_guest"]["qualifications"][1]["binary_sha256"] =
json!("ac".repeat(32));
candidate["trusted_os_active_guest"]["qualifications"][1]["qualification_sha256"] =
json!("05".repeat(32));
Fixture {
settings: serde_json::to_vec_pretty(&settings).unwrap(),
pin: serde_json::to_vec_pretty(&pin).unwrap(),
time: serde_json::to_vec_pretty(&time).unwrap(),
candidate: serde_json::to_vec_pretty(&candidate).unwrap(),
}
}
fn render_fixture(f: &Fixture) -> Result<CodePairTransition> {
render(Inputs {
settings: &f.settings,
pin: &f.pin,
time_profile: &f.time,
qualified_candidate_time_profile: &f.candidate,
target_agent_sha256: &"ef".repeat(32),
target_helper_sha256: &"ac".repeat(32),
})
}
#[test]
fn windows_transition_preserves_raw_policy_bytes_and_binds_prequalified_time_profile() {
let f = fixture();
let result = render_fixture(&f).unwrap();
let old: Settings = serde_json::from_slice(&f.settings).unwrap();
let new: Settings = serde_json::from_slice(result.settings_bytes()).unwrap();
assert_eq!(
new.allowed_services[0].binary_sha256,
old.agent.binary_sha256
);
let reversed = String::from_utf8(result.settings_bytes().to_vec())
.unwrap()
.replace(&"ef".repeat(32), &"ab".repeat(32))
.replace(&"ac".repeat(32), &"cd".repeat(32));
assert_eq!(reversed.as_bytes(), f.settings);
assert_eq!(result.time_profile_bytes(), f.candidate);
let new_pin: Pin = serde_json::from_slice(result.pin_bytes()).unwrap();
assert_eq!(
new_pin.policy_sha256,
hash(&serde_json::to_vec(&new).unwrap())
);
let PeerPinTransition::WindowsCodePairV1 {
time_profile: Some(t),
..
} = result.proof()
else {
panic!("fixed clock transition")
};
assert_eq!(t.old_time_profile_sha256, hash(&f.time));
assert_eq!(t.new_time_profile_sha256, hash(&f.candidate));
assert_eq!(t.agent_qualification_sha256, "04".repeat(32));
#[cfg(windows)]
{
// Both OS-native production codecs must derive the SAME policy
// hash; a mirrored test-only serialization cannot satisfy this.
let actual: crate::helper_system::Settings =
serde_json::from_slice(result.settings_bytes()).unwrap();
assert_eq!(actual.policy_sha256().unwrap(), new_pin.policy_sha256);
let _: crate::helper_ipc::Pin = serde_json::from_slice(result.pin_bytes()).unwrap();
}
}
#[test]
fn windows_transition_denies_changed_time_trust_reused_qualification_and_unbound_pin() {
for change in [
"key",
"platform",
"qualification",
"role",
"extra",
"pin",
"null",
] {
let mut f = fixture();
if change == "pin" {
let mut value: Value = serde_json::from_slice(&f.pin).unwrap();
value["policy_sha256"] = json!("ff".repeat(32));
f.pin = serde_json::to_vec(&value).unwrap();
} else if change == "null" {
let mut value: Value = serde_json::from_slice(&f.settings).unwrap();
value["allowed_msi_recipe_sha256"] = Value::Null;
f.settings = serde_json::to_vec(&value).unwrap();
} else {
let mut value: Value = serde_json::from_slice(&f.candidate).unwrap();
match change {
"key" => value["key_generation"] = json!(2),
"platform" => {
value["trusted_os_active_guest"]["platform_provenance_sha256"] =
json!("ff".repeat(32))
}
"qualification" => {
value["trusted_os_active_guest"]["qualifications"][0]["qualification_sha256"] =
json!("02".repeat(32))
}
"role" => {
value["trusted_os_active_guest"]["qualifications"][1]["role"] =
json!("agent")
}
_ => value["trusted_os_active_guest"]["assume_ready"] = json!(true),
}
f.candidate = serde_json::to_vec(&value).unwrap();
}
assert!(render_fixture(&f).is_err(), "changed field {change}");
}
let f = fixture();
let mut value: Value = serde_json::from_slice(&f.pin).unwrap();
value["helper"]["binary_sha256"] = json!("ff".repeat(32));
assert!(
render(Inputs {
settings: &f.settings,
pin: &serde_json::to_vec(&value).unwrap(),
time_profile: &f.time,
qualified_candidate_time_profile: &f.candidate,
target_agent_sha256: &"ef".repeat(32),
target_helper_sha256: &"ac".repeat(32)
})
.is_err()
);
}
}