diff --git a/crates/agent-core/tests/support/windows_review_fixture.rs b/crates/agent-core/tests/support/windows_review_fixture.rs index 7772a35..15b1b33 100644 --- a/crates/agent-core/tests/support/windows_review_fixture.rs +++ b/crates/agent-core/tests/support/windows_review_fixture.rs @@ -13,6 +13,12 @@ use rmm_protocol::{Envelope, Payload, SyncRequest, SyncResponse}; use rusqlite::{Connection, params}; use uuid::Uuid; pub fn verified_pair() -> Result<(Connection, Connection, Connection, Binding, SigningKey)> { + verified_pair_for(Uuid::new_v4(), Uuid::new_v4()) +} +pub fn verified_pair_for( + tenant_id: Uuid, + asset_id: Uuid, +) -> Result<(Connection, Connection, Connection, Binding, SigningKey)> { let a = Connection::open_in_memory()?; let l = Connection::open_in_memory()?; let h = Connection::open_in_memory()?; @@ -29,9 +35,9 @@ pub fn verified_pair() -> Result<(Connection, Connection, Connection, Binding, S let peer = Uuid::new_v4(); let key = SigningKey::from_bytes(&[13; 32]); // Public deterministic fixture only. let binding = Binding { - tenant_id: Uuid::new_v4(), + tenant_id, agent_id: Uuid::parse_str(AGENT)?, - asset_id: Uuid::new_v4(), + asset_id, assignment_version: 1, enrollment_generation: 1, public_key_hex: key diff --git a/crates/agent-windows/examples/windows_reviewed_recovery.rs b/crates/agent-windows/examples/windows_reviewed_recovery.rs index 1241e39..bfdcea5 100644 --- a/crates/agent-windows/examples/windows_reviewed_recovery.rs +++ b/crates/agent-windows/examples/windows_reviewed_recovery.rs @@ -166,11 +166,19 @@ mod windows { args.len() == 1 && matches!( args[0].as_str(), - "prepare" | "read" | "verify-receipt" | "apply" + "prepare" + | "read" + | "verify-receipt" + | "apply" + | "echo-read" + | "echo-verify-receipt" + | "echo-apply" ), "use prepare, read, verify-receipt or apply" ); - let apply = args[0] == "apply"; + let echo = args[0].starts_with("echo-"); + let mode = args[0].strip_prefix("echo-").unwrap_or(&args[0]); + let apply = mode == "apply"; let key_readers = [ipc::service_sid(SERVICE_NAME)?]; let _root = PinnedFile::open(Path::new(ROOT), true, &key_readers, &[], false)?; let mut binding_file = PinnedFile::open( @@ -196,16 +204,28 @@ mod windows { &[], false, )?; - ensure!( - config.sha256()? == PASSIVE, - "operator must restore passive config first" - ); + if echo { + let expected = serde_json::json!({ + "server_name":"discovery.ease-technologies.de","connect_address":"88.99.80.202:443", + "ca_file":Path::new(ROOT).join("server-ca.pem"),"state_directory":STATE, + "enrollment_token_file":Path::new(STATE).join("enrollment.token"),"transport":"auto", + "job_binding_file":Path::new(ROOT).join("binding.json"),"enable_jobs":true, + "windows_execution_profile":"powershell_51_remote_signed","windows_echo_probe_only":true}); + let actual: serde_json::Value = + serde_json::from_slice(&data(&mut config.file, 32768)?)?; + ensure!(actual == expected, "expected exact Echo-only configuration"); + } else { + ensure!( + config.sha256()? == PASSIVE, + "operator must restore passive config first" + ); + } let boot = tokio::runtime::Builder::new_current_thread() .enable_all() .build()? .block_on(native::boot_id())?; ensure!(boot == BOOT, "unexpected Windows boot"); - let review = if matches!(args[0].as_str(), "verify-receipt" | "apply") { + let review = if matches!(mode, "verify-receipt" | "apply") { let _folder = PinnedFile::open( Path::new(RECEIPT).parent().context("bootstrap path")?, true, @@ -214,12 +234,13 @@ mod windows { false, )?; let mut file = PinnedFile::open(Path::new(RECEIPT), false, &[], &[], false)?; - Some(Reviewed::verify( - data(&mut file.file, 65536)?, - &agent, - &settings.binding, - &witness, - )?) + let bytes = data(&mut file.file, 65536)?; + Some(if echo { + let scope = rmm_agent_windows::echo_probe::protected_scope()?; + Reviewed::verify_echo(bytes, &agent, &settings.binding, &witness, &scope)? + } else { + Reviewed::verify(bytes, &agent, &settings.binding, &witness)? + }) } else { None }; @@ -315,7 +336,10 @@ mod windows { ); if let Some(review) = &review { review.timely(chrono::Utc::now())?; - println!("valid human review for the verified local history"); + println!( + "valid {} review for the verified local history", + if echo { "simulated Echo-only" } else { "human" } + ); } println!( "verified contracted history; fault={}", diff --git a/crates/agent-windows/examples/windows_reviewed_recovery/local.rs b/crates/agent-windows/examples/windows_reviewed_recovery/local.rs index 05df041..c8594c8 100644 --- a/crates/agent-windows/examples/windows_reviewed_recovery/local.rs +++ b/crates/agent-windows/examples/windows_reviewed_recovery/local.rs @@ -13,22 +13,34 @@ use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params, types use serde_json::Value; use sha2::{Digest, Sha256}; +use rmm_agent_windows::echo_probe; +use rmm_domain::windows_echo_probe::{ProbeReceipt, ProbeScope}; +use uuid::Uuid; +const ECHO_AUDIT: &str = "windows_echo_checkpoint_recovery"; const AUDIT: &str = "windows_human_checkpoint_recovery"; const AUDIT_SQL: &str = "CREATE TABLE windows_human_checkpoint_recovery(id INTEGER PRIMARY KEY CHECK(id=1),review_id TEXT NOT NULL,receipt_id TEXT NOT NULL,old_fault TEXT NOT NULL,original_receipt BLOB NOT NULL,inventory_sha256 TEXT NOT NULL,applied_at TEXT NOT NULL)"; +struct ReviewFields { + request_id: Uuid, + receipt_id: Uuid, + issued_at: DateTime, + valid_until: DateTime, + witness: Value, +} pub struct Reviewed { - receipt: Receipt, + receipt: ReviewFields, original: Vec, + echo: Option<(ProbeScope, Vec)>, } impl Reviewed { - pub fn verify( - raw: Vec, + fn signed( + raw: &[u8], agent: &Binding, helper: &Binding, expected: &Value, - ) -> Result { + ) -> Result { ensure!(raw.len() <= 65536, "recovery envelope size"); - let envelope: SignedReceipt = serde_json::from_slice(&raw)?; + let envelope: SignedReceipt = serde_json::from_slice(raw)?; ensure!( envelope.payload.len() <= 16384 && envelope.signature.len() == 64, "recovery signature size" @@ -49,6 +61,15 @@ impl Reviewed { "recovery signature" ); } + Ok(envelope) + } + pub fn verify( + raw: Vec, + agent: &Binding, + helper: &Binding, + expected: &Value, + ) -> Result { + let envelope = Self::signed(&raw, agent, helper, expected)?; let receipt: Receipt = serde_json::from_slice(&envelope.payload)?; // Historical validity is sufficient for looking up a previously committed receipt. ensure!( @@ -56,8 +77,40 @@ impl Reviewed { "historical human review" ); Ok(Self { - receipt, + receipt: ReviewFields { + request_id: receipt.request_id, + receipt_id: receipt.receipt_id, + issued_at: receipt.issued_at, + valid_until: receipt.valid_until, + witness: receipt.witness, + }, original: raw, + echo: None, + }) + } + pub fn verify_echo( + raw: Vec, + agent: &Binding, + helper: &Binding, + expected: &Value, + configured: &ProbeScope, + ) -> Result { + let envelope = Self::signed(&raw, agent, helper, expected)?; + let r: ProbeReceipt = serde_json::from_slice(&envelope.payload)?; + ensure!( + r.matches_reviewed_witness(expected, r.issued_at) && &r.scope == configured, + "simulated echo scope/receipt" + ); + Ok(Self { + receipt: ReviewFields { + request_id: r.request_id, + receipt_id: r.receipt_id, + issued_at: r.issued_at, + valid_until: r.valid_until, + witness: r.witness, + }, + original: raw, + echo: Some((r.scope, r.job_payload_bytes)), }) } pub fn timely(&self, now: DateTime) -> Result<()> { @@ -84,7 +137,11 @@ fn include(hash: &mut Sha256, tag: u8, bytes: &[u8]) { } /// Compare the full logical contents and schema, excluding only the receipt and normalized fault. +#[cfg(test)] fn inventory(db: &Connection) -> Result { + inventory_for(db, false) +} +fn inventory_for(db: &Connection, echo: bool) -> Result { let check: String = db.query_row("PRAGMA integrity_check", [], |r| r.get(0))?; ensure!(check == "ok", "journal integrity"); let mut statement = db.prepare( @@ -97,6 +154,9 @@ fn inventory(db: &Connection) -> Result { let kind: String = row.get(0)?; let name: String = row.get(1)?; let table: String = row.get(2)?; + if echo && (echo_probe::OBJECTS.contains(&name.as_str()) || name == ECHO_AUDIT) { + continue; + } let sql: Option = row.get(3)?; ensure!( matches!(kind.as_str(), "table" | "index" | "trigger") @@ -174,25 +234,37 @@ impl LocalJournals<'_> { let tx = self .agent .transaction_with_behavior(TransactionBehavior::Immediate)?; + let echo = reviewed.echo.is_some(); + let audit = if echo { ECHO_AUDIT } else { AUDIT }; + let ddl = AUDIT_SQL.replace(AUDIT, audit); + let other = if echo { AUDIT } else { ECHO_AUDIT }; + ensure!( + !tx.query_row( + "SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE name=?)", + [other], + |r| r.get::<_, bool>(0) + )?, + "another recovery mode already exists" + ); let prior: Option = tx .query_row( "SELECT sql FROM sqlite_schema WHERE name=?1", - [AUDIT], + [audit], |r| r.get(0), ) .optional()?; let applied = prior.is_some(); if let Some(schema) = prior { ensure!( - schema == AUDIT_SQL + schema == ddl && tx.query_row( "SELECT count(*) FROM sqlite_schema WHERE tbl_name=?1", - [AUDIT], + [audit], |r| r.get::<_, usize>(0) )? == 1, "foreign archive" ); - let identical:bool=tx.query_row("SELECT EXISTS(SELECT 1 FROM windows_human_checkpoint_recovery WHERE id=1 AND review_id=? AND receipt_id=? AND old_fault=? AND original_receipt=?)",params![reviewed.receipt.request_id.to_string(),reviewed.receipt.receipt_id.to_string(),FAULT,reviewed.original],|r|r.get(0))?; + let identical:bool=tx.query_row(&format!("SELECT EXISTS(SELECT 1 FROM {audit} WHERE id=1 AND review_id=? AND receipt_id=? AND old_fault=? AND original_receipt=?)"),params![reviewed.receipt.request_id.to_string(),reviewed.receipt.receipt_id.to_string(),FAULT,reviewed.original],|r|r.get(0))?; ensure!(identical, "another recovery already exists"); } let original = verify_local_history( @@ -241,18 +313,27 @@ impl LocalJournals<'_> { } if applied { let saved: String = tx.query_row( - "SELECT inventory_sha256 FROM windows_human_checkpoint_recovery WHERE id=1", + &format!("SELECT inventory_sha256 FROM {audit} WHERE id=1"), [], |r| r.get(0), )?; - ensure!(inventory(&tx)? == saved, "archive inventory changed"); + if let Some((scope, bytes)) = &reviewed.echo { + echo_probe::check(&tx, scope, bytes, &reviewed.original)?; + } + ensure!( + inventory_for(&tx, echo)? == saved, + "archive inventory changed" + ); return Ok("already applied"); } reviewed.timely(now())?; - let before = inventory(&tx)?; - tx.execute(AUDIT_SQL, [])?; + let before = inventory_for(&tx, echo)?; + if let Some((scope, bytes)) = &reviewed.echo { + echo_probe::install(&tx, scope, bytes, &reviewed.original)?; + } + tx.execute(&ddl, [])?; tx.execute( - "INSERT INTO windows_human_checkpoint_recovery VALUES(1,?,?,?,?,?,?)", + &format!("INSERT INTO {audit} VALUES(1,?,?,?,?,?,?)"), params![ reviewed.receipt.request_id.to_string(), reviewed.receipt.receipt_id.to_string(), @@ -269,7 +350,7 @@ impl LocalJournals<'_> { |r| r.get(0), )?; ensure!( - cleared && inventory(&tx)? == before, + cleared && inventory_for(&tx, echo)? == before, "unrelated journal data changed" ); reviewed.timely(now())?; @@ -294,7 +375,7 @@ mod tests { "/../agent-core/tests/support/windows_review_fixture.rs" )); } - fn signed(r: &Receipt, k: &SigningKey) -> Result> { + fn signed(r: &impl serde::Serialize, k: &SigningKey) -> Result> { let payload = serde_json::to_vec(r)?; Ok(serde_json::to_vec(&SignedReceipt { signature: k.sign(&payload).to_bytes().to_vec(), @@ -302,6 +383,154 @@ mod tests { })?) } #[test] + fn scoped_echo_preserves_journals_and_rejects_other_offers() -> Result<()> { + use rmm_domain::{ + jobs::{Action, JobPayload, PlanPayload, PlannedJob, WindowsExecutionProfile}, + windows_echo_probe as echo, + }; + use rmm_protocol::JobOffer; + let (mut a, l, h, binding, key) = data::verified_pair_for(echo::TENANT, echo::ASSET)?; + a.execute_batch("DROP TABLE job_attempts; CREATE TABLE job_attempts(job TEXT NOT NULL,attempt TEXT NOT NULL,offer BLOB NOT NULL,state TEXT NOT NULL,PRIMARY KEY(job,attempt))")?; + let now = Utc::now(); + let job = JobPayload { + schema_version: 1, + tenant_id: binding.tenant_id, + asset_id: binding.asset_id, + agent_id: binding.agent_id, + 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 + Duration::minutes(15), + max_runtime_seconds: 60, + max_output_bytes: 65536, + }; + let bytes = serde_json::to_vec(&job)?; + let plan = PlanPayload { + schema_version: 1, + plan_id: Uuid::new_v4(), + tenant_id: echo::TENANT, + principal: format!("automation:{}", echo::TENANT), + reason: "fixture".into(), + jobs: vec![PlannedJob { + payload: job.clone(), + job_payload_hash: hash(&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("fixed Echo plan")?; + let mut w = case_witness(); + let (j, p): (String, String) = a.query_row( + "SELECT journal_id,helper_id FROM reconcile_meta WHERE id=1", + [], + |r| Ok((r.get(0)?, r.get(1)?)), + )?; + w["verification_key_id"] = hash(&key.verifying_key().to_bytes()).into(); + w["agent_journal_id"] = j.into(); + w["helper_journal_id"] = p.into(); + w["decisions"] = verify_local_history(&a, &l, &h, &binding, &binding, Some(FAULT))?.into(); + let receipt = ProbeReceipt { + domain: echo::DOMAIN.into(), + schema_version: 1, + request_id: Uuid::new_v4(), + receipt_id: Uuid::new_v4(), + witness: w.clone(), + witness_sha256: inventory_sha256(&w)?, + scope: scope.clone(), + scope_sha256: scope.digest().context("scope digest")?, + job_payload_bytes: bytes.clone(), + key_id: hash(&key.verifying_key().to_bytes()), + issued_at: now, + valid_until: now + Duration::minutes(10), + confirmed_by: echo::TEST_PRINCIPAL.into(), + approval_origin: "dev_test_browser_simulation".into(), + testsimulation: true, + }; + let raw = signed(&receipt, &key)?; + assert!(Reviewed::verify(raw.clone(), &binding, &binding, &w).is_err()); + let mut different = scope.clone(); + different.attempt_id = Uuid::new_v4(); + assert!(Reviewed::verify_echo(raw.clone(), &binding, &binding, &w, &different).is_err()); + let reviewed = Reviewed::verify_echo(raw, &binding, &binding, &w, &scope)?; + let original = inventory(&a)?; + let local = inventory(&l)?; + let helper = inventory(&h)?; + let mut db = LocalJournals { + agent: &mut a, + consumption: &l, + helper: &h, + agent_binding: &binding, + helper_binding: &binding, + }; + assert!(db.apply(&reviewed, || now + Duration::minutes(11)).is_err()); + db.apply(&reviewed, || now)?; + assert_eq!(inventory_for(db.agent, true)?, original); + assert_eq!((inventory(&l)?, inventory(&h)?), (local, helper)); + assert_eq!( + db.apply(&reviewed, || now + Duration::days(1))?, + "already applied" + ); + let offer = JobOffer { + job_id: scope.job_id.to_string(), + attempt_id: scope.attempt_id.to_string(), + authorization_id: Uuid::new_v4().to_string(), + plan_hash: scope.plan_hash.clone(), + job_payload_hash: scope.job_payload_hash.clone(), + payload_bytes: bytes, + }; + assert!(echo_probe::permits_offer(&scope, &offer, &job)); + let store = |o: &JobOffer| { + db.agent.execute( + "INSERT INTO job_attempts VALUES(?,?,?,'accepted')", + params![o.job_id, o.attempt_id, o.encode_to_vec()], + ) + }; + for field in 0..4 { + let mut bad = offer.clone(); + match field { + 0 => bad.attempt_id = Uuid::new_v4().to_string(), + 1 => bad.plan_hash = "0".repeat(64), + 2 => bad.payload_bytes.push(b' '), + _ => bad.job_id = Uuid::new_v4().to_string(), + } + assert!(!echo_probe::permits_offer(&scope, &bad, &job)); + assert!(store(&bad).is_err()); + } + assert_eq!(store(&offer)?, 1); + assert!( + db.agent + .execute("UPDATE job_attempts SET offer=x'01'", []) + .is_err() + ); + assert!( + db.agent + .execute("UPDATE windows_echo_probe_scope SET job='other'", []) + .is_err() + ); + assert!( + db.agent + .execute("DELETE FROM windows_echo_probe_scope", []) + .is_err() + ); + assert!(db.agent.execute("INSERT OR REPLACE INTO windows_echo_probe_scope SELECT * FROM windows_echo_probe_scope",[]).is_err()); + assert!(db.apply(&reviewed, || now).is_err()); + Ok(()) + } + #[test] fn archived_human_review_preserves_both_journals() -> Result<()> { let (mut a, l, h, binding, key) = data::verified_pair()?; let now = Utc::now(); diff --git a/crates/agent-windows/src/echo_probe.rs b/crates/agent-windows/src/echo_probe.rs new file mode 100644 index 0000000..ea40823 --- /dev/null +++ b/crates/agent-windows/src/echo_probe.rs @@ -0,0 +1,177 @@ +//! Persist the exact test offer through service and binary restarts. +//! A subsequent, separate operator decision is needed to change this constraint. +use anyhow::{Context, Result, ensure}; +use prost::Message; +use rmm_domain::{ + jobs::{JobPayload, hash}, + windows_echo_probe::ProbeScope, +}; +use rmm_protocol::JobOffer; +use rusqlite::{Connection, Transaction, params}; +use uuid::Uuid; + +pub const TABLE: &str = "windows_echo_probe_scope"; +pub const OBJECTS: [&str; 6] = [ + TABLE, + "windows_echo_probe_no_replace", + "windows_echo_probe_no_change", + "windows_echo_probe_no_delete", + "windows_echo_probe_offer_insert", + "windows_echo_probe_offer_update", +]; +const POLICY: &str = "CREATE TABLE windows_echo_probe_scope(id INTEGER PRIMARY KEY CHECK(id=1),scope BLOB NOT NULL,review BLOB NOT NULL,job TEXT NOT NULL,attempt TEXT NOT NULL,prefix BLOB NOT NULL,suffix BLOB NOT NULL)"; +const IMMUTABLE: &str = "CREATE TRIGGER windows_echo_probe_no_change BEFORE UPDATE ON windows_echo_probe_scope BEGIN SELECT RAISE(ABORT,'WINDOWS_ECHO_SCOPE_IMMUTABLE'); END"; +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] { + [ + 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}" + ), + format!( + "CREATE TRIGGER windows_echo_probe_offer_update BEFORE UPDATE OF job,attempt,offer ON job_attempts {BOUND}" + ), + ] +} +fn blobs(scope: &ProbeScope, payload: &[u8]) -> Result<(Vec, Vec)> { + let job: JobPayload = serde_json::from_slice(payload)?; + ensure!( + scope.matches_job(&job) + && serde_json::to_vec(&job)? == payload + && hash(payload) == scope.job_payload_hash, + "echo job bytes" + ); + let offer = JobOffer { + job_id: job.job_id.to_string(), + attempt_id: job.attempt_id.to_string(), + authorization_id: Uuid::nil().to_string(), + plan_hash: scope.plan_hash.clone(), + job_payload_hash: scope.job_payload_hash.clone(), + payload_bytes: payload.to_vec(), + }; + // Derive the span of the sole variable protobuf field, whose canonical UUID + // is separately checked by normal offer and signed grant verification. + let base = offer.encode_to_vec(); + let changed = JobOffer { + authorization_id: "x".repeat(36), + ..offer + } + .encode_to_vec(); + let at = base + .iter() + .zip(&changed) + .position(|(a, b)| a != b) + .context("authorization span")?; + ensure!( + base.len() == changed.len() + && base[at..at + 36] == *Uuid::nil().to_string().as_bytes() + && base[at + 36..] == changed[at + 36..], + "authorization wire shape" + ); + Ok((base[..at].to_vec(), base[at + 36..].to_vec())) +} +pub fn install( + tx: &Transaction<'_>, + scope: &ProbeScope, + payload: &[u8], + review: &[u8], +) -> Result<()> { + let (prefix, suffix) = blobs(scope, payload)?; + for sql in schema() { + tx.execute_batch(&sql)?; + } + tx.execute( + "INSERT INTO windows_echo_probe_scope VALUES(1,?,?,?,?,?,?)", + params![ + serde_json::to_vec(scope)?, + review, + scope.job_id.to_string(), + scope.attempt_id.to_string(), + prefix, + suffix + ], + )?; + check(tx, scope, payload, review) +} +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 actual: String = + db.query_row("SELECT sql FROM sqlite_schema WHERE name=?", [name], |r| { + r.get(0) + })?; + ensure!(actual == expected, "echo scope schema"); + } + let matches: bool=db.query_row("SELECT EXISTS(SELECT 1 FROM windows_echo_probe_scope WHERE id=1 AND scope=? AND review=? AND job=? AND attempt=? AND prefix=? AND suffix=?)", params![serde_json::to_vec(scope)?,review,scope.job_id.to_string(),scope.attempt_id.to_string(),prefix,suffix],|r|r.get(0))?; + ensure!(matches, "stored echo scope"); + Ok(()) +} +pub fn installed( + db: &Connection, + binding: &rmm_agent_core::auth::Binding, +) -> Result> { + use rmm_agent_core::crypto::{DalekVerifier, Ed25519Verifier}; + use rmm_domain::{ + checkpoint_repair::SignedReceipt, windows_echo_probe::ProbeReceipt, + windows_sync_history::case_witness, + }; + let objects:u32=db.query_row("SELECT count(*) FROM sqlite_schema WHERE name IN ('windows_echo_probe_scope','windows_echo_checkpoint_recovery')",[],|r|r.get(0))?; + if objects == 0 { + return Ok(None); + } + ensure!(objects == 2, "incomplete Echo scope archive"); + let raw:Vec=db.query_row("SELECT original_receipt FROM windows_echo_checkpoint_recovery WHERE id=1 AND length(original_receipt) BETWEEN 1 AND 65536",[],|r|r.get(0))?; + let envelope: SignedReceipt = serde_json::from_slice(&raw)?; + let r: ProbeReceipt = serde_json::from_slice(&envelope.payload)?; + let b = &binding.public_key_hex; + ensure!(b.len() == 64 && b.is_ascii(), "echo job pin size"); + let key = (0..64) + .step_by(2) + .map(|i| u8::from_str_radix(&b[i..i + 2], 16)) + .collect::, _>>()?; + ensure!( + hash(&key) == r.key_id + && DalekVerifier.verify(&key, &envelope.payload, &envelope.signature)? + && r.matches_reviewed_witness(&case_witness(), r.issued_at), + "Echo archive signature" + ); + check(db, &r.scope, &r.job_payload_bytes, &raw)?; + Ok(Some(r.scope)) +} +pub fn permits_offer(scope: &ProbeScope, offer: &JobOffer, job: &JobPayload) -> bool { + scope.matches_job(job) + && scope.job_id.to_string() == offer.job_id + && scope.attempt_id.to_string() == offer.attempt_id + && scope.plan_hash == offer.plan_hash + && scope.job_payload_hash == offer.job_payload_hash + && hash(&offer.payload_bytes) == scope.job_payload_hash +} + +#[cfg(all(windows, feature = "system-helper"))] +pub fn protected_scope() -> Result { + use crate::{ + SERVICE_NAME, + helper_ipc::{self, PinnedFile}, + }; + use std::{io::Read, path::Path}; + let path = Path::new(r"C:\ProgramData\RustDiscovery\windows-echo-scope.json"); + let readers = [helper_ipc::service_sid(SERVICE_NAME)?]; + let _root = PinnedFile::open( + path.parent().context("echo scope parent")?, + true, + &readers, + &[], + false, + )?; + let mut file = PinnedFile::open(path, false, &readers, &[], false)?; + let mut bytes = Vec::new(); + (&mut file.file).take(8193).read_to_end(&mut bytes)?; + ensure!(bytes.len() <= 8192, "echo scope size"); + file.check()?; + Ok(serde_json::from_slice(&bytes)?) +} diff --git a/crates/agent-windows/src/lib.rs b/crates/agent-windows/src/lib.rs index 3dd66db..14c80aa 100644 --- a/crates/agent-windows/src/lib.rs +++ b/crates/agent-windows/src/lib.rs @@ -5,6 +5,7 @@ pub mod actions; pub mod certificate_rotation; #[cfg(windows)] pub mod clock; +pub mod echo_probe; pub mod event_log; #[cfg(windows)] pub mod event_log_job; diff --git a/crates/agent-windows/src/runtime.rs b/crates/agent-windows/src/runtime.rs index bb71932..714c055 100644 --- a/crates/agent-windows/src/runtime.rs +++ b/crates/agent-windows/src/runtime.rs @@ -39,6 +39,10 @@ struct Config { // Explicit protected opt-in only; this flag never qualifies a clock or pins. #[serde(default)] enable_jobs: bool, + #[serde(default)] + windows_echo_probe_only: bool, + #[serde(skip)] + echo_scope: Option, #[serde( default, deserialize_with = "rmm_domain::jobs::deserialize_windows_execution_profile" @@ -55,6 +59,15 @@ impl Config { fn read(path: &Path) -> Result { let raw = protected_read(path, 32768)?; let config: Self = serde_json::from_slice(&raw)?; + if config.windows_echo_probe_only { + ensure!( + config.profile_enabled( + rmm_domain::jobs::WindowsExecutionProfile::PowerShell51RemoteSigned + ) && config.server_name == "discovery.ease-technologies.de" + && config.state_directory == Path::new(r"C:\ProgramData\RustDiscovery\state"), + "WINDOWS_ECHO_CONFIGURATION" + ); + } if let Some(profile) = config.windows_execution_profile { ensure!( config.profile_enabled(profile), @@ -876,6 +889,15 @@ impl Agent { }) } fn supported_job(&self, job: &rmm_domain::jobs::JobPayload) -> bool { + if self.config.windows_echo_probe_only + && !self + .config + .echo_scope + .as_ref() + .is_some_and(|s| s.matches_job(job)) + { + return false; + } if native::require_local_service().is_err() { return false; } @@ -906,15 +928,28 @@ impl Agent { false } } + fn scope_permits(&self, offer: &JobOffer, job: &rmm_domain::jobs::JobPayload) -> bool { + !self.config.windows_echo_probe_only + || self.config.echo_scope.as_ref().is_some_and(|scope| { + rmm_agent_windows::echo_probe::permits_offer(scope, offer, job) + }) + } fn capabilities(&self) -> Vec { let mut caps: Vec = CAPABILITIES.iter().map(|c| c.to_string()).collect(); - caps.push("agent.update/1".into()); + if self.config.windows_echo_probe_only { + caps.push("windows.echo-probe/1".into()); + } else { + caps.push("agent.update/1".into()); + } if self.config.enable_jobs && cfg!(feature = "system-helper") && self.binding.is_some() && native::require_local_service().is_ok() { - caps.extend(["rmm.sync.v1", "refresh_inventory"].map(str::to_string)); + caps.push("rmm.sync.v1".into()); + if !self.config.windows_echo_probe_only { + caps.push("refresh_inventory".into()); + } if rmm_agent_windows::actions::powershell().is_ok() { caps.extend(["run_script", "script.powershell/1"].map(str::to_string)); if self.config.profile_enabled( @@ -1290,7 +1325,10 @@ impl Agent { return Ok(()); } let (job, grant) = verified_window(&binding, &request, &self.clock)?; - ensure!(self.supported_job(&job), "UNSUPPORTED_CAPABILITY"); + ensure!( + self.supported_job(&job) && self.scope_permits(&offer, &job), + "UNSUPPORTED_CAPABILITY" + ); let system = job.execution_identity == "system"; ensure!( self.ready_identity(generation, system), @@ -1486,6 +1524,7 @@ impl Agent { let work_offer = offer.clone(); let work_grant = grant.clone(); let original_boot = Uuid::parse_str(&self.boot)?; + let echo_scope = self.config.echo_scope.clone(); let worker = tokio::task::spawn_blocking(move || { let mut outcome = (|| -> Result { if !fence.allows(generation, &clock) @@ -1496,6 +1535,12 @@ impl Agent { "START_WINDOW_OR_CLOCK_INVALID_BEFORE_EFFECT", )); } + if let Some(scope) = &echo_scope { + ensure!( + rmm_agent_windows::echo_probe::permits_offer(scope, &work_offer, &job), + "WINDOWS_ECHO_DISPATCH_SCOPE" + ); + } let prepared = match rmm_agent_windows::actions::PreparedAction::prepare( &job, &directory, @@ -1736,6 +1781,7 @@ impl Agent { let now=self.clock.now()?; if let Some(offer)=jobs::next_at(self.journal.connection(),now)? { let job=self.binding.as_ref().context("JOB_BINDING_REQUIRED")?.job(&offer.payload_bytes)?; + ensure!(self.scope_permits(&offer,&job),"WINDOWS_ECHO_OFFER_OUT_OF_SCOPE"); if now>=job.start_before {self.record(generation,&offer,"",jobs::no_start("expired","START_DEADLINE_EXPIRED"))?;needs_sync=true;} else if now-chrono::Duration::seconds(2)>=job.not_before && self.ready_identity(generation,job.execution_identity=="system") { jobs::reserve_request(self.journal.connection(),&offer)?; @@ -1760,7 +1806,8 @@ impl Agent { ensure!(self.config.enable_jobs,"UNSUPPORTED_EXECUTION_CAPABILITY"); let binding=self.binding.as_ref().context("JOB_BINDING_REQUIRED")?.clone(); let accepted=self.envelope(generation,Payload::JobAccepted(JobAccepted{job_id:offer.job_id.clone(),attempt_id:offer.attempt_id.clone(),job_payload_hash:offer.job_payload_hash.clone(),journal_proof:rmm_domain::jobs::hash(&offer.encode_to_vec())}))?; - let supported=self.supported_job(&binding.job(&offer.payload_bytes)?); + let job=binding.job(&offer.payload_bytes)?; + let supported=self.supported_job(&job) && self.scope_permits(&offer,&job); let tx=self.journal.connection_mut().transaction()?; let fresh=jobs::accept(&tx,&binding,&offer,|_|supported)?; jobs::event(&tx,&accepted)?;tx.commit()?;needs_sync|=fresh; @@ -1935,7 +1982,21 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> { for child in fs::read_dir(&config.state_directory)? { let child=child?;native::private_path(&child.path(),child.file_type()?.is_dir())?; } let (ledger,ledger_file)=match &binding {Some(binding)=>{let (db,file)=open_ledger(&config.state_directory,binding)?;(Some(db),Some(file))},None=>(None,None)}; let clock=JobClock::new(config.enable_jobs); - let sync=if config.enable_jobs {binding.clone().map(|binding|reconcile::ClientSync::new(binding).with_helper_identity(reconcile::HelperIdentity::System))} else {None}; + let mut config=config; + if config.enable_jobs { + config.echo_scope=rmm_agent_windows::echo_probe::installed(journal.connection(),binding.as_ref().context("JOB_BINDING_REQUIRED")?)?; + } + if config.enable_jobs && config.echo_scope.is_some() {ensure!(config.windows_echo_probe_only, "WINDOWS_ECHO_PROFILE_REQUIRED");} + if config.windows_echo_probe_only { + ensure!(identity.agent_id==rmm_domain::windows_echo_probe::AGENT.to_string() + && identity.asset_id==rmm_domain::windows_echo_probe::ASSET.to_string() + && boot==rmm_agent_core::windows_sync_history::BOOT,"WINDOWS_ECHO_DEVICE"); + #[cfg(feature="system-helper")] + if let Some(scope)=&config.echo_scope { + ensure!(rmm_agent_windows::echo_probe::protected_scope()? == *scope, "WINDOWS_ECHO_CONFIGURATION_CHANGED"); + } + } + let sync=if config.enable_jobs && (!config.windows_echo_probe_only || config.echo_scope.is_some()) {binding.clone().map(|binding|reconcile::ClientSync::new(binding).with_helper_identity(reconcile::HelperIdentity::System))} else {None}; let (completed_tx,completed_rx)=tokio::sync::mpsc::channel(1); let mut agent = Agent { config, diff --git a/docs/windows-profile-acceptance.md b/docs/windows-profile-acceptance.md index 0b0e039..7bbfc12 100644 --- a/docs/windows-profile-acceptance.md +++ b/docs/windows-profile-acceptance.md @@ -574,3 +574,17 @@ Die gegenwärtige Mitgliedschaft des vorhandenen simulierten Principals wurde auf dem Projektserver lesend als `test_human`, nicht widerrufen und mit `plans:approve` bestätigt. Neue zusätzliche Anmeldedaten sind für diesen begrenzten Testpfad nicht erforderlich. + +Der abgeschlossene Gastbuild hat Agent-SHA-256 +`78c16dcaee53fe9a04d4d84c7a1475330c5a1af30c104f8f9d6f56b5b7408513`. +Der native Operator hat SHA-256 +`72996a5714b29ed96a607cf8516d10a6bc9778e59d8f77a690a863ecbd0cac45`. +Windows-Release und Cross-Clippy mit `-D warnings` bestanden. Der öffentliche +Buildbeleg hat SHA-256 +`44ac22b926b4f860da2280dbcefe0d2b3f22fb07c3ad37e856e435296a75a6b3`. +Die drei unverändert aus dem Referenzcommit eingebundenen Transportmodule +sind ergänzend durch Beleg +`9bb9aa28b9b02e2a05a90546ef0208757ff2c856c848fd1ed33b64a2a313b0ef` +erfasst. Der Windows-Fixture-Nachweis für den passiven Medienbau ist ausdrücklich +eine protokollierte Konsolenablesung mit Foto-/Testbinaryhash, SHA-256 +`4228c05aafb3cbf5d0cbbc06cb211bfb82b0d084e8c509db3afea159bef82c7f`.