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:
@@ -33,6 +33,7 @@ impl Binding {
|
||||
);
|
||||
ensure!(
|
||||
j.action.validate()
|
||||
&& j.action.valid_execution_identity(&j.execution_identity)
|
||||
&& j.action
|
||||
.valid_job_limits(j.max_runtime_seconds, j.max_output_bytes)
|
||||
&& j.not_before < j.start_before,
|
||||
|
||||
@@ -41,6 +41,7 @@ fn fixture() -> (Binding, Request, ExecutionPermitPayload, DateTime<Utc>) {
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("Hello\n".into()),
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
},
|
||||
execution_identity: "agent_service".into(),
|
||||
not_before: now - Duration::minutes(1),
|
||||
@@ -181,6 +182,7 @@ fn exact_permit_bytes_time_and_all_identity_hash_bindings_are_required() {
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("Hello\r\n".into()),
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
};
|
||||
request.job_bytes = encode(&job).unwrap();
|
||||
permit.job_payload_hash = hash(&request.job_bytes);
|
||||
|
||||
@@ -868,6 +868,7 @@ fn script() -> Action {
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("hello".into()),
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
}
|
||||
}
|
||||
fn success() -> ReconciledOutcome {
|
||||
|
||||
@@ -606,6 +606,7 @@ fn script() -> Action {
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("hello".into()),
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
}
|
||||
}
|
||||
fn success() -> ReconciledOutcome {
|
||||
|
||||
@@ -85,6 +85,12 @@ impl ScriptRequest {
|
||||
}
|
||||
|
||||
pub fn run_script(request: &ScriptRequest) -> Result<ScriptOutput> {
|
||||
run_script_controlled(request, || Ok(()))
|
||||
}
|
||||
pub fn run_script_controlled(
|
||||
request: &ScriptRequest,
|
||||
observe: impl FnMut() -> Result<()>,
|
||||
) -> Result<ScriptOutput> {
|
||||
ensure!(
|
||||
request.interpreter.available(),
|
||||
"UNSUPPORTED_CAPABILITY: interpreter unavailable"
|
||||
@@ -115,11 +121,12 @@ pub fn run_script(request: &ScriptRequest) -> Result<ScriptOutput> {
|
||||
path.to_str().context("non-UTF8 temp path")?.to_owned(),
|
||||
];
|
||||
args.extend(request.arguments.clone());
|
||||
process::run(
|
||||
process::run_controlled(
|
||||
request.interpreter.path(),
|
||||
&args,
|
||||
request.timeout,
|
||||
request.max_output_bytes,
|
||||
observe,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
+232
-108
@@ -15,11 +15,19 @@ pub struct Output {
|
||||
pub stderr: Vec<u8>,
|
||||
pub truncated: bool,
|
||||
pub timed_out: bool,
|
||||
pub interrupted: bool,
|
||||
}
|
||||
|
||||
// Nonblocking pipes avoid both unbounded output and reader threads held open by
|
||||
// grandchildren. The child has a separate process group, cleaned even on success.
|
||||
pub(crate) fn run(program: &str, args: &[String], timeout: Duration, cap: usize) -> Result<Output> {
|
||||
run_controlled(program, args, timeout, cap, || Ok(()))
|
||||
}
|
||||
pub(crate) fn run_controlled(
|
||||
program: &str,
|
||||
args: &[String],
|
||||
timeout: Duration,
|
||||
cap: usize,
|
||||
mut observe: impl FnMut() -> Result<()>,
|
||||
) -> Result<Output> {
|
||||
ensure!(!timeout.is_zero() && cap > 0, "invalid process limits");
|
||||
let mut command = Command::new(program);
|
||||
command
|
||||
@@ -34,144 +42,260 @@ pub(crate) fn run(program: &str, args: &[String], timeout: Duration, cap: usize)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.process_group(0);
|
||||
observe()?;
|
||||
let mut child = command
|
||||
.spawn()
|
||||
.with_context(|| format!("spawn {program}"))?;
|
||||
struct Group(u32);
|
||||
// Keep the group leader unreaped until AFTER the last signal and cleanup.
|
||||
// Its reserved PID prevents the numerical PGID from becoming a foreign group.
|
||||
struct Group {
|
||||
pid: u32,
|
||||
reserved: bool,
|
||||
}
|
||||
impl Group {
|
||||
fn kill(&self) {
|
||||
if self.reserved {
|
||||
unsafe {
|
||||
libc::kill(-(self.pid as i32), libc::SIGKILL);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Drop for Group {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: negative PID addresses only the group created for this child.
|
||||
unsafe {
|
||||
libc::kill(-(self.0 as i32), libc::SIGKILL);
|
||||
}
|
||||
self.kill();
|
||||
}
|
||||
}
|
||||
let group = Group(child.id());
|
||||
let mut group = Group {
|
||||
pid: child.id(),
|
||||
reserved: true,
|
||||
};
|
||||
let mut stdout = child.stdout.take().context("missing stdout")?;
|
||||
let mut stderr = child.stderr.take().context("missing stderr")?;
|
||||
for fd in [stdout.as_raw_fd(), stderr.as_raw_fd()] {
|
||||
// SAFETY: these are live owned pipe descriptors; flags are not pointers.
|
||||
let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
|
||||
if flags < 0 || unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) } < 0 {
|
||||
drop(group);
|
||||
let _ = child.wait();
|
||||
return Err(std::io::Error::last_os_error().into());
|
||||
}
|
||||
}
|
||||
fn drain(
|
||||
pipe: &mut impl Read,
|
||||
target: &mut Vec<u8>,
|
||||
remaining: &mut usize,
|
||||
truncated: &mut bool,
|
||||
) -> Result<bool> {
|
||||
let mut bytes = [0; 4096];
|
||||
// Bound each pass too: a continuously writing child cannot starve timeout.
|
||||
for _ in 0..16 {
|
||||
match pipe.read(&mut bytes) {
|
||||
Ok(0) => return Ok(true),
|
||||
Ok(n) => {
|
||||
let keep = n.min(*remaining);
|
||||
target.extend_from_slice(&bytes[..keep]);
|
||||
*remaining -= keep;
|
||||
*truncated |= keep < n;
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
let started = Instant::now();
|
||||
let mut result = Output {
|
||||
let began = Instant::now();
|
||||
let mut output = Output {
|
||||
code: None,
|
||||
stdout: vec![],
|
||||
stderr: vec![],
|
||||
truncated: false,
|
||||
timed_out: false,
|
||||
interrupted: false,
|
||||
};
|
||||
let mut remaining = cap;
|
||||
let status = loop {
|
||||
let drained = drain(
|
||||
&mut stdout,
|
||||
&mut result.stdout,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
)
|
||||
.and_then(|_| {
|
||||
let mut failure = None;
|
||||
for fd in [stdout.as_raw_fd(), stderr.as_raw_fd()] {
|
||||
let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
|
||||
if flags < 0 || unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) } < 0 {
|
||||
failure = Some(anyhow::Error::from(std::io::Error::last_os_error()));
|
||||
break;
|
||||
}
|
||||
}
|
||||
if failure.is_none() {
|
||||
loop {
|
||||
if let Err(e) = drain(
|
||||
&mut stdout,
|
||||
&mut output.stdout,
|
||||
&mut remaining,
|
||||
&mut output.truncated,
|
||||
)
|
||||
.and_then(|_| {
|
||||
drain(
|
||||
&mut stderr,
|
||||
&mut output.stderr,
|
||||
&mut remaining,
|
||||
&mut output.truncated,
|
||||
)
|
||||
}) {
|
||||
failure = Some(e);
|
||||
break;
|
||||
}
|
||||
// WNOWAIT deliberately observes without releasing this child's PID.
|
||||
let mut info = std::mem::MaybeUninit::<libc::siginfo_t>::zeroed();
|
||||
let state = unsafe {
|
||||
libc::waitid(
|
||||
libc::P_PID,
|
||||
child.id(),
|
||||
info.as_mut_ptr(),
|
||||
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
|
||||
)
|
||||
};
|
||||
if state < 0 {
|
||||
let e = std::io::Error::last_os_error();
|
||||
if e.kind() == std::io::ErrorKind::Interrupted {
|
||||
continue;
|
||||
}
|
||||
if e.raw_os_error() == Some(libc::ECHILD) {
|
||||
group.reserved = false;
|
||||
}
|
||||
failure = Some(e.into());
|
||||
break;
|
||||
}
|
||||
if unsafe { info.assume_init().si_pid() } != 0 {
|
||||
break;
|
||||
}
|
||||
let fenced = observe().is_err();
|
||||
if began.elapsed() >= timeout || fenced {
|
||||
output.timed_out = began.elapsed() >= timeout;
|
||||
output.interrupted = fenced;
|
||||
break;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
}
|
||||
if !group.reserved {
|
||||
// An unexpected external reap destroyed the group identity proof. Never
|
||||
// signal/adopt a numerical replacement; caller records Unknown.
|
||||
return Err(failure.unwrap_or_else(|| anyhow::anyhow!("OWNED_GROUP_IDENTITY_LOST")));
|
||||
}
|
||||
group.kill();
|
||||
let cleanup = Instant::now();
|
||||
loop {
|
||||
// A setup error may have left a blocking pipe. It must not become an
|
||||
// unbounded cleanup read; retain only group ownership in that path.
|
||||
let out_closed = if failure.is_some() {
|
||||
Ok(true)
|
||||
} else {
|
||||
drain(
|
||||
&mut stdout,
|
||||
&mut output.stdout,
|
||||
&mut remaining,
|
||||
&mut output.truncated,
|
||||
)
|
||||
};
|
||||
let err_closed = if failure.is_some() {
|
||||
Ok(true)
|
||||
} else {
|
||||
drain(
|
||||
&mut stderr,
|
||||
&mut result.stderr,
|
||||
&mut output.stderr,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
&mut output.truncated,
|
||||
)
|
||||
});
|
||||
if let Err(e) = drained {
|
||||
drop(group);
|
||||
let _ = child.wait();
|
||||
return Err(e);
|
||||
};
|
||||
if out_closed.is_err() || err_closed.is_err() {
|
||||
output.truncated = true;
|
||||
}
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => break status,
|
||||
Ok(None) => {}
|
||||
Err(e) => {
|
||||
drop(group);
|
||||
let _ = child.wait();
|
||||
return Err(e.into());
|
||||
// Only zombies may remain while the *owned* leader stays unreaped.
|
||||
// They cannot execute or retain pipe writers. Unclear /proc state keeps
|
||||
// this owner and the caller's executor lock instead of a replacement.
|
||||
if group_has_no_live_members(group.pid) {
|
||||
if out_closed.unwrap_or(true) && err_closed.unwrap_or(true) {
|
||||
break;
|
||||
}
|
||||
// A privileged script may deliberately give a pipe to an unrelated
|
||||
// process. That process is outside our ownership; never kill it.
|
||||
if cleanup.elapsed() >= Duration::from_millis(250) {
|
||||
output.truncated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if started.elapsed() >= timeout {
|
||||
result.timed_out = true;
|
||||
// SAFETY: this is the dedicated group created for this child.
|
||||
unsafe {
|
||||
libc::kill(-(child.id() as i32), libc::SIGKILL);
|
||||
}
|
||||
break child.wait()?;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(5));
|
||||
};
|
||||
let pgid = child.id();
|
||||
drop(group);
|
||||
// SIGKILL delivery is asynchronous. A single WouldBlock is not EOF and
|
||||
// does not prove that descendants have stopped. Bound both cleanup waiting
|
||||
// and output draining, and withhold a successful exit code if unconfirmed.
|
||||
let cleanup_started = Instant::now();
|
||||
loop {
|
||||
let stdout_closed = drain(
|
||||
&mut stdout,
|
||||
&mut result.stdout,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
)?;
|
||||
let stderr_closed = drain(
|
||||
&mut stderr,
|
||||
&mut result.stderr,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
)?;
|
||||
// SAFETY: signal zero only probes the dedicated process group.
|
||||
let absent = unsafe { libc::kill(-(pgid as i32), 0) } == -1
|
||||
&& std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH);
|
||||
if stdout_closed && stderr_closed && absent {
|
||||
result.code = status.code();
|
||||
break;
|
||||
}
|
||||
if cleanup_started.elapsed() >= Duration::from_millis(250) {
|
||||
result.truncated |= !stdout_closed || !stderr_closed;
|
||||
// None explicitly means no confirmed successful completion. This
|
||||
// can also occur for lingering zombies: never guess their state.
|
||||
result.code = None;
|
||||
break;
|
||||
if cleanup.elapsed() >= Duration::from_millis(250) {
|
||||
output.timed_out = true;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
Ok(result)
|
||||
// Disarm BEFORE releasing the reserved leader PID: no later Drop can signal
|
||||
// a reused PGID. All assigned living members have already ended.
|
||||
group.reserved = false;
|
||||
let status = child.wait()?;
|
||||
if let Some(e) = failure {
|
||||
return Err(e);
|
||||
}
|
||||
output.interrupted |= observe().is_err();
|
||||
output.code = if output.timed_out || began.elapsed() >= timeout {
|
||||
None
|
||||
} else {
|
||||
status.code()
|
||||
};
|
||||
Ok(output)
|
||||
}
|
||||
fn drain(
|
||||
pipe: &mut impl Read,
|
||||
target: &mut Vec<u8>,
|
||||
remaining: &mut usize,
|
||||
truncated: &mut bool,
|
||||
) -> Result<bool> {
|
||||
let mut bytes = [0; 4096];
|
||||
for _ in 0..16 {
|
||||
match pipe.read(&mut bytes) {
|
||||
Ok(0) => return Ok(true),
|
||||
Ok(n) => {
|
||||
let keep = n.min(*remaining);
|
||||
target.extend_from_slice(&bytes[..keep]);
|
||||
*remaining -= keep;
|
||||
*truncated |= keep < n;
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
fn group_has_no_live_members(pgid: u32) -> bool {
|
||||
let Ok(entries) = std::fs::read_dir("/proc") else {
|
||||
return false;
|
||||
};
|
||||
for entry in entries {
|
||||
let Ok(entry) = entry else {
|
||||
return false;
|
||||
};
|
||||
if entry.file_name().to_string_lossy().parse::<u32>().is_err() {
|
||||
continue;
|
||||
}
|
||||
let bytes = match std::fs::read_to_string(entry.path().join("stat")) {
|
||||
Ok(v) => v,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
|
||||
Err(_) => return false,
|
||||
};
|
||||
let Some((_, rest)) = bytes.rsplit_once(") ") else {
|
||||
return false;
|
||||
};
|
||||
let fields: Vec<_> = rest.split_whitespace().take(3).collect();
|
||||
if fields.len() != 3 {
|
||||
return false;
|
||||
}
|
||||
let Ok(group) = fields[2].parse::<u32>() else {
|
||||
return false;
|
||||
};
|
||||
if group == pgid && fields[0] != "Z" && fields[0] != "X" {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn cancellation_observation_terminates_only_owned_group_and_keeps_raw_bounded_output() {
|
||||
let began = Instant::now();
|
||||
let output = run_controlled(
|
||||
"/bin/sh",
|
||||
&[
|
||||
"-c".into(),
|
||||
"printf before; printf err >&2; sleep 10".into(),
|
||||
],
|
||||
Duration::from_secs(5),
|
||||
64,
|
||||
|| {
|
||||
ensure!(
|
||||
began.elapsed() < Duration::from_millis(80),
|
||||
"TEST_CANCELLED"
|
||||
);
|
||||
Ok(())
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert!(output.interrupted);
|
||||
assert!(!output.timed_out);
|
||||
assert_eq!(output.stdout, b"before");
|
||||
assert_eq!(output.stderr, b"err");
|
||||
assert_ne!(output.code, Some(0));
|
||||
assert!(began.elapsed() < Duration::from_secs(2));
|
||||
}
|
||||
#[test]
|
||||
fn exited_leader_does_not_leave_background_effects_or_open_pipes() {
|
||||
let directory =
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
@@ -13,6 +13,12 @@ pub fn socket_for(
|
||||
general: Option<OsString>,
|
||||
apt: Option<OsString>,
|
||||
) -> Result<PathBuf> {
|
||||
if job.action.full_maintenance() {
|
||||
return Ok(PathBuf::from(
|
||||
std::env::var_os("RMM_FULL_MAINTENANCE_HELPER_SOCKET")
|
||||
.context("FULL_MAINTENANCE_SOCKET_NOT_CONFIGURED")?,
|
||||
));
|
||||
}
|
||||
select_socket(provider::is_apt_action(job), general, apt)
|
||||
}
|
||||
fn select_socket(
|
||||
@@ -216,6 +222,23 @@ pub fn invoke(binding: &Binding, job: &JobPayload, request: &Request) -> Result<
|
||||
rmm_privileged_helper::invoke(&socket, request, job.max_runtime_seconds)
|
||||
}
|
||||
|
||||
pub fn invoke_with_control(
|
||||
binding: &Binding,
|
||||
job: &JobPayload,
|
||||
request: &Request,
|
||||
observe: impl FnMut() -> Result<()>,
|
||||
) -> Result<Outcome> {
|
||||
if !job.action.full_maintenance() {
|
||||
return invoke(binding, job, request);
|
||||
}
|
||||
ensure!(
|
||||
crate::helper_sync::general_supported(binding, job),
|
||||
"FULL_MAINTENANCE_POLICY_REQUIRED"
|
||||
);
|
||||
let socket = socket_for(job, None, None)?;
|
||||
rmm_privileged_helper::invoke_controlled(&socket, request, job.max_runtime_seconds, observe)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -354,6 +377,7 @@ mod tests {
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
},
|
||||
execution_identity: "root".into(),
|
||||
not_before: now,
|
||||
|
||||
@@ -9,6 +9,7 @@ struct Endpoint {
|
||||
socket: PathBuf,
|
||||
profile: String,
|
||||
hash: String,
|
||||
binary_hash: Option<String>,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct Helpers {
|
||||
@@ -39,24 +40,44 @@ fn map(s: &root::Snapshot) -> reconcile::HelperSnapshot {
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
fn general(binding: &Binding) -> Result<control::Response> {
|
||||
let socket = std::env::var_os("RMM_HELPER_SOCKET").context("NO_GENERAL_HELPER")?;
|
||||
let path = std::env::var_os("RMM_HELPER_POLICY_FILE").context("GENERAL_POLICY_PIN_REQUIRED")?;
|
||||
fn general(binding: &Binding, full: bool) -> Result<control::Response> {
|
||||
let (socket_name, pin_name, profile) = if full {
|
||||
(
|
||||
"RMM_FULL_MAINTENANCE_HELPER_SOCKET",
|
||||
"RMM_FULL_MAINTENANCE_POLICY_FILE",
|
||||
"full_maintenance_v1",
|
||||
)
|
||||
} else {
|
||||
("RMM_HELPER_SOCKET", "RMM_HELPER_POLICY_FILE", "general")
|
||||
};
|
||||
let socket = std::env::var_os(socket_name).context("NO_GENERAL_HELPER")?;
|
||||
let path = std::env::var_os(pin_name).context("GENERAL_POLICY_PIN_REQUIRED")?;
|
||||
let pin = control::GeneralPin::read(Path::new(&path), binding)?;
|
||||
ensure!(pin.profile == profile, "HELPER_PROFILE_ROUTE_MISMATCH");
|
||||
control::general_probe(Path::new(&socket), binding, &pin)
|
||||
}
|
||||
impl Helpers {
|
||||
pub fn configured(binding: &Binding) -> Result<Self> {
|
||||
let mut endpoints = vec![];
|
||||
if let Some(socket) = std::env::var_os("RMM_HELPER_SOCKET") {
|
||||
let path = std::env::var_os("RMM_HELPER_POLICY_FILE")
|
||||
.context("GENERAL_POLICY_PIN_REQUIRED")?;
|
||||
let pin = control::GeneralPin::read(Path::new(&path), binding)?;
|
||||
endpoints.push(Endpoint {
|
||||
socket: socket.into(),
|
||||
profile: "general".into(),
|
||||
hash: pin.policy_sha256,
|
||||
});
|
||||
for (socket_name, pin_name, profile) in [
|
||||
("RMM_HELPER_SOCKET", "RMM_HELPER_POLICY_FILE", "general"),
|
||||
(
|
||||
"RMM_FULL_MAINTENANCE_HELPER_SOCKET",
|
||||
"RMM_FULL_MAINTENANCE_POLICY_FILE",
|
||||
"full_maintenance_v1",
|
||||
),
|
||||
] {
|
||||
if let Some(socket) = std::env::var_os(socket_name) {
|
||||
let path = std::env::var_os(pin_name).context("GENERAL_POLICY_PIN_REQUIRED")?;
|
||||
let pin = control::GeneralPin::read(Path::new(&path), binding)?;
|
||||
ensure!(pin.profile == profile, "HELPER_PROFILE_ROUTE_MISMATCH");
|
||||
endpoints.push(Endpoint {
|
||||
socket: socket.into(),
|
||||
profile: profile.into(),
|
||||
hash: pin.policy_sha256,
|
||||
binary_hash: pin.helper_binary_sha256,
|
||||
});
|
||||
}
|
||||
}
|
||||
if let Some(socket) = std::env::var_os("RMM_APT_HELPER_SOCKET") {
|
||||
ensure!(
|
||||
@@ -70,6 +91,7 @@ impl Helpers {
|
||||
socket: socket.into(),
|
||||
profile: "apt_only".into(),
|
||||
hash: pin.provider_stack_sha256,
|
||||
binary_hash: None,
|
||||
});
|
||||
}
|
||||
Ok(Self {
|
||||
@@ -79,7 +101,9 @@ impl Helpers {
|
||||
}
|
||||
fn validate(&self, e: &Endpoint, r: &control::Response) -> Result<()> {
|
||||
ensure!(
|
||||
r.profile == e.profile && r.policy_sha256 == e.hash,
|
||||
r.profile == e.profile
|
||||
&& r.policy_sha256 == e.hash
|
||||
&& r.helper_binary_sha256 == e.binary_hash,
|
||||
"HELPER_PIN_PROFILE_MISMATCH"
|
||||
);
|
||||
Ok(())
|
||||
@@ -153,13 +177,39 @@ impl Helpers {
|
||||
}
|
||||
}
|
||||
pub fn general_capabilities(binding: &Binding) -> Vec<String> {
|
||||
let mut caps = profile_capabilities(binding, false);
|
||||
caps.extend(profile_capabilities(binding, true));
|
||||
caps.sort();
|
||||
caps.dedup();
|
||||
caps
|
||||
}
|
||||
fn profile_capabilities(binding: &Binding, full: bool) -> Vec<String> {
|
||||
(|| -> Result<Vec<String>> {
|
||||
let response = general(binding)?;
|
||||
let response = general(binding, full)?;
|
||||
let policy = response.policy.context("NO_GENERAL_POLICY")?;
|
||||
let mut caps = vec![
|
||||
"helper.root.v1".into(),
|
||||
format!("helper.policy.sha256:{}", response.policy_sha256),
|
||||
];
|
||||
if full {
|
||||
ensure!(
|
||||
policy.schema_version == 2
|
||||
&& policy.profile == "full_maintenance_v1"
|
||||
&& policy.allowed_script_profiles.as_deref()
|
||||
== Some(&[rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1]),
|
||||
"FULL_MAINTENANCE_POLICY_REQUIRED"
|
||||
);
|
||||
let binary = policy
|
||||
.helper_binary_sha256
|
||||
.as_ref()
|
||||
.context("FULL_MAINTENANCE_BINARY_PIN_REQUIRED")?;
|
||||
ensure!(
|
||||
response.helper_binary_sha256.as_ref() == Some(binary),
|
||||
"FULL_MAINTENANCE_BINARY_PROOF_REQUIRED"
|
||||
);
|
||||
caps.push(format!("helper.binary.sha256:{binary}"));
|
||||
caps.push(rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY.into());
|
||||
}
|
||||
let mut actions = vec![];
|
||||
if policy.allow_root_scripts && rmm_agent_linux::actions::Interpreter::PosixSh.available() {
|
||||
actions.push("run_script");
|
||||
@@ -180,10 +230,22 @@ pub fn general_capabilities(binding: &Binding) -> Vec<String> {
|
||||
}
|
||||
pub fn general_supported(binding: &Binding, job: &rmm_domain::jobs::JobPayload) -> bool {
|
||||
(|| -> Result<bool> {
|
||||
let p = general(binding)?.policy.context("NO_GENERAL_POLICY")?;
|
||||
let p = general(binding, job.action.full_maintenance())?
|
||||
.policy
|
||||
.context("NO_GENERAL_POLICY")?;
|
||||
Ok(match &job.action {
|
||||
rmm_domain::jobs::Action::RunScript { interpreter, .. } => {
|
||||
p.allow_root_scripts
|
||||
&& job.action.valid_execution_identity(&job.execution_identity)
|
||||
&& job
|
||||
.action
|
||||
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
|
||||
&& (!job.action.full_maintenance()
|
||||
|| p.allowed_script_profiles.as_ref().is_some_and(|v| {
|
||||
v.contains(
|
||||
&rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
|
||||
)
|
||||
}))
|
||||
&& match interpreter.as_str() {
|
||||
"posix_sh" => rmm_agent_linux::actions::Interpreter::PosixSh.available(),
|
||||
"bash" => rmm_agent_linux::actions::Interpreter::Bash.available(),
|
||||
|
||||
@@ -50,6 +50,7 @@ struct Agent<C: reconcile::SyncClock = reconcile::NativeClock> {
|
||||
inventory_tx: tokio::sync::mpsc::Sender<Result<(Vec<u8>, i64)>>,
|
||||
inventory_rx: tokio::sync::mpsc::Receiver<Result<(Vec<u8>, i64)>>,
|
||||
inventory_inflight: bool,
|
||||
running_cancels: std::collections::HashMap<(String, String), Arc<AtomicBool>>,
|
||||
sync: Option<reconcile::ClientSync>,
|
||||
sync_clock: C,
|
||||
helpers: Option<helper_sync::Helpers>,
|
||||
@@ -61,6 +62,7 @@ struct Agent<C: reconcile::SyncClock = reconcile::NativeClock> {
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct EffectFence {
|
||||
running_generation: AtomicU64,
|
||||
generation: AtomicU64,
|
||||
deadline: AtomicI64,
|
||||
root: AtomicBool,
|
||||
@@ -80,6 +82,14 @@ fn report_closed_gate(error: &anyhow::Error) {
|
||||
}
|
||||
impl EffectFence {
|
||||
fn close(&self) {
|
||||
self.running_generation.store(0, Ordering::SeqCst);
|
||||
self.close_starts();
|
||||
}
|
||||
// A signed Sync/start lease authorizes NEW starts. Its natural expiry
|
||||
// cannot retroactively stop an approved bounded process (spec22.3).
|
||||
// Running effects instead observe their exact cancellation and current
|
||||
// connection generation; transport/signed refusal closes both fences.
|
||||
fn close_starts(&self) {
|
||||
self.generation.store(0, Ordering::SeqCst);
|
||||
self.root.store(false, Ordering::SeqCst);
|
||||
}
|
||||
@@ -117,7 +127,7 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
})
|
||||
}
|
||||
async fn start_sync(&mut self, wire: &wire_channel::Handle, generation: u64) -> Result<()> {
|
||||
self.fence.close();
|
||||
self.fence.close_starts();
|
||||
let helpers = self.helpers.clone();
|
||||
let snapshot = tokio::task::spawn_blocking(move || match helpers {
|
||||
Some(h) => h.snapshot(generation),
|
||||
@@ -182,6 +192,9 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
.as_ref()
|
||||
.and_then(|s| s.validity_deadline())
|
||||
.context("SIGNED_LEASE_REQUIRED")?;
|
||||
self.fence
|
||||
.running_generation
|
||||
.store(generation, Ordering::SeqCst);
|
||||
self.fence
|
||||
.deadline
|
||||
.store(deadline.timestamp_millis(), Ordering::SeqCst);
|
||||
@@ -189,6 +202,9 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
.root
|
||||
.store(self.ready(generation, true), Ordering::SeqCst);
|
||||
self.fence.generation.store(generation, Ordering::SeqCst);
|
||||
} else {
|
||||
// A valid signed refusal is a fence too, not just parse/I/O errors.
|
||||
self.fence.close();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -322,6 +338,11 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
}));
|
||||
jobs::event(&tx, &envelope)?;
|
||||
tx.commit()?;
|
||||
let cancellation = Arc::new(AtomicBool::new(false));
|
||||
self.running_cancels.insert(
|
||||
(offer.job_id.clone(), offer.attempt_id.clone()),
|
||||
cancellation.clone(),
|
||||
);
|
||||
let completed = self.completed_tx.clone();
|
||||
let clock = self.clock.clone();
|
||||
let fence = self.fence.clone();
|
||||
@@ -334,7 +355,16 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
{
|
||||
jobs::no_start("failed", "START_WINDOW_OR_CLOCK_INVALID_BEFORE_EFFECT")
|
||||
} else if job.execution_identity == "root" {
|
||||
apt::invoke(&binding, &job, &request).unwrap_or_else(|_| {
|
||||
apt::invoke_with_control(&binding, &job, &request, || {
|
||||
ensure!(
|
||||
!cancellation.load(Ordering::SeqCst)
|
||||
&& fence.running_generation.load(Ordering::SeqCst) == generation
|
||||
&& clock.trusted(),
|
||||
"SCRIPT_RUNNING_CANCEL_OR_FENCE"
|
||||
);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap_or_else(|_| {
|
||||
rmm_privileged_helper::Outcome::unknown("HELPER_TRANSPORT_EFFECT_UNKNOWN")
|
||||
})
|
||||
} else {
|
||||
@@ -537,6 +567,7 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
rusqlite::params![cancel.job_id,cancel.attempt_id], |r| Ok((r.get(0)?,r.get(1)?,r.get(2)?))).optional()?
|
||||
};
|
||||
if let Some((bytes,state,grant)) = row {
|
||||
if let Some(flag) = self.running_cancels.get(&(cancel.job_id.clone(),cancel.attempt_id.clone())) { flag.store(true,Ordering::SeqCst); }
|
||||
self.db.execute("UPDATE job_attempts SET cancel_requested=1 WHERE job=?1 AND attempt=?2", rusqlite::params![cancel.job_id,cancel.attempt_id])?;
|
||||
if state == "accepted" { self.record(generation, &JobOffer::decode(bytes.as_slice())?, &grant, jobs::no_start("cancelled", "CANCELLED_BEFORE_START"))?; }
|
||||
// Running script cancellation is not confirmed by an
|
||||
@@ -549,6 +580,7 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
}
|
||||
}
|
||||
Some((offer, grant, outcome)) = self.completed_rx.recv() => {
|
||||
self.running_cancels.remove(&(offer.job_id.clone(),offer.attempt_id.clone()));
|
||||
// First preserve the original completion without unlocking.
|
||||
// A startup can replay it if the journal transaction is lost.
|
||||
let state = outcome.state.clone();
|
||||
@@ -807,6 +839,7 @@ async fn main() -> Result<()> {
|
||||
inventory_tx,
|
||||
inventory_rx,
|
||||
inventory_inflight: false,
|
||||
running_cancels: std::collections::HashMap::new(),
|
||||
sync,
|
||||
sync_clock: reconcile::NativeClock::default(),
|
||||
helpers,
|
||||
|
||||
@@ -51,6 +51,7 @@ fn new_process_persists_interruption_before_helper_io_without_unlock_or_repeat()
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("fixture only; never executed\n".into()),
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
},
|
||||
execution_identity: "root".into(),
|
||||
not_before: now,
|
||||
@@ -139,6 +140,7 @@ fn new_process_persists_interruption_before_helper_io_without_unlock_or_repeat()
|
||||
inventory_tx: itx,
|
||||
inventory_rx: irx,
|
||||
inventory_inflight: false,
|
||||
running_cancels: std::collections::HashMap::new(),
|
||||
sync: Some(reconcile::ClientSync::new(binding.clone())),
|
||||
sync_clock: Clock(true),
|
||||
helpers: None,
|
||||
@@ -525,6 +527,7 @@ async fn run(mode: wire_channel::Mode, trusted: bool, forged: bool, rounds: u64)
|
||||
inventory_tx: itx,
|
||||
inventory_rx: irx,
|
||||
inventory_inflight: false,
|
||||
running_cancels: std::collections::HashMap::new(),
|
||||
sync: Some(reconcile::ClientSync::new(binding)),
|
||||
sync_clock: Clock(trusted),
|
||||
helpers: None,
|
||||
|
||||
@@ -595,6 +595,7 @@ fn script() -> Action {
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("hello".into()),
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
}
|
||||
}
|
||||
fn success() -> ReconciledOutcome {
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
//! Reproducible Rust-codec fixtures consumed directly by the WebUI tests.
|
||||
use rmm_domain::jobs::*;
|
||||
use serde_json::json;
|
||||
use uuid::Uuid;
|
||||
fn main() {
|
||||
let cases = [
|
||||
(
|
||||
"legacy_linux_agent",
|
||||
"agent_service",
|
||||
"posix_sh",
|
||||
"printf 'hello\\n'\n",
|
||||
None,
|
||||
None,
|
||||
),
|
||||
(
|
||||
"linux_root_full",
|
||||
"root",
|
||||
"posix_sh",
|
||||
"id\nprintf 'root stdout\\n'\nprintf 'root stderr\\n' >&2\n",
|
||||
None,
|
||||
Some(PrivilegedScriptProfile::FullMaintenanceV1),
|
||||
),
|
||||
(
|
||||
"windows_system_full",
|
||||
"system",
|
||||
"powershell",
|
||||
"Write-Output 'SYSTEM stdout'\r\n[Console]::Error.WriteLine('SYSTEM stderr')\r\n",
|
||||
Some(WindowsExecutionProfile::PowerShell51RemoteSigned),
|
||||
Some(PrivilegedScriptProfile::FullMaintenanceV1),
|
||||
),
|
||||
];
|
||||
let values: Vec<_> = cases.into_iter().enumerate().map(|(index, (name, identity, interpreter, script, windows_execution_profile, privileged_script_profile))| {
|
||||
let tenant = Uuid::from_u128(1);
|
||||
let job = JobPayload {
|
||||
schema_version: 1, tenant_id: tenant, asset_id: Uuid::from_u128(2), agent_id: Uuid::from_u128(3),
|
||||
enrollment_generation: 1, assignment_version: 1, job_id: Uuid::from_u128(4+index as u128*10), attempt_id: Uuid::from_u128(5+index as u128*10),
|
||||
action: Action::RunScript { interpreter: interpreter.into(), script_utf8: script.into(), arguments: vec![], expected_stdout: None, windows_execution_profile, privileged_script_profile },
|
||||
execution_identity: identity.into(), not_before: "2026-11-14T12:00:00Z".parse().unwrap(), start_before: "2026-11-14T13:00:00Z".parse().unwrap(), max_runtime_seconds: 30, max_output_bytes: 4096,
|
||||
};
|
||||
let job_bytes = encode(&job).unwrap();
|
||||
let job_hash = hash(&job_bytes);
|
||||
let script_sha256 = hash(script.as_bytes());
|
||||
let plan = PlanPayload { schema_version: 1, plan_id: Uuid::from_u128(6+index as u128*10), tenant_id: tenant, principal: "simulated-dev-script-console".into(), reason: format!("Codec fixture: {name}; no native execution"), jobs: vec![PlannedJob { payload: job, job_payload_hash: job_hash.clone(), script_sha256: Some(script_sha256.clone()) }], max_parallel: 1, halt_after_failures: 1, recipe_references: vec![], artifact_references: vec![] };
|
||||
let bytes = encode(&plan).unwrap();
|
||||
json!({"name":name,"plan_payload_bytes":bytes,"plan_hash":hash(&bytes),"job_payload_bytes":job_bytes,"job_payload_hash":job_hash,"script_sha256":script_sha256})
|
||||
}).collect();
|
||||
println!("{}", serde_json::to_string_pretty(&values).unwrap());
|
||||
}
|
||||
+240
-3
@@ -48,6 +48,61 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// Explicit authority for a separately qualified, fully privileged script.
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
|
||||
pub enum PrivilegedScriptProfile {
|
||||
#[serde(rename = "full_maintenance_v1")]
|
||||
FullMaintenanceV1,
|
||||
}
|
||||
pub const FULL_MAINTENANCE_CAPABILITY: &str = "script.full_maintenance/1";
|
||||
pub fn deserialize_privileged_script_profile<'de, D>(
|
||||
d: D,
|
||||
) -> Result<Option<PrivilegedScriptProfile>, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
let value = String::deserialize(d)?;
|
||||
match value.as_str() {
|
||||
"full_maintenance_v1" => Ok(Some(PrivilegedScriptProfile::FullMaintenanceV1)),
|
||||
_ => Err(serde::de::Error::unknown_variant(
|
||||
&value,
|
||||
&["full_maintenance_v1"],
|
||||
)),
|
||||
}
|
||||
}
|
||||
/// Optional metadata pins preserve old codecs when missing, reject null or
|
||||
/// noncanonical digests when explicitly supplied.
|
||||
pub fn deserialize_optional_sha256<'de, D>(d: D) -> Result<Option<String>, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
let value = String::deserialize(d)?;
|
||||
if value.len() != 64
|
||||
|| !value
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_digit() || b"abcdef".contains(&b))
|
||||
{
|
||||
return Err(serde::de::Error::custom("lowercase SHA256 required"));
|
||||
}
|
||||
Ok(Some(value))
|
||||
}
|
||||
|
||||
/// Policy lists are strict when present; omission is deny, never a wildcard.
|
||||
pub fn deserialize_script_profiles<'de, D>(
|
||||
d: D,
|
||||
) -> Result<Option<Vec<PrivilegedScriptProfile>>, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
let values = Vec::<String>::deserialize(d)?;
|
||||
if values.len() != 1 || values[0] != "full_maintenance_v1" {
|
||||
return Err(serde::de::Error::custom(
|
||||
"exact full_maintenance_v1 profile required",
|
||||
));
|
||||
}
|
||||
Ok(Some(vec![PrivilegedScriptProfile::FullMaintenanceV1]))
|
||||
}
|
||||
|
||||
/// Missing preserves Linux codecs; explicit null/nonobject is never a manifest.
|
||||
pub fn deserialize_windows_msi_manifest<'de, D>(
|
||||
deserializer: D,
|
||||
@@ -74,6 +129,13 @@ pub enum Action {
|
||||
)]
|
||||
#[schemars(with = "WindowsExecutionProfile")]
|
||||
windows_execution_profile: Option<WindowsExecutionProfile>,
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "deserialize_privileged_script_profile",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
#[schemars(with = "PrivilegedScriptProfile")]
|
||||
privileged_script_profile: Option<PrivilegedScriptProfile>,
|
||||
},
|
||||
RefreshInventory {
|
||||
scope: String,
|
||||
@@ -160,6 +222,7 @@ impl Action {
|
||||
arguments,
|
||||
expected_stdout,
|
||||
windows_execution_profile,
|
||||
..
|
||||
} => {
|
||||
matches!(interpreter.as_str(), "posix_sh" | "bash" | "powershell")
|
||||
&& (windows_execution_profile.is_none() || interpreter == "powershell")
|
||||
@@ -296,6 +359,26 @@ impl Action {
|
||||
(matches!(self,Self::SetServiceState{state,..} if matches!(state.as_str(),"running"|"stopped"))
|
||||
&& self.validate())
|
||||
|| (identity == "system" && self.windows_msi().is_some() && self.validate())
|
||||
|| (identity == "system"
|
||||
&& self.full_maintenance()
|
||||
&& self.script_platform() == Some("windows")
|
||||
&& self.validate())
|
||||
}
|
||||
pub fn full_maintenance(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::RunScript {
|
||||
privileged_script_profile: Some(PrivilegedScriptProfile::FullMaintenanceV1),
|
||||
..
|
||||
}
|
||||
)
|
||||
}
|
||||
pub fn valid_execution_identity(&self, identity: &str) -> bool {
|
||||
!self.full_maintenance()
|
||||
|| matches!(
|
||||
(identity, self.script_platform()),
|
||||
("root", Some("linux")) | ("system", Some("windows"))
|
||||
)
|
||||
}
|
||||
pub fn is_windows_event_log_fixture(&self) -> bool {
|
||||
matches!(self, Self::QueryLogs { unit, .. } if unit == WINDOWS_EVENT_LOG_FIXTURE_SOURCE)
|
||||
@@ -304,6 +387,14 @@ impl Action {
|
||||
/// its inner Event Log calls retain their own cooperative <=5s deadline.
|
||||
pub fn valid_job_limits(&self, runtime_seconds: u32, output_bytes: u32) -> bool {
|
||||
(1..=3600).contains(&runtime_seconds)
|
||||
&& (!self.full_maintenance()
|
||||
|| (output_bytes <= 65536
|
||||
&& runtime_seconds
|
||||
<= if self.script_platform() == Some("windows") {
|
||||
120
|
||||
} else {
|
||||
300
|
||||
}))
|
||||
&& (self.windows_msi().is_none()
|
||||
|| ((10..=120).contains(&runtime_seconds)
|
||||
&& (1024..=65536).contains(&output_bytes)))
|
||||
@@ -325,11 +416,23 @@ impl Action {
|
||||
}
|
||||
/// Shared plan/revalidation/start gate. Passive Windows never implies job support.
|
||||
pub fn available_for(&self, identity: &str, capabilities: &[String]) -> bool {
|
||||
if identity == "system" && !self.valid_helper_denial_shape(identity) {
|
||||
if !self.valid_execution_identity(identity)
|
||||
|| (identity == "system" && !self.valid_helper_denial_shape(identity))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let has = |cap: &str| capabilities.iter().any(|c| c == cap);
|
||||
if !has(self.name()) {
|
||||
if !has(self.name())
|
||||
|| (self.full_maintenance()
|
||||
&& !(has(FULL_MAINTENANCE_CAPABILITY)
|
||||
&& has("rmm.sync.v1")
|
||||
&& has(&format!("{}:run_script", identity))
|
||||
&& has(if identity == "root" {
|
||||
"helper.root.v1"
|
||||
} else {
|
||||
"helper.system.v1"
|
||||
})))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
match self {
|
||||
@@ -338,7 +441,7 @@ impl Action {
|
||||
windows_execution_profile,
|
||||
..
|
||||
} if interpreter == "powershell" => {
|
||||
identity == "agent_service"
|
||||
(identity == "agent_service" || (identity == "system" && self.full_maintenance()))
|
||||
&& has("windows.base/1")
|
||||
&& !has("linux.base/1")
|
||||
&& has("rmm.sync.v1")
|
||||
@@ -643,6 +746,7 @@ mod tests {
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
};
|
||||
let mut all = caps;
|
||||
all.extend(["run_script".into(), "script.powershell/1".into()]);
|
||||
@@ -653,6 +757,7 @@ mod tests {
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
};
|
||||
let reboot = Action::Reboot {
|
||||
reason: "fixed test".into(),
|
||||
@@ -675,6 +780,7 @@ mod tests {
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("Hello\r\n".into()),
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
};
|
||||
let caps: Vec<String> = [
|
||||
"windows.base/1",
|
||||
@@ -744,6 +850,136 @@ mod tests {
|
||||
));
|
||||
}
|
||||
#[test]
|
||||
fn full_maintenance_is_explicit_strict_identity_and_capability_bound() {
|
||||
let legacy = br#"{"action":"run_script","interpreter":"posix_sh","script_utf8":"id\n","arguments":[],"expected_stdout":null}"#;
|
||||
let mut action: Action = serde_json::from_slice(legacy).unwrap();
|
||||
assert_eq!(encode(&action).unwrap(), legacy);
|
||||
for value in [
|
||||
serde_json::Value::Null,
|
||||
serde_json::json!({"FullMaintenanceV1":null}),
|
||||
serde_json::json!("latest"),
|
||||
serde_json::json!(true),
|
||||
] {
|
||||
let mut input: serde_json::Value = serde_json::from_slice(legacy).unwrap();
|
||||
input["privileged_script_profile"] = value;
|
||||
assert!(serde_json::from_value::<Action>(input).is_err());
|
||||
}
|
||||
if let Action::RunScript {
|
||||
privileged_script_profile,
|
||||
..
|
||||
} = &mut action
|
||||
{
|
||||
*privileged_script_profile = Some(PrivilegedScriptProfile::FullMaintenanceV1);
|
||||
}
|
||||
assert!(action.validate());
|
||||
assert!(action.valid_execution_identity("root"));
|
||||
assert!(!action.valid_execution_identity("agent_service"));
|
||||
assert!(!action.valid_execution_identity("system"));
|
||||
assert!(action.valid_job_limits(300, 65536));
|
||||
assert!(!action.valid_job_limits(301, 65536));
|
||||
assert!(!action.valid_job_limits(300, 65537));
|
||||
let caps: Vec<String> = [
|
||||
"linux.base/1",
|
||||
"rmm.sync.v1",
|
||||
"helper.root.v1",
|
||||
"run_script",
|
||||
"root:run_script",
|
||||
FULL_MAINTENANCE_CAPABILITY,
|
||||
]
|
||||
.into_iter()
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
assert!(action.available_for("root", &caps));
|
||||
for missing in &caps {
|
||||
assert!(
|
||||
!action.available_for(
|
||||
"root",
|
||||
&caps
|
||||
.iter()
|
||||
.filter(|c| *c != missing)
|
||||
.cloned()
|
||||
.collect::<Vec<_>>()
|
||||
)
|
||||
);
|
||||
}
|
||||
assert!(!action.available_for("agent_service", &caps));
|
||||
if let Action::RunScript {
|
||||
interpreter,
|
||||
script_utf8,
|
||||
windows_execution_profile,
|
||||
..
|
||||
} = &mut action
|
||||
{
|
||||
*interpreter = "powershell".into();
|
||||
*script_utf8 = "Write-Output 'hi'\r\n".into();
|
||||
*windows_execution_profile = Some(WindowsExecutionProfile::PowerShell51RemoteSigned);
|
||||
}
|
||||
assert!(action.valid_helper_denial_shape("system"));
|
||||
assert!(!action.valid_helper_denial_shape("root"));
|
||||
assert!(action.valid_job_limits(120, 65536));
|
||||
assert!(!action.valid_job_limits(121, 65536));
|
||||
let caps: Vec<String> = [
|
||||
"windows.base/1",
|
||||
"rmm.sync.v1",
|
||||
"helper.system.v1",
|
||||
"run_script",
|
||||
"system:run_script",
|
||||
"script.powershell/1",
|
||||
"script.powershell.process_remote_signed/1",
|
||||
FULL_MAINTENANCE_CAPABILITY,
|
||||
]
|
||||
.into_iter()
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
assert!(action.available_for("system", &caps));
|
||||
for missing in &caps {
|
||||
assert!(
|
||||
!action.available_for(
|
||||
"system",
|
||||
&caps
|
||||
.iter()
|
||||
.filter(|c| *c != missing)
|
||||
.cloned()
|
||||
.collect::<Vec<_>>()
|
||||
)
|
||||
);
|
||||
}
|
||||
assert!(!action.available_for("root", &caps));
|
||||
}
|
||||
#[test]
|
||||
fn script_console_golden_plans_use_actual_rust_codec() {
|
||||
let cases: Vec<serde_json::Value> = serde_json::from_str(include_str!(
|
||||
"../../../tests/script_console/codec-golden.json"
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(cases.len(), 3);
|
||||
for case in cases {
|
||||
let bytes: Vec<u8> =
|
||||
serde_json::from_value(case["plan_payload_bytes"].clone()).unwrap();
|
||||
let plan: PlanPayload = serde_json::from_slice(&bytes).unwrap();
|
||||
assert_eq!(encode(&plan).unwrap(), bytes);
|
||||
assert_eq!(hash(&bytes), case["plan_hash"]);
|
||||
let job = &plan.jobs[0];
|
||||
let job_bytes = encode(&job.payload).unwrap();
|
||||
assert_eq!(
|
||||
serde_json::to_value(&job_bytes).unwrap(),
|
||||
case["job_payload_bytes"]
|
||||
);
|
||||
assert_eq!(hash(&job_bytes), job.job_payload_hash);
|
||||
assert_eq!(job.job_payload_hash, case["job_payload_hash"]);
|
||||
assert!(job.payload.action.validate());
|
||||
assert!(
|
||||
job.payload
|
||||
.action
|
||||
.valid_execution_identity(&job.payload.execution_identity)
|
||||
);
|
||||
let Action::RunScript { script_utf8, .. } = &job.payload.action else {
|
||||
panic!("script fixture")
|
||||
};
|
||||
assert_eq!(hash(script_utf8.as_bytes()), case["script_sha256"]);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn codec_golden_and_exact_script_bytes() {
|
||||
let a = Action::RunScript {
|
||||
interpreter: "posix_sh".into(),
|
||||
@@ -751,6 +987,7 @@ mod tests {
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
};
|
||||
assert_eq!(
|
||||
String::from_utf8(encode(&a).unwrap()).unwrap(),
|
||||
|
||||
@@ -482,6 +482,7 @@ fn signed_request() -> (
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
},
|
||||
execution_identity: "root".into(),
|
||||
not_before: now - chrono::Duration::seconds(1),
|
||||
|
||||
@@ -69,6 +69,18 @@ pub struct Policy {
|
||||
pub allowed_services: Vec<String>,
|
||||
pub allow_root_scripts: bool,
|
||||
pub allow_reboot: bool,
|
||||
#[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>>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
deserialize_with = "rmm_domain::jobs::deserialize_optional_sha256"
|
||||
)]
|
||||
pub helper_binary_sha256: Option<String>,
|
||||
}
|
||||
impl Policy {
|
||||
pub fn sha256(&self) -> Result<String> {
|
||||
@@ -90,6 +102,12 @@ pub struct Response {
|
||||
pub ledger_inode: u64,
|
||||
pub lock_device: u64,
|
||||
pub lock_inode: u64,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
deserialize_with = "rmm_domain::jobs::deserialize_optional_sha256"
|
||||
)]
|
||||
pub helper_binary_sha256: Option<String>,
|
||||
}
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
@@ -98,6 +116,12 @@ pub struct GeneralPin {
|
||||
pub profile: String,
|
||||
pub identity: Identity,
|
||||
pub policy_sha256: String,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
deserialize_with = "rmm_domain::jobs::deserialize_optional_sha256"
|
||||
)]
|
||||
pub helper_binary_sha256: Option<String>,
|
||||
}
|
||||
impl GeneralPin {
|
||||
pub fn read(path: &Path, binding: &Binding) -> Result<Self> {
|
||||
@@ -105,8 +129,12 @@ impl GeneralPin {
|
||||
ensure!(fs::metadata(path)?.len() <= 8192, "POLICY_PIN_LIMIT");
|
||||
let pin: Self = serde_json::from_slice(&fs::read(path)?)?;
|
||||
ensure!(
|
||||
pin.schema_version == 1
|
||||
((pin.schema_version == 1
|
||||
&& pin.profile == "general"
|
||||
&& pin.helper_binary_sha256.is_none())
|
||||
|| (pin.schema_version == 2
|
||||
&& pin.profile == "full_maintenance_v1"
|
||||
&& pin.helper_binary_sha256.as_ref().is_some_and(|h| digest(h))))
|
||||
&& pin.identity == Identity::from_binding(binding)?
|
||||
&& digest(&pin.policy_sha256),
|
||||
"POLICY_PIN_BINDING"
|
||||
@@ -199,9 +227,20 @@ pub fn validate_response(request: &Request, response: &Response, binding: &Bindi
|
||||
&& response.challenge == challenge
|
||||
&& &response.identity == identity
|
||||
&& response.identity == Identity::from_binding(binding)?
|
||||
&& matches!(response.profile.as_str(), "general" | "apt_only")
|
||||
&& matches!(
|
||||
response.profile.as_str(),
|
||||
"general" | "apt_only" | "full_maintenance_v1"
|
||||
)
|
||||
&& response.ledger_inode != 0
|
||||
&& response.lock_inode != 0,
|
||||
&& response.lock_inode != 0
|
||||
&& if response.profile == "full_maintenance_v1" {
|
||||
response
|
||||
.helper_binary_sha256
|
||||
.as_ref()
|
||||
.is_some_and(|h| digest(h))
|
||||
} else {
|
||||
response.helper_binary_sha256.is_none()
|
||||
},
|
||||
"HELPER_CONTROL_RESPONSE_BINDING"
|
||||
);
|
||||
Ok(())
|
||||
@@ -214,8 +253,23 @@ pub fn general_probe(socket: &Path, binding: &Binding, pin: &GeneralPin) -> Resu
|
||||
let response = call(socket, binding, &request)?;
|
||||
let policy = response.policy.as_ref().context("GENERAL_POLICY_MISSING")?;
|
||||
ensure!(
|
||||
response.profile == "general"
|
||||
&& policy.profile == "general"
|
||||
response.profile == pin.profile
|
||||
&& policy.profile == pin.profile
|
||||
&& ((policy.schema_version == 1
|
||||
&& policy.profile == "general"
|
||||
&& policy.allowed_script_profiles.is_none()
|
||||
&& policy.helper_binary_sha256.is_none()
|
||||
&& pin.helper_binary_sha256.is_none())
|
||||
|| (policy.schema_version == 2
|
||||
&& policy.profile == "full_maintenance_v1"
|
||||
&& policy.allowed_script_profiles.as_deref()
|
||||
== Some(&[rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1])
|
||||
&& policy.helper_binary_sha256 == pin.helper_binary_sha256
|
||||
&& response.helper_binary_sha256 == pin.helper_binary_sha256
|
||||
&& pin.helper_binary_sha256.is_some()
|
||||
&& policy.allow_root_scripts
|
||||
&& !policy.allow_reboot
|
||||
&& policy.allowed_services.is_empty()))
|
||||
&& response.policy_sha256 == pin.policy_sha256
|
||||
&& policy.sha256()? == pin.policy_sha256
|
||||
&& policy.identity == pin.identity,
|
||||
@@ -264,8 +318,21 @@ mod tests {
|
||||
ledger_inode: 2,
|
||||
lock_device: 1,
|
||||
lock_inode: 3,
|
||||
helper_binary_sha256: None,
|
||||
};
|
||||
validate_response(&q, &r, &b).unwrap();
|
||||
let legacy = serde_json::to_value(&r).unwrap();
|
||||
assert!(legacy.get("helper_binary_sha256").is_none());
|
||||
let mut null = legacy.clone();
|
||||
null["helper_binary_sha256"] = serde_json::Value::Null;
|
||||
assert!(serde_json::from_value::<Response>(null).is_err());
|
||||
r.profile = "full_maintenance_v1".into();
|
||||
assert!(validate_response(&q, &r, &b).is_err());
|
||||
r.helper_binary_sha256 = Some("ab".repeat(32));
|
||||
validate_response(&q, &r, &b).unwrap();
|
||||
r.profile = "general".into();
|
||||
assert!(validate_response(&q, &r, &b).is_err());
|
||||
r.helper_binary_sha256 = None;
|
||||
r.challenge = Uuid::new_v4();
|
||||
assert!(validate_response(&q, &r, &b).is_err());
|
||||
r.challenge = challenge;
|
||||
@@ -313,6 +380,8 @@ mod tests {
|
||||
allowed_services: vec!["rmm-acceptance.service".into()],
|
||||
allow_root_scripts: false,
|
||||
allow_reboot: false,
|
||||
allowed_script_profiles: None,
|
||||
helper_binary_sha256: None,
|
||||
};
|
||||
let old = p.sha256().unwrap();
|
||||
let mut changed = p.clone();
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
//! Root observes its own *running* executable. An agent-readable configured
|
||||
//! pathname or a build claim is never substituted for this descriptor.
|
||||
use anyhow::{Result, ensure};
|
||||
use openssl::sha::Sha256;
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{Read, Seek, SeekFrom},
|
||||
os::unix::fs::MetadataExt,
|
||||
};
|
||||
|
||||
pub struct RunningImage {
|
||||
file: File,
|
||||
expected: String,
|
||||
}
|
||||
impl RunningImage {
|
||||
pub fn current(expected: &str) -> Result<Self> {
|
||||
let mut value = Self {
|
||||
file: File::open("/proc/self/exe")?,
|
||||
expected: expected.into(),
|
||||
};
|
||||
value.verify()?;
|
||||
Ok(value)
|
||||
}
|
||||
pub fn verify(&mut self) -> Result<String> {
|
||||
let before = self.file.metadata()?;
|
||||
ensure!(
|
||||
before.is_file()
|
||||
&& before.uid() == 0
|
||||
&& before.mode() & 0o022 == 0
|
||||
&& before.len() > 0
|
||||
&& before.len() <= 128 * 1024 * 1024,
|
||||
"RUNNING_HELPER_IMAGE_METADATA"
|
||||
);
|
||||
let identity = |m: &std::fs::Metadata| {
|
||||
(
|
||||
m.dev(),
|
||||
m.ino(),
|
||||
m.len(),
|
||||
m.uid(),
|
||||
m.mode(),
|
||||
m.mtime(),
|
||||
m.mtime_nsec(),
|
||||
m.ctime(),
|
||||
m.ctime_nsec(),
|
||||
)
|
||||
};
|
||||
self.file.seek(SeekFrom::Start(0))?;
|
||||
let mut hash = Sha256::new();
|
||||
let mut buffer = [0u8; 65536];
|
||||
let mut length = 0u64;
|
||||
loop {
|
||||
let n = self.file.read(&mut buffer)?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
length += n as u64;
|
||||
ensure!(
|
||||
length <= before.len(),
|
||||
"RUNNING_HELPER_IMAGE_LENGTH_CHANGED"
|
||||
);
|
||||
hash.update(&buffer[..n]);
|
||||
}
|
||||
let actual = hex::encode(hash.finish());
|
||||
ensure!(
|
||||
length == before.len()
|
||||
&& identity(&before) == identity(&self.file.metadata()?)
|
||||
&& actual == self.expected,
|
||||
"RUNNING_HELPER_IMAGE_PIN_MISMATCH"
|
||||
);
|
||||
Ok(actual)
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn actual_running_image_is_independent_of_a_claimed_path_or_digest() {
|
||||
let metadata = std::fs::metadata("/proc/self/exe").unwrap();
|
||||
let bytes = std::fs::read("/proc/self/exe").unwrap();
|
||||
let actual = hex::encode(openssl::sha::sha256(&bytes));
|
||||
if metadata.uid() == 0 && metadata.mode() & 0o022 == 0 {
|
||||
let mut image = RunningImage::current(&actual).unwrap();
|
||||
assert_eq!(image.verify().unwrap(), actual);
|
||||
} else {
|
||||
// An untrusted-owned/writable executable must fail even if its
|
||||
// content hash is correct. This is a tested denial, never a skip.
|
||||
assert!(RunningImage::current(&actual).is_err());
|
||||
}
|
||||
assert!(RunningImage::current(&"00".repeat(32)).is_err());
|
||||
}
|
||||
}
|
||||
@@ -124,13 +124,17 @@ pub fn save_start(
|
||||
}
|
||||
|
||||
pub fn script(job: &JobPayload) -> Result<Outcome> {
|
||||
use rmm_agent_linux::actions::{Interpreter, ScriptRequest, run_script};
|
||||
script_controlled(job, || Ok(()))
|
||||
}
|
||||
pub fn script_controlled(job: &JobPayload, observe: impl FnMut() -> Result<()>) -> Result<Outcome> {
|
||||
use rmm_agent_linux::actions::{Interpreter, ScriptRequest, run_script_controlled};
|
||||
let rmm_domain::jobs::Action::RunScript {
|
||||
interpreter,
|
||||
script_utf8,
|
||||
arguments,
|
||||
expected_stdout,
|
||||
windows_execution_profile: None,
|
||||
..
|
||||
} = &job.action
|
||||
else {
|
||||
anyhow::bail!("NOT_SCRIPT")
|
||||
@@ -147,14 +151,15 @@ pub fn script(job: &JobPayload) -> Result<Outcome> {
|
||||
std::time::Duration::from_secs(job.max_runtime_seconds.into()),
|
||||
job.max_output_bytes as usize,
|
||||
)?;
|
||||
let output = run_script(&request)?;
|
||||
let output = run_script_controlled(&request, observe)?;
|
||||
let passed = output.code == Some(0)
|
||||
&& !output.timed_out
|
||||
&& !output.interrupted
|
||||
&& expected_stdout
|
||||
.as_ref()
|
||||
.is_none_or(|s| !output.truncated && output.stdout == s.as_bytes());
|
||||
Ok(Outcome {
|
||||
state: if output.timed_out || output.code.is_none() {
|
||||
state: if output.timed_out || output.interrupted || output.code.is_none() {
|
||||
"unknown"
|
||||
} else if passed {
|
||||
"succeeded"
|
||||
@@ -167,9 +172,11 @@ pub fn script(job: &JobPayload) -> Result<Outcome> {
|
||||
exit_code: output.code,
|
||||
output_truncated: output.truncated,
|
||||
reboot_required: false,
|
||||
evidence: serde_json::json!({"postconditions_passed":passed}),
|
||||
evidence: serde_json::json!({"postconditions_passed":passed,"script_sha256":rmm_domain::jobs::hash(script_utf8.as_bytes()),"privileged_script_profile":if job.action.full_maintenance(){Some("full_maintenance_v1")}else{None},"execution_uid":unsafe{libc::geteuid()},"output_encoding":"raw_native_bytes","cancel_or_fence_observed":output.interrupted,"termination_does_not_prove_absence_of_effects":output.interrupted||output.timed_out}),
|
||||
error_code: if passed {
|
||||
""
|
||||
} else if output.interrupted {
|
||||
"CANCEL_OR_FENCE_EFFECT_UNKNOWN"
|
||||
} else if output.timed_out {
|
||||
"TIMEOUT_EFFECT_UNKNOWN"
|
||||
} else {
|
||||
@@ -210,6 +217,14 @@ pub struct TrustedClock {
|
||||
/// Local client authenticates the root process as well as the root-owned socket.
|
||||
/// A malicious same-user Unix server must not be able to forge helper success.
|
||||
pub fn invoke(socket: &Path, request: &Request, max_runtime_seconds: u32) -> Result<Outcome> {
|
||||
invoke_controlled(socket, request, max_runtime_seconds, || Ok(()))
|
||||
}
|
||||
pub fn invoke_controlled(
|
||||
socket: &Path,
|
||||
request: &Request,
|
||||
max_runtime_seconds: u32,
|
||||
mut observe: impl FnMut() -> Result<()>,
|
||||
) -> Result<Outcome> {
|
||||
use std::{
|
||||
io::{Read, Write},
|
||||
os::{
|
||||
@@ -256,16 +271,50 @@ pub fn invoke(socket: &Path, request: &Request, max_runtime_seconds: u32) -> Res
|
||||
stream.set_read_timeout(Some(Duration::from_secs(
|
||||
u64::from(max_runtime_seconds) + 10,
|
||||
)))?;
|
||||
observe()?;
|
||||
let bytes = serde_json::to_vec(request)?;
|
||||
ensure!(bytes.len() <= 512 * 1024, "HELPER_REQUEST_SIZE");
|
||||
stream.write_all(&(u32::try_from(bytes.len())?).to_be_bytes())?;
|
||||
stream.write_all(&bytes)?;
|
||||
stream.set_read_timeout(Some(Duration::from_millis(50)))?;
|
||||
let started = std::time::Instant::now();
|
||||
let mut closed = false;
|
||||
let mut read = |stream: &mut UnixStream, mut target: &mut [u8]| -> Result<()> {
|
||||
while !target.is_empty() {
|
||||
if !closed && observe().is_err() {
|
||||
// Half-close only this exact authenticated request stream. The
|
||||
// helper treats its EOF as cancellation; result reads continue.
|
||||
stream.shutdown(std::net::Shutdown::Write)?;
|
||||
closed = true;
|
||||
}
|
||||
ensure!(
|
||||
started.elapsed() < Duration::from_secs(u64::from(max_runtime_seconds) + 10),
|
||||
"HELPER_RESPONSE_TIMEOUT_EFFECT_UNKNOWN"
|
||||
);
|
||||
match stream.read(target) {
|
||||
Ok(0) => anyhow::bail!("HELPER_RESPONSE_CLOSED_EFFECT_UNKNOWN"),
|
||||
Ok(n) => target = &mut target[n..],
|
||||
Err(e)
|
||||
if matches!(
|
||||
e.kind(),
|
||||
std::io::ErrorKind::WouldBlock
|
||||
| std::io::ErrorKind::TimedOut
|
||||
| std::io::ErrorKind::Interrupted
|
||||
) =>
|
||||
{
|
||||
continue;
|
||||
}
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
let mut length = [0; 4];
|
||||
stream.read_exact(&mut length)?;
|
||||
read(&mut stream, &mut length)?;
|
||||
let length = u32::from_be_bytes(length) as usize;
|
||||
ensure!(length <= 2 * 1024 * 1024, "HELPER_RESPONSE_SIZE");
|
||||
let mut bytes = vec![0; length];
|
||||
stream.read_exact(&mut bytes)?;
|
||||
read(&mut stream, &mut bytes)?;
|
||||
let outcome: Outcome = serde_json::from_slice(&bytes)?;
|
||||
ensure!(
|
||||
outcome.stdout.len() + outcome.stderr.len() <= 262144,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
mod image;
|
||||
use anyhow::{Result, ensure};
|
||||
use rmm_domain::jobs::Action;
|
||||
use rmm_privileged_helper::{
|
||||
@@ -33,6 +34,16 @@ struct Config {
|
||||
allowed_services: Vec<String>,
|
||||
allow_reboot: bool,
|
||||
allow_root_scripts: bool,
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "rmm_domain::jobs::deserialize_script_profiles"
|
||||
)]
|
||||
allowed_script_profiles: Option<Vec<rmm_domain::jobs::PrivilegedScriptProfile>>,
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "rmm_domain::jobs::deserialize_optional_sha256"
|
||||
)]
|
||||
helper_binary_sha256: Option<String>,
|
||||
#[serde(default)]
|
||||
apt_provider: Option<rmm_privileged_helper::apt::ProviderConfig>,
|
||||
}
|
||||
@@ -42,16 +53,28 @@ enum HelperProfile {
|
||||
#[default]
|
||||
General,
|
||||
AptOnly,
|
||||
FullMaintenanceV1,
|
||||
}
|
||||
impl Config {
|
||||
fn general_policy(&self) -> Result<control::Policy> {
|
||||
Ok(control::Policy {
|
||||
schema_version: 1,
|
||||
profile: "general".into(),
|
||||
schema_version: if self.profile == HelperProfile::FullMaintenanceV1 {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
},
|
||||
profile: if self.profile == HelperProfile::FullMaintenanceV1 {
|
||||
"full_maintenance_v1"
|
||||
} else {
|
||||
"general"
|
||||
}
|
||||
.into(),
|
||||
identity: rmm_privileged_helper::readiness::Identity::from_binding(&self.binding)?,
|
||||
allowed_services: self.allowed_services.clone(),
|
||||
allow_root_scripts: self.allow_root_scripts,
|
||||
allow_reboot: self.allow_reboot,
|
||||
allowed_script_profiles: self.allowed_script_profiles.clone(),
|
||||
helper_binary_sha256: self.helper_binary_sha256.clone(),
|
||||
})
|
||||
}
|
||||
fn validate_profile(&self) -> Result<()> {
|
||||
@@ -60,7 +83,19 @@ impl Config {
|
||||
== std::path::Path::new(rmm_privileged_helper::readiness::SHARED_STATE),
|
||||
"SHARED_HELPER_LEDGER_REQUIRED"
|
||||
);
|
||||
if self.profile == HelperProfile::AptOnly {
|
||||
if self.profile == HelperProfile::FullMaintenanceV1 {
|
||||
ensure!(
|
||||
self.apt_provider.is_none()
|
||||
&& self.allowed_services.is_empty()
|
||||
&& !self.allow_reboot
|
||||
&& self.allow_root_scripts
|
||||
&& self.allowed_script_profiles.as_deref()
|
||||
== Some(&[rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1])
|
||||
&& self.socket.as_path()
|
||||
!= std::path::Path::new(rmm_privileged_helper::readiness::SOCKET),
|
||||
"FULL_MAINTENANCE_PROFILE"
|
||||
);
|
||||
} else if self.profile == HelperProfile::AptOnly {
|
||||
ensure!(
|
||||
self.agent_uid == 993
|
||||
&& self.socket.as_path()
|
||||
@@ -79,6 +114,19 @@ impl Config {
|
||||
"GENERAL_HELPER_CANNOT_RUN_APT"
|
||||
);
|
||||
}
|
||||
ensure!(
|
||||
self.profile == HelperProfile::FullMaintenanceV1
|
||||
|| self.allowed_script_profiles.is_none(),
|
||||
"FULL_MAINTENANCE_EXPLICIT_PROFILE_REQUIRED"
|
||||
);
|
||||
ensure!(
|
||||
if self.profile == HelperProfile::FullMaintenanceV1 {
|
||||
self.helper_binary_sha256.is_some()
|
||||
} else {
|
||||
self.helper_binary_sha256.is_none()
|
||||
},
|
||||
"FULL_MAINTENANCE_BINARY_PIN_REQUIRED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -138,9 +186,21 @@ fn policy(config: &Config, job: &rmm_domain::jobs::JobPayload) -> Result<()> {
|
||||
config.profile != HelperProfile::AptOnly,
|
||||
"APT_ONLY_CROSS_ACTION_DENIED"
|
||||
);
|
||||
ensure!(
|
||||
config.profile != HelperProfile::FullMaintenanceV1 || job.action.full_maintenance(),
|
||||
"FULL_MAINTENANCE_ONLY_SCRIPT"
|
||||
);
|
||||
match &job.action {
|
||||
Action::RunScript { interpreter, .. } => {
|
||||
ensure!(config.allow_root_scripts, "ROOT_SCRIPT_DENIED");
|
||||
ensure!(
|
||||
job.action.full_maintenance()
|
||||
== (config.profile == HelperProfile::FullMaintenanceV1)
|
||||
&& job.action.valid_execution_identity(&job.execution_identity)
|
||||
&& (!job.action.full_maintenance()
|
||||
|| (job.max_runtime_seconds <= 300 && job.max_output_bytes <= 65536)),
|
||||
"ROOT_SCRIPT_PROFILE_DENIED"
|
||||
);
|
||||
let available = match interpreter.as_str() {
|
||||
"posix_sh" => rmm_agent_linux::actions::Interpreter::PosixSh.available(),
|
||||
"bash" => rmm_agent_linux::actions::Interpreter::Bash.available(),
|
||||
@@ -267,6 +327,7 @@ fn handle(
|
||||
clock: &rmm_privileged_helper::TrustedClock,
|
||||
sync: &mut reconcile::HelperSync,
|
||||
sync_clock: &reconcile::NativeClock,
|
||||
mut image: Option<&mut image::RunningImage>,
|
||||
) -> Result<()> {
|
||||
use rusqlite::OptionalExtension;
|
||||
peer_allowed(stream, config.agent_uid)?;
|
||||
@@ -278,6 +339,11 @@ fn handle(
|
||||
ensure!(size <= 8 * 1024 * 1024, "REQUEST_SIZE");
|
||||
let mut bytes = vec![0; size];
|
||||
stream.read_exact(&mut bytes)?;
|
||||
let binary_sha256 = image.as_mut().map(|i| i.verify()).transpose()?;
|
||||
ensure!(
|
||||
binary_sha256 == config.helper_binary_sha256,
|
||||
"RUNNING_HELPER_BINARY_CHANGED"
|
||||
);
|
||||
let request: Request = match serde_json::from_slice::<Incoming>(&bytes)? {
|
||||
Incoming::Job(request) => {
|
||||
ensure!(size <= 512 * 1024, "JOB_REQUEST_SIZE");
|
||||
@@ -328,11 +394,11 @@ fn handle(
|
||||
unlocked = applied.unlocked_grants;
|
||||
}
|
||||
control::Request::Policy { .. } => ensure!(
|
||||
config.profile == HelperProfile::General,
|
||||
config.profile != HelperProfile::AptOnly,
|
||||
"GENERAL_POLICY_PROFILE"
|
||||
),
|
||||
}
|
||||
let general = config.profile == HelperProfile::General;
|
||||
let general = config.profile != HelperProfile::AptOnly;
|
||||
let policy = if general {
|
||||
Some(config.general_policy()?)
|
||||
} else {
|
||||
@@ -355,7 +421,14 @@ fn handle(
|
||||
schema_version: 1,
|
||||
challenge,
|
||||
identity: identity.clone(),
|
||||
profile: if general { "general" } else { "apt_only" }.into(),
|
||||
profile: if config.profile == HelperProfile::FullMaintenanceV1 {
|
||||
"full_maintenance_v1"
|
||||
} else if general {
|
||||
"general"
|
||||
} else {
|
||||
"apt_only"
|
||||
}
|
||||
.into(),
|
||||
policy_sha256,
|
||||
policy,
|
||||
snapshot,
|
||||
@@ -364,6 +437,7 @@ fn handle(
|
||||
ledger_inode: ledger.ino(),
|
||||
lock_device: lock.dev(),
|
||||
lock_inode: lock.ino(),
|
||||
helper_binary_sha256: binary_sha256.clone(),
|
||||
};
|
||||
let bytes = serde_json::to_vec(&response)?;
|
||||
ensure!(bytes.len() <= 8 * 1024 * 1024, "CONTROL_RESPONSE_LIMIT");
|
||||
@@ -441,6 +515,10 @@ fn handle(
|
||||
if let Some(apt) = &apt {
|
||||
apt.verify_retry_history(db)?;
|
||||
}
|
||||
ensure!(
|
||||
image.as_mut().map(|i| i.verify()).transpose()? == config.helper_binary_sha256,
|
||||
"RUNNING_HELPER_BINARY_CHANGED"
|
||||
);
|
||||
rmm_privileged_helper::begin_execution(db, &permit, &request)?;
|
||||
let mut outcome =
|
||||
if !clock.trusted() || config.binding.verify(&request, chrono::Utc::now()).is_err() {
|
||||
@@ -454,7 +532,31 @@ fn handle(
|
||||
apt.execute(db)
|
||||
.unwrap_or_else(|_| Outcome::unknown("APT_HELPER_EFFECT_UNKNOWN"))
|
||||
} else {
|
||||
execute(&job).unwrap_or_else(|_| Outcome::unknown("HELPER_EFFECT_UNKNOWN"))
|
||||
if job.action.full_maintenance() {
|
||||
rmm_privileged_helper::script_controlled(&job, || {
|
||||
ensure!(clock.trusted(), "CLOCK_UNTRUSTED");
|
||||
peer_allowed(stream, config.agent_uid)?;
|
||||
let mut byte = 0u8;
|
||||
let read = unsafe {
|
||||
libc::recv(
|
||||
stream.as_raw_fd(),
|
||||
(&mut byte as *mut u8).cast(),
|
||||
1,
|
||||
libc::MSG_PEEK | libc::MSG_DONTWAIT,
|
||||
)
|
||||
};
|
||||
ensure!(
|
||||
read < 0
|
||||
&& std::io::Error::last_os_error().kind()
|
||||
== std::io::ErrorKind::WouldBlock,
|
||||
"SCRIPT_CALLER_CANCELLED_OR_DISCONNECTED"
|
||||
);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap_or_else(|_| Outcome::unknown("HELPER_SCRIPT_EFFECT_UNKNOWN"))
|
||||
} else {
|
||||
execute(&job).unwrap_or_else(|_| Outcome::unknown("HELPER_EFFECT_UNKNOWN"))
|
||||
}
|
||||
}
|
||||
};
|
||||
if rmm_privileged_helper::apt::is_apt_action(&job) {
|
||||
@@ -497,7 +599,7 @@ fn run() -> Result<()> {
|
||||
let args: Vec<_> = std::env::args_os().skip(1).collect();
|
||||
if args == [std::ffi::OsString::from("--help")] {
|
||||
println!(
|
||||
"rmm-privileged-helper [--help|--inspect-general-profile|--inspect-apt-profile|--probe-native|--install-apt-provider]\nRMM_HELPER_CONFIG=/etc/rmm/helper.json (root-owned 0600).\nDaemon mode accepts only authenticated typed IPC; all effects need independent signed Sync and a fresh consumed grant. Administrative install/probe modes are explicit bootstrap actions, never network commands."
|
||||
"rmm-privileged-helper [--help|--inspect-general-profile|--inspect-full-maintenance-profile|--inspect-apt-profile|--probe-native|--install-apt-provider]\nRMM_HELPER_CONFIG=/etc/rmm/helper.json (root-owned 0600).\nDaemon mode accepts only authenticated typed IPC; all effects need independent signed Sync and a fresh consumed grant. Administrative install/probe modes are explicit bootstrap actions, never network commands."
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
@@ -510,7 +612,11 @@ fn run() -> Result<()> {
|
||||
args.is_empty()
|
||||
|| args == [std::ffi::OsString::from("--probe-native")]
|
||||
|| args == [std::ffi::OsString::from("--inspect-apt-profile")]
|
||||
|| args == [std::ffi::OsString::from("--inspect-general-profile")],
|
||||
|| args == [std::ffi::OsString::from("--inspect-general-profile")]
|
||||
|| args
|
||||
== [std::ffi::OsString::from(
|
||||
"--inspect-full-maintenance-profile"
|
||||
)],
|
||||
"UNKNOWN_HELPER_MODE"
|
||||
);
|
||||
let path = PathBuf::from(
|
||||
@@ -533,17 +639,38 @@ fn run() -> Result<()> {
|
||||
config.binding.public_key_hex = key.public_key_hex;
|
||||
}
|
||||
config.validate_profile()?;
|
||||
if args == [std::ffi::OsString::from("--inspect-general-profile")] {
|
||||
let mut running_image = config
|
||||
.helper_binary_sha256
|
||||
.as_deref()
|
||||
.map(image::RunningImage::current)
|
||||
.transpose()?;
|
||||
if args == [std::ffi::OsString::from("--inspect-general-profile")]
|
||||
|| args
|
||||
== [std::ffi::OsString::from(
|
||||
"--inspect-full-maintenance-profile",
|
||||
)]
|
||||
{
|
||||
ensure!(
|
||||
config.profile == HelperProfile::General,
|
||||
(config.profile == HelperProfile::General
|
||||
&& args == [std::ffi::OsString::from("--inspect-general-profile")])
|
||||
|| (config.profile == HelperProfile::FullMaintenanceV1
|
||||
&& args
|
||||
== [std::ffi::OsString::from(
|
||||
"--inspect-full-maintenance-profile"
|
||||
)]),
|
||||
"GENERAL_POLICY_PROFILE"
|
||||
);
|
||||
let policy = config.general_policy()?;
|
||||
let pin = control::GeneralPin {
|
||||
schema_version: 1,
|
||||
profile: "general".into(),
|
||||
schema_version: if config.profile == HelperProfile::FullMaintenanceV1 {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
},
|
||||
profile: policy.profile.clone(),
|
||||
identity: policy.identity.clone(),
|
||||
policy_sha256: policy.sha256()?,
|
||||
helper_binary_sha256: running_image.as_mut().map(|i| i.verify()).transpose()?,
|
||||
};
|
||||
println!("{}", serde_json::to_string(&pin)?);
|
||||
return Ok(());
|
||||
@@ -627,6 +754,7 @@ fn run() -> Result<()> {
|
||||
&clock,
|
||||
&mut sync,
|
||||
&sync_clock,
|
||||
running_image.as_mut(),
|
||||
) {
|
||||
let code = safe_error_code(&error);
|
||||
eprintln!("helper request rejected: {code}");
|
||||
@@ -704,6 +832,34 @@ mod tests {
|
||||
assert!(config.validate_profile().is_err());
|
||||
}
|
||||
#[test]
|
||||
fn full_maintenance_is_a_separate_explicit_profile_and_shared_ledger() {
|
||||
let id = uuid::Uuid::new_v4();
|
||||
let now = chrono::Utc::now();
|
||||
let mut config:Config=serde_json::from_value(serde_json::json!({"profile":"general","binding":{"tenant_id":id,"asset_id":id,"agent_id":id,"enrollment_generation":1,"assignment_version":1,"public_key_hex":"00".repeat(32)},"agent_uid":993,"socket_gid":993,"socket":"/run/rmm-helper-maintenance/control.sock","state":rmm_privileged_helper::readiness::SHARED_STATE,"allowed_services":[],"allow_reboot":false,"allow_root_scripts":true})).unwrap();
|
||||
config.validate_profile().unwrap();
|
||||
let mut job:rmm_domain::jobs::JobPayload=serde_json::from_value(serde_json::json!({"schema_version":1,"tenant_id":id,"asset_id":id,"agent_id":id,"enrollment_generation":1,"assignment_version":1,"job_id":id,"attempt_id":id,"execution_identity":"root","not_before":now,"start_before":now+chrono::Duration::minutes(1),"max_runtime_seconds":30,"max_output_bytes":4096,"action":{"action":"run_script","interpreter":"posix_sh","script_utf8":"id\n","arguments":[],"expected_stdout":null,"privileged_script_profile":"full_maintenance_v1"}})).unwrap();
|
||||
assert!(policy(&config, &job).is_err());
|
||||
config.allowed_script_profiles = Some(vec![
|
||||
rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
|
||||
]);
|
||||
assert!(config.validate_profile().is_err());
|
||||
config.profile = HelperProfile::FullMaintenanceV1;
|
||||
assert!(config.validate_profile().is_err());
|
||||
config.helper_binary_sha256 = Some("ab".repeat(32));
|
||||
config.validate_profile().unwrap();
|
||||
assert!(policy(&config, &job).is_ok());
|
||||
let proof = config.general_policy().unwrap();
|
||||
assert_eq!(proof.schema_version, 2);
|
||||
assert_eq!(proof.profile, "full_maintenance_v1");
|
||||
job.action = Action::SetServiceState {
|
||||
unit: "rmm-mvp-test.service".into(),
|
||||
state: "running".into(),
|
||||
};
|
||||
assert!(policy(&config, &job).is_err());
|
||||
config.state = "/var/lib/another-ledger".into();
|
||||
assert!(config.validate_profile().is_err());
|
||||
}
|
||||
#[test]
|
||||
fn peer_acl_does_not_trust_request_identity() {
|
||||
let (a, _b) = UnixStream::pair().unwrap();
|
||||
// SAFETY: geteuid has no preconditions.
|
||||
@@ -733,6 +889,8 @@ mod tests {
|
||||
allowed_services: vec!["rmm-acceptance.service".into()],
|
||||
allow_reboot: false,
|
||||
allow_root_scripts: false,
|
||||
allowed_script_profiles: None,
|
||||
helper_binary_sha256: None,
|
||||
apt_provider: None,
|
||||
};
|
||||
let now = chrono::Utc::now();
|
||||
@@ -751,6 +909,7 @@ mod tests {
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
},
|
||||
execution_identity: "agent_service".into(),
|
||||
not_before: now,
|
||||
@@ -763,6 +922,13 @@ mod tests {
|
||||
assert!(policy(&config, &job).is_err());
|
||||
config.allow_root_scripts = true;
|
||||
assert!(policy(&config, &job).is_ok());
|
||||
// The additive full profile must not alter historical local General
|
||||
// ceilings; the independent central legacy policy remains unchanged.
|
||||
job.max_runtime_seconds = 301;
|
||||
job.max_output_bytes = 65537;
|
||||
assert!(policy(&config, &job).is_ok());
|
||||
job.max_runtime_seconds = 180;
|
||||
job.max_output_bytes = 4096;
|
||||
job.action = Action::SetServiceState {
|
||||
unit: "not-approved.service".into(),
|
||||
state: "running".into(),
|
||||
|
||||
@@ -34,6 +34,7 @@ fn fixture() -> (
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("Hello World\n".into()),
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
},
|
||||
execution_identity: "agent_service".into(),
|
||||
not_before: now - chrono::Duration::seconds(60),
|
||||
|
||||
@@ -433,6 +433,7 @@ fn script() -> Action {
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("hello".into()),
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
}
|
||||
}
|
||||
fn success() -> ReconciledOutcome {
|
||||
|
||||
@@ -519,6 +519,7 @@ mod tests {
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
},
|
||||
execution_identity: "agent_service".into(),
|
||||
not_before: c.issued_at,
|
||||
|
||||
@@ -292,6 +292,21 @@ fn windows_event_log_success_evidence(
|
||||
|
||||
// The profile records the requested process option, never an effective GPO policy.
|
||||
fn script_profile_evidence(action: &Action, evidence: &Value) -> Result<()> {
|
||||
if action.full_maintenance() {
|
||||
let Action::RunScript { script_utf8, .. } = action else {
|
||||
unreachable!()
|
||||
};
|
||||
ensure!(
|
||||
evidence["privileged_script_profile"] == "full_maintenance_v1"
|
||||
&& evidence["script_sha256"] == hash(script_utf8.as_bytes())
|
||||
&& match action.script_platform() {
|
||||
Some("linux") => evidence["execution_uid"] == 0,
|
||||
Some("windows") => evidence["execution_sid"] == "S-1-5-18",
|
||||
_ => false,
|
||||
},
|
||||
"full maintenance identity/profile evidence mismatch"
|
||||
);
|
||||
}
|
||||
if let Action::RunScript {
|
||||
script_utf8,
|
||||
windows_execution_profile: Some(WindowsExecutionProfile::PowerShell51RemoteSigned),
|
||||
@@ -411,6 +426,7 @@ mod script_profile_tests {
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: Some(WindowsExecutionProfile::PowerShell51RemoteSigned),
|
||||
privileged_script_profile: None,
|
||||
};
|
||||
let evidence = json!({"windows_execution_profile":"powershell_51_remote_signed",
|
||||
"execution_policy":"process_remote_signed_requested", "execution_policy_requested":"RemoteSigned",
|
||||
@@ -628,7 +644,8 @@ pub async fn permit(
|
||||
if !crate::permissions::allowed(&mut tx, &approver, "plans:approve").await?
|
||||
|| !crate::permissions::allowed(&mut tx, &plan.principal, "operations:submit").await?
|
||||
|| (matches!(payload.action, Action::RunScript { .. })
|
||||
&& !crate::permissions::allowed(&mut tx, &plan.principal, "scripts:execute").await?)
|
||||
&& (!crate::permissions::allowed(&mut tx, &plan.principal, "scripts:execute").await?
|
||||
|| !crate::permissions::allowed(&mut tx, &approver, "scripts:execute").await?))
|
||||
{
|
||||
return Ok(denied("AUTHORIZATION_REVOKED"));
|
||||
}
|
||||
|
||||
@@ -162,6 +162,13 @@ pub struct Variant {
|
||||
#[derive(Clone, Deserialize, Serialize, schemars::JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct WebParameters {
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "deserialize_privileged_script_profile",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
#[schemars(with = "PrivilegedScriptProfile")]
|
||||
privileged_script_profile: Option<PrivilegedScriptProfile>,
|
||||
execution_identity: String,
|
||||
timeout_seconds: u32,
|
||||
max_output_bytes: u32,
|
||||
@@ -230,6 +237,7 @@ impl PlanRequest {
|
||||
arguments: p.arguments.clone().unwrap_or_default(),
|
||||
expected_stdout: p.expected_stdout.clone(),
|
||||
windows_execution_profile: v.windows_execution_profile,
|
||||
privileged_script_profile: p.privileged_script_profile,
|
||||
}
|
||||
}
|
||||
"refresh_inventory" => Action::RefreshInventory {
|
||||
@@ -329,6 +337,7 @@ fn validate_variants(variants: &[Variant]) -> Result<()> {
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: v.windows_execution_profile,
|
||||
privileged_script_profile: None,
|
||||
};
|
||||
if v.encoding != "utf-8"
|
||||
|| action.script_platform() != Some(v.os_family.as_str())
|
||||
@@ -346,6 +355,15 @@ fn capabilities(value: Value) -> Result<Vec<String>> {
|
||||
serde_json::from_value(value).map_err(|_| fail("UNSUPPORTED_CAPABILITY"))
|
||||
}
|
||||
fn target_action(input: &PlanInput, caps: &[String]) -> Result<Action> {
|
||||
if !input
|
||||
.action
|
||||
.valid_execution_identity(&input.execution_identity)
|
||||
|| (input.execution_identity == "system"
|
||||
&& matches!(input.action, Action::RunScript { .. })
|
||||
&& !input.action.full_maintenance())
|
||||
{
|
||||
return Err(fail("VALIDATION_ERROR"));
|
||||
}
|
||||
if input.script_variants.is_empty() {
|
||||
return Ok(input.action.clone());
|
||||
}
|
||||
@@ -356,6 +374,7 @@ fn target_action(input: &PlanInput, caps: &[String]) -> Result<Action> {
|
||||
arguments,
|
||||
expected_stdout,
|
||||
windows_execution_profile,
|
||||
privileged_script_profile,
|
||||
} = &input.action
|
||||
else {
|
||||
return Err(fail("VALIDATION_ERROR"));
|
||||
@@ -364,7 +383,7 @@ fn target_action(input: &PlanInput, caps: &[String]) -> Result<Action> {
|
||||
if interpreter != &first.interpreter
|
||||
|| script_utf8 != &first.script_utf8
|
||||
|| windows_execution_profile != &first.windows_execution_profile
|
||||
|| (input.execution_identity != "agent_service"
|
||||
|| (input.execution_identity == "root"
|
||||
&& input
|
||||
.script_variants
|
||||
.iter()
|
||||
@@ -391,6 +410,7 @@ fn target_action(input: &PlanInput, caps: &[String]) -> Result<Action> {
|
||||
arguments: arguments.clone(),
|
||||
expected_stdout: expected_stdout.clone(),
|
||||
windows_execution_profile: v.windows_execution_profile,
|
||||
privileged_script_profile: *privileged_script_profile,
|
||||
})
|
||||
}
|
||||
async fn policy(tx: &mut Transaction<'_, Postgres>) -> Result<()> {
|
||||
@@ -413,6 +433,9 @@ pub async fn plan(
|
||||
if input.targets.asset_ids.is_empty()
|
||||
|| input.targets.asset_ids.len() > 100
|
||||
|| !input.action.validate_plan_shape()
|
||||
|| !input
|
||||
.action
|
||||
.valid_execution_identity(&input.execution_identity)
|
||||
|| !matches!(
|
||||
input.execution_identity.as_str(),
|
||||
"agent_service" | "root" | "system"
|
||||
@@ -821,6 +844,9 @@ async fn authorize_http(
|
||||
return Err(fail("AUTHORIZATION_REVOKED"));
|
||||
}
|
||||
for job in &plan.jobs {
|
||||
if matches!(job.payload.action, Action::RunScript { .. }) {
|
||||
crate::permissions::require_principal(&mut tx, &p, "scripts:execute").await?;
|
||||
}
|
||||
if let Some(permission) =
|
||||
crate::root_policy::execution_permission(&job.payload.execution_identity)
|
||||
{
|
||||
@@ -1116,6 +1142,28 @@ mod windows_contract_tests {
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn full_maintenance_web_profile_is_action_wide_strict_and_identity_bound() {
|
||||
let request = serde_json::json!({"tenant_id":Uuid::nil(),"action":"run_script","targets":{"asset_ids":[Uuid::nil()]},"parameters":{"execution_identity":"system","timeout_seconds":30,"max_output_bytes":4096,"privileged_script_profile":"full_maintenance_v1","variants":[{"os_family":"windows","interpreter":"powershell","encoding":"utf-8","script_utf8":"Write-Output 'hi'\r\n","windows_execution_profile":"powershell_51_remote_signed"}]},"schedule":{"not_before":"2026-11-14T12:00:00Z","start_before":"2026-11-14T13:00:00Z","offline_policy":"wait_until_deadline"},"rollout":{"max_parallel":1,"halt_after_failures":1},"reason":"codec only"});
|
||||
let resolved = serde_json::from_value::<PlanRequest>(request.clone())
|
||||
.unwrap()
|
||||
.resolve(Uuid::nil())
|
||||
.unwrap();
|
||||
let action = target_action(&resolved, &["windows.base/1".into()]).unwrap();
|
||||
assert!(action.full_maintenance());
|
||||
let mut invalid = resolved.clone();
|
||||
invalid.execution_identity = "agent_service".into();
|
||||
assert!(target_action(&invalid, &["windows.base/1".into()]).is_err());
|
||||
for value in [
|
||||
serde_json::Value::Null,
|
||||
serde_json::json!("unknown"),
|
||||
serde_json::json!({"full_maintenance_v1":null}),
|
||||
] {
|
||||
let mut request = request.clone();
|
||||
request["parameters"]["privileged_script_profile"] = value;
|
||||
assert!(serde_json::from_value::<PlanRequest>(request).is_err());
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn remote_signed_fixed_variants_bind_profile_without_linux_inheritance() {
|
||||
let mut i = input();
|
||||
let legacy_linux = encode(&i.action).unwrap();
|
||||
@@ -1130,6 +1178,7 @@ mod windows_contract_tests {
|
||||
windows,
|
||||
Action::RunScript {
|
||||
windows_execution_profile: Some(WindowsExecutionProfile::PowerShell51RemoteSigned),
|
||||
privileged_script_profile: None,
|
||||
..
|
||||
}
|
||||
));
|
||||
|
||||
@@ -28,9 +28,19 @@ struct RootScope {
|
||||
assignment_version: u64,
|
||||
principals: Vec<String>,
|
||||
helper_policy_sha256: String,
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "rmm_domain::jobs::deserialize_optional_sha256"
|
||||
)]
|
||||
helper_binary_sha256: Option<String>,
|
||||
acceptance_evidence_id: String,
|
||||
allowed_services: Vec<String>,
|
||||
allow_root_scripts: bool,
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "rmm_domain::jobs::deserialize_script_profiles"
|
||||
)]
|
||||
allowed_script_profiles: Option<Vec<rmm_domain::jobs::PrivilegedScriptProfile>>,
|
||||
allow_reboot: bool,
|
||||
#[serde(default)]
|
||||
apt: Option<RootAptPolicy>,
|
||||
@@ -96,6 +106,9 @@ impl RootPolicy {
|
||||
}
|
||||
fn required_permissions(job: &JobPayload, sensitive_log: bool) -> Vec<&'static str> {
|
||||
let mut permissions = vec!["root:execute"];
|
||||
if matches!(job.action, Action::RunScript { .. }) {
|
||||
permissions.push("scripts:execute");
|
||||
}
|
||||
if matches!(job.action, Action::AptNativeAcceptance { .. }) {
|
||||
permissions.push("apt:native_acceptance");
|
||||
}
|
||||
@@ -205,7 +218,21 @@ impl RootScope {
|
||||
&& (20..=3600).contains(&job.max_runtime_seconds)
|
||||
&& (1..=65536).contains(&job.max_output_bytes)
|
||||
}
|
||||
Action::RunScript { .. } => self.allow_root_scripts && job.max_runtime_seconds <= 300,
|
||||
Action::RunScript { .. } => {
|
||||
self.allow_root_scripts
|
||||
&& job.max_runtime_seconds <= 300
|
||||
&& job.action.valid_execution_identity(&job.execution_identity)
|
||||
&& (!job.action.full_maintenance()
|
||||
|| (self.helper_binary_sha256.as_ref().is_some_and(|h| {
|
||||
capabilities.contains(&format!("helper.binary.sha256:{h}"))
|
||||
}) && self.allowed_script_profiles.as_ref().is_some_and(|v| {
|
||||
v.contains(
|
||||
&rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
|
||||
)
|
||||
}) && capabilities
|
||||
.iter()
|
||||
.any(|c| c == rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY)))
|
||||
}
|
||||
Action::SetServiceState { unit, state } => {
|
||||
self.allowed_services.contains(unit)
|
||||
&& matches!(state.as_str(), "running" | "stopped")
|
||||
@@ -265,7 +292,12 @@ fn load() -> Result<RootPolicy, Error> {
|
||||
}
|
||||
let policy: RootPolicy =
|
||||
serde_json::from_slice(&fs::read(path).map_err(|_| disabled())?).map_err(|_| disabled())?;
|
||||
if policy.schema_version != 1
|
||||
if !matches!(policy.schema_version, 1 | 2)
|
||||
|| (policy.schema_version == 1
|
||||
&& policy
|
||||
.scopes
|
||||
.iter()
|
||||
.any(|s| s.allowed_script_profiles.is_some() || s.helper_binary_sha256.is_some()))
|
||||
|| policy.profile != "development"
|
||||
|| policy.expires_at <= Utc::now()
|
||||
|| policy.scopes.is_empty()
|
||||
@@ -342,7 +374,7 @@ mod tests {
|
||||
fn no_capability_or_relabel_shortcut() {
|
||||
let id = Uuid::new_v4();
|
||||
let now = Utc::now();
|
||||
let job = JobPayload {
|
||||
let mut job = JobPayload {
|
||||
schema_version: 1,
|
||||
tenant_id: id,
|
||||
asset_id: id,
|
||||
@@ -357,6 +389,7 @@ mod tests {
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
},
|
||||
execution_identity: "root".into(),
|
||||
not_before: now,
|
||||
@@ -364,7 +397,7 @@ mod tests {
|
||||
max_runtime_seconds: 60,
|
||||
max_output_bytes: 1024,
|
||||
};
|
||||
let scope = RootScope {
|
||||
let mut scope = RootScope {
|
||||
tenant_id: id,
|
||||
asset_id: id,
|
||||
agent_id: id,
|
||||
@@ -372,9 +405,11 @@ mod tests {
|
||||
assignment_version: 1,
|
||||
principals: vec!["selected".into()],
|
||||
helper_policy_sha256: "ab".repeat(32),
|
||||
helper_binary_sha256: None,
|
||||
acceptance_evidence_id: "native-test-record".into(),
|
||||
allowed_services: vec![],
|
||||
allow_root_scripts: true,
|
||||
allowed_script_profiles: None,
|
||||
allow_reboot: false,
|
||||
apt: None,
|
||||
root_logs: None,
|
||||
@@ -389,6 +424,26 @@ mod tests {
|
||||
assert!(scope.permits("selected", &job, &caps, None));
|
||||
assert!(!scope.permits("automation", &job, &caps, None));
|
||||
assert!(!scope.permits("selected", &job, &caps[..4], None));
|
||||
if let Action::RunScript {
|
||||
privileged_script_profile,
|
||||
..
|
||||
} = &mut job.action
|
||||
{
|
||||
*privileged_script_profile =
|
||||
Some(rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1);
|
||||
}
|
||||
assert!(!scope.permits("selected", &job, &caps, None));
|
||||
scope.allowed_script_profiles = Some(vec![
|
||||
rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
|
||||
]);
|
||||
assert!(!scope.permits("selected", &job, &caps, None));
|
||||
let mut caps = caps;
|
||||
caps.push(rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY.into());
|
||||
assert!(!scope.permits("selected", &job, &caps, None));
|
||||
scope.helper_binary_sha256 = Some("cd".repeat(32));
|
||||
assert!(!scope.permits("selected", &job, &caps, None));
|
||||
caps.push(format!("helper.binary.sha256:{}", "cd".repeat(32)));
|
||||
assert!(scope.permits("selected", &job, &caps, None));
|
||||
let mut windows = caps;
|
||||
windows.push("windows.base/1".into());
|
||||
assert!(!scope.permits("selected", &job, &windows, None));
|
||||
|
||||
@@ -40,6 +40,11 @@ struct SystemScope {
|
||||
#[serde(default, deserialize_with = "strict_optional_hashes")]
|
||||
allowed_msi_recipe_sha256: Option<Vec<String>>,
|
||||
max_runtime_seconds: u32,
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "rmm_domain::jobs::deserialize_script_profiles"
|
||||
)]
|
||||
allowed_script_profiles: Option<Vec<rmm_domain::jobs::PrivilegedScriptProfile>>,
|
||||
}
|
||||
fn strict_optional_hashes<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
|
||||
where
|
||||
@@ -106,6 +111,10 @@ impl SystemScope {
|
||||
.len()
|
||||
== hashes.len()
|
||||
})
|
||||
&& self
|
||||
.allowed_script_profiles
|
||||
.as_deref()
|
||||
.is_none_or(|v| v == [rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1])
|
||||
&& (1..=120).contains(&self.max_runtime_seconds)
|
||||
}
|
||||
fn permits(
|
||||
@@ -114,6 +123,7 @@ impl SystemScope {
|
||||
job: &JobPayload,
|
||||
capabilities: &[String],
|
||||
allow_msi: bool,
|
||||
allow_scripts: bool,
|
||||
) -> bool {
|
||||
let has = |cap: &str| capabilities.iter().any(|c| c == cap);
|
||||
self.valid()
|
||||
@@ -145,6 +155,20 @@ impl SystemScope {
|
||||
&& has("system:set_service_state")
|
||||
&& has("set_service_state")
|
||||
}
|
||||
Action::RunScript { .. } => {
|
||||
allow_scripts
|
||||
&& job.action.full_maintenance()
|
||||
&& self.allowed_script_profiles.as_ref().is_some_and(|v| {
|
||||
v.contains(
|
||||
&rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
|
||||
)
|
||||
})
|
||||
&& job.action.validate()
|
||||
&& job
|
||||
.action
|
||||
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
|
||||
&& job.action.available_for("system", capabilities)
|
||||
}
|
||||
_ if allow_msi => job.action.windows_msi().is_some_and(|m| {
|
||||
job.action.validate()
|
||||
&& job
|
||||
@@ -164,12 +188,17 @@ impl SystemScope {
|
||||
}
|
||||
impl SystemPolicy {
|
||||
fn valid(&self, now: DateTime<Utc>) -> bool {
|
||||
matches!(self.schema_version, 1 | 2)
|
||||
&& (self.schema_version == 2
|
||||
matches!(self.schema_version, 1..=3)
|
||||
&& (self.schema_version >= 2
|
||||
|| self
|
||||
.scopes
|
||||
.iter()
|
||||
.all(|scope| scope.allowed_msi_recipe_sha256.is_none()))
|
||||
&& (self.schema_version == 3
|
||||
|| self
|
||||
.scopes
|
||||
.iter()
|
||||
.all(|scope| scope.allowed_script_profiles.is_none()))
|
||||
&& self.profile == "development"
|
||||
&& self.expires_at > now
|
||||
&& !self.scopes.is_empty()
|
||||
@@ -184,10 +213,15 @@ impl SystemPolicy {
|
||||
now: DateTime<Utc>,
|
||||
) -> bool {
|
||||
self.valid(now)
|
||||
&& self
|
||||
.scopes
|
||||
.iter()
|
||||
.any(|scope| scope.permits(principal, job, capabilities, self.schema_version == 2))
|
||||
&& self.scopes.iter().any(|scope| {
|
||||
scope.permits(
|
||||
principal,
|
||||
job,
|
||||
capabilities,
|
||||
self.schema_version >= 2,
|
||||
self.schema_version == 3,
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
fn disabled() -> Error {
|
||||
@@ -310,6 +344,9 @@ pub async fn authorize(
|
||||
}
|
||||
// Independent DB permission; root:execute never implies this scope.
|
||||
crate::permissions::require(tx, principal, "system:execute").await?;
|
||||
if matches!(job.action, Action::RunScript { .. }) {
|
||||
crate::permissions::require(tx, principal, "scripts:execute").await?;
|
||||
}
|
||||
let policy = load()?;
|
||||
let caps:serde_json::Value=sqlx::query_scalar("SELECT capabilities FROM agent_installations WHERE tenant_id=$1 AND agent_id=$2 AND asset_id=$3 AND revoked_at IS NULL AND enrollment_generation=$4 AND assignment_version=$5").bind(job.tenant_id).bind(job.agent_id).bind(job.asset_id).bind(i64::try_from(job.enrollment_generation).map_err(|_|Error(StatusCode::CONFLICT,"BINDING_MISMATCH"))?).bind(i64::try_from(job.assignment_version).map_err(|_|Error(StatusCode::CONFLICT,"BINDING_MISMATCH"))?).fetch_optional(&mut **tx).await?.ok_or(Error(StatusCode::CONFLICT,"AUTHORIZATION_REVOKED"))?;
|
||||
let capabilities: Vec<String> = serde_json::from_value(caps)?;
|
||||
@@ -422,6 +459,42 @@ mod tests {
|
||||
assert!(!policy.permits("selected", &job, &caps, policy.expires_at));
|
||||
}
|
||||
#[test]
|
||||
fn full_script_requires_v3_explicit_scope_and_does_not_inherit_scm_or_msi() {
|
||||
let (mut policy, mut job, mut caps) = fixture();
|
||||
job.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,
|
||||
),
|
||||
};
|
||||
caps.extend([
|
||||
"run_script".into(),
|
||||
"system:run_script".into(),
|
||||
"script.powershell/1".into(),
|
||||
rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY.into(),
|
||||
]);
|
||||
for version in [1, 2, 3] {
|
||||
policy.schema_version = version;
|
||||
assert!(!policy.permits("selected", &job, &caps, Utc::now()));
|
||||
}
|
||||
policy.scopes[0].allowed_script_profiles = Some(vec![
|
||||
rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
|
||||
]);
|
||||
for version in [1, 2] {
|
||||
policy.schema_version = version;
|
||||
assert!(!policy.permits("selected", &job, &caps, Utc::now()));
|
||||
}
|
||||
policy.schema_version = 3;
|
||||
assert!(policy.permits("selected", &job, &caps, Utc::now()));
|
||||
assert!(!policy.permits("foreign", &job, &caps, Utc::now()));
|
||||
caps.retain(|c| c != rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY);
|
||||
assert!(!policy.permits("selected", &job, &caps, Utc::now()));
|
||||
}
|
||||
#[test]
|
||||
fn narrow_scm_ceiling_denies_unreviewed_effects_and_provider_inputs() {
|
||||
let (mut policy, mut job, caps) = fixture();
|
||||
let now = Utc::now();
|
||||
@@ -443,6 +516,7 @@ mod tests {
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
};
|
||||
assert!(!policy.permits("selected", &job, &caps, now));
|
||||
job.action = Action::SetServiceState {
|
||||
|
||||
Reference in New Issue
Block a user