Implement guarded Linux updater runtime and compatible baseline tooling
Rust development slice / linux (push) Failing after 8s
Rust development slice / linux (push) Failing after 8s
This commit is contained in:
@@ -0,0 +1,355 @@
|
||||
//! Administrative public metadata only. No files, keys, services or jobs written.
|
||||
use anyhow::{Result, ensure};
|
||||
use ed25519_dalek::VerifyingKey;
|
||||
use rmm_domain::{
|
||||
agent_update::{ReleaseEnvelope, ReleaseManifest, UpdateKeyringFile},
|
||||
agent_update_provisioning::{HealthKeyPin, InstalledReleaseRecord, LocalUpdatePolicy},
|
||||
jobs::hash,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use std::io::Read;
|
||||
use uuid::Uuid;
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "operation", rename_all = "snake_case", deny_unknown_fields)]
|
||||
enum Input {
|
||||
RenderFull {
|
||||
config: Vec<u8>,
|
||||
pin: Vec<u8>,
|
||||
job_public_key_hex: String,
|
||||
new_helper_sha256: String,
|
||||
},
|
||||
Registry {
|
||||
qualification_sha256: String,
|
||||
},
|
||||
QualifyPair {
|
||||
minimum_generation: u64,
|
||||
expected_agent_sha256: String,
|
||||
expected_helper_sha256: String,
|
||||
unit_pins: Vec<rmm_domain::agent_update_provisioning::LocalServicePin>,
|
||||
},
|
||||
ValidatePublicBundle {
|
||||
record: Vec<u8>,
|
||||
policy: Vec<u8>,
|
||||
keyring: Vec<u8>,
|
||||
health_pin: Vec<u8>,
|
||||
},
|
||||
CanonicalRelease {
|
||||
manifest: ReleaseManifest,
|
||||
},
|
||||
CanonicalRecord {
|
||||
record: InstalledReleaseRecord,
|
||||
},
|
||||
CanonicalPolicy {
|
||||
policy: Box<LocalUpdatePolicy>,
|
||||
},
|
||||
ValidateRelease {
|
||||
envelope: ReleaseEnvelope,
|
||||
},
|
||||
}
|
||||
/// Independent, read-only administrator sample after the coordinated pair
|
||||
/// bootstrap. Fresh normal server signatures are checked at the CURRENT native
|
||||
/// clock; neither old historical rows nor bootstrap metadata create a lease.
|
||||
fn qualify_pair(
|
||||
minimum_generation: u64,
|
||||
agent_sha256: &str,
|
||||
helper_sha256: &str,
|
||||
pins: &[rmm_domain::agent_update_provisioning::LocalServicePin],
|
||||
) -> Result<serde_json::Value> {
|
||||
use prost::Message;
|
||||
use rmm_agent_core::{
|
||||
auth::Binding,
|
||||
auth::HelperIdentity,
|
||||
crypto::DalekVerifier,
|
||||
helper_reconcile::{SignedResponse, verify_checkpoint_repair_history_with},
|
||||
reconcile::{Channel, SyncClock, verify_response_with},
|
||||
};
|
||||
use rmm_protocol::{SyncRequest, SyncResponse};
|
||||
use rmm_updater_linux::{
|
||||
Budget,
|
||||
services::{Service, ServicePolicy, Systemd},
|
||||
};
|
||||
use rusqlite::{Connection, OpenFlags};
|
||||
use std::os::{fd::AsRawFd, unix::fs::MetadataExt};
|
||||
ensure!(
|
||||
unsafe { libc::geteuid() } == 0
|
||||
&& minimum_generation > 0
|
||||
&& [agent_sha256, helper_sha256]
|
||||
.iter()
|
||||
.all(|v| rmm_domain::agent_update::digest(v)),
|
||||
"BOOTSTRAP_QUALIFICATION_SCOPE"
|
||||
);
|
||||
let boot: Uuid = std::fs::read_to_string("/proc/sys/kernel/random/boot_id")?
|
||||
.trim()
|
||||
.parse()?;
|
||||
let budget = Budget::new(boot, std::time::Duration::from_secs(30))?;
|
||||
let clock = rmm_updater_worker::clock::NativeClock::new()?;
|
||||
let mut policies = Vec::new();
|
||||
for (index, pin) in pins.iter().enumerate() {
|
||||
let service = match index {
|
||||
0 => Service::Agent,
|
||||
1 => Service::General,
|
||||
2 => Service::Full,
|
||||
3 => Service::Apt,
|
||||
_ => anyhow::bail!("BOOTSTRAP_UNIT_PIN_SET"),
|
||||
};
|
||||
ensure!(pin.unit == service.unit(), "BOOTSTRAP_UNIT_PIN_SET");
|
||||
policies.push(ServicePolicy {
|
||||
service,
|
||||
image_sha256: if index == 0 {
|
||||
agent_sha256
|
||||
} else {
|
||||
helper_sha256
|
||||
}
|
||||
.into(),
|
||||
unit_sha256: pin.unit_sha256.clone(),
|
||||
});
|
||||
}
|
||||
let system = Systemd::new(policies)?;
|
||||
let held = [
|
||||
system.observe(Service::Agent, &budget)?,
|
||||
system.observe(Service::General, &budget)?,
|
||||
system.observe(Service::Full, &budget)?,
|
||||
];
|
||||
if pins.len() == 4 {
|
||||
system.verify_inactive(Service::Apt, &budget)?;
|
||||
}
|
||||
let binding_path = std::path::Path::new("/var/lib/rmm-agent-remote/binding.json");
|
||||
let metadata = std::fs::symlink_metadata(binding_path)?;
|
||||
ensure!(
|
||||
metadata.is_file()
|
||||
&& !metadata.file_type().is_symlink()
|
||||
&& metadata.uid() == 993
|
||||
&& metadata.nlink() == 1
|
||||
&& metadata.mode() & 0o077 == 0,
|
||||
"BOOTSTRAP_AGENT_PUBLIC_BINDING"
|
||||
);
|
||||
let binding_raw = std::fs::read(binding_path)?;
|
||||
ensure!(binding_raw.len() <= 8192, "BOOTSTRAP_BINDING_LIMIT");
|
||||
let mut binding: Binding = serde_json::from_slice(&binding_raw)?;
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct PublicKeyRecord { key_id:String, algorithm:String, schema_version:u32, public_key_hex:String }
|
||||
let mut effective = None;
|
||||
for (path,owner) in [("/var/lib/rmm-agent-remote/job-signing-key.json",993),("/etc/rmm-remote/helper-signing-key.json",0)] {
|
||||
let path=std::path::Path::new(path);let info=std::fs::symlink_metadata(path)?;
|
||||
ensure!(info.is_file()&&!info.file_type().is_symlink()&&info.uid()==owner&&info.nlink()==1&&info.mode()&0o022==0&&info.len()<=4096,"BOOTSTRAP_PROTECTED_PUBLIC_KEY_RECORD");
|
||||
let raw=std::fs::read(path)?;let key:PublicKeyRecord=serde_json::from_slice(&raw)?;let public:[u8;32]=hex::decode(&key.public_key_hex)?.try_into().map_err(|_|anyhow::anyhow!("BOOTSTRAP_PUBLIC_KEY_SIZE"))?;
|
||||
ensure!(key.schema_version==1&&key.algorithm=="Ed25519"&&key.key_id==hash(&public)&&!VerifyingKey::from_bytes(&public)?.is_weak(),"BOOTSTRAP_PUBLIC_KEY_RECORD");
|
||||
if let Some(old)=&effective{ensure!(old==&key.public_key_hex,"BOOTSTRAP_INDEPENDENT_KEY_PINS_DIFFER");}else{effective=Some(key.public_key_hex);}
|
||||
ensure!(std::fs::read(path)?==raw,"BOOTSTRAP_PUBLIC_KEY_RECORD_CHANGED");
|
||||
}
|
||||
let effective=effective.ok_or_else(||anyhow::anyhow!("BOOTSTRAP_PUBLIC_KEY_REQUIRED"))?;
|
||||
ensure!(binding.public_key_hex.is_empty()||binding.public_key_hex==effective,"BOOTSTRAP_BINDING_PUBLIC_KEY");binding.public_key_hex=effective;
|
||||
let lock = std::fs::File::open("/var/lib/rmm-helper/executor.lock")?;
|
||||
ensure!(
|
||||
unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0,
|
||||
"BOOTSTRAP_HELPER_BUSY"
|
||||
);
|
||||
let open = |path: &str| -> Result<Connection> {
|
||||
ensure!(
|
||||
!std::path::Path::new(&format!("{path}-wal")).exists()
|
||||
&& !std::path::Path::new(&format!("{path}-shm")).exists(),
|
||||
"BOOTSTRAP_DELETE_JOURNAL_REQUIRED"
|
||||
);
|
||||
let db = Connection::open_with_flags(
|
||||
path,
|
||||
OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
|
||||
)?;
|
||||
db.busy_timeout(std::time::Duration::from_millis(250))?;
|
||||
db.execute_batch("PRAGMA query_only=ON;")?;
|
||||
ensure!(
|
||||
db.query_row("PRAGMA journal_mode", [], |r| r.get::<_, String>(0))? == "delete"
|
||||
&& db.query_row("PRAGMA integrity_check", [], |r| r.get::<_, String>(0))? == "ok",
|
||||
"BOOTSTRAP_JOURNAL_INTEGRITY"
|
||||
);
|
||||
Ok(db)
|
||||
};
|
||||
let agent = open("/var/lib/rmm-agent-remote/journal.sqlite")?;
|
||||
let consumption = open("/var/lib/rmm-agent-remote/consumption.sqlite")?;
|
||||
let helper = open("/var/lib/rmm-helper/consumption.sqlite")?;
|
||||
ensure!(agent.query_row("SELECT count(*) FROM job_attempts WHERE state NOT IN ('succeeded','failed','cancelled','expired')",[],|r|r.get::<_,u64>(0))?==0,"BOOTSTRAP_OPEN_AGENT_JOB");
|
||||
for db in [&consumption, &helper] {
|
||||
ensure!(
|
||||
db.query_row(
|
||||
"SELECT count(*) FROM consumed WHERE result IS NULL",
|
||||
[],
|
||||
|r| r.get::<_, u64>(0)
|
||||
)? == 0,
|
||||
"BOOTSTRAP_UNRESOLVED_CONSUMPTION"
|
||||
);
|
||||
}
|
||||
let (generation,decision):(u64,String)=agent.query_row("SELECT generation,last_decision FROM reconcile_meta WHERE id=1 AND fault IS NULL AND pending_request IS NULL",[],|r|Ok((r.get(0)?,r.get(1)?)))?;
|
||||
ensure!(
|
||||
generation > minimum_generation,
|
||||
"BOOTSTRAP_NEW_GENERATION_REQUIRED"
|
||||
);
|
||||
let (h_generation, h_decision): (u64, String) = helper.query_row(
|
||||
"SELECT generation,last_decision FROM helper_sync_meta WHERE id=1 AND fault IS NULL",
|
||||
[],
|
||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
||||
)?;
|
||||
ensure!(
|
||||
generation == h_generation && decision == h_decision,
|
||||
"BOOTSTRAP_PAIR_NORMAL_SYNC_NOT_ALIGNED"
|
||||
);
|
||||
let (hrequest, hresponse): (Vec<u8>, Vec<u8>) = helper.query_row(
|
||||
"SELECT request,response FROM helper_sync_decisions WHERE decision_id=?1",
|
||||
[&decision],
|
||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
||||
)?;
|
||||
let signed: SignedResponse = serde_json::from_slice(&hresponse)?;
|
||||
let request = SyncRequest::decode(hrequest.as_slice())?;
|
||||
ensure!(
|
||||
request.encode_to_vec() == hrequest,
|
||||
"BOOTSTRAP_SYNC_REQUEST_CANONICAL"
|
||||
);
|
||||
let response = SyncResponse {
|
||||
decision_bytes: signed.decision_bytes.clone(),
|
||||
signature: signed.signature.clone(),
|
||||
};
|
||||
let applied = verify_response_with(
|
||||
&DalekVerifier,
|
||||
&binding,
|
||||
&request,
|
||||
&Channel {
|
||||
connection_generation: generation,
|
||||
boot_id: boot,
|
||||
},
|
||||
&response,
|
||||
clock.now()?,
|
||||
)?;
|
||||
ensure!(
|
||||
applied.decision_id.to_string() == decision
|
||||
&& applied.ready
|
||||
&& applied.helper_ready
|
||||
&& applied
|
||||
.attempts
|
||||
.iter()
|
||||
.all(|a| a.update_inflight.is_none() && a.outcome_state != "unknown"),
|
||||
"BOOTSTRAP_FRESH_NORMAL_SYNC_REQUIRED"
|
||||
);
|
||||
let stored: Vec<u8> = agent.query_row(
|
||||
"SELECT response FROM reconcile_requests WHERE id=?1 AND generation=?2",
|
||||
rusqlite::params![request.request_id, generation],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(
|
||||
SyncResponse::decode(stored.as_slice())? == response,
|
||||
"BOOTSTRAP_BOTH_NORMAL_ORIGINAL_RESPONSES"
|
||||
);
|
||||
verify_checkpoint_repair_history_with(
|
||||
&helper,
|
||||
&binding,
|
||||
None,
|
||||
HelperIdentity::Root,
|
||||
&DalekVerifier,
|
||||
)?;
|
||||
for service in &held {
|
||||
service.verify(&budget)?;
|
||||
}
|
||||
ensure!(
|
||||
std::fs::read(binding_path)? == binding_raw,
|
||||
"BOOTSTRAP_BINDING_CHANGED"
|
||||
);
|
||||
clock.now()?;
|
||||
budget.check()?;
|
||||
Ok(
|
||||
serde_json::json!({"schema_version":1,"profile":"linux_compatible_baseline_qualification_v1","boot_id":boot,"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,
|
||||
"services":held.iter().map(|v|v.proof()).collect::<Vec<_>>(),"normal_signed_sync_observed":true,"generation":generation,"decision_id":decision,"request_sha256":hash(&hrequest),"decision_sha256":hash(&signed.decision_bytes),"signature_sha256":hash(&signed.signature),"observed_at":clock.now()?,"ready":false,"helper_ready":false,"unlock":false,"job_authority":false,"apt_native_runtime_qualified":false}),
|
||||
)
|
||||
}
|
||||
|
||||
fn run() -> Result<()> {
|
||||
ensure!(std::env::args().count() == 1, "BOOTSTRAP_NO_ARGUMENTS");
|
||||
let mut raw = Vec::new();
|
||||
std::io::stdin()
|
||||
.take(512 * 1024 + 1)
|
||||
.read_to_end(&mut raw)?;
|
||||
ensure!(raw.len() <= 512 * 1024, "BOOTSTRAP_INPUT_LIMIT");
|
||||
let output = match serde_json::from_slice::<Input>(&raw)? {
|
||||
Input::RenderFull {
|
||||
config,
|
||||
pin,
|
||||
job_public_key_hex,
|
||||
new_helper_sha256,
|
||||
} => {
|
||||
let key: [u8; 32] = hex::decode(job_public_key_hex)?
|
||||
.try_into()
|
||||
.map_err(|_| anyhow::anyhow!("BOOTSTRAP_PUBLIC_KEY_SIZE"))?;
|
||||
let key = VerifyingKey::from_bytes(&key)?;
|
||||
let value =
|
||||
rmm_updater_handoff::render_linux_full(&config, &pin, &new_helper_sha256, &key)?;
|
||||
serde_json::json!({"proof":value.proof(),"config":value.new_config_bytes(),"pin":value.new_pin_bytes()})
|
||||
}
|
||||
Input::QualifyPair {
|
||||
minimum_generation,
|
||||
expected_agent_sha256,
|
||||
expected_helper_sha256,
|
||||
unit_pins,
|
||||
} => qualify_pair(
|
||||
minimum_generation,
|
||||
&expected_agent_sha256,
|
||||
&expected_helper_sha256,
|
||||
&unit_pins,
|
||||
)?,
|
||||
Input::Registry {
|
||||
qualification_sha256,
|
||||
} => {
|
||||
let boot: Uuid = std::fs::read_to_string("/proc/sys/kernel/random/boot_id")?
|
||||
.trim()
|
||||
.parse()?;
|
||||
let budget = rmm_updater_linux::Budget::new(boot, std::time::Duration::from_secs(30))?;
|
||||
serde_json::to_value(rmm_updater_worker::reader_registry::bootstrap_metadata(
|
||||
&qualification_sha256,
|
||||
&budget,
|
||||
)?)?
|
||||
}
|
||||
Input::CanonicalRelease { manifest } => {
|
||||
ensure!(manifest.validate(), "BOOTSTRAP_RELEASE_SHAPE");
|
||||
let bytes = serde_json::to_vec(&manifest)?;
|
||||
serde_json::json!({"bytes":bytes,"sha256":hash(&bytes)})
|
||||
}
|
||||
Input::CanonicalRecord { record } => {
|
||||
let bytes = record.bytes().map_err(anyhow::Error::msg)?;
|
||||
serde_json::json!({"bytes":bytes,"sha256":hash(&bytes)})
|
||||
}
|
||||
Input::CanonicalPolicy { policy } => {
|
||||
ensure!(policy.validate(), "BOOTSTRAP_POLICY_SHAPE");
|
||||
let bytes = serde_json::to_vec(&policy)?;
|
||||
serde_json::json!({"bytes":bytes,"sha256":hash(&bytes)})
|
||||
}
|
||||
Input::ValidateRelease { envelope } => {
|
||||
let decoded = envelope.decode().map_err(anyhow::Error::msg)?;
|
||||
serde_json::json!({"manifest":decoded.manifest,"manifest_sha256":hash(&decoded.payload_bytes),"shape_only_not_signature_verified":true})
|
||||
}
|
||||
Input::ValidatePublicBundle {
|
||||
record,
|
||||
policy,
|
||||
keyring,
|
||||
health_pin,
|
||||
} => {
|
||||
let installed =
|
||||
InstalledReleaseRecord::from_bytes(&record).map_err(anyhow::Error::msg)?;
|
||||
let (local, policy_sha256) =
|
||||
LocalUpdatePolicy::from_bytes(&policy).map_err(anyhow::Error::msg)?;
|
||||
let keys: UpdateKeyringFile = serde_json::from_slice(&keyring)?;
|
||||
let health: HealthKeyPin = serde_json::from_slice(&health_pin)?;
|
||||
ensure!(
|
||||
keys.validate()
|
||||
&& health.validate()
|
||||
&& local.initial_record_sha256 == hash(&record)
|
||||
&& local.initial_activation_floor == installed.activation_floor,
|
||||
"BOOTSTRAP_PUBLIC_BUNDLE_SHAPE"
|
||||
);
|
||||
serde_json::json!({"record_sha256":hash(&record),"policy_sha256":policy_sha256,"keyring_sha256":hash(&keyring),"health_pin_sha256":hash(&health_pin),"shape_only_not_signature_verified":true})
|
||||
}
|
||||
};
|
||||
println!("{}", serde_json::to_string(&output)?);
|
||||
Ok(())
|
||||
}
|
||||
fn main() {
|
||||
if run().is_err() {
|
||||
eprintln!("LINUX_BOOTSTRAP_METADATA_FAILED");
|
||||
std::process::exit(1)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user