//! Exact approved SYSTEM script bytes, created only after helper consumption. use crate::helper_ipc::PinnedFile; use anyhow::{Context, Result, ensure}; use rmm_agent_core::auth::Outcome; use rmm_domain::jobs::{Action, JobPayload, WindowsExecutionProfile, hash}; use std::{ fs::OpenOptions, io::Write, os::windows::fs::OpenOptionsExt, path::Path, sync::atomic::AtomicBool, time::{Duration, Instant}, }; /// Static breadcrumbs only. They never classify absence of effects or grant /// authority to retry. No path, command, argument or arbitrary error text exits. #[derive(Clone, Copy, Debug)] enum Stage { Root, Create, Write, Flush, Pin, Bytes, Executable, Arguments, Process, BeforeStart, DuringProcess } impl Stage { fn name(self) -> &'static str { match self { Self::Root => "root_directory", Self::Create => "create_script", Self::Write => "write_script", Self::Flush => "flush_script", Self::Pin => "pin_script", Self::Bytes => "read_script", Self::Executable => "powershell_path", Self::Arguments => "script_arguments", Self::Process => "process", Self::BeforeStart => "observe_before_start", Self::DuringProcess => "observe_running", }} } impl std::fmt::Display for Stage { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.name()) } } /// Sanitized passive failure evidence. Even a preparation-stage error remains /// unknown after consumption; it never authorizes a re-execution or nonstart. pub(crate) fn diagnostic(error: &anyhow::Error) -> serde_json::Value { const CODES: &[&str] = &["SYSTEM_SCRIPT_PROFILE_REQUIRED", "SYSTEM_SCRIPT_REQUIRED", "SYSTEM_SCRIPT_BYTES_CHANGED", "SYSTEM_SCRIPT_PREPARATION_TIMEOUT", "SYSTEM_SCRIPT_CANCELLED", "SYSTEM_SCRIPT_START_FENCED", "PROCESS_CREATION_REFUSED", "PROCESS_PIPE", "PROCESS_JOB_LIMITS", "PROCESS_ATTRIBUTES", "PROCESS_ATTRIBUTE_BINDING", "PROCESS_CANCELLED_BEFORE_START", "PROCESS_ARGUMENT_LIMIT", "TIME_STALE_RESPONSE", "TIME_RUNTIME_NO_EVIDENCE", "TIME_RUNTIME_GENERATION", "TIME_RUNTIME_CONNECTION_CHANGED"]; let ipc = crate::helper_ipc::diagnostic(error); let code = error.chain().find_map(|e| CODES.iter().copied().find(|c| *c == e.to_string())).unwrap_or(ipc.code); let stage = error.downcast_ref::().copied().map_or("unclassified", Stage::name); let native = error.chain().filter_map(|e| e.downcast_ref::()).find_map(|e| e.raw_os_error()).and_then(|v| u32::try_from(v).ok()).or(ipc.win32); serde_json::json!({"stage":stage,"code":code,"native_win32":native,"diagnostic_only":true,"effect_status":"unknown","automatic_retry":false}) } pub(crate) fn execute( job: &JobPayload, grant: uuid::Uuid, helper_sid: &str, began: Instant, mut observe: impl FnMut(bool) -> Result<()>, ) -> Result { ensure!( job.execution_identity == "system" && job.action.full_maintenance() && job.action.valid_execution_identity("system") && job.action.validate() && job .action .valid_job_limits(job.max_runtime_seconds, job.max_output_bytes), "SYSTEM_SCRIPT_PROFILE_REQUIRED" ); let Action::RunScript { script_utf8, expected_stdout, windows_execution_profile, .. } = &job.action else { anyhow::bail!("SYSTEM_SCRIPT_REQUIRED") }; let directory = Path::new(crate::helper_system::STATE_ROOT); let writers = [helper_sid.to_owned()]; let mut root = PinnedFile::open_read_shared(directory, true, &[], &writers).context(Stage::Root)?; let path = directory.join(format!("script-{}-{}.ps1", job.attempt_id, grant)); let mut file = OpenOptions::new() .create_new(true) .read(true) .write(true) .share_mode(windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ) .open(&path).context(Stage::Create)?; file.write_all(script_utf8.as_bytes()).context(Stage::Write)?; file.sync_all().context(Stage::Flush)?; drop(file); struct Cleanup(std::path::PathBuf); impl Drop for Cleanup { fn drop(&mut self) { let _ = std::fs::remove_file(&self.0); } } let _cleanup = Cleanup(path.clone()); let mut pinned = PinnedFile::open(&path, false, &[], &writers, false).context(Stage::Pin)?; ensure!( std::fs::read(&path).context(Stage::Bytes)? == script_utf8.as_bytes(), "SYSTEM_SCRIPT_BYTES_CHANGED" ); let executable = crate::actions::powershell().context(Stage::Executable)?; let arguments = crate::actions::script_arguments(job, &path).context(Stage::Arguments)?; let timeout = Duration::from_secs(job.max_runtime_seconds.into()); let remaining = timeout .checked_sub(began.elapsed()) .filter(|d| !d.is_zero()) .ok_or_else(|| anyhow::anyhow!("SYSTEM_SCRIPT_PREPARATION_TIMEOUT"))?; let mut first = true; let output = crate::process::run_observed( &executable, &arguments, directory, remaining, job.max_output_bytes as usize, &AtomicBool::new(false), || { let stage = if first { Stage::BeforeStart } else { Stage::DuringProcess }; root.check().context(stage)?; pinned.check().context(stage)?; observe(first).context(stage)?; first = false; Ok(()) }, ).map_err(|error| { if error.downcast_ref::().is_some() { error } else { error.context(Stage::Process) } })?; let expected = expected_stdout .as_ref() .is_none_or(|s| output.stdout == s.as_bytes()); let interrupted = output.interrupted || began.elapsed() >= timeout || observe(false).is_err(); let success = !interrupted && output.exit_code == Some(0) && expected && !output.truncated; let mut evidence = serde_json::json!({"postconditions_passed":success,"interpreter":"powershell", "script_sha256":hash(script_utf8.as_bytes()),"privileged_script_profile":"full_maintenance_v1", "execution_sid":"S-1-5-18","output_encoding":"raw_native_bytes","comparison":"exact_utf8_bytes", "execution_policy":"inherited","own_job_object_tree_bounded":true,"full_host_effects_not_contained":true,"full_host_authority":true, "cancel_or_fence_observed":output.cancelled,"termination_does_not_prove_absence_of_effects":interrupted}); if windows_execution_profile == &Some(WindowsExecutionProfile::PowerShell51RemoteSigned) { evidence["windows_execution_profile"] = "powershell_51_remote_signed".into(); evidence["execution_policy"] = "process_remote_signed_requested".into(); evidence["execution_policy_requested"] = "RemoteSigned".into(); evidence["execution_policy_scope"] = "process".into(); } Ok(Outcome { state: if interrupted { "unknown" } else if success { "succeeded" } else { "failed" } .into(), stdout: output.stdout, stderr: output.stderr, exit_code: output.exit_code, output_truncated: output.truncated, reboot_required: false, error_code: if success { "" } else if interrupted { "SYSTEM_SCRIPT_INTERRUPTED_EFFECT_UNKNOWN" } else if output.truncated { "OUTPUT_LIMIT_REACHED" } else if !expected { "STDOUT_POSTCONDITION_FAILED" } else { "POWERSHELL_PROCESS_FAILED" } .into(), evidence, }) }