feat: add approval bound full maintenance script console and executors
Rust development slice / linux (push) Failing after 6s
Rust development slice / linux (push) Failing after 6s
This commit is contained in:
@@ -15,7 +15,7 @@ use std::{
|
||||
/// native clock/boot/job qualification; this constant grants no capability.
|
||||
pub const REMOTE_SIGNED_PROFILE_CAPABILITY: &str = "script.powershell.process_remote_signed/1";
|
||||
|
||||
fn script_arguments(job: &JobPayload, path: &Path) -> Result<Vec<OsString>> {
|
||||
pub(crate) fn script_arguments(job: &JobPayload, path: &Path) -> Result<Vec<OsString>> {
|
||||
let Action::RunScript {
|
||||
interpreter,
|
||||
arguments,
|
||||
@@ -26,7 +26,9 @@ fn script_arguments(job: &JobPayload, path: &Path) -> Result<Vec<OsString>> {
|
||||
anyhow::bail!("SCRIPT_REQUIRED")
|
||||
};
|
||||
ensure!(
|
||||
job.execution_identity == "agent_service"
|
||||
(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"
|
||||
@@ -303,6 +305,7 @@ mod tests {
|
||||
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,
|
||||
|
||||
@@ -470,6 +470,14 @@ fn verified_mirror_row(
|
||||
Ok(outcome)
|
||||
}
|
||||
fn system_shape(job: &JobPayload) -> bool {
|
||||
if job.action.full_maintenance() {
|
||||
return job.execution_identity == "system"
|
||||
&& job.action.validate()
|
||||
&& job.action.valid_execution_identity("system")
|
||||
&& job
|
||||
.action
|
||||
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes);
|
||||
}
|
||||
if job.action.windows_msi().is_some() {
|
||||
return job.execution_identity == "system"
|
||||
&& job.action.validate()
|
||||
@@ -544,6 +552,41 @@ pub(super) fn checked_outcome(job: &JobPayload, outcome: &Outcome) -> Result<()>
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if job.action.full_maintenance() {
|
||||
let Action::RunScript {
|
||||
script_utf8,
|
||||
expected_stdout,
|
||||
windows_execution_profile,
|
||||
..
|
||||
} = &job.action
|
||||
else {
|
||||
anyhow::bail!("SYSTEM_SCRIPT_REQUIRED")
|
||||
};
|
||||
let e = &outcome.evidence;
|
||||
ensure!(
|
||||
system_shape(job)
|
||||
&& outcome.exit_code == Some(0)
|
||||
&& !outcome.output_truncated
|
||||
&& !outcome.reboot_required
|
||||
&& e["postconditions_passed"] == true
|
||||
&& e["privileged_script_profile"] == "full_maintenance_v1"
|
||||
&& e["execution_sid"] == "S-1-5-18"
|
||||
&& e["script_sha256"] == rmm_domain::jobs::hash(script_utf8.as_bytes())
|
||||
&& expected_stdout
|
||||
.as_ref()
|
||||
.is_none_or(|s| outcome.stdout == s.as_bytes()),
|
||||
"SYSTEM_SCRIPT_POSTCONDITION_BINDING"
|
||||
);
|
||||
if windows_execution_profile.is_some() {
|
||||
ensure!(
|
||||
e["windows_execution_profile"] == "powershell_51_remote_signed"
|
||||
&& e["execution_policy_requested"] == "RemoteSigned"
|
||||
&& e["execution_policy_scope"] == "process",
|
||||
"SYSTEM_SCRIPT_PROCESS_PROFILE_BINDING"
|
||||
);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let Action::SetServiceState { unit, state } = &job.action else {
|
||||
anyhow::bail!("SYSTEM_TYPED_SERVICE_REQUIRED");
|
||||
};
|
||||
@@ -585,6 +628,49 @@ pub fn map_snapshot(s: &Snapshot) -> HelperSnapshot {
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod script_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn system_script_success_requires_exact_profile_identity_bytes_and_raw_output() {
|
||||
let mut job = msi_test_job();
|
||||
job.action = Action::RunScript {
|
||||
interpreter: "powershell".into(),
|
||||
script_utf8: "Write-Output 'hi'\r\n".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("hi\r\n".into()),
|
||||
windows_execution_profile: Some(
|
||||
rmm_domain::jobs::WindowsExecutionProfile::PowerShell51RemoteSigned,
|
||||
),
|
||||
privileged_script_profile: Some(
|
||||
rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
|
||||
),
|
||||
};
|
||||
assert!(system_shape(&job));
|
||||
let mut outcome = Outcome {
|
||||
state: "succeeded".into(),
|
||||
stdout: b"hi\r\n".to_vec(),
|
||||
stderr: vec![],
|
||||
exit_code: Some(0),
|
||||
output_truncated: false,
|
||||
reboot_required: false,
|
||||
error_code: String::new(),
|
||||
evidence: json!({"postconditions_passed":true,"privileged_script_profile":"full_maintenance_v1","execution_sid":"S-1-5-18","script_sha256":rmm_domain::jobs::hash(b"Write-Output 'hi'\r\n"),"windows_execution_profile":"powershell_51_remote_signed","execution_policy_requested":"RemoteSigned","execution_policy_scope":"process"}),
|
||||
};
|
||||
checked_outcome(&job, &outcome).unwrap();
|
||||
outcome.evidence["execution_sid"] = "S-1-5-19".into();
|
||||
assert!(checked_outcome(&job, &outcome).is_err());
|
||||
outcome.evidence["execution_sid"] = "S-1-5-18".into();
|
||||
outcome.stdout = b"other".to_vec();
|
||||
assert!(checked_outcome(&job, &outcome).is_err());
|
||||
outcome.state = "unknown".into();
|
||||
outcome.evidence = serde_json::Value::Null;
|
||||
checked_outcome(&job, &outcome).unwrap();
|
||||
job.execution_identity = "root".into();
|
||||
assert!(!system_shape(&job));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn msi_test_job() -> JobPayload {
|
||||
use rmm_domain::windows_execution::*;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! SYSTEM service with an independent signed-sync gate and durable ledger.
|
||||
//! Only fixed, policy-pinned SCM state changes exist; no arbitrary SYSTEM CLI.
|
||||
//! Versioned policy independently admits fixed SCM/MSI actions or the explicit
|
||||
//! full_maintenance_v1 SYSTEM script profile; none inherit another's authority.
|
||||
//!
|
||||
//! Bootstrap contract (not performed by this module): install exactly
|
||||
//! `RmmDiscoverySystemHelper` as an OWN_PROCESS LocalSystem service with its
|
||||
@@ -75,6 +76,12 @@ pub struct Settings {
|
||||
deserialize_with = "strict_recipe_hashes"
|
||||
)]
|
||||
pub allowed_msi_recipe_sha256: Option<Vec<String>>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
deserialize_with = "rmm_domain::jobs::deserialize_script_profiles"
|
||||
)]
|
||||
pub allowed_script_profiles: Option<Vec<rmm_domain::jobs::PrivilegedScriptProfile>>,
|
||||
}
|
||||
fn strict_recipe_hashes<'de, D: serde::Deserializer<'de>>(
|
||||
d: D,
|
||||
@@ -83,7 +90,7 @@ fn strict_recipe_hashes<'de, D: serde::Deserializer<'de>>(
|
||||
}
|
||||
impl Settings {
|
||||
fn permits_msi(&self, job: &JobPayload) -> bool {
|
||||
self.schema_version == 2
|
||||
self.schema_version >= 2
|
||||
&& job.execution_identity == "system"
|
||||
&& job.action.validate()
|
||||
&& job
|
||||
@@ -96,10 +103,24 @@ impl Settings {
|
||||
.is_some_and(|h| h.contains(&m.recipe_sha256))
|
||||
})
|
||||
}
|
||||
fn permits_script(&self, job: &JobPayload) -> bool {
|
||||
self.schema_version == 3
|
||||
&& 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)
|
||||
&& job.max_runtime_seconds <= self.max_runtime_seconds
|
||||
&& self.allowed_script_profiles.as_deref()
|
||||
== Some(&[rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1])
|
||||
}
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
ensure!(
|
||||
matches!(self.schema_version, 1 | 2)
|
||||
&& (self.schema_version == 2 || self.allowed_msi_recipe_sha256.is_none())
|
||||
matches!(self.schema_version, 1..=3)
|
||||
&& (self.schema_version >= 2 || self.allowed_msi_recipe_sha256.is_none())
|
||||
&& (self.schema_version == 3 || self.allowed_script_profiles.is_none())
|
||||
&& self
|
||||
.allowed_msi_recipe_sha256
|
||||
.as_ref()
|
||||
@@ -112,6 +133,9 @@ impl Settings {
|
||||
.len()
|
||||
== hashes.len()
|
||||
})
|
||||
&& self.allowed_script_profiles.as_deref().is_none_or(
|
||||
|v| v == [rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1]
|
||||
)
|
||||
&& !self.allow_reboot
|
||||
&& (1..=120).contains(&self.max_runtime_seconds)
|
||||
&& self.allowed_services.len() <= 16,
|
||||
@@ -1018,7 +1042,8 @@ impl SystemHelper {
|
||||
job.execution_identity == "system"
|
||||
&& job.max_runtime_seconds <= self.settings.max_runtime_seconds
|
||||
&& (matches!(&job.action,Action::SetServiceState{unit,state} if matches!(state.as_str(),"running"|"stopped")&&self.settings.allowed_services.iter().any(|r|r.name==*unit))
|
||||
|| self.settings.permits_msi(&job)),
|
||||
|| self.settings.permits_msi(&job)
|
||||
|| self.settings.permits_script(&job)),
|
||||
"SYSTEM_ABANDON_POLICY_DENIED"
|
||||
);
|
||||
self.sync()?;
|
||||
@@ -1109,6 +1134,9 @@ impl SystemHelper {
|
||||
),
|
||||
"SYSTEM_SIGNED_SYNC_REQUIRED"
|
||||
);
|
||||
if job.action.full_maintenance() {
|
||||
return self.execute_script(generation, request, &job, &permit, peer);
|
||||
}
|
||||
if job.action.windows_msi().is_some() {
|
||||
return self.execute_msi(generation, request, &job, &permit, peer);
|
||||
}
|
||||
@@ -1150,6 +1178,78 @@ impl SystemHelper {
|
||||
ledger::finish(&self.db, &permit, &outcome)?;
|
||||
Ok(outcome)
|
||||
}
|
||||
fn execute_script(
|
||||
&mut self,
|
||||
generation: u64,
|
||||
request: &Request,
|
||||
job: &JobPayload,
|
||||
permit: &ExecutionPermitPayload,
|
||||
peer: &mut ipc::PeerProof,
|
||||
) -> Result<Outcome> {
|
||||
let began = Instant::now();
|
||||
ensure!(
|
||||
self.settings.permits_script(job),
|
||||
"SYSTEM_SCRIPT_POLICY_DENIED"
|
||||
);
|
||||
self.observe_unsettled_msi()?;
|
||||
ensure!(
|
||||
self.unsettled_msi.is_none(),
|
||||
"SYSTEM_MSI_PREVIOUS_PROCESS_UNSETTLED"
|
||||
);
|
||||
self.recheck()?;
|
||||
peer.check()?;
|
||||
let (_, fresh, recorded_at) =
|
||||
verified_window(&self.settings.binding, request, &self.clock)?;
|
||||
ensure!(
|
||||
&fresh == permit && !STOP.load(Ordering::SeqCst),
|
||||
"SYSTEM_SCRIPT_START_FENCED"
|
||||
);
|
||||
crate::helper_runtime::intent::Store::require_not_denied(
|
||||
request,
|
||||
self.boot.current_boot()?,
|
||||
generation,
|
||||
&self.pin.policy_sha256,
|
||||
&self.pin.helper.binary_sha256,
|
||||
)?;
|
||||
ledger::begin_execution(
|
||||
&mut self.db,
|
||||
permit,
|
||||
request,
|
||||
self.boot.current_boot()?,
|
||||
recorded_at,
|
||||
)?;
|
||||
self.sync.as_mut().unwrap().close();
|
||||
let helper_sid = self.settings.helper.service_sid.clone();
|
||||
let result = crate::system_script::execute(
|
||||
job,
|
||||
permit.grant_id,
|
||||
&helper_sid,
|
||||
began,
|
||||
|before_start| {
|
||||
self.recheck()?;
|
||||
peer.check()?;
|
||||
self.clock.now()?;
|
||||
ensure!(!STOP.load(Ordering::SeqCst), "SYSTEM_SCRIPT_CANCELLED");
|
||||
crate::helper_runtime::intent::Store::require_not_denied(
|
||||
request,
|
||||
self.boot.current_boot()?,
|
||||
generation,
|
||||
&self.pin.policy_sha256,
|
||||
&self.pin.helper.binary_sha256,
|
||||
)?;
|
||||
if before_start {
|
||||
verified_window(&self.settings.binding, request, &self.clock)?;
|
||||
}
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
let outcome =
|
||||
result.unwrap_or_else(|_| Outcome::unknown("SYSTEM_SCRIPT_EFFECT_UNRESOLVED"));
|
||||
ledger::persist_outcome(&self.db, permit, &outcome)?;
|
||||
self.guard.check(&self.db)?;
|
||||
ledger::finish(&self.db, permit, &outcome)?;
|
||||
Ok(outcome)
|
||||
}
|
||||
fn execute_msi(
|
||||
&mut self,
|
||||
generation: u64,
|
||||
@@ -1517,6 +1617,7 @@ mod tests {
|
||||
enable_effects: false,
|
||||
allow_reboot: false,
|
||||
allowed_msi_recipe_sha256: None,
|
||||
allowed_script_profiles: None,
|
||||
};
|
||||
let legacy = serde_json::to_value(&settings).unwrap();
|
||||
assert!(legacy.get("allowed_msi_recipe_sha256").is_none());
|
||||
@@ -1538,6 +1639,29 @@ mod tests {
|
||||
settings.max_runtime_seconds = 30;
|
||||
settings.allowed_msi_recipe_sha256 = Some(vec!["cd".repeat(32)]);
|
||||
assert!(!settings.permits_msi(&job));
|
||||
let mut script = job.clone();
|
||||
script.action = Action::RunScript {
|
||||
interpreter: "powershell".into(),
|
||||
script_utf8: "Write-Output 'hi'\r\n".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: Some(
|
||||
rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
|
||||
),
|
||||
};
|
||||
assert!(!settings.permits_script(&script));
|
||||
settings.allowed_script_profiles = Some(vec![
|
||||
rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
|
||||
]);
|
||||
assert!(!settings.permits_script(&script));
|
||||
settings.schema_version = 3;
|
||||
assert!(settings.permits_script(&script));
|
||||
script.execution_identity = "root".into();
|
||||
assert!(!settings.permits_script(&script));
|
||||
let mut null = legacy;
|
||||
null["allowed_script_profiles"] = serde_json::Value::Null;
|
||||
assert!(serde_json::from_value::<Settings>(null).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn service_adapter_exposes_only_implemented_states() {
|
||||
|
||||
@@ -18,15 +18,17 @@ pub mod inventory;
|
||||
#[cfg(windows)]
|
||||
pub mod job_binding;
|
||||
pub mod journal;
|
||||
pub mod package;
|
||||
#[cfg(all(windows, feature = "system-helper"))]
|
||||
pub mod msi_cache;
|
||||
#[cfg(windows)]
|
||||
pub mod native;
|
||||
pub mod package;
|
||||
#[cfg(windows)]
|
||||
pub mod process;
|
||||
#[cfg(windows)]
|
||||
pub mod service;
|
||||
#[cfg(all(windows, feature = "system-helper"))]
|
||||
mod system_script;
|
||||
|
||||
pub const SERVICE_NAME: &str = "RmmDiscoveryWindows";
|
||||
pub const CAPABILITIES: &[&str] = &["windows.base/1", "heartbeat/1"];
|
||||
|
||||
@@ -194,9 +194,31 @@ pub fn run(
|
||||
seconds: u32,
|
||||
max_bytes: usize,
|
||||
cancel: &AtomicBool,
|
||||
) -> Result<Output> {
|
||||
run_observed(
|
||||
executable,
|
||||
arguments,
|
||||
cwd,
|
||||
Duration::from_secs(seconds.into()),
|
||||
max_bytes,
|
||||
cancel,
|
||||
|| Ok(()),
|
||||
)
|
||||
}
|
||||
pub(crate) fn run_observed(
|
||||
executable: &Path,
|
||||
arguments: &[OsString],
|
||||
cwd: &Path,
|
||||
timeout: Duration,
|
||||
max_bytes: usize,
|
||||
cancel: &AtomicBool,
|
||||
mut observe: impl FnMut() -> Result<()>,
|
||||
) -> Result<Output> {
|
||||
ensure!(
|
||||
executable.is_absolute() && cwd.is_absolute() && seconds > 0 && max_bytes <= 512 * 1024,
|
||||
executable.is_absolute()
|
||||
&& cwd.is_absolute()
|
||||
&& !timeout.is_zero()
|
||||
&& max_bytes <= 512 * 1024,
|
||||
"PROCESS_LIMITS"
|
||||
);
|
||||
let (stdout, out_write) = pipe()?;
|
||||
@@ -268,7 +290,17 @@ pub fn run(
|
||||
// Minimal environment: no inherited tokens, proxy secrets, device paths,
|
||||
// PSModulePath overrides, user profile or caller-controlled executable PATH.
|
||||
let mut environment = Vec::new();
|
||||
let system_text = system
|
||||
.to_str()
|
||||
.ok_or_else(|| anyhow::anyhow!("SYSTEM_DIRECTORY_ENCODING"))?;
|
||||
ensure!(
|
||||
system_text.as_bytes().get(1) == Some(&b':')
|
||||
&& system_text.as_bytes()[0].is_ascii_alphabetic(),
|
||||
"SYSTEM_DRIVE_REQUIRED"
|
||||
);
|
||||
let system_drive = &system_text[..2];
|
||||
for value in [
|
||||
format!("SystemDrive={system_drive}"),
|
||||
format!("PATH={}\\System32;{}", system.display(), system.display()),
|
||||
format!("SystemRoot={}", system.display()),
|
||||
format!("TEMP={}", cwd.display()),
|
||||
@@ -279,6 +311,11 @@ pub fn run(
|
||||
}
|
||||
environment.push(0);
|
||||
let mut process: PROCESS_INFORMATION = unsafe { zeroed() };
|
||||
observe()?;
|
||||
ensure!(
|
||||
!cancel.load(Ordering::SeqCst),
|
||||
"PROCESS_CANCELLED_BEFORE_START"
|
||||
);
|
||||
ensure!(
|
||||
unsafe {
|
||||
CreateProcessW(
|
||||
@@ -303,32 +340,101 @@ pub fn run(
|
||||
drop(stdin);
|
||||
drop(out_write);
|
||||
drop(err_write);
|
||||
let mut result = Output {
|
||||
stdout: Vec::new(),
|
||||
stderr: Vec::new(),
|
||||
exit_code: None,
|
||||
truncated: false,
|
||||
interrupted: false,
|
||||
cancelled: false,
|
||||
};
|
||||
let began = Instant::now();
|
||||
let mut remaining = max_bytes;
|
||||
loop {
|
||||
drain(
|
||||
&stdout,
|
||||
&mut result.stdout,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
)?;
|
||||
drain(
|
||||
&stderr,
|
||||
&mut result.stderr,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
)?;
|
||||
let mut accounting: JOBOBJECT_BASIC_ACCOUNTING_INFORMATION = unsafe { zeroed() };
|
||||
let result = (|| -> Result<Output> {
|
||||
let mut result = Output {
|
||||
stdout: Vec::new(),
|
||||
stderr: Vec::new(),
|
||||
exit_code: None,
|
||||
truncated: false,
|
||||
interrupted: false,
|
||||
cancelled: false,
|
||||
};
|
||||
let began = Instant::now();
|
||||
let mut remaining = max_bytes;
|
||||
loop {
|
||||
drain(
|
||||
&stdout,
|
||||
&mut result.stdout,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
)?;
|
||||
drain(
|
||||
&stderr,
|
||||
&mut result.stderr,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
)?;
|
||||
let mut accounting: JOBOBJECT_BASIC_ACCOUNTING_INFORMATION = unsafe { zeroed() };
|
||||
ensure!(
|
||||
unsafe {
|
||||
QueryInformationJobObject(
|
||||
job.as_raw_handle(),
|
||||
JobObjectBasicAccountingInformation,
|
||||
ptr::addr_of_mut!(accounting).cast(),
|
||||
size_of_val(&accounting) as u32,
|
||||
ptr::null_mut(),
|
||||
)
|
||||
} != 0,
|
||||
"PROCESS_TREE_STATE"
|
||||
);
|
||||
if accounting.ActiveProcesses == 0 {
|
||||
break;
|
||||
}
|
||||
let fenced = observe().is_err();
|
||||
if !result.interrupted
|
||||
&& (began.elapsed() >= timeout || cancel.load(Ordering::SeqCst) || fenced)
|
||||
{
|
||||
result.cancelled = cancel.load(Ordering::SeqCst) || fenced;
|
||||
result.interrupted = true;
|
||||
ensure!(
|
||||
unsafe { TerminateJobObject(job.as_raw_handle(), 1) } != 0,
|
||||
"PROCESS_TREE_TERMINATION"
|
||||
);
|
||||
// This wait proves termination, not absence of effects.
|
||||
ensure!(
|
||||
unsafe { WaitForSingleObject(process_handle.as_raw_handle(), 5000) } == 0,
|
||||
"PROCESS_TERMINATION_UNCONFIRMED"
|
||||
);
|
||||
// Keep this JobObject/process handle owner until *all* assigned
|
||||
// processes are observed inactive. Waiting for the leader alone
|
||||
// cannot release the helper lane or heal an interrupted outcome.
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
// No writer can outlive job destruction. Drain the bounded OS pipe buffers.
|
||||
for _ in 0..8 {
|
||||
drain(
|
||||
&stdout,
|
||||
&mut result.stdout,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
)?;
|
||||
drain(
|
||||
&stderr,
|
||||
&mut result.stderr,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
)?;
|
||||
}
|
||||
let mut code = 0;
|
||||
ensure!(
|
||||
unsafe {
|
||||
unsafe { GetExitCodeProcess(process_handle.as_raw_handle(), &mut code) } != 0
|
||||
&& code != STILL_ACTIVE as u32,
|
||||
"PROCESS_EXIT_UNCONFIRMED"
|
||||
);
|
||||
result.exit_code = Some(code as i32);
|
||||
Ok(result)
|
||||
})();
|
||||
if result.is_err() {
|
||||
// Keep exact owned handles and the caller's helper lane on any observer
|
||||
// or I/O error. Termination/leader exit alone cannot prove the whole
|
||||
// assigned tree inactive; never drop ownership and admit replacement.
|
||||
unsafe {
|
||||
TerminateJobObject(job.as_raw_handle(), 1);
|
||||
}
|
||||
loop {
|
||||
let mut accounting: JOBOBJECT_BASIC_ACCOUNTING_INFORMATION = unsafe { zeroed() };
|
||||
let ok = unsafe {
|
||||
QueryInformationJobObject(
|
||||
job.as_raw_handle(),
|
||||
JobObjectBasicAccountingInformation,
|
||||
@@ -336,52 +442,14 @@ pub fn run(
|
||||
size_of_val(&accounting) as u32,
|
||||
ptr::null_mut(),
|
||||
)
|
||||
} != 0,
|
||||
"PROCESS_TREE_STATE"
|
||||
);
|
||||
if accounting.ActiveProcesses == 0 {
|
||||
break;
|
||||
};
|
||||
if ok != 0 && accounting.ActiveProcesses == 0 {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
if began.elapsed() >= Duration::from_secs(seconds.into()) || cancel.load(Ordering::SeqCst) {
|
||||
result.cancelled = cancel.load(Ordering::SeqCst);
|
||||
result.interrupted = true;
|
||||
ensure!(
|
||||
unsafe { TerminateJobObject(job.as_raw_handle(), 1) } != 0,
|
||||
"PROCESS_TREE_TERMINATION"
|
||||
);
|
||||
// This wait proves termination, not absence of effects.
|
||||
ensure!(
|
||||
unsafe { WaitForSingleObject(process_handle.as_raw_handle(), 5000) } == 0,
|
||||
"PROCESS_TERMINATION_UNCONFIRMED"
|
||||
);
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
// No writer can outlive job destruction. Drain the bounded OS pipe buffers.
|
||||
drop(job);
|
||||
for _ in 0..8 {
|
||||
drain(
|
||||
&stdout,
|
||||
&mut result.stdout,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
)?;
|
||||
drain(
|
||||
&stderr,
|
||||
&mut result.stderr,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
)?;
|
||||
}
|
||||
let mut code = 0;
|
||||
ensure!(
|
||||
unsafe { GetExitCodeProcess(process_handle.as_raw_handle(), &mut code) } != 0
|
||||
&& code != STILL_ACTIVE as u32,
|
||||
"PROCESS_EXIT_UNCONFIRMED"
|
||||
);
|
||||
result.exit_code = Some(code as i32);
|
||||
Ok(result)
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
//! Exact approved SYSTEM script bytes, created only after helper consumption.
|
||||
use crate::helper_ipc::PinnedFile;
|
||||
use anyhow::{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},
|
||||
};
|
||||
|
||||
pub(crate) fn execute(
|
||||
job: &JobPayload,
|
||||
grant: uuid::Uuid,
|
||||
helper_sid: &str,
|
||||
began: Instant,
|
||||
mut observe: impl FnMut(bool) -> Result<()>,
|
||||
) -> Result<Outcome> {
|
||||
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(directory, true, &[], &writers, false)?;
|
||||
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)?;
|
||||
file.write_all(script_utf8.as_bytes())?;
|
||||
file.sync_all()?;
|
||||
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)?;
|
||||
ensure!(
|
||||
std::fs::read(&path)? == script_utf8.as_bytes(),
|
||||
"SYSTEM_SCRIPT_BYTES_CHANGED"
|
||||
);
|
||||
let executable = crate::actions::powershell()?;
|
||||
let arguments = crate::actions::script_arguments(job, &path)?;
|
||||
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),
|
||||
|| {
|
||||
root.check()?;
|
||||
pinned.check()?;
|
||||
observe(first)?;
|
||||
first = false;
|
||||
Ok(())
|
||||
},
|
||||
)?;
|
||||
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,
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user