Separate SYSTEM policy and verify thirteen policy guards on cloud Linux
Rust development slice / linux (push) Failing after 7s
Rust development slice / linux (push) Failing after 7s
This commit is contained in:
@@ -0,0 +1,453 @@
|
||||
//! Independent development-only Windows SYSTEM ceiling. Policy never approves a
|
||||
//! plan, publishes a capability, provisions a helper or substitutes for Sync.
|
||||
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::{self, File},
|
||||
io::Read,
|
||||
os::unix::fs::{MetadataExt, PermissionsExt},
|
||||
path::Path,
|
||||
};
|
||||
use uuid::Uuid;
|
||||
|
||||
const POLICY_LIMIT: u64 = 65536;
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct SystemPolicy {
|
||||
schema_version: u32,
|
||||
profile: String,
|
||||
expires_at: DateTime<Utc>,
|
||||
scopes: Vec<SystemScope>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct SystemScope {
|
||||
tenant_id: Uuid,
|
||||
asset_id: Uuid,
|
||||
agent_id: Uuid,
|
||||
enrollment_generation: u64,
|
||||
assignment_version: u64,
|
||||
principals: Vec<String>,
|
||||
helper_policy_sha256: String,
|
||||
helper_binary_sha256: String,
|
||||
// Administrative evidence pin, never an approval or authorization ID.
|
||||
acceptance_evidence_id: Uuid,
|
||||
allowed_services: Vec<String>,
|
||||
max_runtime_seconds: u32,
|
||||
}
|
||||
fn digest(value: &str) -> bool {
|
||||
value.len() == 64
|
||||
&& value
|
||||
.bytes()
|
||||
.all(|c| c.is_ascii_digit() || b"abcdef".contains(&c))
|
||||
}
|
||||
fn fixture_service(name: &str) -> bool {
|
||||
name.starts_with("RmmDiscoveryFixture")
|
||||
&& name.len() > "RmmDiscoveryFixture".len()
|
||||
&& name.len() <= 80
|
||||
&& name
|
||||
.bytes()
|
||||
.all(|c| c.is_ascii_alphanumeric() || b"_-".contains(&c))
|
||||
}
|
||||
impl SystemScope {
|
||||
fn valid(&self) -> bool {
|
||||
!self.tenant_id.is_nil()
|
||||
&& !self.asset_id.is_nil()
|
||||
&& !self.agent_id.is_nil()
|
||||
&& self.enrollment_generation > 0
|
||||
&& self.assignment_version > 0
|
||||
&& !self.acceptance_evidence_id.is_nil()
|
||||
&& digest(&self.helper_policy_sha256)
|
||||
&& digest(&self.helper_binary_sha256)
|
||||
&& !self.principals.is_empty()
|
||||
&& self.principals.len() <= 64
|
||||
&& self
|
||||
.principals
|
||||
.iter()
|
||||
.all(|p| !p.trim().is_empty() && p.len() <= 256)
|
||||
&& self
|
||||
.principals
|
||||
.iter()
|
||||
.collect::<std::collections::BTreeSet<_>>()
|
||||
.len()
|
||||
== self.principals.len()
|
||||
&& self.allowed_services.len() <= 16
|
||||
&& self
|
||||
.allowed_services
|
||||
.iter()
|
||||
.all(|name| fixture_service(name))
|
||||
&& self
|
||||
.allowed_services
|
||||
.iter()
|
||||
.collect::<std::collections::BTreeSet<_>>()
|
||||
.len()
|
||||
== self.allowed_services.len()
|
||||
&& (1..=120).contains(&self.max_runtime_seconds)
|
||||
}
|
||||
fn permits(&self, principal: &str, job: &JobPayload, capabilities: &[String]) -> bool {
|
||||
let has = |cap: &str| capabilities.iter().any(|c| c == cap);
|
||||
self.valid()
|
||||
&& job.execution_identity == "system"
|
||||
&& 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
|
||||
&& self.principals.iter().any(|p| p == principal)
|
||||
&& has("windows.base/1")
|
||||
&& !has("linux.base/1")
|
||||
&& has("rmm.sync.v1")
|
||||
&& has("helper.system.v1")
|
||||
&& has(&format!(
|
||||
"helper.policy.sha256:{}",
|
||||
self.helper_policy_sha256
|
||||
))
|
||||
&& has(&format!(
|
||||
"helper.binary.sha256:{}",
|
||||
self.helper_binary_sha256
|
||||
))
|
||||
&& has("system:set_service_state")
|
||||
&& has("set_service_state")
|
||||
&& (1..=self.max_runtime_seconds).contains(&job.max_runtime_seconds)
|
||||
&& (1..=65536).contains(&job.max_output_bytes)
|
||||
&& matches!(&job.action,Action::SetServiceState{unit,state}
|
||||
if self.allowed_services.contains(unit) && matches!(state.as_str(),"running"|"stopped"))
|
||||
}
|
||||
}
|
||||
impl SystemPolicy {
|
||||
fn valid(&self, now: DateTime<Utc>) -> bool {
|
||||
self.schema_version == 1
|
||||
&& self.profile == "development"
|
||||
&& self.expires_at > now
|
||||
&& !self.scopes.is_empty()
|
||||
&& self.scopes.len() <= 64
|
||||
&& self.scopes.iter().all(SystemScope::valid)
|
||||
}
|
||||
fn permits(
|
||||
&self,
|
||||
principal: &str,
|
||||
job: &JobPayload,
|
||||
capabilities: &[String],
|
||||
now: DateTime<Utc>,
|
||||
) -> bool {
|
||||
self.valid(now)
|
||||
&& self
|
||||
.scopes
|
||||
.iter()
|
||||
.any(|scope| scope.permits(principal, job, capabilities))
|
||||
}
|
||||
}
|
||||
fn disabled() -> Error {
|
||||
Error(StatusCode::CONFLICT, "UNSUPPORTED_CAPABILITY")
|
||||
}
|
||||
fn no_symlink_components(path: &Path) -> Result<(), Error> {
|
||||
let absolute = if path.is_absolute() {
|
||||
path.to_path_buf()
|
||||
} else {
|
||||
std::env::current_dir().map_err(|_| disabled())?.join(path)
|
||||
};
|
||||
for component in absolute.ancestors() {
|
||||
if fs::symlink_metadata(component)
|
||||
.map_err(|_| disabled())?
|
||||
.file_type()
|
||||
.is_symlink()
|
||||
{
|
||||
return Err(disabled());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn protected_parent_chain(path: &Path, owner: u32) -> Result<(), Error> {
|
||||
// A private immediate parent can itself be renamed through an unsafe
|
||||
// ancestor. Trust every directory owner, and reject writable ancestors
|
||||
// unless their sticky bit protects the trusted-owned next component.
|
||||
// This deliberately preserves /tmp's root-owned sticky-directory contract.
|
||||
let absolute = if path.is_absolute() {
|
||||
path.to_path_buf()
|
||||
} else {
|
||||
std::env::current_dir().map_err(|_| disabled())?.join(path)
|
||||
};
|
||||
for ancestor in absolute.ancestors().skip(1) {
|
||||
let directory = fs::symlink_metadata(ancestor).map_err(|_| disabled())?;
|
||||
let mode = directory.permissions().mode();
|
||||
if !directory.is_dir()
|
||||
|| ![0, owner].contains(&directory.uid())
|
||||
|| (mode & 0o022 != 0 && mode & 0o1000 == 0)
|
||||
{
|
||||
return Err(disabled());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn protected_bytes(path: &Path, owner: u32) -> Result<Vec<u8>, Error> {
|
||||
no_symlink_components(path)?;
|
||||
protected_parent_chain(path, owner)?;
|
||||
let before = fs::symlink_metadata(path).map_err(|_| disabled())?;
|
||||
let parent = path.parent().ok_or_else(disabled)?;
|
||||
let directory = fs::symlink_metadata(parent).map_err(|_| disabled())?;
|
||||
if !before.is_file()
|
||||
|| before.uid() != owner
|
||||
|| before.permissions().mode() & 0o777 != 0o600
|
||||
|| before.len() > POLICY_LIMIT
|
||||
|| !directory.is_dir()
|
||||
|| ![0, owner].contains(&directory.uid())
|
||||
|| directory.permissions().mode() & 0o022 != 0
|
||||
{
|
||||
return Err(disabled());
|
||||
}
|
||||
// The protected immediate parent excludes unprivileged swaps. Additionally
|
||||
// bind the opened descriptor to the lstat identity and bound the actual read.
|
||||
let mut file = File::open(path).map_err(|_| disabled())?;
|
||||
let opened = file.metadata().map_err(|_| disabled())?;
|
||||
if opened.dev() != before.dev() || opened.ino() != before.ino() {
|
||||
return Err(disabled());
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
file.by_ref()
|
||||
.take(POLICY_LIMIT + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|_| disabled())?;
|
||||
no_symlink_components(path)?;
|
||||
protected_parent_chain(path, owner)?;
|
||||
let after = fs::symlink_metadata(path).map_err(|_| disabled())?;
|
||||
if bytes.len() as u64 > POLICY_LIMIT
|
||||
|| !after.is_file()
|
||||
|| after.dev() != before.dev()
|
||||
|| after.ino() != before.ino()
|
||||
|| after.uid() != owner
|
||||
|| after.permissions().mode() & 0o777 != 0o600
|
||||
|| after.len() != before.len()
|
||||
|| after.mtime() != before.mtime()
|
||||
|| after.mtime_nsec() != before.mtime_nsec()
|
||||
{
|
||||
return Err(disabled());
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
fn load() -> Result<SystemPolicy, Error> {
|
||||
if std::env::var("RMM_PROFILE").as_deref() != Ok("development")
|
||||
|| std::env::var("RMM_DEV_SYSTEM_ENABLED").as_deref() != Ok("true")
|
||||
{
|
||||
return Err(disabled());
|
||||
}
|
||||
let path = std::env::var("RMM_DEV_SYSTEM_POLICY_FILE").map_err(|_| disabled())?;
|
||||
let key =
|
||||
std::env::var("RMM_JOB_KEY_FILE").unwrap_or_else(|_| "devstate/jobs/ed25519.pem".into());
|
||||
// Inspect only signing-key metadata, never read/log/export the private key.
|
||||
no_symlink_components(Path::new(&key))?;
|
||||
let key = fs::symlink_metadata(key).map_err(|_| disabled())?;
|
||||
if !key.is_file() {
|
||||
return Err(disabled());
|
||||
}
|
||||
let policy: SystemPolicy =
|
||||
serde_json::from_slice(&protected_bytes(Path::new(&path), key.uid())?)
|
||||
.map_err(|_| disabled())?;
|
||||
if !policy.valid(Utc::now()) {
|
||||
return Err(disabled());
|
||||
}
|
||||
Ok(policy)
|
||||
}
|
||||
pub async fn authorize(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
principal: &str,
|
||||
job: &JobPayload,
|
||||
) -> Result<(), Error> {
|
||||
if job.execution_identity != "system" {
|
||||
return Err(Error(StatusCode::FORBIDDEN, "SYSTEM_IDENTITY_REQUIRED"));
|
||||
}
|
||||
// Independent DB permission; root:execute never implies this scope.
|
||||
crate::permissions::require(tx, principal, "system: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)?;
|
||||
if !policy.permits(principal, job, &capabilities, Utc::now()) {
|
||||
return Err(Error(
|
||||
StatusCode::FORBIDDEN,
|
||||
"SYSTEM_SCOPE_OR_HELPER_POLICY_DENIED",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
fn fixture() -> (SystemPolicy, JobPayload, Vec<String>) {
|
||||
let id = Uuid::new_v4();
|
||||
let now = Utc::now();
|
||||
let policy:SystemPolicy=serde_json::from_value(json!({"schema_version":1,"profile":"development","expires_at":now+chrono::Duration::minutes(10),"scopes":[{"tenant_id":id,"asset_id":id,"agent_id":id,"enrollment_generation":1,"assignment_version":1,"principals":["selected"],"helper_policy_sha256":"ab".repeat(32),"helper_binary_sha256":"cd".repeat(32),"acceptance_evidence_id":Uuid::new_v4(),"allowed_services":["RmmDiscoveryFixtureService"],"max_runtime_seconds":30}]})).unwrap();
|
||||
let job = JobPayload {
|
||||
schema_version: 1,
|
||||
tenant_id: id,
|
||||
asset_id: id,
|
||||
agent_id: id,
|
||||
enrollment_generation: 1,
|
||||
assignment_version: 1,
|
||||
job_id: Uuid::new_v4(),
|
||||
attempt_id: Uuid::new_v4(),
|
||||
action: Action::SetServiceState {
|
||||
unit: "RmmDiscoveryFixtureService".into(),
|
||||
state: "running".into(),
|
||||
},
|
||||
execution_identity: "system".into(),
|
||||
not_before: now,
|
||||
start_before: now + chrono::Duration::minutes(5),
|
||||
max_runtime_seconds: 30,
|
||||
max_output_bytes: 4096,
|
||||
};
|
||||
let caps = vec![
|
||||
"windows.base/1".into(),
|
||||
"rmm.sync.v1".into(),
|
||||
"helper.system.v1".into(),
|
||||
format!("helper.policy.sha256:{}", "ab".repeat(32)),
|
||||
format!("helper.binary.sha256:{}", "cd".repeat(32)),
|
||||
"system:set_service_state".into(),
|
||||
"set_service_state".into(),
|
||||
];
|
||||
(policy, job, caps)
|
||||
}
|
||||
#[test]
|
||||
fn system_permission_and_helper_requirement_are_distinct_from_root() {
|
||||
let id = Uuid::new_v4();
|
||||
let principal = crate::auth::Principal {
|
||||
tenant: id,
|
||||
name: "root-only".into(),
|
||||
operator: true,
|
||||
session_hash: None,
|
||||
csrf: None,
|
||||
scopes: Some(std::collections::BTreeSet::from(["root:execute".into()])),
|
||||
testsimulation: false,
|
||||
identity: None,
|
||||
tenants: vec![id],
|
||||
};
|
||||
assert!(principal.permits_scope(crate::root_policy::execution_permission("root").unwrap()));
|
||||
assert!(
|
||||
!principal.permits_scope(crate::root_policy::execution_permission("system").unwrap())
|
||||
);
|
||||
assert!(crate::root_policy::needs_helper("system"));
|
||||
assert!(crate::root_policy::needs_helper("root"));
|
||||
assert!(!crate::root_policy::needs_helper("agent_service"));
|
||||
let (policy, job, caps) = fixture();
|
||||
let mut empty = policy;
|
||||
empty.scopes.clear();
|
||||
assert!(!empty.permits("selected", &job, &caps, Utc::now()));
|
||||
}
|
||||
#[test]
|
||||
fn exact_system_scope_never_inherits_root_or_other_device_authority() {
|
||||
let (policy, job, caps) = fixture();
|
||||
let now = Utc::now();
|
||||
assert!(policy.permits("selected", &job, &caps, now));
|
||||
assert!(!policy.permits("root-operator", &job, &caps, now));
|
||||
for identity in ["root", "agent_service", "SYSTEM"] {
|
||||
let mut other = job.clone();
|
||||
other.execution_identity = identity.into();
|
||||
assert!(!policy.permits("selected", &other, &caps, now));
|
||||
}
|
||||
for field in ["tenant", "asset", "agent", "enrollment", "assignment"] {
|
||||
let mut other = job.clone();
|
||||
match field {
|
||||
"tenant" => other.tenant_id = Uuid::new_v4(),
|
||||
"asset" => other.asset_id = Uuid::new_v4(),
|
||||
"agent" => other.agent_id = Uuid::new_v4(),
|
||||
"enrollment" => other.enrollment_generation += 1,
|
||||
_ => other.assignment_version += 1,
|
||||
}
|
||||
assert!(!policy.permits("selected", &other, &caps, now));
|
||||
}
|
||||
for i in 0..caps.len() {
|
||||
let mut missing = caps.clone();
|
||||
missing.remove(i);
|
||||
assert!(!policy.permits("selected", &job, &missing, now));
|
||||
}
|
||||
let mut mixed = caps.clone();
|
||||
mixed.push("linux.base/1".into());
|
||||
assert!(!policy.permits("selected", &job, &mixed, now));
|
||||
let mut wrong = caps.clone();
|
||||
wrong[4] = format!("helper.binary.sha256:{}", "ef".repeat(32));
|
||||
assert!(!policy.permits("selected", &job, &wrong, now));
|
||||
assert!(!policy.permits("selected", &job, &caps, policy.expires_at));
|
||||
}
|
||||
#[test]
|
||||
fn narrow_scm_ceiling_denies_unreviewed_effects_and_provider_inputs() {
|
||||
let (mut policy, mut job, caps) = fixture();
|
||||
let now = Utc::now();
|
||||
for (unit, state) in [
|
||||
("RmmDiscoveryWindows", "stopped"),
|
||||
("RmmDiscoverySystemHelper", "stopped"),
|
||||
("Spooler", "running"),
|
||||
("RmmDiscoveryFixtureService", "restarted"),
|
||||
] {
|
||||
job.action = Action::SetServiceState {
|
||||
unit: unit.into(),
|
||||
state: state.into(),
|
||||
};
|
||||
assert!(!policy.permits("selected", &job, &caps, now));
|
||||
}
|
||||
job.action = Action::RunScript {
|
||||
interpreter: "powershell".into(),
|
||||
script_utf8: "Write-Output 'hello'".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
};
|
||||
assert!(!policy.permits("selected", &job, &caps, now));
|
||||
job.action = Action::SetServiceState {
|
||||
unit: "RmmDiscoveryFixtureService".into(),
|
||||
state: "stopped".into(),
|
||||
};
|
||||
assert!(policy.permits("selected", &job, &caps, now));
|
||||
job.max_runtime_seconds = 31;
|
||||
assert!(!policy.permits("selected", &job, &caps, now));
|
||||
job.max_runtime_seconds = 30;
|
||||
policy.scopes[0].acceptance_evidence_id = Uuid::nil();
|
||||
assert!(!policy.permits("selected", &job, &caps, now));
|
||||
let invalid = json!({"schema_version":1,"profile":"development","expires_at":now,"scopes":[],"allow_system_scripts":true});
|
||||
assert!(serde_json::from_value::<SystemPolicy>(invalid).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn policy_file_refuses_symlinks_public_mode_wrong_owner_and_writable_parent() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let directory = std::env::temp_dir().join(format!("rmm-windows-policy-{}", Uuid::new_v4()));
|
||||
fs::create_dir(&directory).unwrap();
|
||||
fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let path = directory.join("policy.json");
|
||||
fs::write(&path, b"{}").unwrap();
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();
|
||||
let owner = fs::metadata(&path).unwrap().uid();
|
||||
assert_eq!(protected_bytes(&path, owner).unwrap(), b"{}");
|
||||
assert!(protected_bytes(&path, owner.wrapping_add(1)).is_err());
|
||||
let link = directory.join("link.json");
|
||||
symlink(&path, &link).unwrap();
|
||||
assert!(protected_bytes(&link, owner).is_err());
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o640)).unwrap();
|
||||
assert!(protected_bytes(&path, owner).is_err());
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();
|
||||
fs::set_permissions(&directory, fs::Permissions::from_mode(0o770)).unwrap();
|
||||
assert!(protected_bytes(&path, owner).is_err());
|
||||
fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
fs::write(&path, vec![b' '; POLICY_LIMIT as usize + 1]).unwrap();
|
||||
assert!(protected_bytes(&path, owner).is_err());
|
||||
let real = directory.join("real");
|
||||
let nested = real.join("nested");
|
||||
fs::create_dir_all(&nested).unwrap();
|
||||
fs::set_permissions(&nested, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let data = nested.join("policy.json");
|
||||
fs::write(&data, b"{}").unwrap();
|
||||
fs::set_permissions(&data, fs::Permissions::from_mode(0o600)).unwrap();
|
||||
// The immediate parent remains protected throughout. A writable
|
||||
// ancestor still permits substitution of that entire directory.
|
||||
fs::set_permissions(&real, fs::Permissions::from_mode(0o777)).unwrap();
|
||||
assert!(protected_bytes(&data, owner).is_err());
|
||||
fs::set_permissions(&real, fs::Permissions::from_mode(0o1777)).unwrap();
|
||||
assert_eq!(protected_bytes(&data, owner).unwrap(), b"{}");
|
||||
fs::set_permissions(&real, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let alias = directory.join("alias");
|
||||
symlink(&real, &alias).unwrap();
|
||||
assert!(protected_bytes(&alias.join("nested/policy.json"), owner).is_err());
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user