Use script-only execution on Linux and preserve the enrolled helper through updates
This commit is contained in:
+45
-225
@@ -1,183 +1,46 @@
|
||||
use anyhow::{Result, ensure};
|
||||
use anyhow::Result;
|
||||
#[cfg(test)]
|
||||
use prost::Message;
|
||||
#[cfg(test)]
|
||||
use rmm_domain::jobs::hash;
|
||||
use rmm_domain::jobs::{Action, JobPayload};
|
||||
use rmm_privileged_helper::{Binding, Outcome};
|
||||
use rmm_privileged_helper::Binding;
|
||||
use rmm_protocol::*;
|
||||
use rusqlite::Connection;
|
||||
#[cfg(test)]
|
||||
use uuid::Uuid;
|
||||
|
||||
pub fn supported(job: &JobPayload) -> bool {
|
||||
if rmm_privileged_helper::apt::is_apt_action(job) {
|
||||
// A configured environment path alone is never a capability proof.
|
||||
// Caller binding is independently provisioned, not taken from the job.
|
||||
pub fn supported_with_binding(job: &JobPayload, binding: Option<&Binding>) -> bool {
|
||||
let Action::RunScript { interpreter, .. } = &job.action else {
|
||||
return false;
|
||||
};
|
||||
if unsafe { libc::geteuid() } == 0
|
||||
|| !job.action.valid_execution_identity(&job.execution_identity)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
// The network process must never execute a script with accidental root.
|
||||
supported_as(
|
||||
job,
|
||||
unsafe { libc::geteuid() },
|
||||
std::env::var_os("RMM_HELPER_SOCKET").is_some(),
|
||||
)
|
||||
}
|
||||
pub fn supported_with_binding(job: &JobPayload, binding: Option<&Binding>) -> bool {
|
||||
if matches!(job.action, Action::UpdateAgent { .. }) {
|
||||
return binding.is_some_and(|b| crate::agent_update_apply::supported(b, job));
|
||||
}
|
||||
if rmm_privileged_helper::apt::is_apt_action(job) {
|
||||
// SAFETY: geteuid has no preconditions.
|
||||
return unsafe { libc::geteuid() } != 0
|
||||
&& binding.is_some_and(|b| crate::apt::supported(b, job));
|
||||
}
|
||||
if job.execution_identity == "root" {
|
||||
return unsafe { libc::geteuid() } != 0
|
||||
&& binding.is_some_and(|b| crate::helper_sync::general_supported(b, job));
|
||||
}
|
||||
supported(job)
|
||||
}
|
||||
fn supported_as(job: &JobPayload, uid: u32, helper_configured: bool) -> bool {
|
||||
let unprivileged = uid != 0;
|
||||
if job.execution_identity == "root" && unprivileged {
|
||||
return helper_configured
|
||||
&& matches!(
|
||||
job.action,
|
||||
Action::RunScript { .. } | Action::SetServiceState { .. } | Action::Reboot { .. }
|
||||
);
|
||||
}
|
||||
job.execution_identity == "agent_service"
|
||||
&& unprivileged
|
||||
&& match &job.action {
|
||||
Action::RunScript { interpreter, .. } => match interpreter.as_str() {
|
||||
"posix_sh" => rmm_agent_linux::actions::Interpreter::PosixSh.available(),
|
||||
"bash" => rmm_agent_linux::actions::Interpreter::Bash.available(),
|
||||
_ => false,
|
||||
},
|
||||
Action::RefreshInventory { scope } => scope == "linux.base",
|
||||
Action::QueryLogs { .. } => log_request(job).is_ok(),
|
||||
_ => false,
|
||||
match job.execution_identity.as_str() {
|
||||
"root" => {
|
||||
job.action.full_maintenance()
|
||||
&& binding.is_some_and(|b| crate::helper_sync::script_supported(b, job))
|
||||
}
|
||||
"agent_service" => match interpreter.as_str() {
|
||||
"posix_sh" => rmm_agent_linux::actions::Interpreter::PosixSh.available(),
|
||||
"bash" => rmm_agent_linux::actions::Interpreter::Bash.available(),
|
||||
_ => false,
|
||||
},
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
pub use rmm_agent_core::jobs::{
|
||||
denied_request, ack, event, events, interrupted, interrupted_request, next, no_start, permit_request,
|
||||
recover_interrupted_outcome, requesting, reserve_request, result, transition,
|
||||
ack, denied_request, event, events, interrupted, interrupted_request, next, no_start,
|
||||
permit_request, recover_interrupted_outcome, requesting, reserve_request, result, transition,
|
||||
};
|
||||
pub fn accept(db: &Connection, binding: &Binding, offer: &JobOffer) -> Result<bool> {
|
||||
rmm_agent_core::jobs::accept(db, binding, offer, |job| {
|
||||
supported_with_binding(job, Some(binding))
|
||||
})
|
||||
}
|
||||
pub fn execute(job: &JobPayload) -> Outcome {
|
||||
let result = match &job.action {
|
||||
Action::RunScript { .. } => rmm_privileged_helper::script(job),
|
||||
Action::RefreshInventory { .. } => rmm_agent_linux::collect().and_then(|i| {
|
||||
let bytes = serde_json::to_vec(&i)?;
|
||||
ensure!(bytes.len() <= job.max_output_bytes as usize, "INVENTORY_OUTPUT_LIMIT");
|
||||
Ok(Outcome { state: "succeeded".into(), stdout: bytes, stderr: vec![], exit_code: None,
|
||||
output_truncated: false, reboot_required: false,
|
||||
evidence: serde_json::json!({"postconditions_passed":true,"source_id":"linux.base","observed_at":chrono::Utc::now(),"completeness":"partial"}), error_code: String::new() })
|
||||
}),
|
||||
Action::QueryLogs { .. } => query_logs(job),
|
||||
_ => Err(anyhow::anyhow!("unsupported action")),
|
||||
};
|
||||
result.unwrap_or_else(|_| Outcome::unknown("EXECUTOR_EFFECT_UNKNOWN"))
|
||||
}
|
||||
|
||||
fn allowed_log_units() -> Result<Vec<rmm_agent_linux::actions::ServiceUnit>> {
|
||||
let path = std::env::var_os("RMM_LOG_UNITS_FILE")
|
||||
.ok_or_else(|| anyhow::anyhow!("LOG_ALLOWLIST_NOT_CONFIGURED"))?;
|
||||
let path = std::path::Path::new(&path);
|
||||
rmm_privileged_helper::private_path(path, unsafe { libc::geteuid() }, false)?;
|
||||
ensure!(
|
||||
std::fs::metadata(path)?.len() <= 32768,
|
||||
"LOG_ALLOWLIST_SIZE"
|
||||
);
|
||||
let units: Vec<String> = serde_json::from_slice(&std::fs::read(path)?)?;
|
||||
ensure!(
|
||||
!units.is_empty() && units.len() <= 128,
|
||||
"LOG_ALLOWLIST_SIZE"
|
||||
);
|
||||
units
|
||||
.iter()
|
||||
.map(|u| rmm_agent_linux::actions::ServiceUnit::new(u))
|
||||
.collect()
|
||||
}
|
||||
pub fn logs_available() -> bool {
|
||||
allowed_log_units().is_ok()
|
||||
&& rmm_agent_linux::inventory::capabilities()
|
||||
.get("logs.journald")
|
||||
.is_some_and(|o| o.data == Some(true))
|
||||
}
|
||||
fn log_request(job: &JobPayload) -> Result<rmm_agent_linux::inventory::JournalRequest> {
|
||||
log_request_for(job, &allowed_log_units()?)
|
||||
}
|
||||
fn log_request_for(
|
||||
job: &JobPayload,
|
||||
allowed: &[rmm_agent_linux::actions::ServiceUnit],
|
||||
) -> Result<rmm_agent_linux::inventory::JournalRequest> {
|
||||
let Action::QueryLogs {
|
||||
unit,
|
||||
since,
|
||||
until,
|
||||
max_lines,
|
||||
} = &job.action
|
||||
else {
|
||||
anyhow::bail!("NOT_LOG_QUERY")
|
||||
};
|
||||
ensure!(job.max_runtime_seconds >= 20, "LOG_RUNTIME_TOO_SHORT");
|
||||
rmm_agent_linux::inventory::JournalRequest::new(
|
||||
rmm_agent_linux::actions::ServiceUnit::new(unit)?,
|
||||
allowed,
|
||||
u64::try_from(since.timestamp())?,
|
||||
u64::try_from(until.timestamp())?,
|
||||
*max_lines as usize,
|
||||
(job.max_output_bytes as usize).min(256 * 1024),
|
||||
)?
|
||||
.precise_window(*since, *until)
|
||||
}
|
||||
fn query_logs(job: &JobPayload) -> Result<Outcome> {
|
||||
let observation = rmm_agent_linux::inventory::query_journal(&log_request(job)?);
|
||||
let valid = observation.quality == rmm_agent_linux::inventory::Quality::Valid;
|
||||
let error = observation.error_code.clone().unwrap_or_default();
|
||||
let mut value = serde_json::to_value(&observation)?;
|
||||
while serde_json::to_vec(&value)?.len() > job.max_output_bytes as usize {
|
||||
let Some(lines) = value["data"]["json_lines"]
|
||||
.as_array_mut()
|
||||
.filter(|v| !v.is_empty())
|
||||
else {
|
||||
return Ok(Outcome {
|
||||
state: "failed".into(),
|
||||
..Outcome::unknown("LOG_RESULT_METADATA_EXCEEDS_OUTPUT_LIMIT")
|
||||
});
|
||||
};
|
||||
lines.remove(0);
|
||||
value["truncated"] = serde_json::json!(true);
|
||||
value["completeness"] = serde_json::json!("partial");
|
||||
value["error_code"] = serde_json::json!("LOG_SERIALIZED_OUTPUT_LIMIT");
|
||||
}
|
||||
Ok(Outcome {
|
||||
state: if valid { "succeeded" } else { "failed" }.into(),
|
||||
stdout: serde_json::to_vec(&value)?,
|
||||
stderr: vec![],
|
||||
exit_code: None,
|
||||
output_truncated: value["truncated"] == true,
|
||||
reboot_required: false,
|
||||
evidence: serde_json::json!({"postconditions_passed":valid,"source_id":observation.source_id,
|
||||
"observed_at":value["observed_at"],"quality":value["quality"],"completeness":value["completeness"],
|
||||
"cursor_status":"not_advanced_no_ack_contract","provider_error_code":error}),
|
||||
error_code: if valid {
|
||||
String::new()
|
||||
} else if error.is_empty() {
|
||||
"LOG_PROVIDER_UNAVAILABLE".into()
|
||||
} else {
|
||||
error
|
||||
},
|
||||
})
|
||||
}
|
||||
/// With no backend SyncResponse contract, a reconnect/restart cannot prove an
|
||||
/// earlier reservation never started. Telemetry and evidence replay continue;
|
||||
/// all new effects stop. Do not paper over this with a new start request.
|
||||
#[cfg(test)]
|
||||
pub fn begin_session(db: &Connection) -> Result<bool> {
|
||||
@@ -228,8 +91,13 @@ mod tests {
|
||||
assignment_version: 2,
|
||||
job_id: Uuid::new_v4(),
|
||||
attempt_id: Uuid::new_v4(),
|
||||
action: Action::RefreshInventory {
|
||||
scope: "linux.base".into(),
|
||||
action: Action::RunScript {
|
||||
interpreter: "posix_sh".into(),
|
||||
script_utf8: "true".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
},
|
||||
execution_identity: "agent_service".into(),
|
||||
not_before: now,
|
||||
@@ -254,7 +122,7 @@ mod tests {
|
||||
let mut db = storage::open(&path).unwrap();
|
||||
let job = binding.job(&offer.payload_bytes).unwrap();
|
||||
if unsafe { libc::geteuid() } == 0 {
|
||||
assert!(!supported(&job));
|
||||
assert!(!supported_with_binding(&job, Some(&binding)));
|
||||
assert!(accept(&db, &binding, &offer).is_err());
|
||||
} else {
|
||||
assert!(accept(&db, &binding, &offer).unwrap());
|
||||
@@ -326,20 +194,24 @@ mod tests {
|
||||
std::fs::remove_dir_all(path).unwrap();
|
||||
}
|
||||
#[test]
|
||||
fn network_process_never_executes_as_accidental_root() {
|
||||
fn legacy_actions_and_unbound_root_are_rejected_before_any_reservation() {
|
||||
let (path, binding, offer) = fixture();
|
||||
let mut job = binding.job(&offer.payload_bytes).unwrap();
|
||||
assert!(!supported_as(&job, 0, false));
|
||||
assert!(!supported_as(&job, 0, true));
|
||||
job.execution_identity = "root".into();
|
||||
assert!(!supported_as(&job, 1000, false));
|
||||
assert!(!supported_as(&job, 0, true));
|
||||
job.action = Action::Reboot {
|
||||
reason: "explicit root only".into(),
|
||||
reconnect_timeout_seconds: 60,
|
||||
dependency_group: "test".into(),
|
||||
};
|
||||
assert!(supported_as(&job, 1000, true));
|
||||
assert!(!supported_with_binding(&job, Some(&binding)));
|
||||
for identity in ["agent_service", "root"] {
|
||||
job.execution_identity = identity.into();
|
||||
job.action = Action::Reboot {
|
||||
reason: "legacy fixture".into(),
|
||||
reconnect_timeout_seconds: 60,
|
||||
dependency_group: "test".into(),
|
||||
};
|
||||
assert!(!supported_with_binding(&job, Some(&binding)));
|
||||
job.action = Action::RefreshInventory {
|
||||
scope: "linux.base".into(),
|
||||
};
|
||||
assert!(!supported_with_binding(&job, Some(&binding)));
|
||||
}
|
||||
std::fs::remove_dir_all(path).unwrap();
|
||||
}
|
||||
#[test]
|
||||
@@ -363,56 +235,4 @@ mod tests {
|
||||
drop(db);
|
||||
std::fs::remove_dir_all(path).unwrap();
|
||||
}
|
||||
#[test]
|
||||
fn live_logs_enforce_actual_action_window_allowlist_limits_and_runtime() {
|
||||
let (path, binding, offer) = fixture();
|
||||
let mut job = binding.job(&offer.payload_bytes).unwrap();
|
||||
let unit = rmm_agent_linux::actions::ServiceUnit::new("rmm-test.service").unwrap();
|
||||
let now = chrono::Utc::now();
|
||||
job.max_runtime_seconds = 20;
|
||||
job.action = Action::QueryLogs {
|
||||
unit: unit.as_str().into(),
|
||||
since: now - chrono::Duration::minutes(1),
|
||||
until: now,
|
||||
max_lines: 10,
|
||||
};
|
||||
assert!(log_request_for(&job, &[]).is_err());
|
||||
assert!(log_request_for(&job, std::slice::from_ref(&unit)).is_ok());
|
||||
job.max_runtime_seconds = 10;
|
||||
assert!(log_request_for(&job, std::slice::from_ref(&unit)).is_err());
|
||||
job.max_runtime_seconds = 20;
|
||||
job.action = Action::QueryLogs {
|
||||
unit: unit.as_str().into(),
|
||||
since: now - chrono::Duration::hours(25),
|
||||
until: now,
|
||||
max_lines: 10,
|
||||
};
|
||||
assert!(log_request_for(&job, std::slice::from_ref(&unit)).is_err());
|
||||
job.action = Action::QueryLogs {
|
||||
unit: unit.as_str().into(),
|
||||
since: now - chrono::Duration::minutes(1),
|
||||
until: now,
|
||||
max_lines: 1001,
|
||||
};
|
||||
assert!(log_request_for(&job, std::slice::from_ref(&unit)).is_err());
|
||||
std::fs::remove_dir_all(path).unwrap();
|
||||
}
|
||||
#[test]
|
||||
fn refresh_is_a_new_measurement_with_real_observation_time() {
|
||||
let (path, binding, offer) = fixture();
|
||||
let job = binding.job(&offer.payload_bytes).unwrap();
|
||||
let before = chrono::Utc::now();
|
||||
let outcome = execute(&job);
|
||||
assert_eq!(outcome.state, "succeeded");
|
||||
let observed =
|
||||
chrono::DateTime::parse_from_rfc3339(outcome.evidence["observed_at"].as_str().unwrap())
|
||||
.unwrap();
|
||||
assert!(observed >= before);
|
||||
assert!(
|
||||
serde_json::from_slice::<rmm_domain::Inventory>(&outcome.stdout)
|
||||
.unwrap()
|
||||
.validate()
|
||||
);
|
||||
std::fs::remove_dir_all(path).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user