1142 lines
47 KiB
Rust
1142 lines
47 KiB
Rust
mod image;
|
|
use anyhow::{Result, ensure};
|
|
use rmm_domain::jobs::Action;
|
|
use rmm_privileged_helper::{
|
|
Binding, Outcome, Request, control, finish, open_ledger, private_path, reconcile,
|
|
};
|
|
use serde::Deserialize;
|
|
use std::{
|
|
fs,
|
|
io::{Read, Write},
|
|
os::{
|
|
fd::AsRawFd,
|
|
unix::{
|
|
fs::{MetadataExt, PermissionsExt},
|
|
net::{UnixListener, UnixStream},
|
|
},
|
|
},
|
|
path::{Path, PathBuf},
|
|
time::Duration,
|
|
};
|
|
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct Config {
|
|
#[serde(default)]
|
|
profile: HelperProfile,
|
|
binding: Binding,
|
|
#[serde(default)]
|
|
signing_key_file: Option<PathBuf>,
|
|
agent_uid: u32,
|
|
socket_gid: u32,
|
|
socket: PathBuf,
|
|
state: PathBuf,
|
|
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>,
|
|
}
|
|
#[derive(Clone, Copy, Default, PartialEq, Eq, Deserialize)]
|
|
#[serde(rename_all = "snake_case")]
|
|
enum HelperProfile {
|
|
#[default]
|
|
General,
|
|
AptOnly,
|
|
FullMaintenanceV1,
|
|
}
|
|
impl Config {
|
|
fn general_policy(&self) -> Result<control::Policy> {
|
|
Ok(control::Policy {
|
|
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<()> {
|
|
ensure!(
|
|
self.state.as_path()
|
|
== std::path::Path::new(rmm_privileged_helper::readiness::SHARED_STATE),
|
|
"SHARED_HELPER_LEDGER_REQUIRED"
|
|
);
|
|
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()
|
|
== std::path::Path::new(rmm_privileged_helper::readiness::SOCKET)
|
|
&& self.allowed_services.is_empty()
|
|
&& !self.allow_reboot
|
|
&& !self.allow_root_scripts
|
|
&& self.apt_provider.is_some(),
|
|
"APT_ONLY_PROFILE"
|
|
);
|
|
} else {
|
|
ensure!(
|
|
self.apt_provider.is_none()
|
|
&& self.socket.as_path()
|
|
!= std::path::Path::new(rmm_privileged_helper::readiness::SOCKET),
|
|
"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(())
|
|
}
|
|
}
|
|
#[derive(Deserialize)]
|
|
#[serde(untagged)]
|
|
enum Incoming {
|
|
UpdateObserve(rmm_privileged_helper::update_observer::Request),
|
|
NativeUpdate(rmm_agent_core::update_handoff::NativeControlRequest),
|
|
Control(control::Request),
|
|
Probe(rmm_privileged_helper::readiness::Request),
|
|
Job(Request),
|
|
}
|
|
fn peer_uid(stream: &UnixStream) -> Result<u32> {
|
|
let mut credentials = std::mem::MaybeUninit::<libc::ucred>::uninit();
|
|
let mut size = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
|
|
// SAFETY: getsockopt receives correctly aligned writable storage and length.
|
|
ensure!(
|
|
unsafe {
|
|
libc::getsockopt(
|
|
stream.as_raw_fd(),
|
|
libc::SOL_SOCKET,
|
|
libc::SO_PEERCRED,
|
|
credentials.as_mut_ptr().cast(),
|
|
&mut size,
|
|
)
|
|
} == 0,
|
|
"PEER_CREDENTIALS"
|
|
);
|
|
ensure!(
|
|
size as usize == std::mem::size_of::<libc::ucred>(),
|
|
"PEER_SIZE"
|
|
);
|
|
// SAFETY: successful SO_PEERCRED initialized the complete ucred.
|
|
Ok(unsafe { credentials.assume_init() }.uid)
|
|
}
|
|
fn peer_allowed(stream: &UnixStream, uid: u32) -> Result<()> {
|
|
ensure!(uid != 0 && peer_uid(stream)? == uid, "PEER_DENIED");
|
|
Ok(())
|
|
}
|
|
fn policy(config: &Config, job: &rmm_domain::jobs::JobPayload) -> Result<()> {
|
|
ensure!(
|
|
job.execution_identity == "root",
|
|
"HELPER_REQUIRES_EXPLICIT_ROOT_IDENTITY"
|
|
);
|
|
if matches!(job.action, Action::UpdateAgent { .. }) {
|
|
ensure!(
|
|
config.profile == HelperProfile::FullMaintenanceV1
|
|
&& config.agent_uid == 993
|
|
&& config.socket
|
|
== std::path::Path::new("/run/rmm-helper-maintenance/control.sock")
|
|
&& std::path::Path::new("/etc/rmm-agent-updater/policy.json").try_exists()?,
|
|
"UPDATE_REQUIRES_SEPARATELY_PROVISIONED_FULL"
|
|
);
|
|
return Ok(());
|
|
}
|
|
if rmm_privileged_helper::apt::is_apt_action(job) {
|
|
ensure!(
|
|
config.profile == HelperProfile::AptOnly,
|
|
"APT_REQUIRES_DEDICATED_HELPER"
|
|
);
|
|
return rmm_privileged_helper::apt::policy_header(
|
|
job,
|
|
config
|
|
.apt_provider
|
|
.as_ref()
|
|
.ok_or_else(|| anyhow::anyhow!("APT_PROVIDER_NOT_CONFIGURED"))?,
|
|
);
|
|
}
|
|
ensure!(
|
|
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(),
|
|
_ => false,
|
|
};
|
|
ensure!(available, "ROOT_INTERPRETER_UNAVAILABLE");
|
|
}
|
|
Action::SetServiceState { unit, state } => {
|
|
ensure!(
|
|
config.allowed_services.contains(unit)
|
|
&& matches!(state.as_str(), "running" | "stopped"),
|
|
"SERVICE_DENIED"
|
|
);
|
|
rmm_agent_linux::actions::ServiceUnit::new(unit)?;
|
|
// Existing provider has a 120s bounded native service timeout.
|
|
ensure!(job.max_runtime_seconds >= 180, "SERVICE_RUNTIME_TOO_SHORT");
|
|
}
|
|
Action::Reboot { .. } => {
|
|
ensure!(
|
|
config.allow_reboot && job.max_runtime_seconds >= 60,
|
|
"REBOOT_DENIED"
|
|
);
|
|
}
|
|
Action::QueryLogs { unit, .. } => {
|
|
ensure!(
|
|
config.allowed_services.contains(unit) && job.max_runtime_seconds >= 20,
|
|
"ROOT_LOG_UNIT_DENIED"
|
|
);
|
|
}
|
|
// The separate APT bridge requires a complete preserved signed manifest;
|
|
// legacy package actions never fall through into a script/provider.
|
|
_ => anyhow::bail!("UNSUPPORTED_CAPABILITY"),
|
|
}
|
|
Ok(())
|
|
}
|
|
fn execute(job: &rmm_domain::jobs::JobPayload) -> Result<Outcome> {
|
|
use rmm_agent_linux::actions::*;
|
|
if matches!(job.action, Action::RunScript { .. }) {
|
|
return rmm_privileged_helper::script(job);
|
|
}
|
|
if let Action::QueryLogs {
|
|
unit,
|
|
since,
|
|
until,
|
|
max_lines,
|
|
} = &job.action
|
|
{
|
|
let unit = ServiceUnit::new(unit)?;
|
|
let request = rmm_agent_linux::inventory::JournalRequest::new(
|
|
unit.clone(),
|
|
std::slice::from_ref(&unit),
|
|
u64::try_from(since.timestamp())?,
|
|
u64::try_from(until.timestamp())?,
|
|
*max_lines as usize,
|
|
job.max_output_bytes as usize,
|
|
)?
|
|
.precise_window(*since, *until)?;
|
|
let observation = rmm_agent_linux::inventory::query_journal(&request);
|
|
let valid = observation.quality == rmm_agent_linux::inventory::Quality::Valid;
|
|
let bytes = serde_json::to_vec(&observation)?;
|
|
ensure!(
|
|
bytes.len() <= job.max_output_bytes as usize,
|
|
"LOG_SERIALIZED_OUTPUT_LIMIT"
|
|
);
|
|
return Ok(Outcome {
|
|
state: if valid { "succeeded" } else { "failed" }.into(),
|
|
stdout: bytes,
|
|
stderr: vec![],
|
|
exit_code: None,
|
|
output_truncated: observation.truncated,
|
|
reboot_required: false,
|
|
evidence: serde_json::json!({"postconditions_passed":valid,"cursor_status":"not_advanced_no_ack_contract"}),
|
|
error_code: if valid {
|
|
String::new()
|
|
} else {
|
|
observation
|
|
.error_code
|
|
.unwrap_or_else(|| "LOG_PROVIDER_FAILED".into())
|
|
},
|
|
});
|
|
}
|
|
let mut provider = OsActionProvider::new(NativeCommandRunner);
|
|
let result = match &job.action {
|
|
Action::SetServiceState { unit, state } => provider.set_service_state(&ServiceRequest {
|
|
unit: ServiceUnit::new(unit)?,
|
|
desired: if state == "running" {
|
|
DesiredServiceState::Running
|
|
} else {
|
|
DesiredServiceState::Stopped
|
|
},
|
|
})?,
|
|
Action::Reboot { .. } => {
|
|
provider.reboot(&RebootRequest::new(&rmm_agent_linux::boot_id()?)?)?
|
|
}
|
|
_ => anyhow::bail!("UNSUPPORTED_CAPABILITY"),
|
|
};
|
|
let passed = result.state == ActionState::Verified;
|
|
Ok(Outcome {
|
|
state: match result.state {
|
|
ActionState::Verified => "succeeded",
|
|
ActionState::Failed => "failed",
|
|
ActionState::Unknown => "unknown",
|
|
ActionState::AwaitingReboot => "awaiting_reboot",
|
|
}
|
|
.into(),
|
|
stdout: vec![],
|
|
stderr: vec![],
|
|
exit_code: None,
|
|
output_truncated: false,
|
|
reboot_required: result.reboot_required.unwrap_or(false),
|
|
evidence: serde_json::json!({"postconditions_passed":passed,"previous_boot_id":rmm_agent_linux::boot_id()?}),
|
|
error_code: if passed {
|
|
""
|
|
} else {
|
|
"EFFECT_REQUIRES_RECONCILIATION"
|
|
}
|
|
.into(),
|
|
})
|
|
}
|
|
struct RuntimeClocks {
|
|
action: rmm_privileged_helper::TrustedClock,
|
|
sync: reconcile::NativeClock,
|
|
update: Option<rmm_updater_worker::clock::NativeClock>,
|
|
}
|
|
fn handle(
|
|
config: &Config,
|
|
db: &mut rusqlite::Connection,
|
|
stream: &mut UnixStream,
|
|
clocks: &RuntimeClocks,
|
|
sync: &mut reconcile::HelperSync,
|
|
mut image: Option<&mut image::RunningImage>,
|
|
) -> Result<()> {
|
|
use rusqlite::OptionalExtension;
|
|
let clock = &clocks.action;
|
|
let sync_clock = &clocks.sync;
|
|
let update_clock = clocks.update.as_ref();
|
|
let caller_uid = peer_uid(stream)?;
|
|
ensure!(
|
|
caller_uid == config.agent_uid
|
|
|| (caller_uid == 0 && config.profile == HelperProfile::FullMaintenanceV1),
|
|
"PEER_DENIED"
|
|
);
|
|
stream.set_read_timeout(Some(Duration::from_secs(5)))?;
|
|
stream.set_write_timeout(Some(Duration::from_secs(5)))?;
|
|
let mut size = [0; 4];
|
|
stream.read_exact(&mut size)?;
|
|
let size = u32::from_be_bytes(size) as usize;
|
|
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::NativeUpdate(request) => {
|
|
ensure!(
|
|
config.profile == HelperProfile::FullMaintenanceV1
|
|
&& config.socket
|
|
== std::path::Path::new("/run/rmm-helper-maintenance/control.sock")
|
|
&& size <= 32768,
|
|
"UPDATE_FULL_CONTROL_REQUIRED"
|
|
);
|
|
let resource = reconcile::ExecutorGuard::acquire(&config.state, 0)?;
|
|
let response = rmm_privileged_helper::update_control::handle(
|
|
db,
|
|
&resource,
|
|
&config.binding,
|
|
update_clock.ok_or_else(|| anyhow::anyhow!("UPDATE_NOT_CONFIGURED"))?,
|
|
stream,
|
|
&request,
|
|
)?;
|
|
let raw = serde_json::to_vec(&response)?;
|
|
ensure!(raw.len() <= 1536 * 1024, "UPDATE_CONTROL_RESPONSE_LIMIT");
|
|
stream.write_all(&u32::try_from(raw.len())?.to_be_bytes())?;
|
|
stream.write_all(&raw)?;
|
|
return Ok(());
|
|
}
|
|
Incoming::Job(request) => {
|
|
peer_allowed(stream, config.agent_uid)?;
|
|
ensure!(size <= 512 * 1024, "JOB_REQUEST_SIZE");
|
|
request
|
|
}
|
|
Incoming::UpdateObserve(request) => {
|
|
peer_allowed(stream, config.agent_uid)?;
|
|
ensure!(
|
|
size <= 65536
|
|
&& config.profile == HelperProfile::FullMaintenanceV1
|
|
&& config.agent_uid == 993
|
|
&& config.socket == Path::new("/run/rmm-helper-maintenance/control.sock"),
|
|
"UPDATE_OBSERVER_ONLY_FULL"
|
|
);
|
|
let guard = reconcile::ExecutorGuard::acquire(&config.state, 0)?;
|
|
let key_path = config
|
|
.signing_key_file
|
|
.as_deref()
|
|
.unwrap_or(Path::new("/etc/rmm-agent-updater/job-signing-key.json"));
|
|
let policy = config.general_policy()?.sha256()?;
|
|
let response = rmm_privileged_helper::update_observer::collect(
|
|
db,
|
|
rmm_privileged_helper::update_observer::Local {
|
|
executor: &guard,
|
|
binding: &config.binding,
|
|
clock: update_clock.ok_or_else(|| anyhow::anyhow!("UPDATE_NOT_CONFIGURED"))?,
|
|
sync,
|
|
sync_clock,
|
|
key_path,
|
|
policy_sha256: &policy,
|
|
helper_sha256: binary_sha256
|
|
.as_deref()
|
|
.ok_or_else(|| anyhow::anyhow!("UPDATE_FULL_BINARY_PIN_REQUIRED"))?,
|
|
},
|
|
&request,
|
|
)?;
|
|
peer_allowed(stream, config.agent_uid)?;
|
|
let bytes = serde_json::to_vec(&response)?;
|
|
ensure!(bytes.len() <= 192 * 1024, "UPDATE_OBSERVER_REPLY_LIMIT");
|
|
stream.write_all(&u32::try_from(bytes.len())?.to_be_bytes())?;
|
|
stream.write_all(&bytes)?;
|
|
return Ok(());
|
|
}
|
|
Incoming::Control(request) => {
|
|
peer_allowed(stream, config.agent_uid)?;
|
|
let (challenge, identity) = request.binding();
|
|
ensure!(
|
|
!challenge.is_nil()
|
|
&& *identity
|
|
== rmm_privileged_helper::readiness::Identity::from_binding(
|
|
&config.binding
|
|
)?,
|
|
"CONTROL_IDENTITY"
|
|
);
|
|
let guard = reconcile::ExecutorGuard::acquire(&config.state, 0)?;
|
|
let update_guard = if config.profile == HelperProfile::FullMaintenanceV1 {
|
|
rmm_privileged_helper::update_control::active_grant(db)?
|
|
.map(|grant| {
|
|
rmm_privileged_helper::update_guard::FullUpdateGuard::open(
|
|
db,
|
|
&guard,
|
|
&config.binding,
|
|
update_clock.ok_or_else(|| anyhow::anyhow!("UPDATE_NOT_CONFIGURED"))?,
|
|
grant,
|
|
)
|
|
})
|
|
.transpose()?
|
|
} else {
|
|
None
|
|
};
|
|
let (mut snapshot, mut unlocked) = (None, vec![]);
|
|
match &request {
|
|
control::Request::Snapshot { generation, .. } => {
|
|
rmm_privileged_helper::apt_reconcile::refresh(
|
|
db,
|
|
&config.binding,
|
|
&guard,
|
|
reconcile::Clock::now(sync_clock)?,
|
|
)?;
|
|
snapshot = Some(if let Some(owner) = &update_guard {
|
|
sync.snapshot(db, owner, *generation, sync_clock, &reconcile::NativeBoot)?
|
|
} else {
|
|
sync.snapshot(db, &guard, *generation, sync_clock, &reconcile::NativeBoot)?
|
|
})
|
|
}
|
|
control::Request::Apply {
|
|
response,
|
|
request_bytes,
|
|
..
|
|
} => {
|
|
let applied = if let Some(owner) = &update_guard {
|
|
sync.apply(
|
|
db,
|
|
owner,
|
|
response,
|
|
request_bytes,
|
|
sync_clock,
|
|
&reconcile::NativeBoot,
|
|
)?
|
|
} else {
|
|
sync.apply(
|
|
db,
|
|
&guard,
|
|
response,
|
|
request_bytes,
|
|
sync_clock,
|
|
&reconcile::NativeBoot,
|
|
)?
|
|
};
|
|
snapshot = Some(applied.snapshot);
|
|
unlocked = applied.unlocked_grants;
|
|
}
|
|
control::Request::Policy { .. } => ensure!(
|
|
config.profile != HelperProfile::AptOnly,
|
|
"GENERAL_POLICY_PROFILE"
|
|
),
|
|
}
|
|
let general = config.profile != HelperProfile::AptOnly;
|
|
let policy = if general {
|
|
Some(config.general_policy()?)
|
|
} else {
|
|
None
|
|
};
|
|
let policy_sha256 = if let Some(policy) = &policy {
|
|
policy.sha256()?
|
|
} else {
|
|
rmm_privileged_helper::readiness::stack_sha256(
|
|
&config.binding,
|
|
config
|
|
.apt_provider
|
|
.as_ref()
|
|
.ok_or_else(|| anyhow::anyhow!("APT_PROVIDER_REQUIRED"))?,
|
|
)?
|
|
};
|
|
let ledger = fs::metadata(config.state.join("consumption.sqlite"))?;
|
|
let lock = fs::metadata(config.state.join("executor.lock"))?;
|
|
let response = control::Response {
|
|
schema_version: 1,
|
|
challenge,
|
|
identity: identity.clone(),
|
|
profile: if config.profile == HelperProfile::FullMaintenanceV1 {
|
|
"full_maintenance_v1"
|
|
} else if general {
|
|
"general"
|
|
} else {
|
|
"apt_only"
|
|
}
|
|
.into(),
|
|
policy_sha256,
|
|
policy,
|
|
snapshot,
|
|
unlocked_grants: unlocked,
|
|
ledger_device: ledger.dev(),
|
|
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");
|
|
stream.write_all(&u32::try_from(bytes.len())?.to_be_bytes())?;
|
|
stream.write_all(&bytes)?;
|
|
return Ok(());
|
|
}
|
|
Incoming::Probe(request) => {
|
|
peer_allowed(stream, config.agent_uid)?;
|
|
ensure!(
|
|
config.profile == HelperProfile::AptOnly,
|
|
"PROBE_REQUIRES_APT_HELPER"
|
|
);
|
|
let response = rmm_privileged_helper::readiness::answer(
|
|
&request,
|
|
&config.binding,
|
|
config
|
|
.apt_provider
|
|
.as_ref()
|
|
.ok_or_else(|| anyhow::anyhow!("APT_PROVIDER_NOT_CONFIGURED"))?,
|
|
db,
|
|
)?;
|
|
let bytes = serde_json::to_vec(&response)?;
|
|
stream.write_all(&(u32::try_from(bytes.len())?).to_be_bytes())?;
|
|
stream.write_all(&bytes)?;
|
|
return Ok(());
|
|
}
|
|
};
|
|
ensure!(clock.trusted(), "CLOCK_UNTRUSTED");
|
|
let (job, permit) = config.binding.verify(&request, chrono::Utc::now())?;
|
|
policy(config, &job)?;
|
|
// Both profiles use these exact same inodes, locked per effect rather than
|
|
// daemon lifetime so the dedicated and general helper can coexist.
|
|
let resource = reconcile::ExecutorGuard::acquire(&config.state, 0)?;
|
|
if matches!(job.action, Action::UpdateAgent { .. }) {
|
|
let consumed: bool = db.query_row("SELECT EXISTS(SELECT 1 FROM consumed WHERE grant_id=?1 OR (agent=?2 AND generation=?3 AND job=?4 AND attempt=?5))",
|
|
rusqlite::params![permit.grant_id.to_string(),permit.agent_id.to_string(),permit.enrollment_generation,permit.job_id.to_string(),permit.attempt_id.to_string()],|r|r.get(0))?;
|
|
ensure!(!consumed, "UPDATE_ALREADY_CONSUMED_NO_REDISPATCH");
|
|
let key_path = config
|
|
.signing_key_file
|
|
.clone()
|
|
.unwrap_or_else(|| PathBuf::from("/etc/rmm-agent-updater/job-signing-key.json"));
|
|
private_path(&key_path, 0, false)?;
|
|
ensure!(
|
|
fs::metadata(&key_path)?.len() <= 4096,
|
|
"UPDATE_JOB_KEY_RECORD_LIMIT"
|
|
);
|
|
let key = rmm_privileged_helper::SigningKey::read(&key_path, 0)?;
|
|
ensure!(
|
|
key.public_key_hex == config.binding.public_key_hex,
|
|
"UPDATE_LOCAL_JOB_KEY_CHANGED"
|
|
);
|
|
let key_hash = rmm_domain::jobs::hash(&fs::read(&key_path)?);
|
|
let prepared = rmm_privileged_helper::update_admission::Prepared::new(
|
|
db,
|
|
rmm_privileged_helper::update_admission::Local {
|
|
executor: &resource,
|
|
binding: &config.binding,
|
|
clock: update_clock.ok_or_else(|| anyhow::anyhow!("UPDATE_NOT_CONFIGURED"))?,
|
|
job_key_path: &key_path,
|
|
job_key_raw_sha256: &key_hash,
|
|
},
|
|
&request,
|
|
)?;
|
|
peer_allowed(stream, config.agent_uid)?;
|
|
let mut probe = 0u8;
|
|
// Preparation may copy sizeable exact artifacts. Recheck the actual
|
|
// caller at the original consumption boundary without consuming bytes.
|
|
// SAFETY: live socket and a writable byte; MSG_PEEK leaves input intact.
|
|
let available = unsafe {
|
|
libc::recv(
|
|
stream.as_raw_fd(),
|
|
(&mut probe as *mut u8).cast(),
|
|
1,
|
|
libc::MSG_PEEK | libc::MSG_DONTWAIT,
|
|
)
|
|
};
|
|
ensure!(
|
|
available < 0
|
|
&& std::io::Error::last_os_error().kind() == std::io::ErrorKind::WouldBlock,
|
|
"UPDATE_CALLER_CANCELLED_OR_DISCONNECTED"
|
|
);
|
|
let accepted = prepared.consume(db, sync, sync_clock)?;
|
|
let bytes = serde_json::to_vec(&accepted)?;
|
|
ensure!(bytes.len() <= 4096, "UPDATE_HANDOFF_ACK_LIMIT");
|
|
stream.write_all(&u32::try_from(bytes.len())?.to_be_bytes())?;
|
|
stream.write_all(&bytes)?;
|
|
stream.flush()?;
|
|
// Full resumes its listener immediately after this once-only Activate
|
|
// reply. The worker then reads this same original ledger via Full before
|
|
// it may stop Agent/General/Full. This is never a final job Outcome.
|
|
return prepared.dispatch_after_reply();
|
|
}
|
|
let previous: Option<Option<Vec<u8>>> = db
|
|
.query_row(
|
|
"SELECT COALESCE(result,(SELECT outcome FROM execution_evidence WHERE execution_evidence.grant_id=consumed.grant_id)) FROM consumed WHERE grant_id=?1",
|
|
[permit.grant_id.to_string()],
|
|
|r| r.get(0),
|
|
)
|
|
.optional()?;
|
|
let outcome = if let Some(previous) = previous {
|
|
previous
|
|
.map(|b| serde_json::from_slice(&b))
|
|
.transpose()?
|
|
.unwrap_or_else(|| Outcome::unknown("PREVIOUS_EFFECT_UNRESOLVED"))
|
|
} else {
|
|
// A probe, signed job, persisted ready bit or another daemon's sync
|
|
// cannot open this process's independent mutation gate.
|
|
let generation = sync
|
|
.active_generation()
|
|
.ok_or_else(|| anyhow::anyhow!("HELPER_SYNC_REQUIRED"))?;
|
|
ensure!(
|
|
sync.can_start(
|
|
db,
|
|
&resource,
|
|
generation,
|
|
sync_clock,
|
|
&reconcile::NativeBoot
|
|
),
|
|
"HELPER_SYNC_REQUIRED"
|
|
);
|
|
let apt = if rmm_privileged_helper::apt::is_apt_action(&job) {
|
|
Some(rmm_privileged_helper::apt::prepare(
|
|
&config.binding,
|
|
&request,
|
|
config
|
|
.apt_provider
|
|
.as_ref()
|
|
.ok_or_else(|| anyhow::anyhow!("APT_PROVIDER_NOT_CONFIGURED"))?,
|
|
chrono::Utc::now(),
|
|
)?)
|
|
} else {
|
|
None
|
|
};
|
|
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() {
|
|
Outcome {
|
|
state: "failed".into(),
|
|
evidence: serde_json::json!({"not_started":true,"postconditions_passed":false}),
|
|
..Outcome::unknown("START_WINDOW_OR_CLOCK_INVALID_BEFORE_EFFECT")
|
|
}
|
|
} else {
|
|
if let Some(apt) = apt {
|
|
apt.execute(db)
|
|
.unwrap_or_else(|_| Outcome::unknown("APT_HELPER_EFFECT_UNKNOWN"))
|
|
} else {
|
|
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) {
|
|
outcome.evidence["test_acceptance"] =
|
|
serde_json::json!(job.action.name() == "apt_native_acceptance");
|
|
outcome.evidence["noProductionEvidence"] = serde_json::json!(true);
|
|
}
|
|
finish(db, &permit, &outcome)?;
|
|
outcome
|
|
};
|
|
let bytes = serde_json::to_vec(&outcome)?;
|
|
stream.write_all(&(u32::try_from(bytes.len())?).to_be_bytes())?;
|
|
stream.write_all(&bytes)?;
|
|
Ok(())
|
|
}
|
|
fn safe_error_code(error: &anyhow::Error) -> String {
|
|
if error.chain().any(|cause| {
|
|
matches!(cause.downcast_ref::<rusqlite::Error>(),
|
|
Some(rusqlite::Error::SqliteFailure(code, _)) if code.code == rusqlite::ErrorCode::DiskFull)
|
|
}) {
|
|
return "JOURNAL_STORAGE_CAPACITY_BLOCKED".into();
|
|
}
|
|
let text = error.to_string();
|
|
if text.len() <= 96
|
|
&& text
|
|
.bytes()
|
|
.all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_')
|
|
{
|
|
text
|
|
} else {
|
|
"HELPER_VALIDATION_OR_IO_FAILURE".into()
|
|
}
|
|
}
|
|
|
|
fn main() -> Result<()> {
|
|
run().map_err(|error| anyhow::anyhow!(safe_error_code(&error)))
|
|
}
|
|
|
|
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-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(());
|
|
}
|
|
// SAFETY: geteuid has no preconditions or pointers.
|
|
ensure!(unsafe { libc::geteuid() } == 0, "helper must run as root");
|
|
if args == [std::ffi::OsString::from("--install-apt-provider")] {
|
|
return rmm_privileged_helper::apt::install_known_payloads();
|
|
}
|
|
ensure!(
|
|
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-full-maintenance-profile"
|
|
)],
|
|
"UNKNOWN_HELPER_MODE"
|
|
);
|
|
let path = PathBuf::from(
|
|
std::env::var("RMM_HELPER_CONFIG").unwrap_or_else(|_| "/etc/rmm/helper.json".into()),
|
|
);
|
|
private_path(&path, 0, false)?;
|
|
ensure!(fs::metadata(&path)?.len() <= 16384, "CONFIG_SIZE");
|
|
let mut config: Config = serde_json::from_slice(&fs::read(path)?)?;
|
|
if let Some(apt) = &config.apt_provider {
|
|
apt.validate()?;
|
|
}
|
|
if let Some(path) = &config.signing_key_file {
|
|
ensure!(path.is_absolute(), "HELPER_KEY_PATH_ABSOLUTE");
|
|
let key = rmm_privileged_helper::SigningKey::read(path, 0)?;
|
|
ensure!(
|
|
config.binding.public_key_hex.is_empty()
|
|
|| config.binding.public_key_hex == key.public_key_hex,
|
|
"HELPER_PROVISIONED_KEY_MISMATCH"
|
|
);
|
|
config.binding.public_key_hex = key.public_key_hex;
|
|
}
|
|
config.validate_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
|
|
&& 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: 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(());
|
|
}
|
|
if config.profile == HelperProfile::AptOnly
|
|
&& (args.is_empty() || args == [std::ffi::OsString::from("--probe-native")])
|
|
{
|
|
rmm_privileged_helper::apt::verify_controller_profile()?;
|
|
}
|
|
if !args.is_empty() {
|
|
ensure!(
|
|
config.profile == HelperProfile::AptOnly,
|
|
"ADMIN_PROBE_REQUIRES_APT_PROFILE"
|
|
);
|
|
let provider = config
|
|
.apt_provider
|
|
.as_ref()
|
|
.ok_or_else(|| anyhow::anyhow!("APT_PROVIDER_NOT_CONFIGURED"))?;
|
|
if args == [std::ffi::OsString::from("--probe-native")] {
|
|
rmm_privileged_helper::apt::verify_installation()?;
|
|
let status = std::process::Command::new("/usr/bin/python3")
|
|
.args(["-I", rmm_privileged_helper::apt::CODE, "probe-native"])
|
|
.env_clear()
|
|
.env("PATH", "/usr/sbin:/usr/bin:/sbin:/bin")
|
|
.env("LC_ALL", "C")
|
|
.status()?;
|
|
ensure!(status.success(), "APT_NATIVE_PROBE_FAILED");
|
|
} else {
|
|
let pin = rmm_privileged_helper::readiness::Pin {
|
|
schema_version: 1,
|
|
profile: "apt_only".into(),
|
|
identity: rmm_privileged_helper::readiness::Identity::from_binding(
|
|
&config.binding,
|
|
)?,
|
|
provider_stack_sha256: rmm_privileged_helper::readiness::stack_sha256(
|
|
&config.binding,
|
|
provider,
|
|
)?,
|
|
};
|
|
println!("{}", serde_json::to_string(&pin)?);
|
|
}
|
|
return Ok(());
|
|
}
|
|
ensure!(
|
|
config.agent_uid != 0 && config.state.is_absolute() && config.socket.is_absolute(),
|
|
"CONFIG_BINDING"
|
|
);
|
|
let mut db = {
|
|
let _initialization_lock = rmm_privileged_helper::startup_lock_state(&config.state, 0)?;
|
|
open_ledger(&config.state, 0)?
|
|
};
|
|
let update_clock = if config.profile == HelperProfile::FullMaintenanceV1
|
|
&& std::path::Path::new("/etc/rmm-agent-updater/policy.json").try_exists()?
|
|
{
|
|
Some(rmm_updater_worker::clock::NativeClock::new()?)
|
|
} else {
|
|
None
|
|
};
|
|
if update_clock.is_some() {
|
|
let guard = reconcile::ExecutorGuard::acquire(&config.state, 0)?;
|
|
rmm_agent_core::update_handoff::initialize(&db, &guard)?;
|
|
}
|
|
let clocks = RuntimeClocks {
|
|
action: rmm_privileged_helper::TrustedClock::new(),
|
|
sync: reconcile::NativeClock::default(),
|
|
update: update_clock,
|
|
};
|
|
let mut sync = reconcile::HelperSync::new(config.binding.clone(), &clocks.sync)?;
|
|
let parent = config
|
|
.socket
|
|
.parent()
|
|
.ok_or_else(|| anyhow::anyhow!("socket parent"))?;
|
|
let m = fs::symlink_metadata(parent)?;
|
|
ensure!(
|
|
m.is_dir() && !m.file_type().is_symlink() && m.uid() == 0 && m.mode() & 0o022 == 0,
|
|
"UNSAFE_SOCKET_DIRECTORY"
|
|
);
|
|
// Refuse to unlink anything at startup. Bootstrap/recovery must inspect a
|
|
// stale socket explicitly rather than replacing an active/hostile endpoint.
|
|
let listener = UnixListener::bind(&config.socket)?;
|
|
fs::set_permissions(&config.socket, fs::Permissions::from_mode(0o600))?;
|
|
let socket = std::ffi::CString::new(config.socket.as_os_str().as_encoded_bytes())?;
|
|
// SAFETY: the freshly bound socket is in a root-owned, non-writable parent;
|
|
// path is NUL terminated. This does not change any peer's process identity.
|
|
ensure!(
|
|
unsafe { libc::chown(socket.as_ptr(), 0, config.socket_gid) } == 0,
|
|
"SOCKET_GROUP"
|
|
);
|
|
fs::set_permissions(&config.socket, fs::Permissions::from_mode(0o660))?;
|
|
for mut stream in listener.incoming().flatten() {
|
|
if let Err(error) = handle(
|
|
&config,
|
|
&mut db,
|
|
&mut stream,
|
|
&clocks,
|
|
&mut sync,
|
|
running_image.as_mut(),
|
|
) {
|
|
let code = safe_error_code(&error);
|
|
eprintln!("helper request rejected: {code}");
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
#[test]
|
|
fn sqlite_full_is_sanitized_and_failed_transaction_preserves_history() {
|
|
let db = rusqlite::Connection::open_in_memory().unwrap();
|
|
rmm_privileged_helper::bounded_journal_capacity(&db).unwrap();
|
|
db.execute_batch("CREATE TABLE witness(value BLOB);INSERT INTO witness VALUES('retained');PRAGMA max_page_count=4;").unwrap();
|
|
db.execute_batch("BEGIN;INSERT INTO witness VALUES('must roll back');")
|
|
.unwrap();
|
|
let error = db
|
|
.execute("INSERT INTO witness VALUES(zeroblob(1048576))", [])
|
|
.unwrap_err();
|
|
let wrapped = anyhow::Error::new(error).context("private SQL context must never leak");
|
|
assert_eq!(
|
|
safe_error_code(&wrapped),
|
|
"JOURNAL_STORAGE_CAPACITY_BLOCKED"
|
|
);
|
|
assert_eq!(
|
|
db.query_row("SELECT count(*) FROM witness", [], |r| r.get::<_, u32>(0))
|
|
.unwrap(),
|
|
1
|
|
);
|
|
assert_eq!(
|
|
db.query_row("PRAGMA integrity_check", [], |r| r.get::<_, String>(0))
|
|
.unwrap(),
|
|
"ok"
|
|
);
|
|
assert_eq!(
|
|
db.query_row("PRAGMA max_page_count", [], |r| r.get::<_, u32>(0))
|
|
.unwrap(),
|
|
4
|
|
);
|
|
assert_eq!(
|
|
safe_error_code(&anyhow::anyhow!("private SQL text")),
|
|
"HELPER_VALIDATION_OR_IO_FAILURE"
|
|
);
|
|
}
|
|
#[test]
|
|
fn apt_only_profile_denies_scripts_services_reboot_and_wrong_shared_state() {
|
|
let id = uuid::Uuid::new_v4();
|
|
let mut config:Config=serde_json::from_value(serde_json::json!({"profile":"apt_only",
|
|
"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":rmm_privileged_helper::readiness::SOCKET,
|
|
"state":rmm_privileged_helper::readiness::SHARED_STATE,"allowed_services":[],"allow_reboot":false,"allow_root_scripts":false,
|
|
"apt_provider":{"schema_version":1,"execution_profile":"dev-test","allow_fixture_bootstrap":true,
|
|
"allowed_recipes":[rmm_privileged_helper::apt::INSTALL_RECIPE],"runtime_sha256":"a".repeat(64),"apt_config_sha256":"b".repeat(64)}})).unwrap();
|
|
config.validate_profile().unwrap();
|
|
let now = chrono::Utc::now();
|
|
for action in [
|
|
serde_json::json!({"action":"run_script","interpreter":"posix_sh","script_utf8":"true","arguments":[],"expected_stdout":null}),
|
|
serde_json::json!({"action":"set_service_state","unit":"rmm-acceptance.service","state":"running"}),
|
|
serde_json::json!({"action":"reboot","reason":"test","reconnect_timeout_seconds":60,"dependency_group":"test"}),
|
|
] {
|
|
let 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":300,"max_output_bytes":4096,"action":action})).unwrap();
|
|
assert!(policy(&config, &job).is_err());
|
|
}
|
|
config.state = "/var/lib/copied-ledger".into();
|
|
assert!(config.validate_profile().is_err());
|
|
config.state = rmm_privileged_helper::readiness::SHARED_STATE.into();
|
|
config.allow_root_scripts = true;
|
|
assert!(config.validate_profile().is_err());
|
|
config.allow_root_scripts = false;
|
|
config.agent_uid = 1000;
|
|
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.
|
|
let uid = unsafe { libc::geteuid() };
|
|
assert!(peer_allowed(&a, uid.saturating_add(1)).is_err());
|
|
assert_eq!(peer_allowed(&a, uid).is_ok(), uid != 0);
|
|
}
|
|
#[test]
|
|
fn helper_requires_explicit_root_identity_and_separate_local_permissions() {
|
|
use uuid::Uuid;
|
|
let binding = Binding {
|
|
tenant_id: Uuid::new_v4(),
|
|
asset_id: Uuid::new_v4(),
|
|
agent_id: Uuid::new_v4(),
|
|
enrollment_generation: 1,
|
|
assignment_version: 1,
|
|
public_key_hex: "00".repeat(32),
|
|
};
|
|
let mut config = Config {
|
|
profile: HelperProfile::General,
|
|
signing_key_file: None,
|
|
binding: binding.clone(),
|
|
agent_uid: 1000,
|
|
socket_gid: 1000,
|
|
socket: "/run/rmm-helper/control.sock".into(),
|
|
state: "/var/lib/rmm-helper".into(),
|
|
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();
|
|
let mut job = rmm_domain::jobs::JobPayload {
|
|
schema_version: 1,
|
|
tenant_id: binding.tenant_id,
|
|
asset_id: binding.asset_id,
|
|
agent_id: binding.agent_id,
|
|
enrollment_generation: 1,
|
|
assignment_version: 1,
|
|
job_id: Uuid::new_v4(),
|
|
attempt_id: Uuid::new_v4(),
|
|
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,
|
|
start_before: now + chrono::Duration::minutes(1),
|
|
max_runtime_seconds: 180,
|
|
max_output_bytes: 4096,
|
|
};
|
|
assert!(policy(&config, &job).is_err());
|
|
job.execution_identity = "root".into();
|
|
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(),
|
|
};
|
|
assert!(policy(&config, &job).is_err());
|
|
job.action = Action::SetServiceState {
|
|
unit: "rmm-acceptance.service".into(),
|
|
state: "running".into(),
|
|
};
|
|
assert!(policy(&config, &job).is_ok());
|
|
job.action = Action::Reboot {
|
|
reason: "mock".into(),
|
|
reconnect_timeout_seconds: 60,
|
|
dependency_group: "test".into(),
|
|
};
|
|
assert!(policy(&config, &job).is_err());
|
|
config.allow_reboot = true;
|
|
assert!(policy(&config, &job).is_ok());
|
|
job.action = serde_json::from_value(serde_json::json!({
|
|
"action":"apply_updates","provider":"apt","packages":["hello"],"reboot_policy":"never"
|
|
}))
|
|
.unwrap();
|
|
assert!(policy(&config, &job).is_err());
|
|
}
|
|
}
|