458 lines
17 KiB
Rust
458 lines
17 KiB
Rust
use crate::jobs::Error;
|
|
use axum::http::StatusCode;
|
|
use chrono::{DateTime, Utc};
|
|
use rmm_domain::jobs::{Action, JobPayload};
|
|
use serde::Deserialize;
|
|
use sqlx::{Postgres, Transaction};
|
|
use std::{
|
|
fs,
|
|
os::unix::fs::{MetadataExt, PermissionsExt},
|
|
path::Path,
|
|
};
|
|
use uuid::Uuid;
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct RootPolicy {
|
|
schema_version: u32,
|
|
profile: String,
|
|
expires_at: DateTime<Utc>,
|
|
scopes: Vec<RootScope>,
|
|
}
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct RootScope {
|
|
tenant_id: Uuid,
|
|
asset_id: Uuid,
|
|
agent_id: Uuid,
|
|
enrollment_generation: u64,
|
|
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>,
|
|
#[serde(default)]
|
|
root_logs: Option<RootLogPolicy>,
|
|
}
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct RootLogPolicy {
|
|
schema_version: u32,
|
|
allowed_units: Vec<String>,
|
|
#[serde(default)]
|
|
sensitive_units: Vec<String>,
|
|
}
|
|
fn valid_log_unit(unit: &str) -> bool {
|
|
unit.len() > ".service".len()
|
|
&& unit.len() <= 255
|
|
&& unit.ends_with(".service")
|
|
&& unit.as_bytes()[0].is_ascii_alphanumeric()
|
|
&& unit
|
|
.bytes()
|
|
.all(|c| c.is_ascii_alphanumeric() || b"_.@:-".contains(&c))
|
|
}
|
|
fn valid_log_units(units: &[String]) -> bool {
|
|
let distinct = units.iter().collect::<std::collections::BTreeSet<_>>();
|
|
units.len() <= 128 && distinct.len() == units.len() && units.iter().all(|u| valid_log_unit(u))
|
|
}
|
|
fn parse_log_units(raw: Option<&str>) -> Result<Option<Vec<String>>, Error> {
|
|
let Some(raw) = raw else { return Ok(None) };
|
|
// Explicit empty environment means deny-all, never an implicit wildcard.
|
|
let units: Vec<String> = if raw.trim().is_empty() {
|
|
Vec::new()
|
|
} else {
|
|
if raw.len() > 32768 {
|
|
return Err(Error(StatusCode::CONFLICT, "ROOT_LOG_ALLOWLIST_INVALID"));
|
|
}
|
|
serde_json::from_str(raw)
|
|
.map_err(|_| Error(StatusCode::CONFLICT, "ROOT_LOG_ALLOWLIST_INVALID"))?
|
|
};
|
|
if !valid_log_units(&units) {
|
|
return Err(Error(StatusCode::CONFLICT, "ROOT_LOG_ALLOWLIST_INVALID"));
|
|
}
|
|
Ok(Some(units))
|
|
}
|
|
impl RootLogPolicy {
|
|
fn valid(&self) -> bool {
|
|
self.schema_version == 1
|
|
&& valid_log_units(&self.allowed_units)
|
|
&& valid_log_units(&self.sensitive_units)
|
|
}
|
|
}
|
|
impl RootPolicy {
|
|
fn sensitive_log_unit(&self, job: &JobPayload, unit: &str, extra: Option<&[String]>) -> bool {
|
|
matches!(unit, "ssh.service" | "sshd.service" | "auditd.service" | "systemd-logind.service")
|
|
|| (unit.starts_with("sshd@") && unit.ends_with(".service"))
|
|
|| extra.is_some_and(|units| units.iter().any(|u| u == unit))
|
|
// Classification is shared across matching target scopes, not just
|
|
// the first scope/actor that grants a unit. Another scope cannot
|
|
// silently declassify a sensitive source.
|
|
|| self.scopes.iter().any(|scope| scope.matches_target(job)
|
|
&& scope.root_logs.as_ref().is_some_and(|logs| logs.sensitive_units.iter().any(|u| u == unit)))
|
|
}
|
|
}
|
|
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");
|
|
}
|
|
if matches!(job.action, Action::QueryLogs { .. }) {
|
|
permissions.push("logs:read");
|
|
if sensitive_log {
|
|
permissions.push("logs:read_sensitive");
|
|
}
|
|
}
|
|
permissions
|
|
}
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct RootAptPolicy {
|
|
allow_native_acceptance: bool,
|
|
allow_execute: bool,
|
|
provider_sha256: String,
|
|
hook_sha256: String,
|
|
apt_config_sha256: String,
|
|
runtime_sha256: String,
|
|
}
|
|
impl RootAptPolicy {
|
|
fn permits(
|
|
&self,
|
|
m: &rmm_domain::apt_transaction::AptExecutionManifest,
|
|
native: bool,
|
|
caps: &[String],
|
|
) -> bool {
|
|
m.validate()
|
|
&& if native {
|
|
self.allow_native_acceptance && caps.iter().any(|c| c == "apt.native-acceptance.v1")
|
|
} else {
|
|
self.allow_execute && caps.iter().any(|c| c == "apt.native-accepted.v1")
|
|
}
|
|
&& caps.iter().any(|c| c == "apt.manifest.v2")
|
|
&& m.provider_sha256 == self.provider_sha256
|
|
&& m.hook_sha256 == self.hook_sha256
|
|
&& m.apt_config_sha256 == self.apt_config_sha256
|
|
&& m.runtime_sha256 == self.runtime_sha256
|
|
}
|
|
}
|
|
impl RootScope {
|
|
fn matches_target(&self, job: &JobPayload) -> bool {
|
|
self.tenant_id == job.tenant_id
|
|
&& self.asset_id == job.asset_id
|
|
&& self.agent_id == job.agent_id
|
|
&& self.enrollment_generation == job.enrollment_generation
|
|
&& self.assignment_version == job.assignment_version
|
|
}
|
|
fn permits(
|
|
&self,
|
|
principal: &str,
|
|
job: &JobPayload,
|
|
capabilities: &[String],
|
|
global_log_units: Option<&[String]>,
|
|
) -> bool {
|
|
if job.execution_identity != "root" || capabilities.iter().any(|c| c == "windows.base/1") {
|
|
return false;
|
|
}
|
|
if !self.matches_target(job)
|
|
|| !self.principals.iter().any(|p| p == principal)
|
|
|| self.helper_policy_sha256.len() != 64
|
|
|| !self
|
|
.helper_policy_sha256
|
|
.bytes()
|
|
.all(|c| c.is_ascii_digit() || b"abcdef".contains(&c))
|
|
|| self.acceptance_evidence_id.trim().is_empty()
|
|
{
|
|
return false;
|
|
}
|
|
if ![
|
|
"rmm.sync.v1".to_string(),
|
|
"helper.root.v1".to_string(),
|
|
format!("helper.policy.sha256:{}", self.helper_policy_sha256),
|
|
format!("root:{}", job.action.name()),
|
|
job.action.name().into(),
|
|
]
|
|
.iter()
|
|
.all(|cap| capabilities.contains(cap))
|
|
{
|
|
return false;
|
|
}
|
|
if job.max_output_bytes > 65536 {
|
|
return false;
|
|
}
|
|
match &job.action {
|
|
Action::QueryLogs {
|
|
unit,
|
|
since,
|
|
until,
|
|
max_lines,
|
|
} => {
|
|
let allowed = match &self.root_logs {
|
|
Some(logs) => {
|
|
logs.valid()
|
|
&& logs.allowed_units.contains(unit)
|
|
&& global_log_units.is_none_or(|units| units.iter().any(|u| u == unit))
|
|
}
|
|
None => global_log_units.is_some_and(|units| units.iter().any(|u| u == unit)),
|
|
};
|
|
allowed
|
|
&& valid_log_unit(unit)
|
|
&& since.timestamp() >= 0
|
|
&& since < until
|
|
&& *until - *since <= chrono::Duration::hours(24)
|
|
&& (1..=1000).contains(max_lines)
|
|
&& (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
|
|
&& 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")
|
|
&& job.max_runtime_seconds >= 180
|
|
}
|
|
Action::Reboot { .. } => self.allow_reboot && job.max_runtime_seconds >= 60,
|
|
Action::AptNativeAcceptance {
|
|
apt_manifest: m, ..
|
|
} => {
|
|
job.max_runtime_seconds >= 180
|
|
&& self
|
|
.apt
|
|
.as_ref()
|
|
.is_some_and(|p| p.permits(m, true, capabilities))
|
|
}
|
|
Action::EnsurePackage {
|
|
apt_manifest: Some(m),
|
|
..
|
|
}
|
|
| Action::ApplyUpdates {
|
|
apt_manifest: Some(m),
|
|
..
|
|
} => {
|
|
job.max_runtime_seconds >= 180
|
|
&& self
|
|
.apt
|
|
.as_ref()
|
|
.is_some_and(|p| p.permits(m, false, capabilities))
|
|
}
|
|
// Legacy package actions never gain authority from a capability.
|
|
_ => false,
|
|
}
|
|
}
|
|
}
|
|
fn load() -> Result<RootPolicy, Error> {
|
|
let disabled = || Error(StatusCode::CONFLICT, "UNSUPPORTED_CAPABILITY");
|
|
if std::env::var("RMM_PROFILE").as_deref() != Ok("development")
|
|
|| std::env::var("RMM_DEV_ROOT_ENABLED").as_deref() != Ok("true")
|
|
{
|
|
return Err(disabled());
|
|
}
|
|
let path = std::env::var("RMM_DEV_ROOT_POLICY_FILE").map_err(|_| disabled())?;
|
|
let metadata = fs::symlink_metadata(&path).map_err(|_| disabled())?;
|
|
let key =
|
|
std::env::var("RMM_JOB_KEY_FILE").unwrap_or_else(|_| "devstate/jobs/ed25519.pem".into());
|
|
let owner = fs::metadata(key).map_err(|_| disabled())?.uid();
|
|
let parent = Path::new(&path).parent().ok_or_else(disabled)?;
|
|
let parent_meta = fs::symlink_metadata(parent).map_err(|_| disabled())?;
|
|
if !metadata.is_file()
|
|
|| metadata.permissions().mode() & 0o077 != 0
|
|
|| metadata.uid() != owner
|
|
|| metadata.len() > 65536
|
|
|| !parent_meta.is_dir()
|
|
|| parent_meta.permissions().mode() & 0o022 != 0
|
|
{
|
|
return Err(disabled());
|
|
}
|
|
let policy: RootPolicy =
|
|
serde_json::from_slice(&fs::read(path).map_err(|_| disabled())?).map_err(|_| disabled())?;
|
|
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()
|
|
|| policy.scopes.len() > 64
|
|
|| policy
|
|
.scopes
|
|
.iter()
|
|
.any(|scope| scope.root_logs.as_ref().is_some_and(|logs| !logs.valid()))
|
|
{
|
|
return Err(disabled());
|
|
}
|
|
Ok(policy)
|
|
}
|
|
pub fn execution_permission(identity: &str) -> Option<&'static str> {
|
|
match identity {
|
|
"root" => Some("root:execute"),
|
|
"system" => Some("system:execute"),
|
|
_ => None,
|
|
}
|
|
}
|
|
pub fn needs_helper(identity: &str) -> bool {
|
|
execution_permission(identity).is_some()
|
|
}
|
|
pub async fn authorize(
|
|
tx: &mut Transaction<'_, Postgres>,
|
|
principal: &str,
|
|
job: &JobPayload,
|
|
) -> Result<(), Error> {
|
|
if matches!(job.action, Action::UpdateAgent { .. }) {
|
|
return crate::agent_update_policy::authorize(tx, principal, job).await;
|
|
}
|
|
match job.execution_identity.as_str() {
|
|
"system" => return crate::windows_policy::authorize(tx, principal, job).await,
|
|
"agent_service" => return Ok(()),
|
|
"root" => {}
|
|
_ => return Err(Error(StatusCode::FORBIDDEN, "EXECUTION_IDENTITY_DENIED")),
|
|
}
|
|
for permission in required_permissions(job, false) {
|
|
crate::permissions::require(tx, principal, permission).await?;
|
|
}
|
|
let policy = load()?;
|
|
let global_log_units = if matches!(job.action, Action::QueryLogs { .. }) {
|
|
parse_log_units(std::env::var("RMM_ROOT_LOG_UNITS").ok().as_deref())?
|
|
} else {
|
|
None
|
|
};
|
|
if let Action::QueryLogs { unit, .. } = &job.action {
|
|
let sensitive_units = parse_log_units(
|
|
std::env::var("RMM_ROOT_SENSITIVE_LOG_UNITS")
|
|
.ok()
|
|
.as_deref(),
|
|
)?;
|
|
if policy.sensitive_log_unit(job, unit, sensitive_units.as_deref()) {
|
|
// Re-read current membership on every planning/approval/start call.
|
|
// No policy flag, viewer role, capability or test profile grants it.
|
|
crate::permissions::require(tx, principal, "logs:read_sensitive").await?;
|
|
}
|
|
}
|
|
let caps:serde_json::Value=sqlx::query_scalar("SELECT capabilities FROM agent_installations WHERE agent_id=$1 AND asset_id=$2 AND revoked_at IS NULL AND enrollment_generation=$3 AND assignment_version=$4").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 caps: Vec<String> = serde_json::from_value(caps)?;
|
|
if !policy
|
|
.scopes
|
|
.iter()
|
|
.any(|scope| scope.permits(principal, job, &caps, global_log_units.as_deref()))
|
|
{
|
|
return Err(Error(
|
|
StatusCode::FORBIDDEN,
|
|
"ROOT_SCOPE_OR_HELPER_POLICY_DENIED",
|
|
));
|
|
}
|
|
Ok(())
|
|
}
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
#[test]
|
|
fn no_capability_or_relabel_shortcut() {
|
|
let id = Uuid::new_v4();
|
|
let now = Utc::now();
|
|
let mut job = JobPayload {
|
|
schema_version: 1,
|
|
tenant_id: id,
|
|
asset_id: id,
|
|
agent_id: id,
|
|
enrollment_generation: 1,
|
|
assignment_version: 1,
|
|
job_id: id,
|
|
attempt_id: id,
|
|
action: Action::RunScript {
|
|
interpreter: "posix_sh".into(),
|
|
script_utf8: "true\n".into(),
|
|
arguments: vec![],
|
|
expected_stdout: None,
|
|
windows_execution_profile: None,
|
|
privileged_script_profile: None,
|
|
},
|
|
execution_identity: "root".into(),
|
|
not_before: now,
|
|
start_before: now + chrono::Duration::hours(1),
|
|
max_runtime_seconds: 60,
|
|
max_output_bytes: 1024,
|
|
};
|
|
let mut scope = RootScope {
|
|
tenant_id: id,
|
|
asset_id: id,
|
|
agent_id: id,
|
|
enrollment_generation: 1,
|
|
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,
|
|
};
|
|
let caps = vec![
|
|
"rmm.sync.v1".into(),
|
|
"helper.root.v1".into(),
|
|
format!("helper.policy.sha256:{}", "ab".repeat(32)),
|
|
"root:run_script".into(),
|
|
"run_script".into(),
|
|
];
|
|
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));
|
|
}
|
|
}
|
|
#[cfg(test)]
|
|
#[path = "../../../tests/backend_root_logs.rs"]
|
|
mod root_log_tests;
|