//! One create-only protected handoff witness bundle BEFORE consumption. Its //! inner raw hashes are bound by the ORIGINAL atomic helper handoff. Reading //! cannot create a plan, authority, lease, resume or new effect. use crate::{files::FileWitnesses, retained::RetainedSet}; use anyhow::{Result, ensure}; use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use rmm_domain::agent_update::{ParticipantIdentity, ParticipantRole, UpdateDelegation}; use rmm_updater_handoff::Handoff; use rmm_updater_linux::files::{Directory, LedgerIdentity}; use rmm_updater_linux::{ Budget, services::{HeldService, Service}, }; use serde::{Deserialize, Serialize}; use std::{ ffi::OsStr, fs::{self, OpenOptions}, io::Write, os::unix::fs::{DirBuilderExt, OpenOptionsExt}, path::{Path, PathBuf}, }; use uuid::Uuid; const ROOT: &str = "/var/lib/rmm-agent-updater/handoffs"; const MAX_BYTES: usize = 256 * 1024; #[derive(Serialize, Deserialize)] #[serde(deny_unknown_fields)] struct Record { schema_version: u32, grant_id: Uuid, owner_nonce: Uuid, handoff_sha256: String, handoff_record_base64url: String, delegation: UpdateDelegation, files_base64url: String, retained_base64url: String, ledger: LedgerIdentity, } pub struct Loaded { pub header: Header, pub files: FileWitnesses, pub retained: RetainedSet, pub ledger: LedgerIdentity, } pub struct Header { pub handoff: Handoff, pub delegation: UpdateDelegation, } pub struct Participants<'a> { pub delegation: &'a UpdateDelegation, pub original_full: &'a HeldService, pub updater: &'a HeldService, pub budget: &'a Budget, } fn path(handoff: &Handoff) -> PathBuf { Path::new(ROOT).join(handoff.attempt.grant_id.to_string()) } pub fn write_before_handoff( handoff: &Handoff, files: &FileWitnesses, retained: &RetainedSet, ledger: &LedgerIdentity, participants: Participants<'_>, ) -> Result<()> { handoff.validate()?; participants.budget.check()?; participants.original_full.verify(participants.budget)?; participants.updater.verify(participants.budget)?; ensure!( participants.original_full.proof().service == Service::Full && participants.updater.proof().service == Service::Updater && observed_participant(participants.original_full)? == participants.delegation.original_helper && observed_participant(participants.updater)? == participants.delegation.updater, "UPDATE_BUNDLE_PARTICIPANTS_CHANGED" ); validate_delegation(handoff, participants.delegation)?; files.bind(handoff)?; retained.verify()?; ensure!( retained.sha256() == handoff.retained_state_sha256 && ledger.sha256()? == handoff.ledger_identity_sha256, "UPDATE_BUNDLE_BINDING" ); let parent = Directory::open(Path::new(ROOT), 0, true)?; let raw = serde_json::to_vec(&Record { schema_version: 1, grant_id: handoff.attempt.grant_id, owner_nonce: handoff.owner_nonce, handoff_sha256: rmm_domain::jobs::hash(&handoff.bytes()?), handoff_record_base64url: URL_SAFE_NO_PAD.encode(handoff.bytes()?), delegation: participants.delegation.clone(), files_base64url: URL_SAFE_NO_PAD.encode(files.bytes()?), retained_base64url: URL_SAFE_NO_PAD.encode(retained.bytes()?), ledger: ledger.clone(), })?; ensure!(raw.len() <= MAX_BYTES, "UPDATE_BUNDLE_LIMIT"); // create_dir is exclusive; partial/previous bundles are never reused. fs::DirBuilder::new().mode(0o700).create(path(handoff))?; parent.verify()?; let directory = Directory::open(&path(handoff), 0, true)?; let mut file = OpenOptions::new() .create_new(true) .write(true) .mode(0o600) .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC) .open(path(handoff).join("witnesses.json"))?; file.write_all(&raw)?; file.sync_all()?; let current = directory.inspect(OsStr::new("witnesses.json"), 0, MAX_BYTES as u64)?; ensure!( current.proof().sha256 == rmm_domain::jobs::hash(&raw) && current.proof().identity.links == 1, "UPDATE_BUNDLE_WRITE_CHANGED" ); sync_directory(&path(handoff))?; sync_directory(Path::new(ROOT))?; directory.verify()?; parent.verify() } pub fn read_for_handoff(handoff: &Handoff) -> Result { handoff.validate()?; let record = read_record(handoff.attempt.grant_id)?; let header = header(&record)?; ensure!( header.handoff.bytes()? == handoff.bytes()?, "UPDATE_BUNDLE_ORIGINAL_HEADER_CHANGED" ); let files = FileWitnesses::from_bound_bytes(&decode(&record.files_base64url)?, handoff)?; let retained = RetainedSet::from_bound_bytes(&decode(&record.retained_base64url)?, handoff)?; Ok(Loaded { header, files, retained, ledger: record.ledger, }) } pub fn read_header(grant_id: Uuid, owner_nonce: Uuid, handoff_sha256: &str) -> Result
{ ensure!( !grant_id.is_nil() && !owner_nonce.is_nil() && rmm_domain::agent_update::digest(handoff_sha256), "UPDATE_BUNDLE_HEADER_SELECTOR" ); let record = read_record(grant_id)?; ensure!( record.owner_nonce == owner_nonce && record.handoff_sha256 == handoff_sha256, "UPDATE_BUNDLE_HEADER_BINDING" ); header(&record) } fn read_record(grant_id: Uuid) -> Result { ensure!(!grant_id.is_nil(), "UPDATE_BUNDLE_GRANT"); let parent = Directory::open(Path::new(ROOT), 0, true)?; let directory = Directory::open(&Path::new(ROOT).join(grant_id.to_string()), 0, true)?; let mut file = directory.inspect(OsStr::new("witnesses.json"), 0, MAX_BYTES as u64)?; ensure!( file.proof().identity.mode & 0o777 == 0o600 && file.proof().identity.links == 1, "UPDATE_BUNDLE_PRIVATE_FILE" ); let raw = file.bytes(MAX_BYTES as u64)?; let record: Record = serde_json::from_slice(&raw)?; ensure!( serde_json::to_vec(&record)? == raw && record.schema_version == 1 && record.grant_id == grant_id, "UPDATE_BUNDLE_RECORD_BINDING" ); directory.file(OsStr::new("witnesses.json"), file.proof(), MAX_BYTES as u64)?; parent.verify()?; Ok(record) } fn header(record: &Record) -> Result
{ let raw = decode(&record.handoff_record_base64url)?; let handoff: Handoff = serde_json::from_slice(&raw)?; ensure!( handoff.bytes()? == raw && rmm_domain::jobs::hash(&raw) == record.handoff_sha256 && handoff.attempt.grant_id == record.grant_id && handoff.owner_nonce == record.owner_nonce && record.ledger.sha256()? == handoff.ledger_identity_sha256, "UPDATE_BUNDLE_HEADER_CHANGED" ); validate_delegation(&handoff, &record.delegation)?; ensure!( rmm_domain::jobs::hash(&decode(&record.files_base64url)?) == handoff.staged_files_sha256 && rmm_domain::jobs::hash(&decode(&record.retained_base64url)?) == handoff.retained_state_sha256, "UPDATE_BUNDLE_INNER_HASH_CHANGED" ); Ok(Header { handoff, delegation: record.delegation.clone(), }) } fn validate_delegation(handoff: &Handoff, delegation: &UpdateDelegation) -> Result<()> { ensure!( delegation.validate() && delegation.handoff_sha256 == rmm_domain::jobs::hash(&handoff.bytes()?) && delegation.boot_id == handoff.boot_id && delegation.owner_nonce == handoff.owner_nonce && delegation.updater.role == ParticipantRole::LinuxUpdater && delegation.original_helper.role == ParticipantRole::LinuxFullHelper && delegation.updater.image_sha256 == handoff.updater_sha256 && delegation.original_helper.image_sha256 == handoff.predecessor.helper_sha256 && u64::try_from(delegation.prepared_at.timestamp())? == handoff.consumed_at, "UPDATE_BUNDLE_DELEGATION_BINDING" ); Ok(()) } fn observed_participant(held: &HeldService) -> Result { let proof = held.proof(); let role = match proof.service { Service::Updater => ParticipantRole::LinuxUpdater, Service::Full => ParticipantRole::LinuxFullHelper, _ => anyhow::bail!("UPDATE_BUNDLE_PARTICIPANT_ROLE"), }; ensure!(proof.process.uid == 0, "UPDATE_BUNDLE_ROOT_PARTICIPANT"); Ok(ParticipantIdentity { role, pid: proof.process.pid, birth: proof.process.birth, image_sha256: proof.process.image_sha256.clone(), security_principal: "uid:0".into(), service_instance_sha256: rmm_domain::jobs::hash(&serde_json::to_vec(proof)?), }) } fn decode(value: &str) -> Result> { ensure!( !value.is_empty() && value.len() <= 4 * 65536usize.div_ceil(3), "UPDATE_BUNDLE_INNER_LIMIT" ); let raw = URL_SAFE_NO_PAD.decode(value)?; ensure!( !raw.is_empty() && raw.len() <= 65536 && URL_SAFE_NO_PAD.encode(&raw) == value, "UPDATE_BUNDLE_INNER_BASE64" ); Ok(raw) } fn sync_directory(path: &Path) -> Result<()> { OpenOptions::new() .read(true) .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC) .open(path)? .sync_all()?; Ok(()) }