346 lines
12 KiB
Rust
346 lines
12 KiB
Rust
//! Independently usable authorization boundary. No bearer credentials or keys
|
|
//! received with a job are trusted. Both processes keep their own consumption DB.
|
|
extern crate self as rmm_privileged_helper;
|
|
pub mod apt;
|
|
pub mod apt_reconcile;
|
|
pub mod checkpoint_repair;
|
|
pub mod control;
|
|
pub mod readiness;
|
|
pub mod reconcile;
|
|
#[cfg(test)]
|
|
mod tests;
|
|
pub mod update_control;
|
|
pub mod update_guard;
|
|
use anyhow::{Context, Result, ensure};
|
|
use chrono::{DateTime, Utc};
|
|
use openssl::pkey::{Id, PKey};
|
|
use rmm_domain::jobs::{ExecutionPermitPayload, JobPayload, hash};
|
|
use serde::{Deserialize, Serialize};
|
|
use std::{fs, os::unix::fs::MetadataExt, path::Path};
|
|
use uuid::Uuid;
|
|
|
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct SigningKey {
|
|
pub key_id: String,
|
|
pub algorithm: String,
|
|
pub schema_version: u32,
|
|
pub public_key_hex: String,
|
|
}
|
|
impl SigningKey {
|
|
pub fn validate(&self) -> Result<()> {
|
|
let raw = hex::decode(&self.public_key_hex)?;
|
|
ensure!(
|
|
self.algorithm == "Ed25519"
|
|
&& self.schema_version == 1
|
|
&& raw.len() == 32
|
|
&& self.key_id == hash(&raw),
|
|
"SIGNING_KEY_PROFILE"
|
|
);
|
|
PKey::public_key_from_raw_bytes(&raw, Id::ED25519)?;
|
|
Ok(())
|
|
}
|
|
pub fn read(path: &Path, uid: u32) -> Result<Self> {
|
|
private_path(path, uid, false)?;
|
|
ensure!(fs::metadata(path)?.len() <= 4096, "SIGNING_KEY_SIZE");
|
|
let key: Self = serde_json::from_slice(&fs::read(path)?)?;
|
|
key.validate()?;
|
|
Ok(key)
|
|
}
|
|
}
|
|
|
|
pub use rmm_agent_core::auth::{Binding, Outcome, Request};
|
|
|
|
/// Config and journal directories must already be bootstrapped by the intended
|
|
/// owner; do not silently chmod a hostile existing path or follow symlinks.
|
|
pub fn private_path(path: &Path, uid: u32, directory: bool) -> Result<()> {
|
|
let m = fs::symlink_metadata(path)?;
|
|
ensure!(
|
|
!m.file_type().is_symlink()
|
|
&& m.uid() == uid
|
|
&& m.mode() & 0o077 == 0
|
|
&& if directory { m.is_dir() } else { m.is_file() },
|
|
"UNSAFE_LOCAL_PATH"
|
|
);
|
|
Ok(())
|
|
}
|
|
pub fn lock_state(dir: &Path, uid: u32) -> Result<fs::File> {
|
|
use fs2::FileExt;
|
|
use std::os::unix::fs::OpenOptionsExt;
|
|
private_path(dir, uid, true)?;
|
|
let f = fs::OpenOptions::new()
|
|
.read(true)
|
|
.write(true)
|
|
.create(true)
|
|
.truncate(false)
|
|
.mode(0o600)
|
|
.custom_flags(libc::O_NOFOLLOW)
|
|
.open(dir.join("executor.lock"))?;
|
|
private_path(&dir.join("executor.lock"), uid, false)?;
|
|
f.try_lock_exclusive()?;
|
|
Ok(f)
|
|
}
|
|
pub use rmm_agent_core::ledger::{bounded_journal_capacity, consume, finish, persist_outcome};
|
|
|
|
pub fn open_ledger(dir: &Path, uid: u32) -> Result<rusqlite::Connection> {
|
|
use std::os::unix::fs::OpenOptionsExt;
|
|
let path = dir.join("consumption.sqlite");
|
|
let f = fs::OpenOptions::new()
|
|
.read(true)
|
|
.write(true)
|
|
.create(true)
|
|
.truncate(false)
|
|
.mode(0o600)
|
|
.custom_flags(libc::O_NOFOLLOW)
|
|
.open(&path)?;
|
|
f.sync_all()?;
|
|
private_path(&path, uid, false)?;
|
|
let db = rusqlite::Connection::open(path)?;
|
|
rmm_agent_core::ledger::initialize_ledger(&db)?;
|
|
fs::File::open(dir)?.sync_all()?;
|
|
Ok(db)
|
|
}
|
|
/// Atomically reserve and persist the exact original signed request before effect.
|
|
pub fn begin_execution(
|
|
db: &mut rusqlite::Connection,
|
|
permit: &ExecutionPermitPayload,
|
|
request: &Request,
|
|
) -> Result<()> {
|
|
let recorded_at = Utc::now();
|
|
let boot = Uuid::parse_str(&rmm_agent_linux::boot_id()?)?;
|
|
rmm_agent_core::ledger::begin_execution(db, permit, request, boot, recorded_at)
|
|
}
|
|
/// Persist the same exact request/boot/time evidence through the shared ledger.
|
|
pub fn save_start(
|
|
db: &rusqlite::Connection,
|
|
permit: &ExecutionPermitPayload,
|
|
request: &Request,
|
|
) -> Result<()> {
|
|
rmm_agent_core::ledger::save_start(
|
|
db,
|
|
permit,
|
|
request,
|
|
Uuid::parse_str(&rmm_agent_linux::boot_id()?)?,
|
|
Utc::now(),
|
|
)
|
|
}
|
|
|
|
pub fn script(job: &JobPayload) -> Result<Outcome> {
|
|
script_controlled(job, || Ok(()))
|
|
}
|
|
pub fn script_controlled(job: &JobPayload, observe: impl FnMut() -> Result<()>) -> Result<Outcome> {
|
|
use rmm_agent_linux::actions::{Interpreter, ScriptRequest, run_script_controlled};
|
|
let rmm_domain::jobs::Action::RunScript {
|
|
interpreter,
|
|
script_utf8,
|
|
arguments,
|
|
expected_stdout,
|
|
windows_execution_profile: None,
|
|
..
|
|
} = &job.action
|
|
else {
|
|
anyhow::bail!("NOT_SCRIPT")
|
|
};
|
|
let interpreter = match interpreter.as_str() {
|
|
"posix_sh" => Interpreter::PosixSh,
|
|
"bash" => Interpreter::Bash,
|
|
_ => anyhow::bail!("UNSUPPORTED_INTERPRETER"),
|
|
};
|
|
let request = ScriptRequest::new(
|
|
script_utf8.as_bytes().to_vec(),
|
|
interpreter,
|
|
arguments.clone(),
|
|
std::time::Duration::from_secs(job.max_runtime_seconds.into()),
|
|
job.max_output_bytes as usize,
|
|
)?;
|
|
let output = run_script_controlled(&request, observe)?;
|
|
let passed = output.code == Some(0)
|
|
&& !output.timed_out
|
|
&& !output.interrupted
|
|
&& expected_stdout
|
|
.as_ref()
|
|
.is_none_or(|s| !output.truncated && output.stdout == s.as_bytes());
|
|
Ok(Outcome {
|
|
state: if output.timed_out || output.interrupted || output.code.is_none() {
|
|
"unknown"
|
|
} else if passed {
|
|
"succeeded"
|
|
} else {
|
|
"failed"
|
|
}
|
|
.into(),
|
|
stdout: output.stdout,
|
|
stderr: output.stderr,
|
|
exit_code: output.code,
|
|
output_truncated: output.truncated,
|
|
reboot_required: false,
|
|
evidence: serde_json::json!({"postconditions_passed":passed,"script_sha256":rmm_domain::jobs::hash(script_utf8.as_bytes()),"privileged_script_profile":if job.action.full_maintenance(){Some("full_maintenance_v1")}else{None},"execution_uid":unsafe{libc::geteuid()},"output_encoding":"raw_native_bytes","cancel_or_fence_observed":output.interrupted,"termination_does_not_prove_absence_of_effects":output.interrupted||output.timed_out}),
|
|
error_code: if passed {
|
|
""
|
|
} else if output.interrupted {
|
|
"CANCEL_OR_FENCE_EFFECT_UNKNOWN"
|
|
} else if output.timed_out {
|
|
"TIMEOUT_EFFECT_UNKNOWN"
|
|
} else {
|
|
"SCRIPT_POSTCONDITION_FAILED"
|
|
}
|
|
.into(),
|
|
})
|
|
}
|
|
|
|
pub fn read_binding(path: &Path, uid: u32) -> Result<Binding> {
|
|
private_path(path, uid, false)?;
|
|
let bytes = fs::read(path)?;
|
|
ensure!(bytes.len() <= 8192, "CONFIG_SIZE");
|
|
serde_json::from_slice(&bytes).context("invalid provisioned binding")
|
|
}
|
|
|
|
/// A fresh online permit is necessary but does not prove the host clock. Use
|
|
/// Linux's synchronization/error status, never a gateway-supplied time override.
|
|
pub fn clock_trusted() -> bool {
|
|
let mut state = std::mem::MaybeUninit::<libc::timex>::zeroed();
|
|
// SAFETY: zero modes request a read-only query into initialized storage.
|
|
let status = unsafe { libc::adjtimex(state.as_mut_ptr()) };
|
|
// SAFETY: storage was zero initialized, including on an error return.
|
|
let state = unsafe { state.assume_init() };
|
|
status >= 0
|
|
&& status != libc::TIME_ERROR
|
|
&& state.status & libc::STA_UNSYNC == 0
|
|
&& state.maxerror >= 0
|
|
&& state.maxerror <= 5_000_000
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct TrustedClock {
|
|
wall: DateTime<Utc>,
|
|
monotonic: std::time::Instant,
|
|
}
|
|
|
|
/// Local client authenticates the root process as well as the root-owned socket.
|
|
/// A malicious same-user Unix server must not be able to forge helper success.
|
|
pub fn invoke(socket: &Path, request: &Request, max_runtime_seconds: u32) -> Result<Outcome> {
|
|
invoke_controlled(socket, request, max_runtime_seconds, || Ok(()))
|
|
}
|
|
pub fn invoke_controlled(
|
|
socket: &Path,
|
|
request: &Request,
|
|
max_runtime_seconds: u32,
|
|
mut observe: impl FnMut() -> Result<()>,
|
|
) -> Result<Outcome> {
|
|
use std::{
|
|
io::{Read, Write},
|
|
os::{
|
|
fd::AsRawFd,
|
|
unix::{fs::FileTypeExt, net::UnixStream},
|
|
},
|
|
time::Duration,
|
|
};
|
|
let parent = fs::symlink_metadata(socket.parent().context("socket parent")?)?;
|
|
let meta = fs::symlink_metadata(socket)?;
|
|
ensure!(
|
|
parent.is_dir()
|
|
&& !parent.file_type().is_symlink()
|
|
&& parent.uid() == 0
|
|
&& parent.mode() & 0o022 == 0
|
|
&& meta.file_type().is_socket()
|
|
&& meta.uid() == 0
|
|
&& meta.mode() & 0o007 == 0,
|
|
"UNTRUSTED_HELPER_SOCKET"
|
|
);
|
|
let mut stream = UnixStream::connect(socket)?;
|
|
let mut credentials = std::mem::MaybeUninit::<libc::ucred>::uninit();
|
|
let mut size = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
|
|
// SAFETY: correct writable ucred storage and length for a live Unix socket.
|
|
ensure!(
|
|
unsafe {
|
|
libc::getsockopt(
|
|
stream.as_raw_fd(),
|
|
libc::SOL_SOCKET,
|
|
libc::SO_PEERCRED,
|
|
credentials.as_mut_ptr().cast(),
|
|
&mut size,
|
|
)
|
|
} == 0
|
|
&& size as usize == std::mem::size_of::<libc::ucred>(),
|
|
"HELPER_PEER_CREDENTIALS"
|
|
);
|
|
// SAFETY: getsockopt initialized the full ucred on success.
|
|
ensure!(
|
|
unsafe { credentials.assume_init() }.uid == 0,
|
|
"HELPER_PEER_NOT_ROOT"
|
|
);
|
|
stream.set_write_timeout(Some(Duration::from_secs(5)))?;
|
|
stream.set_read_timeout(Some(Duration::from_secs(
|
|
u64::from(max_runtime_seconds) + 10,
|
|
)))?;
|
|
observe()?;
|
|
let bytes = serde_json::to_vec(request)?;
|
|
ensure!(bytes.len() <= 512 * 1024, "HELPER_REQUEST_SIZE");
|
|
stream.write_all(&(u32::try_from(bytes.len())?).to_be_bytes())?;
|
|
stream.write_all(&bytes)?;
|
|
stream.set_read_timeout(Some(Duration::from_millis(50)))?;
|
|
let started = std::time::Instant::now();
|
|
let mut closed = false;
|
|
let mut read = |stream: &mut UnixStream, mut target: &mut [u8]| -> Result<()> {
|
|
while !target.is_empty() {
|
|
if !closed && observe().is_err() {
|
|
// Half-close only this exact authenticated request stream. The
|
|
// helper treats its EOF as cancellation; result reads continue.
|
|
stream.shutdown(std::net::Shutdown::Write)?;
|
|
closed = true;
|
|
}
|
|
ensure!(
|
|
started.elapsed() < Duration::from_secs(u64::from(max_runtime_seconds) + 10),
|
|
"HELPER_RESPONSE_TIMEOUT_EFFECT_UNKNOWN"
|
|
);
|
|
match stream.read(target) {
|
|
Ok(0) => anyhow::bail!("HELPER_RESPONSE_CLOSED_EFFECT_UNKNOWN"),
|
|
Ok(n) => target = &mut target[n..],
|
|
Err(e)
|
|
if matches!(
|
|
e.kind(),
|
|
std::io::ErrorKind::WouldBlock
|
|
| std::io::ErrorKind::TimedOut
|
|
| std::io::ErrorKind::Interrupted
|
|
) =>
|
|
{
|
|
continue;
|
|
}
|
|
Err(e) => return Err(e.into()),
|
|
}
|
|
}
|
|
Ok(())
|
|
};
|
|
let mut length = [0; 4];
|
|
read(&mut stream, &mut length)?;
|
|
let length = u32::from_be_bytes(length) as usize;
|
|
ensure!(length <= 2 * 1024 * 1024, "HELPER_RESPONSE_SIZE");
|
|
let mut bytes = vec![0; length];
|
|
read(&mut stream, &mut bytes)?;
|
|
let outcome: Outcome = serde_json::from_slice(&bytes)?;
|
|
ensure!(
|
|
outcome.stdout.len() + outcome.stderr.len() <= 262144,
|
|
"HELPER_OUTPUT_LIMIT"
|
|
);
|
|
Ok(outcome)
|
|
}
|
|
impl Default for TrustedClock {
|
|
fn default() -> Self {
|
|
Self::new()
|
|
}
|
|
}
|
|
impl TrustedClock {
|
|
pub fn new() -> Self {
|
|
Self {
|
|
wall: Utc::now(),
|
|
monotonic: std::time::Instant::now(),
|
|
}
|
|
}
|
|
pub fn trusted(&self) -> bool {
|
|
let elapsed = Utc::now() - self.wall;
|
|
let skew = elapsed.num_milliseconds()
|
|
- i64::try_from(self.monotonic.elapsed().as_millis()).unwrap_or(i64::MAX);
|
|
clock_trusted() && skew.unsigned_abs() <= 5000
|
|
}
|
|
}
|