790 lines
28 KiB
Rust
790 lines
28 KiB
Rust
//! 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 {
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub native_recovery: Option<rmm_domain::apt_transaction::AptNativeRecovery>,
|
|
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 host_reboot_required: 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<()> {
|
|
if let Some(reference) = &self.native_recovery {
|
|
ensure!(
|
|
reference.validate()
|
|
&& self
|
|
.fixture_package
|
|
.as_ref()
|
|
.is_some_and(|p| p.version == "1.0" && p.status == "install ok unpacked"),
|
|
"APT_RECOVERY_PLANNING_SCOPE"
|
|
);
|
|
}
|
|
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_recovery_planning_v1"
|
|
),
|
|
"APT_PROBE_OPERATION"
|
|
);
|
|
if let Some(planning) = &response.planning {
|
|
ensure!(
|
|
matches!(
|
|
request.operation.as_str(),
|
|
"apt_planning_v1" | "apt_recovery_planning_v1"
|
|
),
|
|
"APT_PLANNING_OPERATION"
|
|
);
|
|
planning.validate(chrono::Utc::now())?;
|
|
ensure!(
|
|
(request.operation == "apt_recovery_planning_v1") == planning.native_recovery.is_some(),
|
|
"APT_RECOVERY_PLANNING_OPERATION"
|
|
);
|
|
}
|
|
if matches!(
|
|
request.operation.as_str(),
|
|
"apt_planning_v1" | "apt_recovery_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")
|
|
}
|
|
pub fn planning_for_recovery(socket: &Path, binding: &Binding, pin: &Pin) -> Result<Response> {
|
|
probe_operation(socket, binding, pin, "apt_recovery_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" | "apt_recovery_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 matches!(
|
|
request.operation.as_str(),
|
|
"apt_planning_v1" | "apt_recovery_planning_v1"
|
|
) {
|
|
// A metadata-only process is bounded separately from package execution.
|
|
// Missing/unsafe/dirty/unprefetched state closes only this observation.
|
|
let planning: PlanningResult = if request.operation == "apt_recovery_planning_v1" {
|
|
recovery_planning(ledger, binding)?
|
|
} else {
|
|
serde_json::from_slice(&rmm_agent_linux::apt_planning_metadata()?)?
|
|
};
|
|
ensure!(
|
|
(request.operation == "apt_recovery_planning_v1") == planning.native_recovery.is_some(),
|
|
"APT_RECOVERY_PLANNING_OPERATION"
|
|
);
|
|
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)
|
|
}
|
|
|
|
fn recovery_planning(ledger: &rusqlite::Connection, binding: &Binding) -> Result<PlanningResult> {
|
|
use anyhow::Context;
|
|
use std::{
|
|
os::unix::process::CommandExt,
|
|
process::{Command, Stdio},
|
|
time::{Duration, Instant},
|
|
};
|
|
ensure!(
|
|
ledger.query_row(
|
|
"SELECT count(*) FROM consumed WHERE result IS NULL",
|
|
[],
|
|
|r| r.get::<_, u64>(0)
|
|
)? == 0,
|
|
"APT_RECOVERY_PLANNING_UNRESOLVED"
|
|
);
|
|
apt::verify_installation()?;
|
|
let partial = crate::apt_reconcile::closed_partial(ledger, binding, None)?;
|
|
let proof: serde_json::Value = serde_json::from_slice(&partial.proof)?;
|
|
let input = serde_json::to_vec(
|
|
&serde_json::json!({"native_recovery":partial.reference,"proof":proof}),
|
|
)?;
|
|
ensure!(
|
|
input.len() <= 1024 * 1024,
|
|
"APT_RECOVERY_PLANNING_INPUT_LIMIT"
|
|
);
|
|
let mut child = Command::new("/usr/bin/python3")
|
|
.args(["-I", apt::CODE, "recovery-planning"])
|
|
.env_clear()
|
|
.env("PATH", "/usr/sbin:/usr/bin:/sbin:/bin")
|
|
.env("LC_ALL", "C")
|
|
.stdin(Stdio::piped())
|
|
.stdout(Stdio::piped())
|
|
.stderr(Stdio::null())
|
|
.process_group(0)
|
|
.spawn()?;
|
|
let result = (|| -> Result<Vec<u8>> {
|
|
let mut stdin = Some(child.stdin.take().context("APT_RECOVERY_PLANNING_STDIN")?);
|
|
let mut stdout = child
|
|
.stdout
|
|
.take()
|
|
.context("APT_RECOVERY_PLANNING_STDOUT")?;
|
|
for fd in [
|
|
stdin
|
|
.as_ref()
|
|
.context("APT_RECOVERY_PLANNING_STDIN")?
|
|
.as_raw_fd(),
|
|
stdout.as_raw_fd(),
|
|
] {
|
|
let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
|
|
ensure!(
|
|
flags >= 0
|
|
&& unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) } >= 0,
|
|
"APT_RECOVERY_PLANNING_PIPE"
|
|
);
|
|
}
|
|
let deadline = Instant::now() + Duration::from_secs(4);
|
|
let mut written = 0;
|
|
let mut output = vec![];
|
|
let mut exited = None;
|
|
let mut eof = false;
|
|
loop {
|
|
ensure!(Instant::now() < deadline, "APT_RECOVERY_PLANNING_TIMEOUT");
|
|
if let Some(pipe) = stdin.as_mut() {
|
|
match pipe.write(&input[written..]) {
|
|
Ok(n) => written += n,
|
|
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
|
|
Err(e) => return Err(e.into()),
|
|
};
|
|
if written == input.len() {
|
|
stdin = None;
|
|
}
|
|
}
|
|
let mut buf = [0; 4096];
|
|
for _ in 0..16 {
|
|
match stdout.read(&mut buf) {
|
|
Ok(0) => {
|
|
eof = true;
|
|
break;
|
|
}
|
|
Ok(n) => {
|
|
ensure!(
|
|
output.len() + n <= 32768,
|
|
"APT_RECOVERY_PLANNING_OUTPUT_LIMIT"
|
|
);
|
|
output.extend_from_slice(&buf[..n]);
|
|
}
|
|
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
|
|
Err(e) => return Err(e.into()),
|
|
}
|
|
}
|
|
if exited.is_none() {
|
|
exited = child.try_wait()?;
|
|
}
|
|
if eof && let Some(status) = exited {
|
|
ensure!(
|
|
status.success() && written == input.len(),
|
|
"APT_RECOVERY_PLANNING_FAILED"
|
|
);
|
|
return Ok(output);
|
|
}
|
|
std::thread::sleep(Duration::from_millis(5));
|
|
}
|
|
})();
|
|
unsafe {
|
|
libc::kill(-(child.id() as i32), libc::SIGKILL);
|
|
}
|
|
let _ = child.wait();
|
|
let planning: PlanningResult = serde_json::from_slice(&result?)?;
|
|
ensure!(
|
|
planning.native_recovery.as_ref() == Some(&partial.reference)
|
|
&& planning.baseline_sha256 == partial.baseline_sha256
|
|
&& planning.status_fingerprint == partial.status_fingerprint,
|
|
"APT_RECOVERY_PLANNING_PROOF_BINDING"
|
|
);
|
|
Ok(planning)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
#[test]
|
|
fn recovery_planning_is_a_distinct_bound_partial_observation() {
|
|
let mut p = planning_fixture();
|
|
let r = rmm_domain::apt_transaction::AptNativeRecovery {
|
|
schema_version: 1,
|
|
previous_grant_id: Uuid::new_v4(),
|
|
previous_attempt_id: Uuid::new_v4(),
|
|
partial_proof_sha256: "a".repeat(64),
|
|
};
|
|
p.native_recovery = Some(r);
|
|
assert!(p.validate(chrono::Utc::now()).is_err());
|
|
p.fixture_package = Some(FixturePackage {
|
|
version: "1.0".into(),
|
|
status: "install ok unpacked".into(),
|
|
});
|
|
p.validate(chrono::Utc::now()).unwrap();
|
|
p.fixture_package.as_mut().unwrap().status = "install ok installed".into();
|
|
assert!(p.validate(chrono::Utc::now()).is_err());
|
|
p.fixture_package.as_mut().unwrap().status = "install ok unpacked".into();
|
|
p.native_recovery.as_mut().unwrap().previous_grant_id = Uuid::nil();
|
|
assert!(p.validate(chrono::Utc::now()).is_err());
|
|
}
|
|
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 {
|
|
native_recovery: None,
|
|
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,
|
|
host_reboot_required: false,
|
|
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);
|
|
}
|
|
}
|