//! Read-only S2 acceptance of one completed SYSTEM script. No execution or repair. //! The protected public input contains only original identifiers and digests. #[cfg(all(windows, feature = "system-helper"))] mod platform { use anyhow::{Result, ensure}; use rmm_agent_core::{ auth::{Binding, Outcome, Request}, crypto::DalekVerifier, }; use rmm_agent_windows::helper_ipc::{self as ipc, PinnedFile}; use rmm_domain::jobs::{Action, WindowsExecutionProfile, hash}; use rusqlite::{Connection, OpenFlags, params}; use serde::Deserialize; use serde_json::{Value, json}; use std::{ fs::{File, OpenOptions}, io::Read, os::windows::fs::OpenOptionsExt, path::Path, time::Duration, }; use uuid::Uuid; const INPUT: &str = r"C:\ProgramData\RustDiscoveryBootstrap\system-script-success-witness.json"; const AGENT: &str = "63ea15b2-0643-403d-b5b4-cba1288dbea3"; const EXPECTED: &[u8] = b"Windows-System-MVP:S-1-5-18\r\n"; const PATHS: [&str; 4] = [ r"C:\ProgramData\RustDiscovery\state\telemetry.sqlite", r"C:\ProgramData\RustDiscovery\state\consumption.sqlite", r"C:\ProgramData\RustDiscoverySystem\state\ledger.sqlite", r"C:\ProgramData\RustDiscoverySystem\agent-intents\system-intents.sqlite", ]; #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Input { schema_version: u32, job_id: Uuid, attempt_id: Uuid, grant_id: Uuid, plan_sha256: String, script_sha256: String, agent_binary_sha256: String, helper_binary_sha256: String, helper_policy_sha256: String, } struct Original { _held: File, identity: ipc::FileIdentity, db: Connection, path: &'static str, } impl Original { fn open(path: &'static str) -> Result { let held = OpenOptions::new() .read(true) .share_mode( windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ | windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE, ) .open(path)?; let identity = ipc::file_identity(&held)?; let db = Connection::open_with_flags( path, OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX, )?; db.busy_timeout(Duration::from_millis(500))?; db.execute_batch("PRAGMA trusted_schema=OFF; PRAGMA query_only=ON; BEGIN")?; let value = Self { _held: held, identity, db, path, }; value.check()?; Ok(value) } fn check(&self) -> Result<()> { ensure!( ipc::file_identity(&self._held)? == self.identity && ipc::file_identity(&File::open(self.path)?)? == self.identity, "SUCCESS_ORIGINAL_FILE_REPLACED" ); Ok(()) } } struct Evidence { request: Request, outcome: Vec, boot: Uuid, report: Value, } fn evidence(db: &Connection, binding: &Binding, input: &Input) -> Result { let job_id = input.job_id.to_string(); let attempt_id = input.attempt_id.to_string(); let grant_id = input.grant_id.to_string(); let count: u64 = db.query_row( "SELECT count(*) FROM consumed WHERE job=?1 OR attempt=?2 OR grant_id=?3", params![job_id, attempt_id, grant_id], |r| r.get(0), )?; ensure!(count == 1, "SUCCESS_EXACTLY_ONE_CONSUMPTION_REQUIRED"); let (start, outcome, finished): (Vec, Vec, Vec) = db.query_row( "SELECT e.start,e.outcome,c.result FROM consumed c JOIN execution_evidence e USING(grant_id) WHERE c.grant_id=?1 AND c.job=?2 AND c.attempt=?3 AND c.agent=?4 AND c.generation=1", params![grant_id, job_id, attempt_id, AGENT], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)), )?; ensure!( start.len() <= 131072 && outcome.len() <= 131072 && outcome == finished, "SUCCESS_ORIGINAL_COMPLETE_OUTCOME_REQUIRED" ); let saved: Value = serde_json::from_slice(&start)?; let request: Request = serde_json::from_value(saved["request"].clone())?; let reserved = serde_json::from_value(saved["reserved_at"].clone())?; let boot = serde_json::from_value(saved["previous_boot_id"].clone())?; let (job, permit) = binding.verify_with(&request, reserved, &DalekVerifier)?; ensure!( (job.job_id, job.attempt_id, permit.grant_id) == (input.job_id, input.attempt_id, input.grant_id) && request.plan_hash == input.plan_sha256 && job.execution_identity == "system" && job.max_runtime_seconds == 30 && job.max_output_bytes == 4096 && job.action.full_maintenance() && !boot.is_nil() && rmm_agent_core::ledger::start_witness_bytes(&permit, &request, boot, reserved)? == start, "SUCCESS_SIGNED_ORIGINAL_START_BINDING" ); let Action::RunScript { interpreter, script_utf8, windows_execution_profile, expected_stdout, .. } = &job.action else { anyhow::bail!("SUCCESS_SYSTEM_SCRIPT_REQUIRED") }; ensure!( interpreter == "powershell" && windows_execution_profile == &Some(WindowsExecutionProfile::PowerShell51RemoteSigned) && expected_stdout.as_deref().map(str::as_bytes) == Some(EXPECTED) && hash(script_utf8.as_bytes()) == input.script_sha256, "SUCCESS_EXACT_APPROVED_SCRIPT" ); let result: Outcome = serde_json::from_slice(&outcome)?; let context = &result.evidence["execution_context"]; ensure!( result.state == "succeeded" && result.exit_code == Some(0) && result.error_code.is_empty() && !result.output_truncated && !result.reboot_required && result.stdout == EXPECTED && result.stderr.is_empty() && result.evidence["postconditions_passed"] == true && result.evidence["execution_sid"] == "S-1-5-18" && result.evidence["script_sha256"] == input.script_sha256 && result.evidence["privileged_script_profile"] == "full_maintenance_v1" && result.evidence["windows_execution_profile"] == "powershell_51_remote_signed" && result.evidence["execution_policy_scope"] == "process" && result.evidence["execution_policy_requested"] == "RemoteSigned" && context["schema_version"] == 1 && context["tenant_id"] == binding.tenant_id.to_string() && context["asset_id"] == binding.asset_id.to_string() && context["agent_id"] == binding.agent_id.to_string() && context["binding_sha256"] == ipc::binding_hash(binding)? && context["agent_binary_sha256"] == input.agent_binary_sha256 && context["helper_binary_sha256"] == input.helper_binary_sha256 && context["policy_sha256"] == input.helper_policy_sha256 && context["rechecked_at_finish"] == true, "SUCCESS_SYSTEM_POSTCONDITIONS_REQUIRED" ); let report = json!({"consumption_count":1,"start_count":1,"outcome_count":1, "original_permit_signature_verified":true,"consumed_result_equals_outcome":true, "request_sha256":hash(&serde_json::to_vec(&request)?),"start_sha256":hash(&start), "outcome_sha256":hash(&outcome),"historical_reserved_at":reserved,"boot_id":boot, "state":"succeeded","exit_code":0,"execution_sid":"S-1-5-18", "stdout_sha256":hash(EXPECTED),"stdout_bytes":EXPECTED.len(),"stderr_bytes":0}); Ok(Evidence { request, outcome, boot, report, }) } pub fn run() -> Result<()> { ensure!(std::env::args().count() == 1, "SUCCESS_FIXED_INPUT_ONLY"); let mut input_root = PinnedFile::open_read_shared( Path::new(r"C:\ProgramData\RustDiscoveryBootstrap"), true, &[], &[], )?; let mut input_file = PinnedFile::open(Path::new(INPUT), false, &[], &[], false)?; ensure!( input_file.file.metadata()?.len() <= 4096, "SUCCESS_PUBLIC_INPUT_BOUND" ); let mut raw = vec![]; (&mut input_file.file).take(4097).read_to_end(&mut raw)?; ensure!(raw.len() <= 4096, "SUCCESS_PUBLIC_INPUT_BOUND"); let input: Input = serde_json::from_slice(&raw)?; ensure!( input.schema_version == 1 && !input.job_id.is_nil() && !input.attempt_id.is_nil() && !input.grant_id.is_nil() && input.grant_id != rmm_domain::windows_system_nonstart::GRANT && [ &input.plan_sha256, &input.script_sha256, &input.agent_binary_sha256, &input.helper_binary_sha256, &input.helper_policy_sha256 ] .into_iter() .all(|s| ipc::digest(s)), "SUCCESS_PUBLIC_INPUT_BINDING" ); let readers = [ipc::service_sid(rmm_agent_windows::SERVICE_NAME)?]; let mut binding_file = PinnedFile::open( Path::new(r"C:\ProgramData\RustDiscovery\binding.json"), false, &readers, &[], false, )?; let mut raw_binding = vec![]; (&mut binding_file.file) .take(8193) .read_to_end(&mut raw_binding)?; ensure!(raw_binding.len() <= 8192, "SUCCESS_PUBLIC_BINDING_BOUND"); let binding: Binding = serde_json::from_slice(&raw_binding)?; ensure!( binding.tenant_id.to_string() == "11111111-1111-4111-8111-111111111111" && binding.asset_id.to_string() == "a176520e-8a91-4e93-a78b-8e7620f430e0" && binding.agent_id.to_string() == AGENT && binding.enrollment_generation == 1 && binding.assignment_version == 1, "SUCCESS_ORIGINAL_DEVICE_REQUIRED" ); let agent = Original::open(PATHS[0])?; let consumption = Original::open(PATHS[1])?; let helper = Original::open(PATHS[2])?; let intents = Original::open(PATHS[3])?; let a = evidence(&consumption.db, &binding, &input)?; let h = evidence(&helper.db, &binding, &input)?; ensure!( serde_json::to_vec(&a.request)? == serde_json::to_vec(&h.request)? && a.outcome == h.outcome && a.boot == h.boot, "SUCCESS_INDEPENDENT_LEDGER_MISMATCH" ); let local_count: u64 = agent.db.query_row( "SELECT count(*) FROM job_attempts WHERE job=?1 AND attempt=?2 AND state='succeeded' AND grant_id=?3", params![input.job_id.to_string(),input.attempt_id.to_string(),input.grant_id.to_string()], |r| r.get(0), )?; ensure!(local_count == 1, "SUCCESS_ORIGINAL_LOCAL_ATTEMPT"); let intent_count: u64 = intents.db.query_row( "SELECT count(*) FROM system_intents WHERE job=?1 OR attempt=?2 OR grant_id=?3", params![ input.job_id.to_string(), input.attempt_id.to_string(), input.grant_id.to_string() ], |r| r.get(0), )?; let (body,digest,phase,cancelled,mirror): (Vec,String,String,u32,String) = intents.db.query_row( "SELECT i.body,i.digest,i.phase,i.cancel_requested,m.outcome_sha256 FROM system_intents i JOIN system_intent_mirrors m USING(id) WHERE i.job=?1 AND i.attempt=?2 AND i.grant_id=?3", params![input.job_id.to_string(),input.attempt_id.to_string(),input.grant_id.to_string()], |r| Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?)), )?; ensure!( intent_count == 1 && body.len() <= 196608 && hash(&body) == digest && phase == "may_have_dispatched" && cancelled == 0 && mirror == hash(&h.outcome), "SUCCESS_ORIGINAL_INTENT_AND_MIRROR" ); let intent: rmm_agent_windows::helper_runtime::intent::Intent = serde_json::from_slice(&body)?; ensure!( intent.schema_version == 1 && !intent.id.is_nil() && intent.original_boot_id == a.boot && intent.policy_sha256 == input.helper_policy_sha256 && intent.helper_binary_sha256 == input.helper_binary_sha256 && serde_json::to_vec(&intent.request)? == serde_json::to_vec(&a.request)?, "SUCCESS_ORIGINAL_INTENT_REQUEST" ); let (ledger, lock, key): (Vec, Vec, String) = helper.db.query_row( "SELECT ledger,executor_lock,binding_sha256 FROM windows_helper_files WHERE id=1", [], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)), )?; ensure!( serde_json::from_slice::(&ledger)? == helper.identity && serde_json::from_slice::(&lock)? == ipc::file_identity(&File::open( r"C:\ProgramData\RustDiscoverySystem\state\executor.lock" )?)? && key == ipc::binding_hash(&binding)?, "SUCCESS_ORIGINAL_HELPER_FILES" ); let stored: Vec = intents.db.query_row( "SELECT file_identity FROM system_intent_meta WHERE id=1", [], |r| r.get(0), )?; ensure!( serde_json::from_slice::(&stored)? == intents.identity, "SUCCESS_ORIGINAL_INTENT_FILE" ); // Validate the earlier reviewed closure from retained signed originals, // never overwrite its original Unknown or reuse its start authorization. let closed_a = rmm_agent_core::windows_system_nonstart::effective_outcome( &consumption.db, Some(&binding), rmm_domain::windows_system_nonstart::GRANT, )?; let closed_h = rmm_agent_core::windows_system_nonstart::effective_outcome( &helper.db, Some(&binding), rmm_domain::windows_system_nonstart::GRANT, )?; ensure!( closed_a.is_some() && closed_a == closed_h, "SUCCESS_OLD221_ORIGINALS_PRESERVED" ); for original in [&agent, &consumption, &helper, &intents] { original.check()?; } input_file.check()?; input_root.check()?; binding_file.check()?; println!( "{}", json!({"schema_version":1,"read_only":true,"verified":true, "job_id":input.job_id,"attempt_id":input.attempt_id,"grant_id":input.grant_id, "plan_sha256":input.plan_sha256,"script_sha256":input.script_sha256, "input_sha256":hash(&raw),"public_binding_sha256":hash(&raw_binding), "agent":a.report,"helper":h.report,"intent_count":1,"intent_body_sha256":digest, "intent_mirror_outcome_sha256":mirror,"old221_original_ledgers_preserved":true, "agent_journal_file_id":agent.identity,"agent_consumption_file_id":consumption.identity, "helper_ledger_file_id":helper.identity,"intent_file_id":intents.identity, "private_key_read":false,"execution_requested":false,"journal_mutation_requested":false}) ); Ok(()) } } #[cfg(all(windows, feature = "system-helper"))] fn main() { if platform::run().is_err() { eprintln!("SYSTEM_SUCCESS_WITNESS_REFUSED"); std::process::exit(1); } } #[cfg(not(all(windows, feature = "system-helper")))] fn main() { eprintln!("Windows system-helper only; no action executed"); std::process::exit(1); }