371 lines
14 KiB
Rust
371 lines
14 KiB
Rust
//! 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, WindowsExecutionProfile, hash};
|
|
use std::{
|
|
ffi::OsString,
|
|
fs::{File, OpenOptions},
|
|
io::Write,
|
|
os::windows::fs::OpenOptionsExt,
|
|
path::{Path, PathBuf},
|
|
sync::atomic::AtomicBool,
|
|
};
|
|
/// Implemented contract name only. Runtime publication still requires its own
|
|
/// native clock/boot/job qualification; this constant grants no capability.
|
|
pub const REMOTE_SIGNED_PROFILE_CAPABILITY: &str = "script.powershell.process_remote_signed/1";
|
|
|
|
pub(crate) fn script_arguments(job: &JobPayload, path: &Path) -> Result<Vec<OsString>> {
|
|
let Action::RunScript {
|
|
interpreter,
|
|
arguments,
|
|
windows_execution_profile,
|
|
..
|
|
} = &job.action
|
|
else {
|
|
anyhow::bail!("SCRIPT_REQUIRED")
|
|
};
|
|
ensure!(
|
|
(job.execution_identity == "agent_service"
|
|
|| (job.execution_identity == "system" && job.action.full_maintenance()))
|
|
&& job.action.valid_execution_identity(&job.execution_identity)
|
|
&& interpreter == "powershell"
|
|
&& job.action.validate(),
|
|
"WINDOWS_SCRIPT_PROFILE_BINDING"
|
|
);
|
|
let mut args: Vec<OsString> = ["-NoLogo", "-NoProfile", "-NonInteractive"]
|
|
.into_iter()
|
|
.map(OsString::from)
|
|
.collect();
|
|
if let Some(WindowsExecutionProfile::PowerShell51RemoteSigned) = windows_execution_profile {
|
|
args.extend([
|
|
OsString::from("-ExecutionPolicy"),
|
|
OsString::from("RemoteSigned"),
|
|
]);
|
|
}
|
|
args.push(OsString::from("-File"));
|
|
args.push(path.as_os_str().into());
|
|
args.extend(arguments.iter().map(OsString::from));
|
|
Ok(args)
|
|
}
|
|
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<PathBuf> {
|
|
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",
|
|
Action::QueryLogs { .. } => crate::event_log::for_job(job).is_ok(),
|
|
_ => false,
|
|
}
|
|
}
|
|
|
|
/// Each prepared operation retains its own typed binding; no non-script action
|
|
/// can fall through to inventory or borrow the PowerShell execution profile.
|
|
pub enum PreparedAction {
|
|
Script(Script),
|
|
Inventory,
|
|
EventLog(crate::event_log_job::Prepared),
|
|
}
|
|
impl PreparedAction {
|
|
pub fn prepare(
|
|
job: &JobPayload,
|
|
directory: &Path,
|
|
grant: uuid::Uuid,
|
|
request: &rmm_agent_core::auth::Request,
|
|
boot: uuid::Uuid,
|
|
) -> Result<Self> {
|
|
ensure!(supported(job), "UNSUPPORTED_CAPABILITY");
|
|
match &job.action {
|
|
Action::RunScript { .. } => Ok(Self::Script(Script::prepare(job, directory, grant)?)),
|
|
Action::RefreshInventory { scope } if scope == "windows.base" => Ok(Self::Inventory),
|
|
Action::QueryLogs { .. } => Ok(Self::EventLog(
|
|
crate::event_log_job::Prepared::prepare(job, directory, request, grant, boot)?,
|
|
)),
|
|
_ => anyhow::bail!("UNSUPPORTED_CAPABILITY"),
|
|
}
|
|
}
|
|
pub fn run(self, job: &JobPayload, cancel: &AtomicBool) -> Result<Outcome> {
|
|
match self {
|
|
Self::Script(script) => script.run(job, cancel),
|
|
Self::Inventory => inventory(job),
|
|
Self::EventLog(log) => log.run(job, cancel),
|
|
}
|
|
}
|
|
}
|
|
|
|
pub struct Script {
|
|
executable: PathBuf,
|
|
path: PathBuf,
|
|
/// Denies write/delete replacement while PowerShell opens the approved file.
|
|
_file: File,
|
|
cwd: PathBuf,
|
|
arguments: Vec<OsString>,
|
|
profile: Option<WindowsExecutionProfile>,
|
|
}
|
|
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<Self> {
|
|
ensure!(supported(job), "UNSUPPORTED_CAPABILITY");
|
|
let Action::RunScript {
|
|
interpreter,
|
|
script_utf8,
|
|
windows_execution_profile,
|
|
..
|
|
} = &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 args = script_arguments(job, &path)?;
|
|
Ok(Self {
|
|
executable: powershell()?,
|
|
path,
|
|
_file: file,
|
|
cwd: directory.to_path_buf(),
|
|
arguments: args,
|
|
profile: *windows_execution_profile,
|
|
})
|
|
}
|
|
pub fn run(self, job: &JobPayload, cancel: &AtomicBool) -> Result<Outcome> {
|
|
ensure!(supported(job), "LOCAL_SERVICE_EXECUTOR_NOT_READY");
|
|
crate::native::private_path(&self.path, false)?;
|
|
let Action::RunScript {
|
|
script_utf8,
|
|
expected_stdout,
|
|
windows_execution_profile,
|
|
..
|
|
} = &job.action
|
|
else {
|
|
anyhow::bail!("SCRIPT_REQUIRED")
|
|
};
|
|
ensure!(
|
|
std::fs::read(&self.path)? == script_utf8.as_bytes(),
|
|
"SCRIPT_BYTES_CHANGED"
|
|
);
|
|
ensure!(
|
|
self.profile == *windows_execution_profile
|
|
&& self.arguments == script_arguments(job, &self.path)?,
|
|
"WINDOWS_SCRIPT_PROFILE_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 {
|
|
""
|
|
};
|
|
let mut 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});
|
|
if self.profile.is_some() {
|
|
evidence["windows_execution_profile"] = serde_json::to_value(self.profile)?;
|
|
evidence["execution_policy"] = serde_json::json!("process_remote_signed_requested");
|
|
evidence["execution_policy_requested"] = serde_json::json!("RemoteSigned");
|
|
evidence["execution_policy_scope"] = serde_json::json!("process");
|
|
}
|
|
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,
|
|
})
|
|
}
|
|
}
|
|
|
|
pub fn inventory(job: &JobPayload) -> Result<Outcome> {
|
|
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"}),
|
|
})
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
#[test]
|
|
fn powershell_policy_is_an_exact_job_profile_before_file_not_a_mutable_default() {
|
|
let id = uuid::Uuid::new_v4();
|
|
let now = chrono::Utc::now();
|
|
let mut job = JobPayload {
|
|
schema_version: 1,
|
|
tenant_id: id,
|
|
asset_id: id,
|
|
agent_id: id,
|
|
enrollment_generation: 1,
|
|
assignment_version: 1,
|
|
job_id: id,
|
|
attempt_id: id,
|
|
action: Action::RunScript {
|
|
interpreter: "powershell".into(),
|
|
script_utf8: "Write-Output 'fixed'\r\n".into(),
|
|
arguments: vec!["-ExecutionPolicy".into(), "Bypass".into()],
|
|
expected_stdout: None,
|
|
windows_execution_profile: None,
|
|
privileged_script_profile: None,
|
|
},
|
|
execution_identity: "agent_service".into(),
|
|
not_before: now,
|
|
start_before: now + chrono::Duration::seconds(60),
|
|
max_runtime_seconds: 30,
|
|
max_output_bytes: 4096,
|
|
};
|
|
let path = Path::new(r"C:\fixed state\approved.ps1");
|
|
let inherited = script_arguments(&job, path).unwrap();
|
|
assert_eq!(
|
|
inherited,
|
|
vec![
|
|
"-NoLogo",
|
|
"-NoProfile",
|
|
"-NonInteractive",
|
|
"-File",
|
|
r"C:\fixed state\approved.ps1",
|
|
"-ExecutionPolicy",
|
|
"Bypass"
|
|
]
|
|
.into_iter()
|
|
.map(OsString::from)
|
|
.collect::<Vec<_>>()
|
|
);
|
|
if let Action::RunScript {
|
|
windows_execution_profile,
|
|
..
|
|
} = &mut job.action
|
|
{
|
|
*windows_execution_profile = Some(WindowsExecutionProfile::PowerShell51RemoteSigned);
|
|
}
|
|
let args = script_arguments(&job, path).unwrap();
|
|
assert_eq!(
|
|
args[..6],
|
|
[
|
|
"-NoLogo",
|
|
"-NoProfile",
|
|
"-NonInteractive",
|
|
"-ExecutionPolicy",
|
|
"RemoteSigned",
|
|
"-File"
|
|
]
|
|
.map(OsString::from)
|
|
);
|
|
assert_eq!(args[6], path.as_os_str()); // approved arguments remain AFTER -File
|
|
assert_ne!(inherited, args);
|
|
let mut unknown = serde_json::to_value(&job.action).unwrap();
|
|
unknown["windows_execution_profile"] = serde_json::json!("Bypass");
|
|
assert!(serde_json::from_value::<Action>(unknown).is_err());
|
|
for identity in ["root", "system"] {
|
|
job.execution_identity = identity.into();
|
|
assert!(script_arguments(&job, path).is_err());
|
|
}
|
|
job.execution_identity = "agent_service".into();
|
|
for other in ["posix_sh", "bash", "pwsh"] {
|
|
if let Action::RunScript { interpreter, .. } = &mut job.action {
|
|
*interpreter = other.into();
|
|
}
|
|
assert!(script_arguments(&job, path).is_err());
|
|
}
|
|
}
|
|
}
|