469 lines
18 KiB
Rust
469 lines
18 KiB
Rust
//! Permanent authorization ceilings for installed, pinned script helpers.
|
|
//! Plan submission, interactive approval and signed start grants are unchanged.
|
|
use crate::{jobs::Error, root_policy::RootScope, windows_policy::SystemScope};
|
|
use axum::http::StatusCode;
|
|
use rmm_domain::{
|
|
agent_update::{ArtifactRole, LINUX_ARM64_RELEASE_CAPABILITY, Platform, ReleaseManifest, digest},
|
|
jobs::{Action, FULL_MAINTENANCE_CAPABILITY, JobPayload},
|
|
};
|
|
use serde::Deserialize;
|
|
use sqlx::{Postgres, Transaction};
|
|
use std::{fs, os::unix::fs::MetadataExt, path::Path};
|
|
use uuid::Uuid;
|
|
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct Policy {
|
|
schema_version: u8,
|
|
linux: Vec<RootScope>,
|
|
windows: Vec<SystemScope>,
|
|
#[serde(default)]
|
|
release_anchors: Vec<ReleaseAnchor>,
|
|
}
|
|
|
|
/// Operator-pinned canonical bytes of an already authorized local policy.
|
|
/// A signed pair changes only the two image digests and the Windows release directory.
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct ReleaseAnchor {
|
|
agent_id: Uuid,
|
|
release_id: Uuid,
|
|
agent_sha256: String,
|
|
helper_sha256: String,
|
|
policy_json: String,
|
|
}
|
|
|
|
impl ReleaseAnchor {
|
|
fn policy_for(&self, manifest: &ReleaseManifest) -> Option<String> {
|
|
if self.policy_json.len() > 8192
|
|
|| self.release_id.is_nil()
|
|
|| !digest(&self.agent_sha256)
|
|
|| !digest(&self.helper_sha256)
|
|
|| self.agent_sha256 == self.helper_sha256
|
|
{
|
|
return None;
|
|
}
|
|
let next = |role| {
|
|
manifest
|
|
.artifacts
|
|
.iter()
|
|
.find(|a| a.role == role)
|
|
.map(|a| a.sha256.as_str())
|
|
};
|
|
let mut raw = self.policy_json.clone();
|
|
let mut replace = |from: String, to: String, count| {
|
|
if raw.matches(&from).count() != count {
|
|
return None;
|
|
}
|
|
raw = raw.replace(&from, &to);
|
|
Some(())
|
|
};
|
|
let field = |name: &str, value: &str| format!(r#""{name}":"{value}""#);
|
|
match manifest.platform {
|
|
Platform::LinuxX64 | Platform::LinuxArm64 => replace(
|
|
field("helper_binary_sha256", &self.helper_sha256),
|
|
field("helper_binary_sha256", next(ArtifactRole::Helper)?),
|
|
1,
|
|
)?,
|
|
Platform::WindowsGnuX64 => {
|
|
replace(
|
|
field("binary_sha256", &self.agent_sha256),
|
|
field("binary_sha256", next(ArtifactRole::Agent)?),
|
|
1,
|
|
)?;
|
|
replace(
|
|
field("binary_sha256", &self.helper_sha256),
|
|
field("binary_sha256", next(ArtifactRole::Helper)?),
|
|
1,
|
|
)?;
|
|
let directory = |release| format!(r"\\releases\\{release}\\");
|
|
replace(
|
|
directory(self.release_id),
|
|
directory(manifest.release_id),
|
|
2,
|
|
)?;
|
|
}
|
|
_ => return None,
|
|
}
|
|
Some(rmm_domain::jobs::hash(raw.as_bytes()))
|
|
}
|
|
}
|
|
|
|
fn invalid() -> Error {
|
|
Error(StatusCode::CONFLICT, "MANAGED_SCRIPT_POLICY_INVALID")
|
|
}
|
|
|
|
// Only a managed device scope can opt in. The authenticated principal remains
|
|
// the token ID for authorization, the plan record and audit.
|
|
const SCOPED_MCP: &str = "mcp:scoped";
|
|
|
|
#[derive(Clone, Copy)]
|
|
enum HelperBinding {
|
|
LocalPins,
|
|
VerifiedInstalledRelease,
|
|
}
|
|
|
|
impl Policy {
|
|
fn permits(
|
|
&self,
|
|
principal: &str,
|
|
job: &JobPayload,
|
|
caps: &[String],
|
|
binding: HelperBinding,
|
|
) -> bool {
|
|
if principal == SCOPED_MCP
|
|
|| !matches!(job.action, Action::RunScript { .. })
|
|
|| !job.action.full_maintenance()
|
|
|| !job.action.validate()
|
|
|| !job.action.available_for(&job.execution_identity, caps)
|
|
|| !job
|
|
.action
|
|
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
|
|
{
|
|
return false;
|
|
}
|
|
let permits_subject = |subject: &str| match job.execution_identity.as_str() {
|
|
"root" => self
|
|
.linux
|
|
.iter()
|
|
.any(|scope| scope.permits(subject, job, caps, None)),
|
|
"system" => self
|
|
.windows
|
|
.iter()
|
|
.any(|scope| scope.permits(subject, job, caps, false, true, false)),
|
|
_ => false,
|
|
};
|
|
permits_subject(principal)
|
|
|| (matches!(binding, HelperBinding::VerifiedInstalledRelease)
|
|
&& principal.strip_prefix("mcp:").is_some_and(|id| {
|
|
Uuid::parse_str(id).is_ok_and(|uuid| !uuid.is_nil() && uuid.to_string() == id)
|
|
})
|
|
&& permits_subject(SCOPED_MCP))
|
|
}
|
|
}
|
|
|
|
fn binding_error() -> Error {
|
|
Error(StatusCode::CONFLICT, "SCRIPT_HELPER_BINDING_INVALID")
|
|
}
|
|
|
|
// Multiple helper roles may coexist on older clients. For the release-managed
|
|
// script profile we require exactly one unambiguous release, policy and binary.
|
|
fn single_value<'a>(caps: &'a [String], prefix: &str) -> Result<&'a str, Error> {
|
|
let mut values = caps.iter().filter_map(|c| c.strip_prefix(prefix));
|
|
let value = values.next().ok_or_else(binding_error)?;
|
|
if value.is_empty() || values.next().is_some() {
|
|
return Err(binding_error());
|
|
}
|
|
Ok(value)
|
|
}
|
|
|
|
fn check_pair(
|
|
manifest: &ReleaseManifest,
|
|
version: Option<&str>,
|
|
identity: &str,
|
|
caps: &[String],
|
|
) -> Result<(), Error> {
|
|
let platform = match identity {
|
|
"root" if caps.iter().any(|cap| cap == LINUX_ARM64_RELEASE_CAPABILITY) => {
|
|
Platform::LinuxArm64
|
|
}
|
|
"root" => Platform::LinuxX64,
|
|
"system" => Platform::WindowsGnuX64,
|
|
_ => return Err(binding_error()),
|
|
};
|
|
let binary = single_value(caps, "helper.binary.sha256:")?;
|
|
if version != Some(manifest.version.as_str())
|
|
|| platform != manifest.platform
|
|
|| !digest(single_value(caps, "helper.policy.sha256:")?)
|
|
|| !manifest
|
|
.artifacts
|
|
.iter()
|
|
.any(|a| a.role == ArtifactRole::Helper && a.sha256 == binary)
|
|
{
|
|
return Err(binding_error());
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub(crate) async fn permits(
|
|
tx: &mut Transaction<'_, Postgres>,
|
|
principal: &str,
|
|
job: &JobPayload,
|
|
caps: &[String],
|
|
) -> Result<bool, Error> {
|
|
if !job.action.full_maintenance() {
|
|
return Ok(false);
|
|
}
|
|
let Some(path) = std::env::var_os("RMM_MANAGED_SCRIPT_POLICY_FILE") else {
|
|
return Ok(false);
|
|
};
|
|
let key = std::env::var_os("RMM_JOB_KEY_FILE").ok_or_else(invalid)?;
|
|
let signer = fs::symlink_metadata(key).map_err(|_| invalid())?;
|
|
if !signer.is_file() {
|
|
return Err(invalid());
|
|
}
|
|
let bytes = crate::windows_policy::protected_bytes(Path::new(&path), signer.uid())
|
|
.map_err(|_| invalid())?;
|
|
let policy: Policy = serde_json::from_slice(&bytes).map_err(|_| invalid())?;
|
|
if policy.schema_version != 1
|
|
|| policy.linux.len() + policy.windows.len() > 64
|
|
|| policy.release_anchors.len() > 64
|
|
|| policy
|
|
.release_anchors
|
|
.iter()
|
|
.any(|a| a.policy_json.len() > 8192)
|
|
|| !policy.windows.iter().all(SystemScope::valid)
|
|
{
|
|
return Err(invalid());
|
|
}
|
|
if !caps
|
|
.iter()
|
|
.any(|cap| cap.starts_with("script.helper.release:"))
|
|
{
|
|
return Ok(policy.permits(principal, job, caps, HelperBinding::LocalPins));
|
|
}
|
|
{
|
|
let release = Uuid::parse_str(single_value(caps, "script.helper.release:")?)
|
|
.map_err(|_| binding_error())?;
|
|
if !caps.iter().any(|cap| cap == FULL_MAINTENANCE_CAPABILITY) {
|
|
return Err(binding_error());
|
|
}
|
|
let version: Option<String> = sqlx::query_scalar(
|
|
"SELECT reported_agent_version FROM agent_installations WHERE tenant_id=$1 AND agent_id=$2 AND asset_id=$3 AND revoked_at IS NULL",
|
|
)
|
|
.bind(job.tenant_id)
|
|
.bind(job.agent_id)
|
|
.bind(job.asset_id)
|
|
.fetch_optional(&mut **tx)
|
|
.await?
|
|
.flatten();
|
|
let manifest = crate::agent_updates::checked_installed_helper_release(tx, release)
|
|
.await
|
|
.map_err(|err| {
|
|
if err.0.is_server_error() {
|
|
err
|
|
} else {
|
|
binding_error()
|
|
}
|
|
})?;
|
|
check_pair(&manifest, version.as_deref(), &job.execution_identity, caps)?;
|
|
if policy.permits(
|
|
principal,
|
|
job,
|
|
caps,
|
|
HelperBinding::VerifiedInstalledRelease,
|
|
) {
|
|
return Ok(true);
|
|
}
|
|
let current_policy = single_value(caps, "helper.policy.sha256:")?;
|
|
for anchor in policy
|
|
.release_anchors
|
|
.iter()
|
|
.filter(|a| a.agent_id == job.agent_id)
|
|
{
|
|
if anchor.policy_for(&manifest).as_deref() != Some(current_policy) {
|
|
continue;
|
|
}
|
|
let original = rmm_domain::jobs::hash(anchor.policy_json.as_bytes());
|
|
let mut pinned = caps.to_owned();
|
|
pinned.retain(|c| {
|
|
!c.starts_with("helper.binary.sha256:") && !c.starts_with("helper.policy.sha256:")
|
|
});
|
|
pinned.push(format!("helper.binary.sha256:{}", anchor.helper_sha256));
|
|
pinned.push(format!("helper.policy.sha256:{original}"));
|
|
if policy.permits(
|
|
principal,
|
|
job,
|
|
&pinned,
|
|
HelperBinding::VerifiedInstalledRelease,
|
|
) {
|
|
return Ok(true);
|
|
}
|
|
}
|
|
}
|
|
Err(Error(StatusCode::FORBIDDEN, "SCRIPT_HELPER_SCOPE_DENIED"))
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use rmm_domain::agent_update::ArtifactDescriptor;
|
|
use serde_json::json;
|
|
|
|
#[test]
|
|
fn scoped_mcp_requires_a_device_opt_in_and_the_same_pinned_script_scope() {
|
|
let token = "mcp:12345678-abcd-4321-b123-123456789abc";
|
|
let verified = HelperBinding::VerifiedInstalledRelease;
|
|
let local = HelperBinding::LocalPins;
|
|
for (platform, identity, interpreter, script) in [
|
|
("linux", "root", "posix_sh", "true\n"),
|
|
("windows", "system", "powershell", "Write-Output 'ok'\r\n"),
|
|
] {
|
|
let mut job = JobPayload {
|
|
schema_version: 1,
|
|
tenant_id: Uuid::new_v4(),
|
|
asset_id: Uuid::new_v4(),
|
|
agent_id: Uuid::new_v4(),
|
|
enrollment_generation: 1,
|
|
assignment_version: 1,
|
|
job_id: Uuid::new_v4(),
|
|
attempt_id: Uuid::new_v4(),
|
|
action: Action::RunScript {
|
|
interpreter: interpreter.into(),
|
|
script_utf8: script.into(),
|
|
arguments: vec![],
|
|
expected_stdout: None,
|
|
windows_execution_profile: None,
|
|
privileged_script_profile: Some(
|
|
rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
|
|
),
|
|
},
|
|
execution_identity: identity.into(),
|
|
not_before: chrono::Utc::now(),
|
|
start_before: chrono::Utc::now() + chrono::Duration::minutes(5),
|
|
max_runtime_seconds: 30,
|
|
max_output_bytes: 4096,
|
|
};
|
|
let binary = "ab".repeat(32);
|
|
let local_policy = "cd".repeat(32);
|
|
let mut caps = vec![
|
|
format!("{platform}.base/1"),
|
|
format!("helper.{identity}.v1"),
|
|
format!("{identity}:run_script"),
|
|
"run_script".into(),
|
|
"rmm.sync.v1".into(),
|
|
FULL_MAINTENANCE_CAPABILITY.into(),
|
|
format!("helper.policy.sha256:{local_policy}"),
|
|
format!("helper.binary.sha256:{binary}"),
|
|
];
|
|
let mut scope = json!({
|
|
"tenant_id": job.tenant_id, "asset_id": job.asset_id, "agent_id": job.agent_id,
|
|
"enrollment_generation": 1, "assignment_version": 1, "principals": ["local:reviewer"],
|
|
"helper_policy_sha256": local_policy, "helper_binary_sha256": binary,
|
|
"acceptance_evidence_id": Uuid::new_v4(), "allowed_services": [],
|
|
"allowed_script_profiles": ["full_maintenance_v1"]
|
|
});
|
|
if platform == "linux" {
|
|
scope["allow_root_scripts"] = json!(true);
|
|
scope["allow_reboot"] = json!(false);
|
|
} else {
|
|
scope["max_runtime_seconds"] = json!(30);
|
|
scope["allowed_script_sha256"] = json!([rmm_domain::jobs::hash(script.as_bytes())]);
|
|
caps.push("script.powershell/1".into());
|
|
}
|
|
let mut config = json!({"schema_version": 1, "linux": [], "windows": []});
|
|
config[platform] = json!([scope]);
|
|
let policy: Policy = serde_json::from_value(config.clone()).unwrap();
|
|
assert!(policy.permits("local:reviewer", &job, &caps, verified));
|
|
assert!(!policy.permits(token, &job, &caps, verified));
|
|
|
|
config[platform][0]["principals"] = json!(["local:reviewer", SCOPED_MCP]);
|
|
let policy: Policy = serde_json::from_value(config).unwrap();
|
|
assert!(policy.permits(token, &job, &caps, verified), "{platform}");
|
|
assert!(!policy.permits(token, &job, &caps, local));
|
|
assert!(policy.permits("local:reviewer", &job, &caps, local));
|
|
assert!(policy.permits("local:reviewer", &job, &caps, verified));
|
|
for other in [
|
|
SCOPED_MCP,
|
|
"local:other",
|
|
"mcp:not-a-uuid",
|
|
"mcp:00000000-0000-0000-0000-000000000000",
|
|
"mcp:12345678ABCD4321B123123456789ABC",
|
|
] {
|
|
assert!(
|
|
!policy.permits(other, &job, &caps, verified),
|
|
"{platform}: {other}"
|
|
);
|
|
}
|
|
let mut without_binary = caps.clone();
|
|
without_binary.retain(|cap| !cap.starts_with("helper.binary.sha256:"));
|
|
assert!(!policy.permits(token, &job, &without_binary, verified));
|
|
job.assignment_version += 1;
|
|
assert!(!policy.permits(token, &job, &caps, verified));
|
|
if platform == "windows" {
|
|
job.assignment_version -= 1;
|
|
if let Action::RunScript { arguments, .. } = &mut job.action {
|
|
arguments.push("other".into());
|
|
}
|
|
assert!(!policy.permits(token, &job, &caps, verified));
|
|
if let Action::RunScript {
|
|
script_utf8,
|
|
arguments,
|
|
..
|
|
} = &mut job.action
|
|
{
|
|
arguments.clear();
|
|
*script_utf8 = "Write-Output 'changed'\r\n".into();
|
|
}
|
|
assert!(!policy.permits(token, &job, &caps, verified));
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn signed_helper_is_bound_to_platform_reported_version_and_unambiguous_local_pins() {
|
|
let binary = "ab".repeat(32);
|
|
let policy = "cd".repeat(32);
|
|
let artifact = |role, sha256| ArtifactDescriptor {
|
|
role,
|
|
sha256,
|
|
artifact_id: Uuid::new_v4(),
|
|
bytes: 4096,
|
|
};
|
|
let m = ReleaseManifest {
|
|
schema_version: 1,
|
|
release_id: Uuid::new_v4(),
|
|
release_sequence: 7,
|
|
version: "0.1.12".into(),
|
|
platform: Platform::WindowsGnuX64,
|
|
published_at: 10,
|
|
expires_at: 500,
|
|
protocol_major: 1,
|
|
state_schema: 1,
|
|
minimum_updater_version: 2,
|
|
artifacts: [
|
|
artifact(ArtifactRole::Agent, "ef".repeat(32)),
|
|
artifact(ArtifactRole::Helper, binary.clone()),
|
|
],
|
|
};
|
|
// Rollover may substitute signed image pins and their release directory only.
|
|
let previous = Uuid::new_v4();
|
|
let original_agent = "12".repeat(32);
|
|
let original_helper = "34".repeat(32);
|
|
let windows = |release: Uuid, agent: &str, helper: &str, runtime: u32| {
|
|
format!(
|
|
r#"{{"agent":{{"binary":"C:\\releases\\{release}\\agent.exe","binary_sha256":"{agent}"}},"helper":{{"binary":"C:\\releases\\{release}\\helper.exe","binary_sha256":"{helper}"}},"max_runtime_seconds":{runtime}}}"#
|
|
)
|
|
};
|
|
let mut anchor = ReleaseAnchor {
|
|
agent_id: Uuid::new_v4(),
|
|
release_id: previous,
|
|
policy_json: windows(previous, &original_agent, &original_helper, 30),
|
|
agent_sha256: original_agent,
|
|
helper_sha256: original_helper,
|
|
};
|
|
let next_agent = &m.artifacts[0].sha256;
|
|
let expected = |limit| {
|
|
rmm_domain::jobs::hash(windows(m.release_id, next_agent, &binary, limit).as_bytes())
|
|
};
|
|
assert_eq!(anchor.policy_for(&m), Some(expected(30)));
|
|
assert_ne!(anchor.policy_for(&m), Some(expected(120)));
|
|
anchor
|
|
.policy_json
|
|
.push_str(&format!(r#","binary_sha256":"{}""#, anchor.helper_sha256));
|
|
assert!(anchor.policy_for(&m).is_none());
|
|
let mut caps = vec![
|
|
format!("helper.binary.sha256:{binary}"),
|
|
format!("helper.policy.sha256:{policy}"),
|
|
];
|
|
assert!(check_pair(&m, Some("0.1.12"), "system", &caps).is_ok());
|
|
assert!(check_pair(&m, Some("0.1.11"), "system", &caps).is_err());
|
|
assert!(check_pair(&m, Some("0.1.12"), "root", &caps).is_err());
|
|
caps.push(format!("helper.binary.sha256:{binary}"));
|
|
assert!(check_pair(&m, Some("0.1.12"), "system", &caps).is_err());
|
|
caps.remove(0);
|
|
caps[1] = format!("helper.binary.sha256:{policy}");
|
|
assert!(check_pair(&m, Some("0.1.12"), "system", &caps).is_err());
|
|
}
|
|
}
|