feat: snapshot Linux-first RMM MVP and pause handover
Rust development slice / linux (push) Failing after 1m10s
Rust development slice / linux (push) Failing after 1m10s
This commit is contained in:
@@ -0,0 +1,893 @@
|
||||
//! Typed, root-only APT bridge. No network fetch, shell conversion or capability
|
||||
//! advertisement. The public constructor always re-verifies the signed request.
|
||||
use crate::{Binding, Outcome, Request, private_path};
|
||||
use anyhow::{Context, Result, bail, ensure};
|
||||
use chrono::{DateTime, Utc};
|
||||
use rmm_domain::jobs::{ExecutionPermitPayload, JobPayload, hash};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
fs::{self, File, OpenOptions},
|
||||
io::{Read, Write},
|
||||
os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt},
|
||||
path::{Path, PathBuf},
|
||||
process::{Command, Stdio},
|
||||
};
|
||||
|
||||
const BASE: &str = "/var/lib/rmm-apt-transaction";
|
||||
pub const CODE: &str = "/usr/lib/rmm-apt-transaction/apt_transaction.py";
|
||||
const HOOK: &str = "/usr/lib/rmm-apt-transaction/hook";
|
||||
const PYTHON: &[u8] = include_bytes!("../../../tools/apt-transaction/apt_transaction.py");
|
||||
const HOOK_BYTES: &[u8] = include_bytes!("../../../tools/apt-transaction/hook");
|
||||
pub const INSTALL_RECIPE: &str = "rmm-apt-fixture-install-1.0";
|
||||
pub const UPDATE_RECIPE: &str = "rmm-apt-fixture-update-1.1";
|
||||
const INSTALL_SHA: &str = "74036ae81223deab3aae994fd2a2a695af408741777e1ce17dcb4e32f1235867";
|
||||
const UPDATE_SHA: &str = "ef67c9fe0ba1443fcfe465768e1204763063c369a2a1da04af6027d8a9c00491";
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ProviderConfig {
|
||||
pub schema_version: u32,
|
||||
pub execution_profile: String,
|
||||
pub allow_fixture_bootstrap: bool,
|
||||
pub allowed_recipes: Vec<String>,
|
||||
pub runtime_sha256: String,
|
||||
pub apt_config_sha256: String,
|
||||
}
|
||||
impl ProviderConfig {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
ensure!(
|
||||
self.schema_version == 1 && self.execution_profile == "dev-test",
|
||||
"APT_PROFILE_NOT_CONFIGURED"
|
||||
);
|
||||
ensure!(
|
||||
!self.allowed_recipes.is_empty()
|
||||
&& self.allowed_recipes.len() <= 2
|
||||
&& self
|
||||
.allowed_recipes
|
||||
.iter()
|
||||
.all(|r| matches!(r.as_str(), INSTALL_RECIPE | UPDATE_RECIPE)),
|
||||
"APT_RECIPE_POLICY"
|
||||
);
|
||||
sha(&self.runtime_sha256)?;
|
||||
sha(&self.apt_config_sha256)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct PackageArchive {
|
||||
pub name: String,
|
||||
pub architecture: String,
|
||||
pub old_version: Option<String>,
|
||||
pub new_version: String,
|
||||
pub origin: String,
|
||||
pub sha256: String,
|
||||
pub size: u64,
|
||||
pub archive_path: String,
|
||||
}
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ResolvedAptTransaction {
|
||||
pub schema_version: u32,
|
||||
pub recipe_id: String,
|
||||
pub recipe_version: String,
|
||||
pub platform: String,
|
||||
pub resolver_config_version: String,
|
||||
pub no_reboot: bool,
|
||||
pub status_fingerprint: String,
|
||||
pub baseline_sha256: String,
|
||||
pub packages: Vec<PackageArchive>,
|
||||
}
|
||||
impl ResolvedAptTransaction {
|
||||
pub fn validate_fixture(&self) -> Result<()> {
|
||||
ensure!(
|
||||
self.schema_version == 1
|
||||
&& self.recipe_version == "1"
|
||||
&& self.platform == "ubuntu-24.04-amd64"
|
||||
&& self.resolver_config_version == "rmm-apt-local-v1"
|
||||
&& self.no_reboot
|
||||
&& self.packages.len() == 1,
|
||||
"APT_TRANSACTION_SCOPE"
|
||||
);
|
||||
sha(&self.status_fingerprint)?;
|
||||
sha(&self.baseline_sha256)?;
|
||||
let p = &self.packages[0];
|
||||
let (old, new, expected_hash) = match self.recipe_id.as_str() {
|
||||
INSTALL_RECIPE => (None, "1.0", INSTALL_SHA),
|
||||
UPDATE_RECIPE => (Some("1.0"), "1.1", UPDATE_SHA),
|
||||
_ => bail!("APT_RECIPE_NOT_CONFIGURED"),
|
||||
};
|
||||
ensure!(
|
||||
p.name == "rmm-mvp-test"
|
||||
&& p.architecture == "all"
|
||||
&& p.origin == "rmm-test"
|
||||
&& p.old_version.as_deref() == old
|
||||
&& p.new_version == new
|
||||
&& p.sha256 == expected_hash
|
||||
&& p.size == 20672
|
||||
&& p.archive_path == format!("{BASE}/archives/{expected_hash}.deb"),
|
||||
"APT_FIXTURE_BYTES_OR_CLOSURE"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Must be a field named `apt_manifest` of the signed domain Action. The full
|
||||
/// transaction object AND its exact serialized bytes are part of those bytes.
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct AptExecutionManifest {
|
||||
#[serde(rename = "type")]
|
||||
pub kind: String,
|
||||
pub schema_version: u32,
|
||||
pub action: String,
|
||||
pub execution_profile: String,
|
||||
pub transaction_sha256: String,
|
||||
pub resolved_apt_transaction: ResolvedAptTransaction,
|
||||
pub transaction_bytes: Vec<u8>,
|
||||
pub provider_sha256: String,
|
||||
pub hook_sha256: String,
|
||||
pub apt_config_sha256: String,
|
||||
pub runtime_sha256: String,
|
||||
pub test_result_id: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ActionCarrier {
|
||||
action: String,
|
||||
apt_manifest: Option<AptExecutionManifest>,
|
||||
#[serde(flatten)]
|
||||
parameters: BTreeMap<String, serde_json::Value>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct SignedJob {
|
||||
schema_version: u32,
|
||||
tenant_id: uuid::Uuid,
|
||||
asset_id: uuid::Uuid,
|
||||
agent_id: uuid::Uuid,
|
||||
enrollment_generation: u64,
|
||||
assignment_version: u64,
|
||||
job_id: uuid::Uuid,
|
||||
attempt_id: uuid::Uuid,
|
||||
action: ActionCarrier,
|
||||
execution_identity: String,
|
||||
not_before: DateTime<Utc>,
|
||||
start_before: DateTime<Utc>,
|
||||
max_runtime_seconds: u32,
|
||||
max_output_bytes: u32,
|
||||
}
|
||||
|
||||
pub fn is_apt_action(job: &JobPayload) -> bool {
|
||||
matches!(
|
||||
job.action.name(),
|
||||
"ensure_package" | "apply_updates" | "apt_native_acceptance"
|
||||
)
|
||||
}
|
||||
pub fn policy_header(job: &JobPayload, config: &ProviderConfig) -> Result<()> {
|
||||
config.validate()?;
|
||||
ensure!(
|
||||
is_apt_action(job) && job.execution_identity == "root" && job.max_runtime_seconds >= 180,
|
||||
"APT_EXPLICIT_ROOT_AND_RUNTIME_REQUIRED"
|
||||
);
|
||||
ensure!(
|
||||
job.action.name() != "apt_native_acceptance" || config.allow_fixture_bootstrap,
|
||||
"APT_BOOTSTRAP_DENIED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Opaque verified capability: callers cannot manufacture one from a manifest.
|
||||
pub struct PreparedApt {
|
||||
job: JobPayload,
|
||||
permit: ExecutionPermitPayload,
|
||||
request: Request,
|
||||
manifest: AptExecutionManifest,
|
||||
}
|
||||
pub fn prepare(
|
||||
binding: &Binding,
|
||||
request: &Request,
|
||||
config: &ProviderConfig,
|
||||
now: DateTime<Utc>,
|
||||
) -> Result<PreparedApt> {
|
||||
let (job, permit) = binding.verify(request, now)?;
|
||||
policy_header(&job, config)?;
|
||||
let manifest = validate_signed_manifest(&job, &request.job_bytes, config)?;
|
||||
verify_installation()?;
|
||||
verify_prefetched(&manifest, &permit)?;
|
||||
Ok(PreparedApt {
|
||||
job,
|
||||
permit,
|
||||
request: request.clone(),
|
||||
manifest,
|
||||
})
|
||||
}
|
||||
|
||||
fn validate_signed_manifest(
|
||||
job: &JobPayload,
|
||||
bytes: &[u8],
|
||||
config: &ProviderConfig,
|
||||
) -> Result<AptExecutionManifest> {
|
||||
let signed: SignedJob = serde_json::from_slice(bytes)?;
|
||||
ensure!(
|
||||
signed.schema_version == job.schema_version
|
||||
&& signed.tenant_id == job.tenant_id
|
||||
&& signed.asset_id == job.asset_id
|
||||
&& signed.agent_id == job.agent_id
|
||||
&& signed.enrollment_generation == job.enrollment_generation
|
||||
&& signed.assignment_version == job.assignment_version
|
||||
&& signed.job_id == job.job_id
|
||||
&& signed.attempt_id == job.attempt_id
|
||||
&& signed.execution_identity == job.execution_identity
|
||||
&& signed.not_before == job.not_before
|
||||
&& signed.start_before == job.start_before
|
||||
&& signed.max_runtime_seconds == job.max_runtime_seconds
|
||||
&& signed.max_output_bytes == job.max_output_bytes
|
||||
&& signed.action.action == job.action.name(),
|
||||
"APT_SIGNED_JOB_BINDING"
|
||||
);
|
||||
let manifest = signed
|
||||
.action
|
||||
.apt_manifest
|
||||
.context("APT_MANIFEST_NOT_CONFIGURED")?;
|
||||
validate_manifest(&manifest, job.action.name(), config)?;
|
||||
// Domain deserialization must preserve the manifest, not ignore an unknown
|
||||
// field. This is the explicit fail-closed gate until the additive domain
|
||||
// contract lands. No separately supplied unsigned manifest is accepted.
|
||||
let mut domain_action = serde_json::to_value(&job.action)?;
|
||||
let embedded = domain_action
|
||||
.as_object_mut()
|
||||
.context("APT_ACTION_OBJECT")?
|
||||
.remove("apt_manifest")
|
||||
.context("APT_DOMAIN_MANIFEST_NOT_CONFIGURED")?;
|
||||
let domain_manifest: AptExecutionManifest = serde_json::from_value(embedded)?;
|
||||
ensure!(
|
||||
serde_json::to_vec(&domain_manifest)? == serde_json::to_vec(&manifest)?,
|
||||
"APT_DOMAIN_MANIFEST_MISMATCH"
|
||||
);
|
||||
let mut original = serde_json::to_value(signed.action.parameters)?;
|
||||
original
|
||||
.as_object_mut()
|
||||
.context("APT_PARAMETERS")?
|
||||
.insert("action".into(), serde_json::json!(job.action.name()));
|
||||
ensure!(
|
||||
original == domain_action,
|
||||
"APT_PARAMETERS_ALIAS_OR_MISMATCH"
|
||||
);
|
||||
// Approved recipe identity is explicit outside the manifest too. Normal
|
||||
// updates bind provider, selected package names and reboot policy as well.
|
||||
let t = &manifest.resolved_apt_transaction;
|
||||
if job.action.name() == "apply_updates" {
|
||||
ensure!(
|
||||
original.get("provider") == Some(&serde_json::json!("apt"))
|
||||
&& original.get("packages") == Some(&serde_json::json!(["rmm-mvp-test"]))
|
||||
&& original.get("reboot_policy") == Some(&serde_json::json!("never"))
|
||||
&& t.recipe_id == UPDATE_RECIPE,
|
||||
"APT_UPDATE_SELECTION"
|
||||
);
|
||||
} else {
|
||||
ensure!(
|
||||
original.get("recipe_id") == Some(&serde_json::json!(t.recipe_id))
|
||||
&& original.get("recipe_version") == Some(&serde_json::json!(t.recipe_version)),
|
||||
"APT_RECIPE_PARAMETER_BINDING"
|
||||
);
|
||||
if job.action.name() == "ensure_package" {
|
||||
let package = &t.packages[0];
|
||||
ensure!(
|
||||
original.get("provider") == Some(&serde_json::json!("apt"))
|
||||
&& original.get("package") == Some(&serde_json::json!(package.name))
|
||||
&& original.get("version") == Some(&serde_json::json!(package.new_version))
|
||||
&& original.get("architecture")
|
||||
== Some(&serde_json::json!(package.architecture))
|
||||
&& original.get("installation_context") == Some(&serde_json::json!("system")),
|
||||
"APT_ENSURE_TARGET_BINDING"
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(manifest)
|
||||
}
|
||||
fn validate_manifest(
|
||||
m: &AptExecutionManifest,
|
||||
action: &str,
|
||||
config: &ProviderConfig,
|
||||
) -> Result<()> {
|
||||
config.validate()?;
|
||||
ensure!(
|
||||
m.kind == "rmm.apt.helper-action"
|
||||
&& m.schema_version == 2
|
||||
&& m.execution_profile == config.execution_profile
|
||||
&& !m.test_result_id.is_empty()
|
||||
&& m.test_result_id.len() <= 128
|
||||
&& m.test_result_id
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b"_.-".contains(&b)),
|
||||
"APT_MANIFEST_SCHEMA"
|
||||
);
|
||||
let bootstrap = action == "apt_native_acceptance";
|
||||
ensure!(
|
||||
matches!(
|
||||
action,
|
||||
"ensure_package" | "apply_updates" | "apt_native_acceptance"
|
||||
) && m.action
|
||||
== if bootstrap {
|
||||
"apt-native-acceptance"
|
||||
} else {
|
||||
"apt-execute"
|
||||
}
|
||||
&& (!bootstrap || config.allow_fixture_bootstrap),
|
||||
"APT_DEDICATED_ACTION_BINDING"
|
||||
);
|
||||
m.resolved_apt_transaction.validate_fixture()?;
|
||||
ensure!(
|
||||
config
|
||||
.allowed_recipes
|
||||
.contains(&m.resolved_apt_transaction.recipe_id),
|
||||
"APT_RECIPE_POLICY"
|
||||
);
|
||||
ensure!(
|
||||
m.transaction_bytes.len() <= 65536 && hash(&m.transaction_bytes) == m.transaction_sha256,
|
||||
"APT_TRANSACTION_EXACT_BYTES_HASH"
|
||||
);
|
||||
let decoded: ResolvedAptTransaction = serde_json::from_slice(&m.transaction_bytes)?;
|
||||
ensure!(
|
||||
decoded == m.resolved_apt_transaction,
|
||||
"APT_NESTED_TRANSACTION_BINDING"
|
||||
);
|
||||
ensure!(
|
||||
m.provider_sha256 == hash(PYTHON)
|
||||
&& m.hook_sha256 == hash(HOOK_BYTES)
|
||||
&& m.runtime_sha256 == config.runtime_sha256
|
||||
&& m.apt_config_sha256 == config.apt_config_sha256,
|
||||
"APT_APPROVED_CODE_OR_RUNTIME"
|
||||
);
|
||||
for value in [
|
||||
&m.transaction_sha256,
|
||||
&m.provider_sha256,
|
||||
&m.hook_sha256,
|
||||
&m.runtime_sha256,
|
||||
&m.apt_config_sha256,
|
||||
] {
|
||||
sha(value)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn sha(value: &str) -> Result<()> {
|
||||
ensure!(
|
||||
value.len() == 64
|
||||
&& value
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)),
|
||||
"APT_SHA256"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn secure(path: &Path, uid: u32, private: bool, directory: bool) -> Result<()> {
|
||||
ensure!(
|
||||
path.is_absolute()
|
||||
&& !path
|
||||
.components()
|
||||
.any(|c| matches!(c, std::path::Component::ParentDir)),
|
||||
"APT_PATH"
|
||||
);
|
||||
for component in path.ancestors() {
|
||||
let m = fs::symlink_metadata(component)?;
|
||||
ensure!(
|
||||
!m.file_type().is_symlink() && m.uid() == uid && m.mode() & 0o022 == 0,
|
||||
"APT_UNSAFE_PATH_COMPONENT"
|
||||
);
|
||||
}
|
||||
if private {
|
||||
private_path(path, uid, directory)?;
|
||||
}
|
||||
let m = fs::symlink_metadata(path)?;
|
||||
ensure!(
|
||||
if directory { m.is_dir() } else { m.is_file() },
|
||||
"APT_PATH_TYPE"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
fn read_sealed(path: &Path, limit: u64) -> Result<Vec<u8>> {
|
||||
secure(path, 0, false, false)?;
|
||||
let mut f = OpenOptions::new()
|
||||
.read(true)
|
||||
.custom_flags(libc::O_NOFOLLOW)
|
||||
.open(path)?;
|
||||
ensure!(f.metadata()?.len() <= limit, "APT_FILE_LIMIT");
|
||||
let mut bytes = vec![];
|
||||
(&mut f).take(limit + 1).read_to_end(&mut bytes)?;
|
||||
ensure!(bytes.len() as u64 <= limit, "APT_FILE_LIMIT");
|
||||
Ok(bytes)
|
||||
}
|
||||
fn create_dir(path: &Path, mode: u32) -> Result<()> {
|
||||
fs::DirBuilder::new().mode(mode).create(path)?;
|
||||
File::open(path.parent().context("APT_PARENT")?)?.sync_all()?;
|
||||
Ok(())
|
||||
}
|
||||
fn write_once(path: &Path, bytes: &[u8], mode: u32) -> Result<()> {
|
||||
let mut f = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.mode(mode)
|
||||
.custom_flags(libc::O_NOFOLLOW)
|
||||
.open(path)?;
|
||||
f.write_all(bytes)?;
|
||||
f.sync_all()?;
|
||||
File::open(path.parent().context("APT_PARENT")?)?.sync_all()?;
|
||||
Ok(())
|
||||
}
|
||||
fn json_once(path: &Path, value: &impl Serialize) -> Result<()> {
|
||||
write_once(path, &serde_json::to_vec(value)?, 0o600)
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct InstallMetadata {
|
||||
schema_version: u32,
|
||||
provider_sha256: String,
|
||||
hook_sha256: String,
|
||||
unit_sha256: String,
|
||||
}
|
||||
/// Administrator bootstrap only, not a network job. Compile-time known bytes,
|
||||
/// fixed paths, create-only. Does not grant execution or create acceptance.
|
||||
pub fn install_known_payloads() -> Result<()> {
|
||||
ensure_root()?;
|
||||
secure(Path::new("/usr/lib"), 0, false, true)?;
|
||||
secure(Path::new("/var/lib"), 0, false, true)?;
|
||||
create_dir(Path::new("/usr/lib/rmm-apt-transaction"), 0o755)?;
|
||||
write_once(Path::new(CODE), PYTHON, 0o644)?;
|
||||
write_once(Path::new(HOOK), HOOK_BYTES, 0o755)?;
|
||||
secure(Path::new("/etc/systemd/system"), 0, false, true)?;
|
||||
write_once(
|
||||
Path::new(crate::readiness::UNIT_PATH),
|
||||
crate::readiness::UNIT_BYTES,
|
||||
0o644,
|
||||
)?;
|
||||
secure(Path::new("/usr/share"), 0, false, true)?;
|
||||
create_dir(Path::new("/usr/share/rmm-mvp-test"), 0o755)?;
|
||||
create_dir(Path::new(BASE), 0o700)?;
|
||||
for dir in ["archives", "baselines", "history", "probes", "log", "state"] {
|
||||
create_dir(&Path::new(BASE).join(dir), 0o700)?;
|
||||
}
|
||||
json_once(
|
||||
&Path::new(BASE).join("install-metadata.json"),
|
||||
&InstallMetadata {
|
||||
schema_version: 2,
|
||||
provider_sha256: hash(PYTHON),
|
||||
hook_sha256: hash(HOOK_BYTES),
|
||||
unit_sha256: hash(crate::readiness::UNIT_BYTES),
|
||||
},
|
||||
)
|
||||
}
|
||||
fn ensure_root() -> Result<()> {
|
||||
// SAFETY: geteuid has no preconditions or pointers.
|
||||
ensure!(unsafe { libc::geteuid() } == 0, "APT_ROOT_REQUIRED");
|
||||
Ok(())
|
||||
}
|
||||
pub fn verify_installation() -> Result<()> {
|
||||
ensure_root()?;
|
||||
secure(Path::new(BASE), 0, true, true)?;
|
||||
let metadata: InstallMetadata = serde_json::from_slice(&read_sealed(
|
||||
&Path::new(BASE).join("install-metadata.json"),
|
||||
4096,
|
||||
)?)?;
|
||||
ensure!(
|
||||
metadata.schema_version == 2
|
||||
&& metadata.provider_sha256 == hash(PYTHON)
|
||||
&& metadata.hook_sha256 == hash(HOOK_BYTES)
|
||||
&& metadata.unit_sha256 == hash(crate::readiness::UNIT_BYTES)
|
||||
&& read_sealed(Path::new(crate::readiness::UNIT_PATH), 65536)?
|
||||
== crate::readiness::UNIT_BYTES
|
||||
&& read_sealed(Path::new(CODE), 1024 * 1024)? == PYTHON
|
||||
&& read_sealed(Path::new(HOOK), 4096)? == HOOK_BYTES,
|
||||
"APT_INSTALLATION_MISMATCH"
|
||||
);
|
||||
// Interpreter may be the distro's root-owned symlink, never a caller path.
|
||||
secure(&fs::canonicalize("/usr/bin/python3")?, 0, false, false)
|
||||
}
|
||||
pub fn verify_controller_profile() -> Result<()> {
|
||||
verify_installation()?;
|
||||
let status = Command::new("/usr/bin/python3")
|
||||
.args(["-I", CODE, "verify-controller"])
|
||||
.env_clear()
|
||||
.env("PATH", "/usr/bin:/bin")
|
||||
.env("LC_ALL", "C")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status()?;
|
||||
ensure!(status.success(), "APT_CONTROLLER_PROFILE_REQUIRED");
|
||||
Ok(())
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct PrefetchReceipt {
|
||||
schema_version: u32,
|
||||
sha256: String,
|
||||
size: u64,
|
||||
sealed_at_ms: i64,
|
||||
}
|
||||
impl PrefetchReceipt {
|
||||
fn validate(&self, package: &PackageArchive, grant_not_before_ms: i64) -> Result<()> {
|
||||
ensure!(
|
||||
self.schema_version == 1
|
||||
&& self.sha256 == package.sha256
|
||||
&& self.size == package.size
|
||||
&& self.sealed_at_ms > 0
|
||||
&& self.sealed_at_ms <= grant_not_before_ms,
|
||||
"APT_PREFETCH_BEFORE_GRANT_REQUIRED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
fn verify_prefetched(m: &AptExecutionManifest, permit: &ExecutionPermitPayload) -> Result<()> {
|
||||
for p in &m.resolved_apt_transaction.packages {
|
||||
let bytes = read_sealed(Path::new(&p.archive_path), p.size)?;
|
||||
let meta = fs::symlink_metadata(&p.archive_path)?;
|
||||
ensure!(
|
||||
bytes.len() as u64 == p.size && hash(&bytes) == p.sha256 && meta.nlink() == 1,
|
||||
"APT_PREFETCH_HASH_SIZE_LINKS"
|
||||
);
|
||||
let receipt: PrefetchReceipt = serde_json::from_slice(&read_sealed(
|
||||
&Path::new(BASE).join(format!("prefetch-{}.json", p.sha256)),
|
||||
4096,
|
||||
)?)?;
|
||||
receipt.validate(p, permit.not_before.timestamp_millis())?;
|
||||
}
|
||||
let baseline = read_sealed(
|
||||
&Path::new(BASE).join("baselines").join(format!(
|
||||
"{}.json",
|
||||
m.resolved_apt_transaction.baseline_sha256
|
||||
)),
|
||||
1024 * 1024,
|
||||
)?;
|
||||
ensure!(
|
||||
hash(&baseline) == m.resolved_apt_transaction.baseline_sha256,
|
||||
"APT_BASELINE_HASH"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl PreparedApt {
|
||||
fn verify_parent_consumption(&self, db: &rusqlite::Connection) -> Result<String> {
|
||||
let row: (i64, String, u64, String, String, Option<Vec<u8>>) = db.query_row(
|
||||
"SELECT rowid,agent,generation,job,attempt,result FROM consumed WHERE grant_id=?1",
|
||||
[self.permit.grant_id.to_string()],
|
||||
|r| {
|
||||
Ok((
|
||||
r.get(0)?,
|
||||
r.get(1)?,
|
||||
r.get(2)?,
|
||||
r.get(3)?,
|
||||
r.get(4)?,
|
||||
r.get(5)?,
|
||||
))
|
||||
},
|
||||
)?;
|
||||
ensure!(
|
||||
row.1 == self.job.agent_id.to_string()
|
||||
&& row.2 == self.job.enrollment_generation
|
||||
&& row.3 == self.job.job_id.to_string()
|
||||
&& row.4 == self.job.attempt_id.to_string()
|
||||
&& row.5.is_none(),
|
||||
"APT_PARENT_CONSUMPTION_REQUIRED"
|
||||
);
|
||||
let start: Vec<u8> = db.query_row(
|
||||
"SELECT start FROM execution_evidence WHERE grant_id=?1",
|
||||
[self.permit.grant_id.to_string()],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let start: serde_json::Value = serde_json::from_slice(&start)?;
|
||||
let saved: Request =
|
||||
serde_json::from_value(start.get("request").context("APT_START_REQUEST")?.clone())?;
|
||||
ensure!(
|
||||
saved.job_bytes == self.request.job_bytes
|
||||
&& saved.permit_bytes == self.request.permit_bytes
|
||||
&& saved.signature == self.request.signature
|
||||
&& saved.plan_hash == self.request.plan_hash
|
||||
&& saved.authorization_id == self.request.authorization_id,
|
||||
"APT_PARENT_START_BINDING"
|
||||
);
|
||||
Ok(format!("apt-{}-{}", self.permit.grant_id, row.0))
|
||||
}
|
||||
/// Requires the same request already consumed and save_start persisted in
|
||||
/// the parent's own ledger. Unknown outcomes never fill consumed.result.
|
||||
pub fn execute(self, db: &rusqlite::Connection) -> Result<Outcome> {
|
||||
ensure_root()?;
|
||||
let ledger_id = self.verify_parent_consumption(db)?;
|
||||
let active = self.stage(db, &ledger_id)?;
|
||||
// No timeout killing the native package manager. Client timeout means
|
||||
// unknown; this helper continues and journals the eventual real outcome.
|
||||
let mut child = Command::new("/usr/bin/python3")
|
||||
.args([
|
||||
"-I",
|
||||
CODE,
|
||||
if self.manifest.action == "apt-native-acceptance" {
|
||||
"native-acceptance"
|
||||
} else {
|
||||
"execute"
|
||||
},
|
||||
])
|
||||
.env_clear()
|
||||
.env("PATH", "/usr/sbin:/usr/bin:/sbin:/bin")
|
||||
.env("LC_ALL", "C")
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()?;
|
||||
let input = serde_json::json!({"transaction_sha256":self.manifest.transaction_sha256,"effect_armed_ledger_id":ledger_id});
|
||||
let write_ok = child
|
||||
.stdin
|
||||
.take()
|
||||
.context("APT_STDIN")?
|
||||
.write_all(&serde_json::to_vec(&input)?)
|
||||
.is_ok();
|
||||
let mut bytes = vec![];
|
||||
let mut output = child.stdout.take().context("APT_STDOUT")?;
|
||||
let mut chunk = [0; 4096];
|
||||
let mut overflow = false;
|
||||
loop {
|
||||
let count = output.read(&mut chunk)?;
|
||||
if count == 0 {
|
||||
break;
|
||||
}
|
||||
if bytes.len() + count <= 65536 {
|
||||
bytes.extend_from_slice(&chunk[..count]);
|
||||
} else {
|
||||
overflow = true;
|
||||
}
|
||||
}
|
||||
let status = child.wait()?;
|
||||
if !write_ok || overflow {
|
||||
return Ok(Outcome::unknown("APT_DRIVER_OUTPUT_OR_IPC_UNKNOWN"));
|
||||
}
|
||||
Ok(map_driver_result(
|
||||
&bytes,
|
||||
status.code(),
|
||||
active.join("hook-armed.json").try_exists()?,
|
||||
&self.manifest,
|
||||
&ledger_id,
|
||||
)
|
||||
.unwrap_or_else(|_| Outcome::unknown("APT_DRIVER_RESULT_UNKNOWN")))
|
||||
}
|
||||
fn stage(&self, db: &rusqlite::Connection, ledger_id: &str) -> Result<PathBuf> {
|
||||
verify_installation()?;
|
||||
verify_prefetched(&self.manifest, &self.permit)?;
|
||||
let remaining = (self.permit.start_before - Utc::now())
|
||||
.num_nanoseconds()
|
||||
.context("APT_DEADLINE_RANGE")?;
|
||||
ensure!(
|
||||
remaining > 0 && Utc::now() >= self.permit.not_before,
|
||||
"APT_START_DEADLINE"
|
||||
);
|
||||
let active = Path::new(BASE).join("active");
|
||||
if active.try_exists()? {
|
||||
secure(&active, 0, true, true)?;
|
||||
let prior: serde_json::Value =
|
||||
serde_json::from_slice(&read_sealed(&active.join("context.json"), 8192)?)?;
|
||||
let grant = prior
|
||||
.get("grant_id")
|
||||
.and_then(|v| v.as_str())
|
||||
.context("APT_PRIOR_GRANT")?;
|
||||
let grant: uuid::Uuid = grant.parse()?;
|
||||
let result: Option<Vec<u8>> = db.query_row(
|
||||
"SELECT result FROM consumed WHERE grant_id=?1",
|
||||
[grant.to_string()],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let result: Outcome =
|
||||
serde_json::from_slice(&result.context("APT_PREVIOUS_EFFECT_UNRESOLVED")?)?;
|
||||
ensure!(
|
||||
matches!(result.state.as_str(), "succeeded" | "failed"),
|
||||
"APT_PREVIOUS_EFFECT_UNRESOLVED"
|
||||
);
|
||||
let history = Path::new(BASE).join("history");
|
||||
secure(&history, 0, true, true)?;
|
||||
let destination = history.join(grant.to_string());
|
||||
ensure!(!destination.try_exists()?, "APT_HISTORY_EXISTS");
|
||||
fs::rename(&active, destination)?;
|
||||
File::open(history)?.sync_all()?;
|
||||
File::open(BASE)?.sync_all()?;
|
||||
}
|
||||
create_dir(&active, 0o700)?;
|
||||
for dir in ["empty", "lists", "cache"] {
|
||||
create_dir(&active.join(dir), 0o700)?;
|
||||
}
|
||||
write_once(
|
||||
&active.join("expectation.json"),
|
||||
&self.manifest.transaction_bytes,
|
||||
0o600,
|
||||
)?;
|
||||
write_once(
|
||||
&active.join("signed-action.json"),
|
||||
&self.request.job_bytes,
|
||||
0o600,
|
||||
)?;
|
||||
let baseline = read_sealed(
|
||||
&Path::new(BASE).join("baselines").join(format!(
|
||||
"{}.json",
|
||||
self.manifest.resolved_apt_transaction.baseline_sha256
|
||||
)),
|
||||
1024 * 1024,
|
||||
)?;
|
||||
write_once(&active.join("baseline.json"), &baseline, 0o600)?;
|
||||
let config = Command::new("/usr/bin/python3")
|
||||
.args(["-I", CODE, "print-config"])
|
||||
.env_clear()
|
||||
.env("PATH", "/usr/bin:/bin")
|
||||
.output()?;
|
||||
ensure!(
|
||||
config.status.success()
|
||||
&& config.stdout.len() <= 16384
|
||||
&& hash(&config.stdout) == self.manifest.apt_config_sha256,
|
||||
"APT_CONFIG_BINDING"
|
||||
);
|
||||
write_once(&active.join("apt.conf"), &config.stdout, 0o600)?;
|
||||
let mut time = std::mem::MaybeUninit::<libc::timespec>::zeroed();
|
||||
// SAFETY: live correctly aligned output; read-only CLOCK_MONOTONIC query.
|
||||
ensure!(
|
||||
unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, time.as_mut_ptr()) } == 0,
|
||||
"APT_MONOTONIC_CLOCK"
|
||||
);
|
||||
// SAFETY: clock_gettime initialized the timespec on success.
|
||||
let time = unsafe { time.assume_init() };
|
||||
// Recompute remaining time immediately at translation: staging/fsync
|
||||
// cannot extend the signed UTC deadline into a fresh monotonic window.
|
||||
let remaining = (self.permit.start_before - Utc::now())
|
||||
.num_nanoseconds()
|
||||
.context("APT_DEADLINE_RANGE")?;
|
||||
ensure!(remaining > 0, "APT_START_DEADLINE");
|
||||
let monotonic = i128::from(time.tv_sec) * 1_000_000_000
|
||||
+ i128::from(time.tv_nsec)
|
||||
+ i128::from(remaining);
|
||||
json_once(
|
||||
&active.join("context.json"),
|
||||
&serde_json::json!({
|
||||
"schema_version":2,"transaction_sha256":self.manifest.transaction_sha256,
|
||||
"job_payload_sha256":hash(&self.request.job_bytes),"action":self.manifest.action,
|
||||
"execution_profile":self.manifest.execution_profile,"effect_armed_ledger_id":ledger_id,
|
||||
"grant_id":self.permit.grant_id,"job_id":self.job.job_id,"attempt_id":self.job.attempt_id,
|
||||
"authorization_id":self.permit.authorization_id,"plan_sha256":self.permit.plan_hash,
|
||||
"not_before_ms":self.permit.not_before.timestamp_millis(),"start_before_ms":self.permit.start_before.timestamp_millis(),
|
||||
"boot_id":rmm_agent_linux::boot_id()?,"monotonic_start_before_ns":u64::try_from(monotonic)?
|
||||
}),
|
||||
)?;
|
||||
Ok(active)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct DriverResult {
|
||||
effect_state: String,
|
||||
code: String,
|
||||
evidence: serde_json::Value,
|
||||
}
|
||||
fn map_driver_result(
|
||||
bytes: &[u8],
|
||||
exit: Option<i32>,
|
||||
armed: bool,
|
||||
m: &AptExecutionManifest,
|
||||
ledger: &str,
|
||||
) -> Result<Outcome> {
|
||||
let result: DriverResult = serde_json::from_slice(bytes)?;
|
||||
ensure!(
|
||||
exit == Some(0) && !result.code.is_empty() && result.code.len() <= 128,
|
||||
"APT_EXIT_NOT_RESULT"
|
||||
);
|
||||
let bootstrap = m.action == "apt-native-acceptance";
|
||||
if bootstrap {
|
||||
ensure!(
|
||||
result.evidence.get("test_acceptance") == Some(&serde_json::json!(true))
|
||||
&& result.evidence.get("noProductionEvidence") == Some(&serde_json::json!(true)),
|
||||
"APT_TEST_AUDIT_FLAGS"
|
||||
);
|
||||
}
|
||||
let state = match result.effect_state.as_str() {
|
||||
"verified_no_change" => {
|
||||
let p = &m.resolved_apt_transaction.packages[0];
|
||||
ensure!(
|
||||
!bootstrap
|
||||
&& !armed
|
||||
&& result.code == "POSTCONDITION_ALREADY_MET"
|
||||
&& result.evidence.get("changed") == Some(&serde_json::json!(false))
|
||||
&& result.evidence.get("already_desired") == Some(&serde_json::json!(true))
|
||||
&& result.evidence.get("postcondition_already_met")
|
||||
== Some(&serde_json::json!(true))
|
||||
&& result.evidence.get("transaction_executed")
|
||||
== Some(&serde_json::json!(false))
|
||||
&& result.evidence.get("effect_armed_ledger_id")
|
||||
== Some(&serde_json::json!(ledger))
|
||||
&& result.evidence.get("packages")
|
||||
== Some(
|
||||
&serde_json::json!([{"name":p.name,"architecture":p.architecture,"version":p.new_version}])
|
||||
)
|
||||
&& result.evidence.get("snapshot_sha256")
|
||||
== Some(&serde_json::json!(
|
||||
m.resolved_apt_transaction.baseline_sha256
|
||||
))
|
||||
&& result.evidence.get("fixture_payload_sha256")
|
||||
== Some(&serde_json::json!(hash(
|
||||
format!("{}\n", p.new_version).as_bytes()
|
||||
)))
|
||||
&& result
|
||||
.evidence
|
||||
.get("reboot_required")
|
||||
.and_then(|v| v.as_bool())
|
||||
.is_some(),
|
||||
"APT_NO_CHANGE_POSTCONDITIONS"
|
||||
);
|
||||
"succeeded"
|
||||
}
|
||||
"verified" => {
|
||||
let p = &m.resolved_apt_transaction.packages[0];
|
||||
ensure!(
|
||||
armed
|
||||
&& result.code == "POSTCONDITIONS_VERIFIED"
|
||||
&& result.evidence.get("effect_armed_ledger_id")
|
||||
== Some(&serde_json::json!(ledger))
|
||||
&& result.evidence.get("packages")
|
||||
== Some(
|
||||
&serde_json::json!([{"name":p.name,"architecture":p.architecture,"version":p.new_version}])
|
||||
)
|
||||
&& result
|
||||
.evidence
|
||||
.get("reboot_required")
|
||||
.and_then(|v| v.as_bool())
|
||||
.is_some(),
|
||||
"APT_POSTCONDITIONS"
|
||||
);
|
||||
sha(result
|
||||
.evidence
|
||||
.get("snapshot_sha256")
|
||||
.and_then(|v| v.as_str())
|
||||
.context("APT_SNAPSHOT")?)?;
|
||||
ensure!(
|
||||
result.evidence.get("fixture_payload_sha256")
|
||||
== Some(&serde_json::json!(hash(
|
||||
format!("{}\n", p.new_version).as_bytes()
|
||||
))),
|
||||
"APT_FIXTURE_PAYLOAD_EVIDENCE"
|
||||
);
|
||||
if bootstrap {
|
||||
sha(result
|
||||
.evidence
|
||||
.get("native_record_sha256")
|
||||
.and_then(|v| v.as_str())
|
||||
.context("APT_NATIVE_RECORD")?)?;
|
||||
ensure!(
|
||||
result.evidence.get("test_result_id")
|
||||
== Some(&serde_json::json!(m.test_result_id)),
|
||||
"APT_TEST_RESULT_BINDING"
|
||||
);
|
||||
}
|
||||
"succeeded"
|
||||
}
|
||||
"known_failed" if !armed => "failed",
|
||||
"known_failed" | "unknown" => "unknown",
|
||||
_ => bail!("APT_UNKNOWN_EFFECT_STATE"),
|
||||
};
|
||||
Ok(Outcome {
|
||||
state: state.into(),
|
||||
stdout: vec![],
|
||||
stderr: vec![],
|
||||
exit_code: exit,
|
||||
output_truncated: false,
|
||||
reboot_required: result
|
||||
.evidence
|
||||
.get("reboot_required")
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false),
|
||||
evidence: serde_json::json!({"postconditions_passed":state=="succeeded","apt":result.evidence,"effect_armed_ledger_id":ledger,
|
||||
"test_acceptance":bootstrap,"noProductionEvidence":true}),
|
||||
error_code: if state == "succeeded" {
|
||||
String::new()
|
||||
} else {
|
||||
result.code
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,456 @@
|
||||
use super::*;
|
||||
use openssl::{pkey::PKey, sign::Signer};
|
||||
use rmm_domain::jobs::{Action, encode};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[test]
|
||||
fn actual_domain_native_action_roundtrips_exact_signed_manifest_to_helper() {
|
||||
let (binding, mut request, key, now) = signed_request();
|
||||
let (config, m) = manifest(true);
|
||||
let mut job: JobPayload = serde_json::from_slice(&request.job_bytes).unwrap();
|
||||
let domain_manifest: rmm_domain::apt_transaction::AptExecutionManifest =
|
||||
serde_json::from_value(serde_json::to_value(&m).unwrap()).unwrap();
|
||||
job.action = Action::AptNativeAcceptance {
|
||||
recipe_id: INSTALL_RECIPE.into(),
|
||||
recipe_version: "1".into(),
|
||||
apt_manifest: domain_manifest,
|
||||
};
|
||||
assert!(job.action.validate());
|
||||
request.job_bytes = encode(&job).unwrap();
|
||||
let mut permit: ExecutionPermitPayload = serde_json::from_slice(&request.permit_bytes).unwrap();
|
||||
permit.action = "apt_native_acceptance".into();
|
||||
permit.job_payload_hash = hash(&request.job_bytes);
|
||||
request.permit_bytes = encode(&permit).unwrap();
|
||||
request.signature = Signer::new_without_digest(&key)
|
||||
.unwrap()
|
||||
.sign_oneshot_to_vec(&request.permit_bytes)
|
||||
.unwrap();
|
||||
let (verified, _) = binding.verify(&request, now).unwrap();
|
||||
policy_header(&verified, &config).unwrap();
|
||||
let parsed = validate_signed_manifest(&verified, &request.job_bytes, &config).unwrap();
|
||||
assert_eq!(parsed.transaction_bytes, m.transaction_bytes);
|
||||
assert_eq!(parsed.transaction_sha256, m.transaction_sha256);
|
||||
// No unsafe root execution in this test: trusted deployment is absent.
|
||||
assert!(prepare(&binding, &request, &config, now).is_err());
|
||||
let mut aliased: serde_json::Value = serde_json::from_slice(&request.job_bytes).unwrap();
|
||||
aliased["action"]["parameters"] = serde_json::json!({"apt_manifest":m});
|
||||
request.job_bytes = serde_json::to_vec(&aliased).unwrap();
|
||||
assert!(binding.verify(&request, now).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefetch_receipt_must_precede_grant_and_match_exact_archive() {
|
||||
let (_, m) = manifest(true);
|
||||
let package = &m.resolved_apt_transaction.packages[0];
|
||||
let receipt = PrefetchReceipt {
|
||||
schema_version: 1,
|
||||
sha256: package.sha256.clone(),
|
||||
size: package.size,
|
||||
sealed_at_ms: 1000,
|
||||
};
|
||||
receipt.validate(package, 1000).unwrap();
|
||||
assert!(receipt.validate(package, 999).is_err());
|
||||
let changed = PackageArchive {
|
||||
size: 1,
|
||||
..package.clone()
|
||||
};
|
||||
assert!(receipt.validate(&changed, 1001).is_err());
|
||||
let changed = PackageArchive {
|
||||
sha256: "0".repeat(64),
|
||||
..package.clone()
|
||||
};
|
||||
assert!(receipt.validate(&changed, 1001).is_err());
|
||||
assert!(serde_json::from_slice::<PrefetchReceipt>(br#"{"schema_version":1,"sha256":"x","size":1,"sealed_at_ms":1000,"download_url":"https://untrusted.invalid"}"#).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn consumed_parent_row_and_original_start_request_are_mandatory() {
|
||||
let (binding, request, _, now) = signed_request();
|
||||
let (job, permit) = binding.verify(&request, now).unwrap();
|
||||
// Test-only construction exercises the ledger validator without granting
|
||||
// access to the root process path or weakening the public constructor.
|
||||
let prepared = PreparedApt {
|
||||
job,
|
||||
permit: permit.clone(),
|
||||
request: request.clone(),
|
||||
manifest: manifest(true).1,
|
||||
};
|
||||
let dir = temporary();
|
||||
// SAFETY: geteuid has no preconditions or pointers.
|
||||
let uid = unsafe { libc::geteuid() };
|
||||
let mut db = crate::open_ledger(&dir, uid).unwrap();
|
||||
assert!(prepared.verify_parent_consumption(&db).is_err());
|
||||
crate::consume(&mut db, &permit).unwrap();
|
||||
assert!(prepared.verify_parent_consumption(&db).is_err());
|
||||
crate::save_start(&db, &permit, &request).unwrap();
|
||||
assert!(
|
||||
prepared
|
||||
.verify_parent_consumption(&db)
|
||||
.unwrap()
|
||||
.starts_with("apt-")
|
||||
);
|
||||
let mut forged = prepared;
|
||||
forged.request.job_bytes.push(b' ');
|
||||
assert!(forged.verify_parent_consumption(&db).is_err());
|
||||
forged.request = request;
|
||||
let mut outcome = Outcome::unknown("");
|
||||
outcome.state = "succeeded".into();
|
||||
crate::finish(&db, &permit, &outcome).unwrap();
|
||||
assert!(forged.verify_parent_consumption(&db).is_err());
|
||||
drop(db);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
fn manifest(bootstrap: bool) -> (ProviderConfig, AptExecutionManifest) {
|
||||
let transaction = ResolvedAptTransaction {
|
||||
schema_version: 1,
|
||||
recipe_id: INSTALL_RECIPE.into(),
|
||||
recipe_version: "1".into(),
|
||||
platform: "ubuntu-24.04-amd64".into(),
|
||||
resolver_config_version: "rmm-apt-local-v1".into(),
|
||||
no_reboot: true,
|
||||
status_fingerprint: "a".repeat(64),
|
||||
baseline_sha256: hash(b"{}"),
|
||||
packages: vec![PackageArchive {
|
||||
name: "rmm-mvp-test".into(),
|
||||
architecture: "all".into(),
|
||||
old_version: None,
|
||||
new_version: "1.0".into(),
|
||||
origin: "rmm-test".into(),
|
||||
sha256: INSTALL_SHA.into(),
|
||||
size: 20672,
|
||||
archive_path: format!("{BASE}/archives/{INSTALL_SHA}.deb"),
|
||||
}],
|
||||
};
|
||||
let bytes = serde_json::to_vec(&transaction).unwrap();
|
||||
let config = ProviderConfig {
|
||||
schema_version: 1,
|
||||
execution_profile: "dev-test".into(),
|
||||
allow_fixture_bootstrap: true,
|
||||
allowed_recipes: vec![INSTALL_RECIPE.into(), UPDATE_RECIPE.into()],
|
||||
runtime_sha256: "d".repeat(64),
|
||||
apt_config_sha256: "e".repeat(64),
|
||||
};
|
||||
let manifest = AptExecutionManifest {
|
||||
kind: "rmm.apt.helper-action".into(),
|
||||
schema_version: 2,
|
||||
action: if bootstrap {
|
||||
"apt-native-acceptance"
|
||||
} else {
|
||||
"apt-execute"
|
||||
}
|
||||
.into(),
|
||||
execution_profile: "dev-test".into(),
|
||||
transaction_sha256: hash(&bytes),
|
||||
resolved_apt_transaction: transaction,
|
||||
transaction_bytes: bytes,
|
||||
provider_sha256: hash(PYTHON),
|
||||
hook_sha256: hash(HOOK_BYTES),
|
||||
apt_config_sha256: config.apt_config_sha256.clone(),
|
||||
runtime_sha256: config.runtime_sha256.clone(),
|
||||
test_result_id: "fixture-test-1".into(),
|
||||
};
|
||||
(config, manifest)
|
||||
}
|
||||
fn temporary() -> PathBuf {
|
||||
let dir = Path::new("/tmp/opencode").join(format!("apt-helper-{}", Uuid::new_v4()));
|
||||
fs::DirBuilder::new().mode(0o700).create(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
fn signed_request() -> (
|
||||
Binding,
|
||||
Request,
|
||||
PKey<openssl::pkey::Private>,
|
||||
DateTime<Utc>,
|
||||
) {
|
||||
let key = PKey::generate_ed25519().unwrap();
|
||||
let raw = key.raw_public_key().unwrap();
|
||||
let now = Utc::now();
|
||||
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: hex::encode(&raw),
|
||||
};
|
||||
let job = 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(),
|
||||
// Existing supported typed action supplies a valid cryptographic/ledger
|
||||
// fixture only. It is never executed and the APT policy rejects it.
|
||||
action: Action::RunScript {
|
||||
interpreter: "posix_sh".into(),
|
||||
script_utf8: "true".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
},
|
||||
execution_identity: "root".into(),
|
||||
not_before: now - chrono::Duration::seconds(1),
|
||||
start_before: now + chrono::Duration::seconds(59),
|
||||
max_runtime_seconds: 300,
|
||||
max_output_bytes: 4096,
|
||||
};
|
||||
let bytes = encode(&job).unwrap();
|
||||
let permit = ExecutionPermitPayload {
|
||||
domain: "rmm.execution-permit".into(),
|
||||
schema_version: 1,
|
||||
grant_id: Uuid::new_v4(),
|
||||
authorization_id: Uuid::new_v4(),
|
||||
tenant_id: job.tenant_id,
|
||||
asset_id: job.asset_id,
|
||||
agent_id: job.agent_id,
|
||||
enrollment_generation: 1,
|
||||
assignment_version: 1,
|
||||
job_id: job.job_id,
|
||||
attempt_id: job.attempt_id,
|
||||
plan_hash: hash(b"approved fixture plan"),
|
||||
job_payload_hash: hash(&bytes),
|
||||
action: "run_script".into(),
|
||||
execution_identity: "root".into(),
|
||||
not_before: job.not_before,
|
||||
start_before: job.start_before,
|
||||
max_runtime_seconds: 300,
|
||||
key_id: hash(&raw),
|
||||
};
|
||||
let permit_bytes = encode(&permit).unwrap();
|
||||
let signature = Signer::new_without_digest(&key)
|
||||
.unwrap()
|
||||
.sign_oneshot_to_vec(&permit_bytes)
|
||||
.unwrap();
|
||||
(
|
||||
binding,
|
||||
Request {
|
||||
job_bytes: bytes,
|
||||
permit_bytes,
|
||||
signature,
|
||||
plan_hash: permit.plan_hash,
|
||||
authorization_id: permit.authorization_id,
|
||||
},
|
||||
key,
|
||||
now,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn narrow_manifest_exact_bytes_and_code_pins() {
|
||||
let (config, m) = manifest(true);
|
||||
validate_manifest(&m, "apt_native_acceptance", &config).unwrap();
|
||||
for field in [
|
||||
"provider_sha256",
|
||||
"hook_sha256",
|
||||
"runtime_sha256",
|
||||
"transaction_sha256",
|
||||
"apt_config_sha256",
|
||||
] {
|
||||
let mut v = serde_json::to_value(&m).unwrap();
|
||||
v[field] = serde_json::json!("0".repeat(64));
|
||||
let changed: AptExecutionManifest = serde_json::from_value(v).unwrap();
|
||||
assert!(
|
||||
validate_manifest(&changed, "apt_native_acceptance", &config).is_err(),
|
||||
"{field}"
|
||||
);
|
||||
}
|
||||
let mut changed = m.clone();
|
||||
changed.transaction_bytes.push(b' ');
|
||||
assert!(validate_manifest(&changed, "apt_native_acceptance", &config).is_err());
|
||||
changed.transaction_sha256 = hash(&changed.transaction_bytes);
|
||||
validate_manifest(&changed, "apt_native_acceptance", &config).unwrap(); // exact approved whitespace is retained
|
||||
changed.resolved_apt_transaction.packages[0].new_version = "1.1".into();
|
||||
assert!(validate_manifest(&changed, "apt_native_acceptance", &config).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn bootstrap_is_not_normal_script_or_production_and_recipe_is_local_policy() {
|
||||
let (mut config, m) = manifest(true);
|
||||
for action in ["run_script", "ensure_package", "apply_updates"] {
|
||||
assert!(validate_manifest(&m, action, &config).is_err());
|
||||
}
|
||||
config.allow_fixture_bootstrap = false;
|
||||
assert!(validate_manifest(&m, "apt_native_acceptance", &config).is_err());
|
||||
config.allow_fixture_bootstrap = true;
|
||||
config.execution_profile = "production".into();
|
||||
assert!(config.validate().is_err());
|
||||
config.execution_profile = "dev-test".into();
|
||||
config.allowed_recipes = vec![UPDATE_RECIPE.into()];
|
||||
assert!(validate_manifest(&m, "apt_native_acceptance", &config).is_err());
|
||||
let mut changed = m.clone();
|
||||
changed
|
||||
.resolved_apt_transaction
|
||||
.packages
|
||||
.push(changed.resolved_apt_transaction.packages[0].clone());
|
||||
assert!(changed.resolved_apt_transaction.validate_fixture().is_err());
|
||||
}
|
||||
#[test]
|
||||
fn duplicate_fields_aliases_and_unsigned_additions_never_authorize() {
|
||||
let (binding, request, _, now) = signed_request();
|
||||
let (config, _) = manifest(false);
|
||||
let (job, _) = binding.verify(&request, now).unwrap();
|
||||
assert!(
|
||||
validate_signed_manifest(&job, &request.job_bytes, &config)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("APT_MANIFEST_NOT_CONFIGURED")
|
||||
);
|
||||
let mut forged = request.clone();
|
||||
forged.signature[0] ^= 1;
|
||||
assert!(prepare(&binding, &forged, &config, now).is_err());
|
||||
forged = request.clone();
|
||||
let mut v: serde_json::Value = serde_json::from_slice(&forged.job_bytes).unwrap();
|
||||
v["action"]["apt_manifest"] = serde_json::to_value(manifest(false).1).unwrap();
|
||||
forged.job_bytes = serde_json::to_vec(&v).unwrap();
|
||||
assert!(prepare(&binding, &forged, &config, now).is_err()); // old signed permit cannot bind any extra field
|
||||
let raw = br#"{"action":"apply_updates","apt_manifest":null,"apt_manifest":null}"#;
|
||||
assert!(serde_json::from_slice::<ActionCarrier>(raw).is_err());
|
||||
let mut m = serde_json::to_value(manifest(false).1).unwrap();
|
||||
m["parameters"] = serde_json::json!({});
|
||||
assert!(serde_json::from_value::<AptExecutionManifest>(m).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn create_only_payloads_fsync_and_hostile_files_fail_closed() {
|
||||
let dir = temporary();
|
||||
let file = dir.join("payload");
|
||||
write_once(&file, b"known", 0o600).unwrap();
|
||||
assert_eq!(fs::read(&file).unwrap(), b"known");
|
||||
assert!(write_once(&file, b"replacement", 0o600).is_err());
|
||||
let link = dir.join("link");
|
||||
std::os::unix::fs::symlink(&file, &link).unwrap();
|
||||
assert!(write_once(&link, b"replacement", 0o600).is_err());
|
||||
assert!(read_sealed(&file, 64).is_err()); // never accept this unprivileged /tmp store as root trusted
|
||||
assert!(verify_installation().is_err()); // no deployment/mutation during tests
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
#[test]
|
||||
fn no_artifact_or_record_is_not_success() {
|
||||
let (_, m) = manifest(true);
|
||||
let (binding, request, _, now) = signed_request();
|
||||
let (_, p) = binding.verify(&request, now).unwrap();
|
||||
assert!(verify_prefetched(&m, &p).is_err());
|
||||
assert!(
|
||||
map_driver_result(
|
||||
br#"{"effect_state":"verified","code":"POSTCONDITIONS_VERIFIED","evidence":{}}"#,
|
||||
Some(0),
|
||||
false,
|
||||
&m,
|
||||
"ledger"
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(map_driver_result(b"not-json", Some(0), false, &m, "ledger").is_err());
|
||||
}
|
||||
#[test]
|
||||
fn structured_effect_state_not_process_exit_and_armed_failures_stay_unknown() {
|
||||
let (_, m) = manifest(true);
|
||||
let ledger = "ledger-1";
|
||||
let p = &m.resolved_apt_transaction.packages[0];
|
||||
let result = serde_json::json!({"effect_state":"verified","code":"POSTCONDITIONS_VERIFIED","evidence":{
|
||||
"test_acceptance":true,"noProductionEvidence":true,"test_result_id":m.test_result_id,"native_record_sha256":"a".repeat(64),
|
||||
"snapshot_sha256":"b".repeat(64),"fixture_payload_sha256":hash(b"1.0\n"),"effect_armed_ledger_id":ledger,"reboot_required":false,
|
||||
"packages":[{"name":p.name,"architecture":p.architecture,"version":p.new_version}]}});
|
||||
let bytes = serde_json::to_vec(&result).unwrap();
|
||||
assert_eq!(
|
||||
map_driver_result(&bytes, Some(0), true, &m, ledger)
|
||||
.unwrap()
|
||||
.state,
|
||||
"succeeded"
|
||||
);
|
||||
assert!(map_driver_result(&bytes, Some(1), true, &m, ledger).is_err());
|
||||
assert!(map_driver_result(&bytes, Some(0), true, &m, "wrong").is_err());
|
||||
let failed = serde_json::json!({"effect_state":"known_failed","code":"START_DEADLINE","evidence":{"test_acceptance":true,"noProductionEvidence":true}});
|
||||
let bytes = serde_json::to_vec(&failed).unwrap();
|
||||
assert_eq!(
|
||||
map_driver_result(&bytes, Some(0), false, &m, ledger)
|
||||
.unwrap()
|
||||
.state,
|
||||
"failed"
|
||||
);
|
||||
assert_eq!(
|
||||
map_driver_result(&bytes, Some(0), true, &m, ledger)
|
||||
.unwrap()
|
||||
.state,
|
||||
"unknown"
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn mapped_unknown_keeps_parent_resource_reservation() {
|
||||
let (binding, request, _, now) = signed_request();
|
||||
let (_, p) = binding.verify(&request, now).unwrap();
|
||||
let dir = temporary();
|
||||
let uid = unsafe { libc::geteuid() };
|
||||
let mut db = crate::open_ledger(&dir, uid).unwrap();
|
||||
crate::consume(&mut db, &p).unwrap();
|
||||
crate::save_start(&db, &p, &request).unwrap();
|
||||
let (_, m) = manifest(false);
|
||||
let result = map_driver_result(
|
||||
br#"{"effect_state":"unknown","code":"EFFECT_UNCERTAIN","evidence":{}}"#,
|
||||
Some(0),
|
||||
true,
|
||||
&m,
|
||||
"ledger",
|
||||
)
|
||||
.unwrap();
|
||||
crate::finish(&db, &p, &result).unwrap();
|
||||
let mut next = p.clone();
|
||||
next.grant_id = Uuid::new_v4();
|
||||
next.job_id = Uuid::new_v4();
|
||||
assert!(crate::consume(&mut db, &next).is_err());
|
||||
drop(db);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verified_no_change_is_bound_not_bootstrap_and_consumes_attempt_once() {
|
||||
let (_, m) = manifest(false);
|
||||
let ledger = "ledger-noop";
|
||||
let p = &m.resolved_apt_transaction.packages[0];
|
||||
let result = serde_json::json!({"effect_state":"verified_no_change","code":"POSTCONDITION_ALREADY_MET","evidence":{
|
||||
"changed":false,"already_desired":true,"postcondition_already_met":true,"transaction_executed":false,
|
||||
"snapshot_sha256":m.resolved_apt_transaction.baseline_sha256,"effect_armed_ledger_id":ledger,
|
||||
"fixture_payload_sha256":hash(format!("{}\n",p.new_version).as_bytes()),"reboot_required":false,
|
||||
"packages":[{"name":p.name,"architecture":p.architecture,"version":p.new_version}]}});
|
||||
let bytes = serde_json::to_vec(&result).unwrap();
|
||||
let outcome = map_driver_result(&bytes, Some(0), false, &m, ledger).unwrap();
|
||||
assert_eq!(outcome.state, "succeeded");
|
||||
assert_eq!(outcome.evidence["apt"]["changed"], false);
|
||||
assert!(map_driver_result(&bytes, Some(0), true, &m, ledger).is_err());
|
||||
assert!(map_driver_result(&bytes, Some(0), false, &m, "other-ledger").is_err());
|
||||
assert!(map_driver_result(&bytes, Some(0), false, &manifest(true).1, ledger).is_err());
|
||||
for (field, value) in [
|
||||
("changed", serde_json::json!(true)),
|
||||
("transaction_executed", serde_json::json!(true)),
|
||||
("snapshot_sha256", serde_json::json!("0".repeat(64))),
|
||||
("packages", serde_json::json!([])),
|
||||
] {
|
||||
let mut bad = result.clone();
|
||||
bad["evidence"][field] = value;
|
||||
assert!(
|
||||
map_driver_result(
|
||||
&serde_json::to_vec(&bad).unwrap(),
|
||||
Some(0),
|
||||
false,
|
||||
&m,
|
||||
ledger
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
let (binding, request, _, now) = signed_request();
|
||||
let (_, permit) = binding.verify(&request, now).unwrap();
|
||||
let dir = temporary();
|
||||
// SAFETY: geteuid has no preconditions.
|
||||
let mut db = crate::open_ledger(&dir, unsafe { libc::geteuid() }).unwrap();
|
||||
crate::consume(&mut db, &permit).unwrap();
|
||||
crate::save_start(&db, &permit, &request).unwrap();
|
||||
crate::finish(&db, &permit, &outcome).unwrap();
|
||||
assert!(crate::consume(&mut db, &permit).is_err());
|
||||
let mut another_grant = permit.clone();
|
||||
another_grant.grant_id = Uuid::new_v4();
|
||||
assert!(crate::consume(&mut db, &another_grant).is_err());
|
||||
drop(db);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
//! Typed, root-peer authenticated synchronization/policy IPC. No action or
|
||||
//! readiness flag supplied by the network process grants root authority.
|
||||
use crate::{
|
||||
Binding,
|
||||
readiness::Identity,
|
||||
reconcile::{SignedResponse, Snapshot},
|
||||
};
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use serde::{Deserialize, Serialize, de::DeserializeOwned};
|
||||
use std::{
|
||||
fs,
|
||||
io::{Read, Write},
|
||||
os::{
|
||||
fd::AsRawFd,
|
||||
unix::{
|
||||
fs::{FileTypeExt, MetadataExt},
|
||||
net::UnixStream,
|
||||
},
|
||||
},
|
||||
path::Path,
|
||||
time::Duration,
|
||||
};
|
||||
use uuid::Uuid;
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(tag = "operation", deny_unknown_fields)]
|
||||
pub enum Request {
|
||||
#[serde(rename = "sync_snapshot_v1")]
|
||||
Snapshot {
|
||||
challenge: Uuid,
|
||||
identity: Identity,
|
||||
generation: u64,
|
||||
},
|
||||
#[serde(rename = "sync_apply_v1")]
|
||||
Apply {
|
||||
challenge: Uuid,
|
||||
identity: Identity,
|
||||
response: SignedResponse,
|
||||
request_bytes: Vec<u8>,
|
||||
},
|
||||
#[serde(rename = "general_policy_v1")]
|
||||
Policy { challenge: Uuid, identity: Identity },
|
||||
}
|
||||
impl Request {
|
||||
pub fn binding(&self) -> (Uuid, &Identity) {
|
||||
match self {
|
||||
Self::Snapshot {
|
||||
challenge,
|
||||
identity,
|
||||
..
|
||||
}
|
||||
| Self::Apply {
|
||||
challenge,
|
||||
identity,
|
||||
..
|
||||
}
|
||||
| Self::Policy {
|
||||
challenge,
|
||||
identity,
|
||||
} => (*challenge, identity),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Policy {
|
||||
pub schema_version: u32,
|
||||
pub profile: String,
|
||||
pub identity: Identity,
|
||||
pub allowed_services: Vec<String>,
|
||||
pub allow_root_scripts: bool,
|
||||
pub allow_reboot: bool,
|
||||
}
|
||||
impl Policy {
|
||||
pub fn sha256(&self) -> Result<String> {
|
||||
Ok(rmm_domain::jobs::hash(&serde_json::to_vec(self)?))
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Response {
|
||||
pub schema_version: u32,
|
||||
pub challenge: Uuid,
|
||||
pub identity: Identity,
|
||||
pub profile: String,
|
||||
pub policy_sha256: String,
|
||||
pub policy: Option<Policy>,
|
||||
pub snapshot: Option<Snapshot>,
|
||||
pub unlocked_grants: Vec<Uuid>,
|
||||
pub ledger_device: u64,
|
||||
pub ledger_inode: u64,
|
||||
pub lock_device: u64,
|
||||
pub lock_inode: u64,
|
||||
}
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct GeneralPin {
|
||||
pub schema_version: u32,
|
||||
pub profile: String,
|
||||
pub identity: Identity,
|
||||
pub policy_sha256: String,
|
||||
}
|
||||
impl GeneralPin {
|
||||
pub fn read(path: &Path, binding: &Binding) -> Result<Self> {
|
||||
trusted(path, false)?;
|
||||
ensure!(fs::metadata(path)?.len() <= 8192, "POLICY_PIN_LIMIT");
|
||||
let pin: Self = serde_json::from_slice(&fs::read(path)?)?;
|
||||
ensure!(
|
||||
pin.schema_version == 1
|
||||
&& pin.profile == "general"
|
||||
&& pin.identity == Identity::from_binding(binding)?
|
||||
&& digest(&pin.policy_sha256),
|
||||
"POLICY_PIN_BINDING"
|
||||
);
|
||||
Ok(pin)
|
||||
}
|
||||
}
|
||||
fn digest(s: &str) -> bool {
|
||||
s.len() == 64
|
||||
&& s.bytes()
|
||||
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
|
||||
}
|
||||
pub fn trusted(path: &Path, socket: bool) -> Result<()> {
|
||||
ensure!(path.is_absolute(), "HELPER_ABSOLUTE_PATH");
|
||||
for (index, parent) in path.ancestors().enumerate() {
|
||||
let m = fs::symlink_metadata(parent)?;
|
||||
ensure!(
|
||||
!m.file_type().is_symlink()
|
||||
&& m.uid() == 0
|
||||
&& (m.mode() & 0o022 == 0 || (socket && index == 0 && m.mode() & 0o007 == 0)),
|
||||
"UNTRUSTED_HELPER_PATH"
|
||||
);
|
||||
}
|
||||
ensure!(
|
||||
if socket {
|
||||
fs::symlink_metadata(path)?.file_type().is_socket()
|
||||
} else {
|
||||
fs::metadata(path)?.is_file()
|
||||
},
|
||||
"HELPER_PATH_TYPE"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
pub fn exchange<Q: Serialize, R: DeserializeOwned>(
|
||||
socket: &Path,
|
||||
request: &Q,
|
||||
timeout: Duration,
|
||||
max_response: usize,
|
||||
) -> Result<R> {
|
||||
trusted(socket, true)?;
|
||||
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: live socket and correctly aligned writable credentials storage.
|
||||
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: successful getsockopt initialized the full credentials.
|
||||
ensure!(
|
||||
unsafe { credentials.assume_init() }.uid == 0,
|
||||
"HELPER_PEER_NOT_ROOT"
|
||||
);
|
||||
stream.set_read_timeout(Some(timeout))?;
|
||||
stream.set_write_timeout(Some(Duration::from_secs(5)))?;
|
||||
let bytes = serde_json::to_vec(request)?;
|
||||
ensure!(
|
||||
bytes.len() <= 8 * 1024 * 1024,
|
||||
"HELPER_CONTROL_REQUEST_LIMIT"
|
||||
);
|
||||
stream.write_all(&u32::try_from(bytes.len())?.to_be_bytes())?;
|
||||
stream.write_all(&bytes)?;
|
||||
let mut length = [0; 4];
|
||||
stream.read_exact(&mut length)?;
|
||||
let length = u32::from_be_bytes(length) as usize;
|
||||
ensure!(length <= max_response, "HELPER_CONTROL_RESPONSE_LIMIT");
|
||||
let mut bytes = vec![0; length];
|
||||
stream.read_exact(&mut bytes)?;
|
||||
Ok(serde_json::from_slice(&bytes)?)
|
||||
}
|
||||
pub fn call(socket: &Path, binding: &Binding, request: &Request) -> Result<Response> {
|
||||
let response: Response = exchange(socket, request, Duration::from_secs(10), 8 * 1024 * 1024)?;
|
||||
validate_response(request, &response, binding)?;
|
||||
Ok(response)
|
||||
}
|
||||
pub fn validate_response(request: &Request, response: &Response, binding: &Binding) -> Result<()> {
|
||||
let (challenge, identity) = request.binding();
|
||||
ensure!(
|
||||
!challenge.is_nil()
|
||||
&& response.schema_version == 1
|
||||
&& response.challenge == challenge
|
||||
&& &response.identity == identity
|
||||
&& response.identity == Identity::from_binding(binding)?
|
||||
&& matches!(response.profile.as_str(), "general" | "apt_only")
|
||||
&& response.ledger_inode != 0
|
||||
&& response.lock_inode != 0,
|
||||
"HELPER_CONTROL_RESPONSE_BINDING"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
pub fn general_probe(socket: &Path, binding: &Binding, pin: &GeneralPin) -> Result<Response> {
|
||||
let request = Request::Policy {
|
||||
challenge: Uuid::new_v4(),
|
||||
identity: Identity::from_binding(binding)?,
|
||||
};
|
||||
let response = call(socket, binding, &request)?;
|
||||
let policy = response.policy.as_ref().context("GENERAL_POLICY_MISSING")?;
|
||||
ensure!(
|
||||
response.profile == "general"
|
||||
&& policy.profile == "general"
|
||||
&& response.policy_sha256 == pin.policy_sha256
|
||||
&& policy.sha256()? == pin.policy_sha256
|
||||
&& policy.identity == pin.identity,
|
||||
"GENERAL_POLICY_PROOF_MISMATCH"
|
||||
);
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn binding() -> 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: hex::encode(
|
||||
openssl::pkey::PKey::generate_ed25519()
|
||||
.unwrap()
|
||||
.raw_public_key()
|
||||
.unwrap(),
|
||||
),
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn control_nonce_identity_and_profile_are_not_unsigned_readiness() {
|
||||
let b = binding();
|
||||
let identity = Identity::from_binding(&b).unwrap();
|
||||
let challenge = Uuid::new_v4();
|
||||
let q = Request::Policy {
|
||||
challenge,
|
||||
identity: identity.clone(),
|
||||
};
|
||||
let mut r = Response {
|
||||
schema_version: 1,
|
||||
challenge,
|
||||
identity,
|
||||
profile: "general".into(),
|
||||
policy_sha256: "ab".repeat(32),
|
||||
policy: None,
|
||||
snapshot: None,
|
||||
unlocked_grants: vec![],
|
||||
ledger_device: 1,
|
||||
ledger_inode: 2,
|
||||
lock_device: 1,
|
||||
lock_inode: 3,
|
||||
};
|
||||
validate_response(&q, &r, &b).unwrap();
|
||||
r.challenge = Uuid::new_v4();
|
||||
assert!(validate_response(&q, &r, &b).is_err());
|
||||
r.challenge = challenge;
|
||||
r.identity.assignment_version = 2;
|
||||
assert!(validate_response(&q, &r, &b).is_err());
|
||||
r.identity = Identity::from_binding(&b).unwrap();
|
||||
r.profile = "fake_root".into();
|
||||
assert!(validate_response(&q, &r, &b).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn apply_preserves_original_signed_bytes_and_rejects_unlock_additions() {
|
||||
let b = binding();
|
||||
let q = Request::Apply {
|
||||
challenge: Uuid::new_v4(),
|
||||
identity: Identity::from_binding(&b).unwrap(),
|
||||
response: SignedResponse {
|
||||
decision_bytes: b" exact signed bytes\n".to_vec(),
|
||||
signature: vec![7; 64],
|
||||
},
|
||||
request_bytes: vec![10, 3, 1, 2, 3],
|
||||
};
|
||||
let bytes = serde_json::to_vec(&q).unwrap();
|
||||
let roundtrip: Request = serde_json::from_slice(&bytes).unwrap();
|
||||
let Request::Apply {
|
||||
response,
|
||||
request_bytes,
|
||||
..
|
||||
} = roundtrip
|
||||
else {
|
||||
panic!("wrong operation")
|
||||
};
|
||||
assert_eq!(response.decision_bytes, b" exact signed bytes\n");
|
||||
assert_eq!(request_bytes, vec![10, 3, 1, 2, 3]);
|
||||
let mut value = serde_json::to_value(q).unwrap();
|
||||
value["unlock"] = serde_json::json!(true);
|
||||
assert!(serde_json::from_value::<Request>(value).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn general_policy_hash_binds_identity_units_and_broad_admin_flags() {
|
||||
let b = binding();
|
||||
let p = Policy {
|
||||
schema_version: 1,
|
||||
profile: "general".into(),
|
||||
identity: Identity::from_binding(&b).unwrap(),
|
||||
allowed_services: vec!["rmm-acceptance.service".into()],
|
||||
allow_root_scripts: false,
|
||||
allow_reboot: false,
|
||||
};
|
||||
let old = p.sha256().unwrap();
|
||||
let mut changed = p.clone();
|
||||
changed.allow_root_scripts = true;
|
||||
assert_ne!(old, changed.sha256().unwrap());
|
||||
changed = p.clone();
|
||||
changed.allowed_services.push("other.service".into());
|
||||
assert_ne!(old, changed.sha256().unwrap());
|
||||
changed = p;
|
||||
changed.identity.assignment_version += 1;
|
||||
assert_ne!(old, changed.sha256().unwrap());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,466 @@
|
||||
//! 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 control;
|
||||
pub mod readiness;
|
||||
pub mod reconcile;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use chrono::{DateTime, Utc};
|
||||
use openssl::{
|
||||
pkey::{Id, PKey},
|
||||
sign::Verifier,
|
||||
};
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Binding {
|
||||
pub tenant_id: Uuid,
|
||||
pub asset_id: Uuid,
|
||||
pub agent_id: Uuid,
|
||||
pub enrollment_generation: u64,
|
||||
pub assignment_version: u64,
|
||||
pub public_key_hex: String,
|
||||
}
|
||||
impl Binding {
|
||||
pub fn job(&self, bytes: &[u8]) -> Result<JobPayload> {
|
||||
ensure!(bytes.len() <= 65536, "JOB_SIZE");
|
||||
let j: JobPayload = serde_json::from_slice(bytes)?;
|
||||
ensure!(
|
||||
j.schema_version == 1
|
||||
&& j.tenant_id == self.tenant_id
|
||||
&& j.asset_id == self.asset_id
|
||||
&& j.agent_id == self.agent_id
|
||||
&& j.enrollment_generation == self.enrollment_generation
|
||||
&& j.assignment_version == self.assignment_version,
|
||||
"IDENTITY_BINDING"
|
||||
);
|
||||
ensure!(
|
||||
j.action.validate()
|
||||
&& (1..=3600).contains(&j.max_runtime_seconds)
|
||||
&& (1..=262144).contains(&j.max_output_bytes)
|
||||
&& j.not_before < j.start_before,
|
||||
"INVALID_JOB"
|
||||
);
|
||||
Ok(j)
|
||||
}
|
||||
pub fn verify(
|
||||
&self,
|
||||
request: &Request,
|
||||
now: DateTime<Utc>,
|
||||
) -> Result<(JobPayload, ExecutionPermitPayload)> {
|
||||
let job = self.job(&request.job_bytes)?;
|
||||
ensure!(
|
||||
request.permit_bytes.len() <= 8192 && request.signature.len() == 64,
|
||||
"PERMIT_SIZE"
|
||||
);
|
||||
let raw = hex::decode(&self.public_key_hex)?;
|
||||
ensure!(raw.len() == 32, "TRUST_KEY_SIZE");
|
||||
let key = PKey::public_key_from_raw_bytes(&raw, Id::ED25519)?;
|
||||
ensure!(
|
||||
Verifier::new_without_digest(&key)?
|
||||
.verify_oneshot(&request.signature, &request.permit_bytes)?,
|
||||
"INVALID_SIGNATURE"
|
||||
);
|
||||
let p: ExecutionPermitPayload = serde_json::from_slice(&request.permit_bytes)?;
|
||||
ensure!(
|
||||
p.domain == "rmm.execution-permit"
|
||||
&& p.schema_version == 1
|
||||
&& p.key_id == hash(&raw)
|
||||
&& !p.grant_id.is_nil()
|
||||
&& !p.authorization_id.is_nil(),
|
||||
"PERMIT_DOMAIN"
|
||||
);
|
||||
ensure!(
|
||||
p.authorization_id == request.authorization_id
|
||||
&& p.plan_hash == request.plan_hash
|
||||
&& p.plan_hash.len() == 64
|
||||
&& hex::decode(&p.plan_hash)?.len() == 32
|
||||
&& p.job_payload_hash == hash(&request.job_bytes)
|
||||
&& p.tenant_id == job.tenant_id
|
||||
&& p.asset_id == job.asset_id
|
||||
&& p.agent_id == job.agent_id
|
||||
&& p.enrollment_generation == job.enrollment_generation
|
||||
&& p.assignment_version == job.assignment_version
|
||||
&& p.job_id == job.job_id
|
||||
&& p.attempt_id == job.attempt_id
|
||||
&& p.action == job.action.name()
|
||||
&& p.execution_identity == job.execution_identity
|
||||
&& p.max_runtime_seconds == job.max_runtime_seconds,
|
||||
"PERMIT_BINDING"
|
||||
);
|
||||
ensure!(
|
||||
p.not_before >= job.not_before
|
||||
&& p.start_before <= job.start_before
|
||||
&& p.not_before < p.start_before
|
||||
&& (p.start_before - p.not_before).num_seconds() <= 60
|
||||
&& now >= p.not_before
|
||||
&& now < p.start_before,
|
||||
"PERMIT_TIME"
|
||||
);
|
||||
Ok((job, p))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Request {
|
||||
pub job_bytes: Vec<u8>,
|
||||
pub permit_bytes: Vec<u8>,
|
||||
pub signature: Vec<u8>,
|
||||
pub plan_hash: String,
|
||||
pub authorization_id: Uuid,
|
||||
}
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Outcome {
|
||||
pub state: String,
|
||||
pub stdout: Vec<u8>,
|
||||
pub stderr: Vec<u8>,
|
||||
pub exit_code: Option<i32>,
|
||||
pub output_truncated: bool,
|
||||
pub reboot_required: bool,
|
||||
pub evidence: serde_json::Value,
|
||||
pub error_code: String,
|
||||
}
|
||||
impl Outcome {
|
||||
pub fn unknown(code: &str) -> Self {
|
||||
Self {
|
||||
state: "unknown".into(),
|
||||
stdout: vec![],
|
||||
stderr: vec![],
|
||||
exit_code: None,
|
||||
output_truncated: false,
|
||||
reboot_required: false,
|
||||
evidence: serde_json::json!({"postconditions_passed":false}),
|
||||
error_code: code.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 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)?;
|
||||
db.execute_batch("PRAGMA synchronous=FULL; PRAGMA journal_mode=DELETE; PRAGMA max_page_count=16384;
|
||||
CREATE TABLE IF NOT EXISTS consumed(grant_id TEXT PRIMARY KEY, agent TEXT NOT NULL, generation INTEGER NOT NULL,
|
||||
job TEXT NOT NULL, attempt TEXT NOT NULL, result BLOB, UNIQUE(agent,generation,job,attempt));
|
||||
CREATE TABLE IF NOT EXISTS execution_evidence(grant_id TEXT PRIMARY KEY, start BLOB NOT NULL, outcome BLOB);")?;
|
||||
let check: String = db.query_row("PRAGMA integrity_check", [], |r| r.get(0))?;
|
||||
ensure!(check == "ok", "JOURNAL_INTEGRITY");
|
||||
fs::File::open(dir)?.sync_all()?;
|
||||
Ok(db)
|
||||
}
|
||||
pub fn consume(db: &mut rusqlite::Connection, p: &ExecutionPermitPayload) -> Result<()> {
|
||||
let tx = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
|
||||
// Unknown effects retain the global device lock, including across restart.
|
||||
let unresolved: i64 = tx.query_row(
|
||||
"SELECT count(*) FROM consumed WHERE result IS NULL",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(unresolved == 0, "UNRESOLVED_EFFECT_RESOURCE_LOCKED");
|
||||
tx.execute(
|
||||
"INSERT INTO consumed(grant_id,agent,generation,job,attempt) VALUES(?1,?2,?3,?4,?5)",
|
||||
rusqlite::params![
|
||||
p.grant_id.to_string(),
|
||||
p.agent_id.to_string(),
|
||||
p.enrollment_generation,
|
||||
p.job_id.to_string(),
|
||||
p.attempt_id.to_string()
|
||||
],
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
pub fn finish(
|
||||
db: &rusqlite::Connection,
|
||||
p: &ExecutionPermitPayload,
|
||||
outcome: &Outcome,
|
||||
) -> Result<()> {
|
||||
db.execute(
|
||||
"UPDATE execution_evidence SET outcome=?2 WHERE grant_id=?1",
|
||||
rusqlite::params![p.grant_id.to_string(), serde_json::to_vec(outcome)?],
|
||||
)?;
|
||||
// Unknown / awaiting reboot keep the resource reserved until a real sync
|
||||
// protocol exists. Never unlock on a process exit or a network reconnect.
|
||||
if outcome.state != "unknown" && outcome.state != "awaiting_reboot" {
|
||||
ensure!(
|
||||
db.execute(
|
||||
"UPDATE consumed SET result=?2 WHERE grant_id=?1 AND result IS NULL",
|
||||
rusqlite::params![p.grant_id.to_string(), serde_json::to_vec(outcome)?]
|
||||
)? == 1,
|
||||
"CONSUMPTION_NOT_FOUND"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Persist the original boot and exact signed request BEFORE any reboot/effect.
|
||||
/// Awaiting/unknown outcomes never release consumed.result's resource lock.
|
||||
pub fn save_start(
|
||||
db: &rusqlite::Connection,
|
||||
permit: &ExecutionPermitPayload,
|
||||
request: &Request,
|
||||
) -> Result<()> {
|
||||
let job: JobPayload = serde_json::from_slice(&request.job_bytes)?;
|
||||
let recorded_at = Utc::now();
|
||||
let deadline = match job.action {
|
||||
rmm_domain::jobs::Action::Reboot {
|
||||
reconnect_timeout_seconds,
|
||||
..
|
||||
} => Some(recorded_at + chrono::Duration::seconds(reconnect_timeout_seconds.into())),
|
||||
_ => None,
|
||||
};
|
||||
let evidence = serde_json::json!({"previous_boot_id":rmm_agent_linux::boot_id()?,
|
||||
"reserved_at":recorded_at,"reconnect_deadline":deadline,"request":request,
|
||||
"reauthentication_required":true,"postconditions_passed":false});
|
||||
db.execute(
|
||||
"INSERT INTO execution_evidence(grant_id,start) VALUES(?1,?2)",
|
||||
rusqlite::params![permit.grant_id.to_string(), serde_json::to_vec(&evidence)?],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn script(job: &JobPayload) -> Result<Outcome> {
|
||||
use rmm_agent_linux::actions::{Interpreter, ScriptRequest, run_script};
|
||||
let rmm_domain::jobs::Action::RunScript {
|
||||
interpreter,
|
||||
script_utf8,
|
||||
arguments,
|
||||
expected_stdout,
|
||||
} = &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(&request)?;
|
||||
let passed = output.code == Some(0)
|
||||
&& !output.timed_out
|
||||
&& expected_stdout
|
||||
.as_ref()
|
||||
.is_none_or(|s| !output.truncated && output.stdout == s.as_bytes());
|
||||
Ok(Outcome {
|
||||
state: if output.timed_out || 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}),
|
||||
error_code: if passed {
|
||||
""
|
||||
} 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> {
|
||||
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,
|
||||
)))?;
|
||||
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)?;
|
||||
let mut length = [0; 4];
|
||||
stream.read_exact(&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];
|
||||
stream.read_exact(&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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,733 @@
|
||||
use anyhow::{Result, ensure};
|
||||
use rmm_domain::jobs::Action;
|
||||
use rmm_privileged_helper::{
|
||||
Binding, Outcome, Request, consume, control, finish, lock_state, 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::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)]
|
||||
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,
|
||||
}
|
||||
impl Config {
|
||||
fn general_policy(&self) -> Result<control::Policy> {
|
||||
Ok(control::Policy {
|
||||
schema_version: 1,
|
||||
profile: "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,
|
||||
})
|
||||
}
|
||||
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::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"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum Incoming {
|
||||
Control(control::Request),
|
||||
Probe(rmm_privileged_helper::readiness::Request),
|
||||
Job(Request),
|
||||
}
|
||||
fn peer_allowed(stream: &UnixStream, uid: u32) -> Result<()> {
|
||||
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.
|
||||
ensure!(
|
||||
unsafe { credentials.assume_init() }.uid == uid && uid != 0,
|
||||
"PEER_DENIED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
fn policy(config: &Config, job: &rmm_domain::jobs::JobPayload) -> Result<()> {
|
||||
ensure!(
|
||||
job.execution_identity == "root",
|
||||
"HELPER_REQUIRES_EXPLICIT_ROOT_IDENTITY"
|
||||
);
|
||||
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"
|
||||
);
|
||||
match &job.action {
|
||||
Action::RunScript { interpreter, .. } => {
|
||||
ensure!(config.allow_root_scripts, "ROOT_SCRIPT_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(),
|
||||
})
|
||||
}
|
||||
fn handle(
|
||||
config: &Config,
|
||||
db: &mut rusqlite::Connection,
|
||||
stream: &mut UnixStream,
|
||||
clock: &rmm_privileged_helper::TrustedClock,
|
||||
sync: &mut reconcile::HelperSync,
|
||||
sync_clock: &reconcile::NativeClock,
|
||||
) -> Result<()> {
|
||||
use rusqlite::OptionalExtension;
|
||||
peer_allowed(stream, config.agent_uid)?;
|
||||
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 request: Request = match serde_json::from_slice::<Incoming>(&bytes)? {
|
||||
Incoming::Job(request) => {
|
||||
ensure!(size <= 512 * 1024, "JOB_REQUEST_SIZE");
|
||||
request
|
||||
}
|
||||
Incoming::Control(request) => {
|
||||
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 (mut snapshot, mut unlocked) = (None, vec![]);
|
||||
match &request {
|
||||
control::Request::Snapshot { generation, .. } => {
|
||||
snapshot = Some(sync.snapshot(
|
||||
db,
|
||||
&guard,
|
||||
*generation,
|
||||
sync_clock,
|
||||
&reconcile::NativeBoot,
|
||||
)?)
|
||||
}
|
||||
control::Request::Apply {
|
||||
response,
|
||||
request_bytes,
|
||||
..
|
||||
} => {
|
||||
let applied = 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::General,
|
||||
"GENERAL_POLICY_PROFILE"
|
||||
),
|
||||
}
|
||||
let general = config.profile == HelperProfile::General;
|
||||
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 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(),
|
||||
};
|
||||
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) => {
|
||||
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)?;
|
||||
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
|
||||
};
|
||||
consume(db, &permit)?;
|
||||
rmm_privileged_helper::save_start(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 {
|
||||
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 main() -> 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-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")],
|
||||
"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()?;
|
||||
if args == [std::ffi::OsString::from("--inspect-general-profile")] {
|
||||
ensure!(
|
||||
config.profile == HelperProfile::General,
|
||||
"GENERAL_POLICY_PROFILE"
|
||||
);
|
||||
let policy = config.general_policy()?;
|
||||
let pin = control::GeneralPin {
|
||||
schema_version: 1,
|
||||
profile: "general".into(),
|
||||
identity: policy.identity.clone(),
|
||||
policy_sha256: policy.sha256()?,
|
||||
};
|
||||
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 = lock_state(&config.state, 0)?;
|
||||
open_ledger(&config.state, 0)?
|
||||
};
|
||||
let clock = rmm_privileged_helper::TrustedClock::new();
|
||||
let sync_clock = reconcile::NativeClock::default();
|
||||
let mut sync = reconcile::HelperSync::new(config.binding.clone(), &sync_clock)?;
|
||||
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,
|
||||
&clock,
|
||||
&mut sync,
|
||||
&sync_clock,
|
||||
) {
|
||||
let text = error.to_string();
|
||||
let code = if text.len() <= 96
|
||||
&& text
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_')
|
||||
{
|
||||
text.as_str()
|
||||
} else {
|
||||
"HELPER_VALIDATION_OR_IO_FAILURE"
|
||||
};
|
||||
eprintln!("helper request rejected: {code}");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[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 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,
|
||||
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,
|
||||
},
|
||||
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());
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,612 @@
|
||||
//! Read-only nonce/identity/profile/stack-bound readiness, never an execution
|
||||
//! permit. A successful response may offer fixture bootstrap, not acceptance.
|
||||
use crate::{Binding, apt};
|
||||
use anyhow::{Result, ensure};
|
||||
use rmm_domain::jobs::hash;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
fs,
|
||||
io::{Read, Write},
|
||||
os::{
|
||||
fd::AsRawFd,
|
||||
unix::{fs::MetadataExt, net::UnixStream},
|
||||
},
|
||||
path::Path,
|
||||
};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub const SOCKET: &str = "/run/rmm-apt-helper/helper.sock";
|
||||
pub const SHARED_STATE: &str = "/var/lib/rmm-helper";
|
||||
pub const UNIT_PATH: &str = "/etc/systemd/system/rmm-apt-helper.service";
|
||||
pub const UNIT_BYTES: &[u8] = include_bytes!("../../../deploy/linux/rmm-apt-helper.service");
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Identity {
|
||||
pub tenant_id: Uuid,
|
||||
pub asset_id: Uuid,
|
||||
pub agent_id: Uuid,
|
||||
pub enrollment_generation: u64,
|
||||
pub assignment_version: u64,
|
||||
pub signing_key_id: String,
|
||||
}
|
||||
impl Identity {
|
||||
pub fn from_binding(binding: &Binding) -> Result<Self> {
|
||||
let public = hex::decode(&binding.public_key_hex)?;
|
||||
ensure!(public.len() == 32, "APT_PROBE_KEY");
|
||||
Ok(Self {
|
||||
tenant_id: binding.tenant_id,
|
||||
asset_id: binding.asset_id,
|
||||
agent_id: binding.agent_id,
|
||||
enrollment_generation: binding.enrollment_generation,
|
||||
assignment_version: binding.assignment_version,
|
||||
signing_key_id: hash(&public),
|
||||
})
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Request {
|
||||
pub operation: String,
|
||||
pub challenge: Uuid,
|
||||
pub identity: Identity,
|
||||
pub expected_stack_sha256: String,
|
||||
}
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Response {
|
||||
pub schema_version: u32,
|
||||
pub challenge: Uuid,
|
||||
pub identity: Identity,
|
||||
pub profile: String,
|
||||
pub provider_stack_sha256: String,
|
||||
pub fixture_acceptance_ready: bool,
|
||||
pub bootstrap_recipes: Vec<String>,
|
||||
pub accepted_recipes: Vec<String>,
|
||||
pub ledger_device: u64,
|
||||
pub ledger_inode: u64,
|
||||
pub lock_device: u64,
|
||||
pub lock_inode: u64,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub planning: Option<PlanningResult>,
|
||||
}
|
||||
|
||||
/// Public, fixed-fixture metadata. No full installed-package list, private
|
||||
/// artifact paths, authorization, readiness or mutation capability is exposed.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct PlanningResult {
|
||||
pub observed_at: chrono::DateTime<chrono::Utc>,
|
||||
pub fixture_package: Option<FixturePackage>,
|
||||
pub baseline_sha256: String,
|
||||
pub sealed_baseline_sha256: String,
|
||||
pub status_fingerprint: String,
|
||||
pub dpkg_updates_empty: bool,
|
||||
pub pending_triggers_empty: bool,
|
||||
pub runtime: std::collections::BTreeMap<String, serde_json::Value>,
|
||||
pub runtime_sha256: String,
|
||||
pub provider_sha256: String,
|
||||
pub hook_sha256: String,
|
||||
pub apt_config_sha256: String,
|
||||
pub prefetch: std::collections::BTreeMap<String, PlanningReceipt>,
|
||||
}
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct FixturePackage {
|
||||
pub version: String,
|
||||
pub status: String,
|
||||
}
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct PlanningReceipt {
|
||||
pub schema_version: u32,
|
||||
pub sha256: String,
|
||||
pub size: u64,
|
||||
pub sealed_at_ms: i64,
|
||||
}
|
||||
impl PlanningResult {
|
||||
pub fn validate(&self, now: chrono::DateTime<chrono::Utc>) -> Result<()> {
|
||||
ensure!(
|
||||
self.observed_at <= now
|
||||
&& now - self.observed_at < chrono::Duration::seconds(30)
|
||||
&& self.dpkg_updates_empty
|
||||
&& self.pending_triggers_empty
|
||||
&& self.baseline_sha256 == self.sealed_baseline_sha256,
|
||||
"APT_PLANNING_STATE_OR_TIME"
|
||||
);
|
||||
for value in [
|
||||
&self.baseline_sha256,
|
||||
&self.status_fingerprint,
|
||||
&self.runtime_sha256,
|
||||
&self.provider_sha256,
|
||||
&self.hook_sha256,
|
||||
&self.apt_config_sha256,
|
||||
] {
|
||||
ensure!(valid_hash(value), "APT_PLANNING_HASH");
|
||||
}
|
||||
let runtime = serde_json::to_vec(&self.runtime)?;
|
||||
ensure!(
|
||||
runtime.is_ascii()
|
||||
&& hash(&runtime) == self.runtime_sha256
|
||||
&& self.runtime.get("apt_config_sha256")
|
||||
== Some(&serde_json::json!(self.apt_config_sha256)),
|
||||
"APT_PLANNING_RUNTIME"
|
||||
);
|
||||
ensure!(self.prefetch.len() == 2, "APT_PLANNING_PREFETCH");
|
||||
for sha in [
|
||||
rmm_domain::apt_transaction::INSTALL_SHA,
|
||||
rmm_domain::apt_transaction::UPDATE_SHA,
|
||||
] {
|
||||
let receipt = self
|
||||
.prefetch
|
||||
.get(sha)
|
||||
.ok_or_else(|| anyhow::anyhow!("APT_PLANNING_PREFETCH"))?;
|
||||
ensure!(
|
||||
receipt.schema_version == 1
|
||||
&& receipt.sha256 == sha
|
||||
&& receipt.size == 20672
|
||||
&& receipt.sealed_at_ms > 0
|
||||
&& receipt.sealed_at_ms <= now.timestamp_millis(),
|
||||
"APT_PLANNING_RECEIPT"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Pin {
|
||||
pub schema_version: u32,
|
||||
pub identity: Identity,
|
||||
pub profile: String,
|
||||
pub provider_stack_sha256: String,
|
||||
}
|
||||
impl Pin {
|
||||
pub fn read(path: &Path, binding: &Binding) -> Result<Self> {
|
||||
trusted_path(path, false)?;
|
||||
ensure!(fs::metadata(path)?.len() <= 8192, "APT_PROBE_PIN_LIMIT");
|
||||
let pin: Self = serde_json::from_slice(&fs::read(path)?)?;
|
||||
ensure!(
|
||||
pin.schema_version == 1
|
||||
&& pin.profile == "apt_only"
|
||||
&& pin.identity == Identity::from_binding(binding)?
|
||||
&& valid_hash(&pin.provider_stack_sha256),
|
||||
"APT_PROBE_PIN_BINDING"
|
||||
);
|
||||
Ok(pin)
|
||||
}
|
||||
}
|
||||
fn valid_hash(value: &str) -> bool {
|
||||
value.len() == 64
|
||||
&& value
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
|
||||
}
|
||||
fn trusted_path(path: &Path, socket: bool) -> Result<()> {
|
||||
ensure!(path.is_absolute(), "APT_PROBE_ABSOLUTE_PATH");
|
||||
for (index, parent) in path.ancestors().enumerate() {
|
||||
let m = fs::symlink_metadata(parent)?;
|
||||
ensure!(
|
||||
!m.file_type().is_symlink() && m.uid() == 0 && m.mode() & 0o022 == 0
|
||||
|| (index == 0
|
||||
&& socket
|
||||
&& m.uid() == 0
|
||||
&& m.mode() & 0o007 == 0
|
||||
&& !m.file_type().is_symlink()),
|
||||
"APT_PROBE_UNTRUSTED_PATH"
|
||||
);
|
||||
}
|
||||
if socket {
|
||||
use std::os::unix::fs::FileTypeExt;
|
||||
ensure!(
|
||||
fs::symlink_metadata(path)?.file_type().is_socket(),
|
||||
"APT_PROBE_NOT_SOCKET"
|
||||
);
|
||||
} else {
|
||||
ensure!(fs::metadata(path)?.is_file(), "APT_PROBE_PIN_TYPE");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn root_peer(stream: &UnixStream) -> Result<()> {
|
||||
let mut credentials = std::mem::MaybeUninit::<libc::ucred>::uninit();
|
||||
let mut size = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
|
||||
// SAFETY: correct live socket and writable, correctly aligned ucred storage.
|
||||
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>(),
|
||||
"APT_PROBE_PEER"
|
||||
);
|
||||
// SAFETY: getsockopt initialized the full object on success.
|
||||
ensure!(
|
||||
unsafe { credentials.assume_init() }.uid == 0,
|
||||
"APT_PROBE_PEER_NOT_ROOT"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
pub fn validate_response(request: &Request, response: &Response) -> Result<()> {
|
||||
ensure!(
|
||||
matches!(
|
||||
request.operation.as_str(),
|
||||
"apt_readiness_v1" | "apt_planning_v1"
|
||||
),
|
||||
"APT_PROBE_OPERATION"
|
||||
);
|
||||
if let Some(planning) = &response.planning {
|
||||
ensure!(
|
||||
request.operation == "apt_planning_v1",
|
||||
"APT_PLANNING_OPERATION"
|
||||
);
|
||||
planning.validate(chrono::Utc::now())?;
|
||||
}
|
||||
if request.operation == "apt_planning_v1" {
|
||||
ensure!(
|
||||
response.planning.is_some()
|
||||
&& !response.fixture_acceptance_ready
|
||||
&& response.bootstrap_recipes.is_empty()
|
||||
&& response.accepted_recipes.is_empty(),
|
||||
"APT_PLANNING_NOT_CAPABILITY"
|
||||
);
|
||||
}
|
||||
ensure!(
|
||||
response.schema_version == 1
|
||||
&& response.challenge == request.challenge
|
||||
&& !request.challenge.is_nil()
|
||||
&& response.identity == request.identity
|
||||
&& response.profile == "apt_only"
|
||||
&& response.provider_stack_sha256 == request.expected_stack_sha256
|
||||
&& valid_hash(&response.provider_stack_sha256)
|
||||
&& response.ledger_inode != 0
|
||||
&& response.lock_inode != 0,
|
||||
"APT_PROBE_RESPONSE_BINDING"
|
||||
);
|
||||
ensure!(
|
||||
response.accepted_recipes.len() <= 2
|
||||
&& response
|
||||
.accepted_recipes
|
||||
.iter()
|
||||
.all(|r| matches!(r.as_str(), apt::INSTALL_RECIPE | apt::UPDATE_RECIPE)),
|
||||
"APT_PROBE_RECIPE_SCOPE"
|
||||
);
|
||||
ensure!(
|
||||
response.bootstrap_recipes.len() <= 2
|
||||
&& response
|
||||
.bootstrap_recipes
|
||||
.iter()
|
||||
.all(|r| matches!(r.as_str(), apt::INSTALL_RECIPE | apt::UPDATE_RECIPE))
|
||||
&& (response.fixture_acceptance_ready || response.bootstrap_recipes.is_empty()),
|
||||
"APT_PROBE_BOOTSTRAP_SCOPE"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
pub fn probe(socket: &Path, binding: &Binding, pin: &Pin) -> Result<Response> {
|
||||
probe_operation(socket, binding, pin, "apt_readiness_v1")
|
||||
}
|
||||
pub fn planning(socket: &Path, binding: &Binding, pin: &Pin) -> Result<Response> {
|
||||
probe_operation(socket, binding, pin, "apt_planning_v1")
|
||||
}
|
||||
fn probe_operation(
|
||||
socket: &Path,
|
||||
binding: &Binding,
|
||||
pin: &Pin,
|
||||
operation: &str,
|
||||
) -> Result<Response> {
|
||||
ensure!(
|
||||
socket == Path::new(SOCKET)
|
||||
&& pin.identity == Identity::from_binding(binding)?
|
||||
&& pin.profile == "apt_only"
|
||||
&& pin.schema_version == 1,
|
||||
"APT_PROBE_ROUTE"
|
||||
);
|
||||
trusted_path(socket, true)?;
|
||||
let mut stream = UnixStream::connect(socket)?;
|
||||
root_peer(&stream)?;
|
||||
stream.set_read_timeout(Some(std::time::Duration::from_secs(5)))?;
|
||||
stream.set_write_timeout(Some(std::time::Duration::from_secs(5)))?;
|
||||
let request = Request {
|
||||
operation: operation.into(),
|
||||
challenge: Uuid::new_v4(),
|
||||
identity: pin.identity.clone(),
|
||||
expected_stack_sha256: pin.provider_stack_sha256.clone(),
|
||||
};
|
||||
let bytes = serde_json::to_vec(&request)?;
|
||||
stream.write_all(&(u32::try_from(bytes.len())?).to_be_bytes())?;
|
||||
stream.write_all(&bytes)?;
|
||||
let mut length = [0; 4];
|
||||
stream.read_exact(&mut length)?;
|
||||
let length = u32::from_be_bytes(length) as usize;
|
||||
ensure!(length <= 32768, "APT_PROBE_RESPONSE_LIMIT");
|
||||
let mut bytes = vec![0; length];
|
||||
stream.read_exact(&mut bytes)?;
|
||||
let response: Response = serde_json::from_slice(&bytes)?;
|
||||
validate_response(&request, &response)?;
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
pub fn stack_sha256(binding: &Binding, config: &apt::ProviderConfig) -> Result<String> {
|
||||
apt::verify_installation()?;
|
||||
let unit = fs::read(UNIT_PATH)?;
|
||||
trusted_path(Path::new(UNIT_PATH), false)?;
|
||||
ensure!(unit == UNIT_BYTES, "APT_UNIT_PROFILE_MISMATCH");
|
||||
let executable = std::env::current_exe()?.canonicalize()?;
|
||||
trusted_path(&executable, false)?;
|
||||
let installed = Path::new("/usr/local/libexec/rmm-privileged-helper");
|
||||
trusted_path(installed, false)?;
|
||||
ensure!(
|
||||
hash(&fs::read(&executable)?) == hash(&fs::read(installed)?),
|
||||
"APT_HELPER_BINARY_PROFILE_MISMATCH"
|
||||
);
|
||||
Ok(hash(&serde_json::to_vec(
|
||||
&serde_json::json!({"schema_version":1,"profile":"apt_only",
|
||||
"identity":Identity::from_binding(binding)?,"provider_policy":config,
|
||||
"helper_sha256":hash(&fs::read(executable)?),"unit_sha256":hash(&unit)}),
|
||||
)?))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct NativeStatus {
|
||||
schema_version: u32,
|
||||
fixture_acceptance_ready: bool,
|
||||
accepted_recipes: Vec<String>,
|
||||
runtime_sha256: String,
|
||||
readiness_report_sha256: String,
|
||||
}
|
||||
pub fn answer(
|
||||
request: &Request,
|
||||
binding: &Binding,
|
||||
config: &apt::ProviderConfig,
|
||||
ledger: &rusqlite::Connection,
|
||||
) -> Result<Response> {
|
||||
ensure!(
|
||||
matches!(
|
||||
request.operation.as_str(),
|
||||
"apt_readiness_v1" | "apt_planning_v1"
|
||||
) && !request.challenge.is_nil()
|
||||
&& request.identity == Identity::from_binding(binding)?,
|
||||
"APT_PROBE_REQUEST_BINDING"
|
||||
);
|
||||
let stack = stack_sha256(binding, config)?;
|
||||
ensure!(
|
||||
stack == request.expected_stack_sha256,
|
||||
"APT_PROBE_STACK_MISMATCH"
|
||||
);
|
||||
if request.operation == "apt_planning_v1" {
|
||||
// A metadata-only process is bounded separately from package execution.
|
||||
// Missing/unsafe/dirty/unprefetched state closes only this observation.
|
||||
let planning: PlanningResult =
|
||||
serde_json::from_slice(&rmm_agent_linux::apt_planning_metadata()?)?;
|
||||
planning.validate(chrono::Utc::now())?;
|
||||
ensure!(
|
||||
planning.runtime_sha256 == config.runtime_sha256
|
||||
&& planning.apt_config_sha256 == config.apt_config_sha256
|
||||
&& planning.provider_sha256
|
||||
== hash(include_bytes!(
|
||||
"../../../tools/apt-transaction/apt_transaction.py"
|
||||
))
|
||||
&& planning.hook_sha256
|
||||
== hash(include_bytes!("../../../tools/apt-transaction/hook")),
|
||||
"APT_PLANNING_POLICY_PINS"
|
||||
);
|
||||
let db = fs::metadata(Path::new(SHARED_STATE).join("consumption.sqlite"))?;
|
||||
let lock = fs::metadata(Path::new(SHARED_STATE).join("executor.lock"))?;
|
||||
let response = Response {
|
||||
schema_version: 1,
|
||||
challenge: request.challenge,
|
||||
identity: request.identity.clone(),
|
||||
profile: "apt_only".into(),
|
||||
provider_stack_sha256: stack,
|
||||
fixture_acceptance_ready: false,
|
||||
bootstrap_recipes: vec![],
|
||||
accepted_recipes: vec![],
|
||||
ledger_device: db.dev(),
|
||||
ledger_inode: db.ino(),
|
||||
lock_device: lock.dev(),
|
||||
lock_inode: lock.ino(),
|
||||
planning: Some(planning),
|
||||
};
|
||||
validate_response(request, &response)?;
|
||||
return Ok(response);
|
||||
}
|
||||
let output = std::process::Command::new("/usr/bin/python3")
|
||||
.args(["-I", apt::CODE, "readiness-status"])
|
||||
.env_clear()
|
||||
.env("PATH", "/usr/bin:/bin")
|
||||
.env("LC_ALL", "C")
|
||||
.output()?;
|
||||
ensure!(
|
||||
output.status.success() && output.stdout.len() <= 16384,
|
||||
"APT_NATIVE_READINESS_REQUIRED"
|
||||
);
|
||||
let status: NativeStatus = serde_json::from_slice(&output.stdout)?;
|
||||
ensure!(
|
||||
status.schema_version == 1
|
||||
&& status.runtime_sha256 == config.runtime_sha256
|
||||
&& valid_hash(&status.readiness_report_sha256),
|
||||
"APT_NATIVE_READINESS_BINDING"
|
||||
);
|
||||
let db = fs::metadata(Path::new(SHARED_STATE).join("consumption.sqlite"))?;
|
||||
let lock = fs::metadata(Path::new(SHARED_STATE).join("executor.lock"))?;
|
||||
let unresolved: i64 = ledger.query_row(
|
||||
"SELECT count(*) FROM consumed WHERE result IS NULL",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let response = Response {
|
||||
schema_version: 1,
|
||||
challenge: request.challenge,
|
||||
identity: request.identity.clone(),
|
||||
profile: "apt_only".into(),
|
||||
provider_stack_sha256: stack,
|
||||
fixture_acceptance_ready: status.fixture_acceptance_ready
|
||||
&& config.allow_fixture_bootstrap
|
||||
&& unresolved == 0,
|
||||
bootstrap_recipes: if status.fixture_acceptance_ready
|
||||
&& config.allow_fixture_bootstrap
|
||||
&& unresolved == 0
|
||||
{
|
||||
config.allowed_recipes.clone()
|
||||
} else {
|
||||
vec![]
|
||||
},
|
||||
accepted_recipes: if unresolved == 0 {
|
||||
status
|
||||
.accepted_recipes
|
||||
.into_iter()
|
||||
.filter(|r| config.allowed_recipes.contains(r))
|
||||
.collect()
|
||||
} else {
|
||||
vec![]
|
||||
},
|
||||
ledger_device: db.dev(),
|
||||
ledger_inode: db.ino(),
|
||||
lock_device: lock.dev(),
|
||||
lock_inode: lock.ino(),
|
||||
planning: None,
|
||||
};
|
||||
validate_response(request, &response)?;
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn planning_fixture() -> PlanningResult {
|
||||
let raw =
|
||||
include_str!("../../../tests/apt_transaction/fixtures/planning-canonical.json").trim();
|
||||
let runtime = serde_json::from_str(raw).unwrap();
|
||||
PlanningResult {
|
||||
observed_at: chrono::Utc::now(),
|
||||
fixture_package: None,
|
||||
baseline_sha256: "b".repeat(64),
|
||||
sealed_baseline_sha256: "b".repeat(64),
|
||||
status_fingerprint: "c".repeat(64),
|
||||
dpkg_updates_empty: true,
|
||||
pending_triggers_empty: true,
|
||||
runtime,
|
||||
runtime_sha256: hash(raw.as_bytes()),
|
||||
provider_sha256: "d".repeat(64),
|
||||
hook_sha256: "e".repeat(64),
|
||||
apt_config_sha256: "a".repeat(64),
|
||||
prefetch: [
|
||||
rmm_domain::apt_transaction::INSTALL_SHA,
|
||||
rmm_domain::apt_transaction::UPDATE_SHA,
|
||||
]
|
||||
.into_iter()
|
||||
.map(|sha| {
|
||||
(
|
||||
sha.into(),
|
||||
PlanningReceipt {
|
||||
schema_version: 1,
|
||||
sha256: sha.into(),
|
||||
size: 20672,
|
||||
sealed_at_ms: 1,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn python_rust_canonical_golden_and_planning_freshness_receipts() {
|
||||
let fixture = planning_fixture();
|
||||
fixture.validate(chrono::Utc::now()).unwrap();
|
||||
assert_eq!(
|
||||
fixture.runtime_sha256,
|
||||
"f5c1f569110924eca83ad5d347882390b47e077fbef91c4eb86abb68621b92c4"
|
||||
);
|
||||
let raw =
|
||||
include_str!("../../../tests/apt_transaction/fixtures/planning-canonical.json").trim();
|
||||
assert_eq!(
|
||||
serde_json::to_vec(&fixture.runtime).unwrap(),
|
||||
raw.as_bytes()
|
||||
);
|
||||
for field in [
|
||||
"runtime_sha256",
|
||||
"baseline_sha256",
|
||||
"status_fingerprint",
|
||||
"dpkg_updates_empty",
|
||||
"pending_triggers_empty",
|
||||
"prefetch",
|
||||
"observed_at",
|
||||
] {
|
||||
let mut value = serde_json::to_value(&fixture).unwrap();
|
||||
value[field] = match field {
|
||||
"dpkg_updates_empty" | "pending_triggers_empty" => serde_json::json!(false),
|
||||
"prefetch" => serde_json::json!({}),
|
||||
"observed_at" => {
|
||||
serde_json::json!(chrono::Utc::now() - chrono::Duration::seconds(31))
|
||||
}
|
||||
"baseline_sha256" => serde_json::json!("0".repeat(64)),
|
||||
_ => serde_json::json!("invalid"),
|
||||
};
|
||||
assert!(
|
||||
serde_json::from_value::<PlanningResult>(value)
|
||||
.unwrap()
|
||||
.validate(chrono::Utc::now())
|
||||
.is_err(),
|
||||
"{field}"
|
||||
);
|
||||
}
|
||||
let mut bad = fixture;
|
||||
bad.prefetch.values_mut().next().unwrap().sealed_at_ms = i64::MAX;
|
||||
assert!(bad.validate(chrono::Utc::now()).is_err());
|
||||
}
|
||||
fn identity() -> Identity {
|
||||
Identity {
|
||||
tenant_id: Uuid::new_v4(),
|
||||
asset_id: Uuid::new_v4(),
|
||||
agent_id: Uuid::new_v4(),
|
||||
enrollment_generation: 1,
|
||||
assignment_version: 1,
|
||||
signing_key_id: "a".repeat(64),
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn forged_nonce_identity_profile_or_stack_never_advertises() {
|
||||
let request = Request {
|
||||
operation: "apt_readiness_v1".into(),
|
||||
challenge: Uuid::new_v4(),
|
||||
identity: identity(),
|
||||
expected_stack_sha256: "a".repeat(64),
|
||||
};
|
||||
let response = Response {
|
||||
schema_version: 1,
|
||||
challenge: request.challenge,
|
||||
identity: request.identity.clone(),
|
||||
profile: "apt_only".into(),
|
||||
provider_stack_sha256: request.expected_stack_sha256.clone(),
|
||||
fixture_acceptance_ready: true,
|
||||
bootstrap_recipes: vec![apt::INSTALL_RECIPE.into()],
|
||||
accepted_recipes: vec![],
|
||||
ledger_device: 1,
|
||||
ledger_inode: 2,
|
||||
lock_device: 1,
|
||||
lock_inode: 3,
|
||||
planning: None,
|
||||
};
|
||||
validate_response(&request, &response).unwrap();
|
||||
for field in ["challenge", "identity", "profile", "provider_stack_sha256"] {
|
||||
let mut value = serde_json::to_value(&response).unwrap();
|
||||
value[field] = match field {
|
||||
"challenge" => serde_json::json!(Uuid::new_v4()),
|
||||
"identity" => serde_json::to_value(identity()).unwrap(),
|
||||
_ => serde_json::json!("forged"),
|
||||
};
|
||||
assert!(validate_response(&request, &serde_json::from_value(value).unwrap()).is_err());
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn kernel_peer_is_required_not_json_root_assertion() {
|
||||
let (a, _b) = UnixStream::pair().unwrap();
|
||||
// SAFETY: geteuid has no preconditions.
|
||||
assert_eq!(root_peer(&a).is_ok(), unsafe { libc::geteuid() } == 0);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,361 @@
|
||||
use super::*;
|
||||
use openssl::sign::Signer;
|
||||
use rmm_domain::jobs::{Action, encode};
|
||||
|
||||
fn fixture() -> (
|
||||
Binding,
|
||||
Request,
|
||||
openssl::pkey::PKey<openssl::pkey::Private>,
|
||||
DateTime<Utc>,
|
||||
) {
|
||||
let key = PKey::generate_ed25519().unwrap();
|
||||
let public = key.raw_public_key().unwrap();
|
||||
let now = DateTime::from_timestamp(1_800_000_000, 0).unwrap();
|
||||
let binding = Binding {
|
||||
tenant_id: Uuid::new_v4(),
|
||||
asset_id: Uuid::new_v4(),
|
||||
agent_id: Uuid::new_v4(),
|
||||
enrollment_generation: 1,
|
||||
assignment_version: 3,
|
||||
public_key_hex: hex::encode(&public),
|
||||
};
|
||||
let job = JobPayload {
|
||||
schema_version: 1,
|
||||
tenant_id: binding.tenant_id,
|
||||
asset_id: binding.asset_id,
|
||||
agent_id: binding.agent_id,
|
||||
enrollment_generation: 1,
|
||||
assignment_version: 3,
|
||||
job_id: Uuid::new_v4(),
|
||||
attempt_id: Uuid::new_v4(),
|
||||
action: Action::RunScript {
|
||||
interpreter: "posix_sh".into(),
|
||||
script_utf8: "printf 'Hello World\\n'".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("Hello World\n".into()),
|
||||
},
|
||||
execution_identity: "agent_service".into(),
|
||||
not_before: now - chrono::Duration::seconds(60),
|
||||
start_before: now + chrono::Duration::seconds(300),
|
||||
max_runtime_seconds: 2,
|
||||
max_output_bytes: 4096,
|
||||
};
|
||||
let bytes = encode(&job).unwrap();
|
||||
let permit = ExecutionPermitPayload {
|
||||
domain: "rmm.execution-permit".into(),
|
||||
schema_version: 1,
|
||||
grant_id: Uuid::new_v4(),
|
||||
authorization_id: Uuid::new_v4(),
|
||||
tenant_id: job.tenant_id,
|
||||
asset_id: job.asset_id,
|
||||
agent_id: job.agent_id,
|
||||
enrollment_generation: job.enrollment_generation,
|
||||
assignment_version: job.assignment_version,
|
||||
job_id: job.job_id,
|
||||
attempt_id: job.attempt_id,
|
||||
plan_hash: hash(b"immutable approved plan"),
|
||||
job_payload_hash: hash(&bytes),
|
||||
action: "run_script".into(),
|
||||
execution_identity: job.execution_identity.clone(),
|
||||
not_before: now - chrono::Duration::seconds(1),
|
||||
start_before: now + chrono::Duration::seconds(59),
|
||||
max_runtime_seconds: 2,
|
||||
key_id: hash(&public),
|
||||
};
|
||||
let mut request = Request {
|
||||
job_bytes: bytes,
|
||||
permit_bytes: encode(&permit).unwrap(),
|
||||
signature: vec![],
|
||||
plan_hash: permit.plan_hash.clone(),
|
||||
authorization_id: permit.authorization_id,
|
||||
};
|
||||
sign(&mut request, &key);
|
||||
(binding, request, key, now)
|
||||
}
|
||||
fn sign(request: &mut Request, key: &openssl::pkey::PKey<openssl::pkey::Private>) {
|
||||
request.signature = Signer::new_without_digest(key)
|
||||
.unwrap()
|
||||
.sign_oneshot_to_vec(&request.permit_bytes)
|
||||
.unwrap();
|
||||
}
|
||||
fn directory() -> std::path::PathBuf {
|
||||
use std::os::unix::fs::DirBuilderExt;
|
||||
let path = std::env::temp_dir().join(format!("rmm-ledger-test-{}", Uuid::new_v4()));
|
||||
fs::DirBuilder::new().mode(0o700).create(&path).unwrap();
|
||||
path
|
||||
}
|
||||
#[test]
|
||||
fn exact_signature_and_every_permit_binding() {
|
||||
let (binding, request, key, now) = fixture();
|
||||
assert!(binding.verify(&request, now).is_ok());
|
||||
let original: serde_json::Value = serde_json::from_slice(&request.permit_bytes).unwrap();
|
||||
for (field, replacement) in [
|
||||
("domain", serde_json::json!("other")),
|
||||
("schema_version", serde_json::json!(2)),
|
||||
("grant_id", serde_json::json!(Uuid::nil())),
|
||||
("authorization_id", serde_json::json!(Uuid::new_v4())),
|
||||
("tenant_id", serde_json::json!(Uuid::new_v4())),
|
||||
("asset_id", serde_json::json!(Uuid::new_v4())),
|
||||
("agent_id", serde_json::json!(Uuid::new_v4())),
|
||||
("enrollment_generation", serde_json::json!(2)),
|
||||
("assignment_version", serde_json::json!(4)),
|
||||
("job_id", serde_json::json!(Uuid::new_v4())),
|
||||
("attempt_id", serde_json::json!(Uuid::new_v4())),
|
||||
("plan_hash", serde_json::json!(hash(b"other"))),
|
||||
("job_payload_hash", serde_json::json!(hash(b"other"))),
|
||||
("action", serde_json::json!("reboot")),
|
||||
("execution_identity", serde_json::json!("root")),
|
||||
("max_runtime_seconds", serde_json::json!(3)),
|
||||
("key_id", serde_json::json!(hash(b"other"))),
|
||||
(
|
||||
"not_before",
|
||||
serde_json::json!(now + chrono::Duration::seconds(1)),
|
||||
),
|
||||
(
|
||||
"start_before",
|
||||
serde_json::json!(now + chrono::Duration::seconds(61)),
|
||||
),
|
||||
] {
|
||||
let mut modified = original.clone();
|
||||
modified[field] = replacement;
|
||||
let mut candidate = request.clone();
|
||||
candidate.permit_bytes = serde_json::to_vec(&modified).unwrap();
|
||||
sign(&mut candidate, &key);
|
||||
assert!(
|
||||
binding.verify(&candidate, now).is_err(),
|
||||
"missing binding: {field}"
|
||||
);
|
||||
}
|
||||
let mut forged = request.clone();
|
||||
forged.signature[0] ^= 1;
|
||||
assert!(binding.verify(&forged, now).is_err());
|
||||
let mut tampered = request.clone();
|
||||
tampered.job_bytes.push(b' ');
|
||||
assert!(binding.verify(&tampered, now).is_err());
|
||||
let mut bad_parameters = request.clone();
|
||||
let mut job: JobPayload = serde_json::from_slice(&bad_parameters.job_bytes).unwrap();
|
||||
job.action = Action::Reboot {
|
||||
reason: "different effect".into(),
|
||||
reconnect_timeout_seconds: 60,
|
||||
dependency_group: "test".into(),
|
||||
};
|
||||
bad_parameters.job_bytes = encode(&job).unwrap();
|
||||
assert!(binding.verify(&bad_parameters, now).is_err());
|
||||
assert!(
|
||||
binding
|
||||
.verify(&request, now + chrono::Duration::seconds(59))
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
binding
|
||||
.verify(&request, now - chrono::Duration::seconds(2))
|
||||
.is_err()
|
||||
);
|
||||
let mut wrong_trust = binding.clone();
|
||||
wrong_trust.public_key_hex =
|
||||
hex::encode(PKey::generate_ed25519().unwrap().raw_public_key().unwrap());
|
||||
assert!(wrong_trust.verify(&request, now).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn independent_identity_binding_all_fields() {
|
||||
let (binding, request, _, now) = fixture();
|
||||
for field in [
|
||||
"tenant_id",
|
||||
"asset_id",
|
||||
"agent_id",
|
||||
"enrollment_generation",
|
||||
"assignment_version",
|
||||
] {
|
||||
let mut value = serde_json::to_value(&binding).unwrap();
|
||||
value[field] = if field.ends_with("id") {
|
||||
serde_json::json!(Uuid::new_v4())
|
||||
} else {
|
||||
serde_json::json!(99)
|
||||
};
|
||||
let wrong: Binding = serde_json::from_value(value).unwrap();
|
||||
assert!(wrong.verify(&request, now).is_err(), "{field}");
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn reopen_consumption_duplicate_grant_attempt_unknown_and_resource_lock() {
|
||||
let (binding, request, _, now) = fixture();
|
||||
let (_, permit) = binding.verify(&request, now).unwrap();
|
||||
let path = directory();
|
||||
// SAFETY: geteuid has no preconditions.
|
||||
let uid = unsafe { libc::geteuid() };
|
||||
let lock = lock_state(&path, uid).unwrap();
|
||||
assert!(lock_state(&path, uid).is_err());
|
||||
let mut db = open_ledger(&path, uid).unwrap();
|
||||
consume(&mut db, &permit).unwrap();
|
||||
drop(db);
|
||||
let mut db = open_ledger(&path, uid).unwrap();
|
||||
assert!(consume(&mut db, &permit).is_err());
|
||||
let mut replacement = permit.clone();
|
||||
replacement.grant_id = Uuid::new_v4();
|
||||
assert!(consume(&mut db, &replacement).is_err());
|
||||
finish(&db, &permit, &Outcome::unknown("crash_after_effect")).unwrap();
|
||||
replacement.job_id = Uuid::new_v4();
|
||||
replacement.attempt_id = Uuid::new_v4();
|
||||
assert!(consume(&mut db, &replacement).is_err());
|
||||
// Only definitive evidence releases the resource, not an ACK or new grant.
|
||||
let mut definitive = Outcome::unknown("");
|
||||
definitive.state = "succeeded".into();
|
||||
finish(&db, &permit, &definitive).unwrap();
|
||||
assert!(consume(&mut db, &permit).is_err());
|
||||
replacement.job_id = permit.job_id;
|
||||
replacement.attempt_id = permit.attempt_id;
|
||||
assert!(consume(&mut db, &replacement).is_err());
|
||||
replacement.job_id = Uuid::new_v4();
|
||||
replacement.attempt_id = Uuid::new_v4();
|
||||
consume(&mut db, &replacement).unwrap();
|
||||
drop(db);
|
||||
drop(lock);
|
||||
fs::remove_dir_all(path).unwrap();
|
||||
}
|
||||
#[test]
|
||||
fn harmless_exact_script_with_bound_output() {
|
||||
let (binding, request, _, now) = fixture();
|
||||
let (job, _) = binding.verify(&request, now).unwrap();
|
||||
let result = script(&job).unwrap();
|
||||
assert_eq!(result.state, "succeeded");
|
||||
assert_eq!(result.stdout, b"Hello World\n");
|
||||
assert_eq!(result.exit_code, Some(0));
|
||||
}
|
||||
#[test]
|
||||
fn unsafe_paths_and_corrupt_ledger_fail_closed() {
|
||||
use std::os::unix::fs::{PermissionsExt, symlink};
|
||||
let path = directory();
|
||||
let uid = unsafe { libc::geteuid() };
|
||||
let db = open_ledger(&path, uid).unwrap();
|
||||
drop(db);
|
||||
fs::write(path.join("consumption.sqlite"), b"corrupt db").unwrap();
|
||||
assert!(open_ledger(&path, uid).is_err());
|
||||
fs::remove_file(path.join("consumption.sqlite")).unwrap();
|
||||
symlink("/dev/null", path.join("consumption.sqlite")).unwrap();
|
||||
assert!(open_ledger(&path, uid).is_err());
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o777)).unwrap();
|
||||
assert!(lock_state(&path, uid).is_err());
|
||||
fs::remove_dir_all(path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wall_clock_jump_is_not_mistaken_for_a_fresh_online_grant() {
|
||||
let clock = TrustedClock {
|
||||
wall: Utc::now() + chrono::Duration::minutes(1),
|
||||
monotonic: std::time::Instant::now(),
|
||||
};
|
||||
assert!(!clock.trusted());
|
||||
let clock = TrustedClock {
|
||||
wall: Utc::now() - chrono::Duration::minutes(1),
|
||||
monotonic: std::time::Instant::now(),
|
||||
};
|
||||
assert!(!clock.trusted());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_helper_connections_share_exact_lock_and_sqlite_consumption() {
|
||||
let (binding, request, _, now) = fixture();
|
||||
let (_, permit) = binding.verify(&request, now).unwrap();
|
||||
let path = directory();
|
||||
// SAFETY: geteuid has no preconditions.
|
||||
let uid = unsafe { libc::geteuid() };
|
||||
let first = lock_state(&path, uid).unwrap();
|
||||
let inode = (
|
||||
first.metadata().unwrap().dev(),
|
||||
first.metadata().unwrap().ino(),
|
||||
);
|
||||
assert!(lock_state(&path, uid).is_err());
|
||||
drop(first);
|
||||
let second = lock_state(&path, uid).unwrap();
|
||||
assert_eq!(
|
||||
inode,
|
||||
(
|
||||
second.metadata().unwrap().dev(),
|
||||
second.metadata().unwrap().ino()
|
||||
)
|
||||
);
|
||||
let mut general = open_ledger(&path, uid).unwrap();
|
||||
let mut apt = open_ledger(&path, uid).unwrap();
|
||||
consume(&mut general, &permit).unwrap();
|
||||
assert!(consume(&mut apt, &permit).is_err());
|
||||
let mut other = permit.clone();
|
||||
other.grant_id = Uuid::new_v4();
|
||||
other.job_id = Uuid::new_v4();
|
||||
other.attempt_id = Uuid::new_v4();
|
||||
assert!(consume(&mut apt, &other).is_err());
|
||||
finish(
|
||||
&general,
|
||||
&permit,
|
||||
&Outcome::unknown("shared unknown effect"),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(consume(&mut apt, &other).is_err());
|
||||
let filename: String = apt
|
||||
.query_row(
|
||||
"SELECT file FROM pragma_database_list WHERE name='main'",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
fs::metadata(filename).unwrap().ino(),
|
||||
fs::metadata(path.join("consumption.sqlite")).unwrap().ino()
|
||||
);
|
||||
drop(general);
|
||||
drop(apt);
|
||||
drop(second);
|
||||
fs::remove_dir_all(path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn awaiting_reboot_preserves_original_boot_and_outcome_across_reopen() {
|
||||
let (binding, mut request, key, now) = fixture();
|
||||
let mut job: JobPayload = serde_json::from_slice(&request.job_bytes).unwrap();
|
||||
job.action = Action::Reboot {
|
||||
reason: "mock reboot; no native effect".into(),
|
||||
reconnect_timeout_seconds: 60,
|
||||
dependency_group: "test".into(),
|
||||
};
|
||||
request.job_bytes = encode(&job).unwrap();
|
||||
let mut payload: ExecutionPermitPayload =
|
||||
serde_json::from_slice(&request.permit_bytes).unwrap();
|
||||
payload.action = "reboot".into();
|
||||
payload.job_payload_hash = hash(&request.job_bytes);
|
||||
request.permit_bytes = encode(&payload).unwrap();
|
||||
sign(&mut request, &key);
|
||||
let (_, permit) = binding.verify(&request, now).unwrap();
|
||||
let path = directory();
|
||||
let uid = unsafe { libc::geteuid() };
|
||||
let mut db = open_ledger(&path, uid).unwrap();
|
||||
consume(&mut db, &permit).unwrap();
|
||||
save_start(&db, &permit, &request).unwrap();
|
||||
let mut outcome = Outcome::unknown("REAUTHENTICATION_REQUIRED");
|
||||
outcome.state = "awaiting_reboot".into();
|
||||
finish(&db, &permit, &outcome).unwrap();
|
||||
drop(db);
|
||||
let mut db = open_ledger(&path, uid).unwrap();
|
||||
let (start, outcome): (Vec<u8>, Vec<u8>) = db
|
||||
.query_row(
|
||||
"SELECT start,outcome FROM execution_evidence WHERE grant_id=?1",
|
||||
[permit.grant_id.to_string()],
|
||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
||||
)
|
||||
.unwrap();
|
||||
let start: serde_json::Value = serde_json::from_slice(&start).unwrap();
|
||||
assert_eq!(
|
||||
start["previous_boot_id"],
|
||||
rmm_agent_linux::boot_id().unwrap()
|
||||
);
|
||||
assert_eq!(start["reauthentication_required"], true);
|
||||
assert!(start["reconnect_deadline"].is_string());
|
||||
assert_eq!(
|
||||
serde_json::from_slice::<Outcome>(&outcome).unwrap().state,
|
||||
"awaiting_reboot"
|
||||
);
|
||||
let mut other = permit.clone();
|
||||
other.grant_id = Uuid::new_v4();
|
||||
other.job_id = Uuid::new_v4();
|
||||
assert!(consume(&mut db, &other).is_err());
|
||||
drop(db);
|
||||
fs::remove_dir_all(path).unwrap();
|
||||
}
|
||||
Reference in New Issue
Block a user