//! Windows platform effects only. Acceptance, signatures, sync and durable //! consumption are supplied by the shared core and the runtime, never bypassed. use anyhow::{Result, ensure}; use rmm_agent_core::auth::Outcome; use rmm_domain::jobs::{Action, JobPayload, hash}; use std::{ ffi::OsString, fs::{File, OpenOptions}, io::Write, os::windows::fs::OpenOptionsExt, path::{Path, PathBuf}, sync::atomic::AtomicBool, }; use windows_sys::Win32::{ Storage::FileSystem::{ FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_READ, }, System::SystemInformation::GetSystemDirectoryW, }; pub fn powershell() -> Result { let mut buffer = [0u16; 32768]; let length = unsafe { GetSystemDirectoryW(buffer.as_mut_ptr(), buffer.len() as u32) } as usize; ensure!(length > 0 && length < buffer.len(), "SYSTEM_DIRECTORY"); let executable = PathBuf::from(String::from_utf16(&buffer[..length])?) .join("WindowsPowerShell/v1.0/powershell.exe"); ensure!(executable.is_file(), "POWERSHELL_51_NOT_AVAILABLE"); Ok(executable) } pub fn supported(job: &JobPayload) -> bool { crate::native::require_local_service().is_ok() && job.execution_identity == "agent_service" && job.action.validate() && match &job.action { Action::RunScript { interpreter, .. } => { interpreter == "powershell" && powershell().is_ok() } Action::RefreshInventory { scope } => scope == "windows.base", _ => false, } } pub struct Script { executable: PathBuf, path: PathBuf, /// Denies write/delete replacement while PowerShell opens the approved file. _file: File, cwd: PathBuf, arguments: Vec, } impl Script { /// Preparation creates only a protected copy of approved bytes, no child. /// Only the runtime may call run after committing one-time consumption. pub fn prepare(job: &JobPayload, directory: &Path, grant: uuid::Uuid) -> Result { ensure!(supported(job), "UNSUPPORTED_CAPABILITY"); let Action::RunScript { interpreter, script_utf8, arguments, .. } = &job.action else { anyhow::bail!("SCRIPT_REQUIRED") }; ensure!( interpreter == "powershell" && !grant.is_nil(), "WINDOWS_SCRIPT_BINDING" ); crate::native::private_path(directory, true)?; let path = directory.join(format!("{}-{}.ps1", job.attempt_id, grant)); let mut file = OpenOptions::new() .create_new(true) .write(true) .read(true) .share_mode(FILE_SHARE_READ) .open(&path)?; file.write_all(script_utf8.as_bytes())?; file.sync_all()?; drop(file); // Retain a READ handle, not the writer: Windows sharing rules would // otherwise prevent PowerShell's own read-only file open. let file = OpenOptions::new() .read(true) .share_mode(FILE_SHARE_READ) .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT) .open(&path)?; use std::os::windows::fs::MetadataExt; ensure!( file.metadata()?.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT == 0, "SCRIPT_REPARSE_POINT" ); crate::native::private_path(&path, false)?; // Never add a BOM, prolog or change line endings after the plan hash. ensure!( hash(&std::fs::read(&path)?) == hash(script_utf8.as_bytes()), "SCRIPT_BYTES_CHANGED" ); let mut args: Vec = ["-NoLogo", "-NoProfile", "-NonInteractive", "-File"] .into_iter() .map(OsString::from) .collect(); args.push(path.clone().into_os_string()); args.extend(arguments.iter().map(OsString::from)); Ok(Self { executable: powershell()?, path, _file: file, cwd: directory.to_path_buf(), arguments: args, }) } pub fn run(self, job: &JobPayload, cancel: &AtomicBool) -> Result { ensure!(supported(job), "LOCAL_SERVICE_EXECUTOR_NOT_READY"); crate::native::private_path(&self.path, false)?; let Action::RunScript { script_utf8, expected_stdout, .. } = &job.action else { anyhow::bail!("SCRIPT_REQUIRED") }; ensure!( std::fs::read(&self.path)? == script_utf8.as_bytes(), "SCRIPT_BYTES_CHANGED" ); let output = crate::process::run( &self.executable, &self.arguments, &self.cwd, job.max_runtime_seconds, job.max_output_bytes as usize, cancel, )?; let expected = expected_stdout .as_ref() .is_none_or(|expected| output.stdout == expected.as_bytes()); let success = !output.interrupted && output.exit_code == Some(0) && expected && !output.truncated; let state = if output.interrupted { "unknown" } else if success { "succeeded" } else { "failed" }; let code = if output.interrupted { if output.cancelled { "CANCELLED_EFFECT_UNKNOWN" } else { "TIMEOUT_EFFECT_UNKNOWN" } } else if output.truncated { "OUTPUT_LIMIT_REACHED" } else if output.exit_code != Some(0) { "POWERSHELL_PROCESS_FAILED" } else if !expected { "STDOUT_POSTCONDITION_FAILED" } else { "" }; Ok(Outcome { state: state.into(), stdout: output.stdout, stderr: output.stderr, exit_code: output.exit_code, output_truncated: output.truncated, reboot_required: false, error_code: code.into(), evidence: serde_json::json!({"postconditions_passed":success,"interpreter":"powershell", "script_sha256":hash(script_utf8.as_bytes()),"execution_sid":"S-1-5-19", "output_encoding":"raw_native_bytes","comparison":"exact_utf8_bytes", "execution_policy":"inherited","process_tree_bounded":true, "cancel_requested":output.cancelled,"termination_does_not_prove_absence_of_effects":output.interrupted}), }) } } pub fn inventory(job: &JobPayload) -> Result { ensure!( supported(job) && matches!(&job.action, Action::RefreshInventory {scope} if scope=="windows.base"), "WINDOWS_INVENTORY_BINDING" ); let data = crate::native::snapshot()?; let stdout = serde_json::to_vec(&data)?; ensure!( stdout.len() <= job.max_output_bytes as usize, "INVENTORY_OUTPUT_LIMIT" ); Ok(Outcome { state: "succeeded".into(), stdout, stderr: vec![], exit_code: None, output_truncated: false, reboot_required: false, error_code: String::new(), evidence: serde_json::json!({"postconditions_passed":true,"source_id":"windows.base", "observed_at":chrono::Utc::now(),"completeness":"partial","execution_sid":"S-1-5-19"}), }) }