// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. //! The agent's state dir: who it is, what it trusts, and the job ids it has seen. //! //! ```text //! agent.json server, team, agent, roles, pinned release keys, root SHA-256, poll seconds //! root.pem the Domi root (hashes to the code's pin) //! chain.pem the agent certificate and the agents intermediate //! key.pem the agent key (0600; never leaves the machine) //! jobs.seen the job guard //! downloads/ artifacts while they are checked (deleted after each job) //! ``` use std::fs; use std::io::{self, Write}; use std::path::{Path, PathBuf}; use legatus_protocol::{JobGuard, Roles}; use serde::{Deserialize, Serialize}; /// What `agent.json` holds. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct AgentFile { /// Always 1. pub v: u32, /// `https://host[:port]`. pub server: String, /// Team id. pub team: String, /// Agent id. pub agent: String, /// Current roles. pub roles: Roles, /// The team's release keys, pinned at enrollment. pub release_keys: Vec, /// SHA-256 of the Domi root, lowercase hex. pub root_sha256: String, /// Long-poll seconds. pub poll_seconds: u32, } /// Everything an enrolled agent loads. #[derive(Debug, Clone)] pub struct Enrolled { /// `agent.json`. pub file: AgentFile, /// The root's DER. pub root_der: Vec, /// `chain.pem`. pub chain_pem: String, /// `key.pem`. pub key_pem: String, } /// Why the state cannot be used. #[derive(Debug, thiserror::Error)] pub enum StateError { /// Not enrolled yet. #[error("this machine is not enrolled; run: legatus enroll ")] NotEnrolled, /// A file is unreadable or inconsistent. #[error("the state in {0} is damaged: {1}")] Damaged(String, String), /// The disk. #[error("the state could not be written: {0}")] Io(#[from] io::Error), } /// The state dir. #[derive(Debug, Clone)] pub struct State { dir: PathBuf, } /// The default state dir for this OS. pub fn default_dir() -> PathBuf { if let Some(d) = std::env::var_os("LEGATUS_STATE") { return PathBuf::from(d); } if cfg!(windows) { let base = std::env::var_os("ProgramData").unwrap_or_else(|| "C:\\ProgramData".into()); PathBuf::from(base).join("Legatus") } else { PathBuf::from("/var/lib/legatus") } } impl State { /// The state in `dir`. pub fn new(dir: impl Into) -> State { State { dir: dir.into() } } /// The dir. pub fn dir(&self) -> &Path { &self.dir } fn path(&self, name: &str) -> PathBuf { self.dir.join(name) } /// Where artifacts are kept while checked. pub fn downloads(&self) -> PathBuf { self.path("downloads") } /// Is there an enrollment? pub fn is_enrolled(&self) -> bool { self.path("agent.json").exists() } /// Load the enrollment. pub fn load(&self) -> Result { if !self.is_enrolled() { return Err(StateError::NotEnrolled); } let damaged = |what: &str, e: String| StateError::Damaged(what.to_owned(), e); let text = fs::read_to_string(self.path("agent.json")) .map_err(|e| damaged("agent.json", e.to_string()))?; let file: AgentFile = serde_json::from_str(&text).map_err(|e| damaged("agent.json", e.to_string()))?; let root_pem = fs::read_to_string(self.path("root.pem")) .map_err(|e| damaged("root.pem", e.to_string()))?; let root_der = domi_pki::chain_der(&root_pem) .ok() .and_then(|mut v| (v.len() == 1).then(|| v.remove(0))) .ok_or_else(|| damaged("root.pem", "not one certificate".into()))?; if legatus_protocol::sha256_hex(&root_der) != file.root_sha256 { return Err(damaged("root.pem", "it is not the pinned root".into())); } Ok(Enrolled { file, root_der, chain_pem: fs::read_to_string(self.path("chain.pem")) .map_err(|e| damaged("chain.pem", e.to_string()))?, key_pem: fs::read_to_string(self.path("key.pem")) .map_err(|e| damaged("key.pem", e.to_string()))?, }) } /// Save a new enrollment (replacing any earlier one). pub fn save_enrollment( &self, file: &AgentFile, root_pem: &str, chain_pem: &str, key_pem: &str, ) -> Result<(), StateError> { fs::create_dir_all(&self.dir)?; write_atomic(&self.path("key.pem"), key_pem.as_bytes(), true)?; write_atomic(&self.path("chain.pem"), chain_pem.as_bytes(), false)?; write_atomic(&self.path("root.pem"), root_pem.as_bytes(), false)?; let _ = fs::remove_file(self.path("jobs.seen")); // agent.json last: until it exists, the machine is not enrolled. self.save_file(file) } /// Save `agent.json`. pub fn save_file(&self, file: &AgentFile) -> Result<(), StateError> { let text = serde_json::to_vec_pretty(file) .map_err(|e| StateError::Damaged("agent.json".into(), e.to_string()))?; write_atomic(&self.path("agent.json"), &text, false)?; Ok(()) } /// Save a renewed certificate and its key. pub fn save_identity(&self, chain_pem: &str, key_pem: &str) -> Result<(), StateError> { write_atomic(&self.path("key.pem"), key_pem.as_bytes(), true)?; write_atomic(&self.path("chain.pem"), chain_pem.as_bytes(), false)?; Ok(()) } /// The job guard as saved (a damaged file is an error: replays must not slip through). pub fn load_guard(&self) -> Result { match fs::read_to_string(self.path("jobs.seen")) { Ok(t) => JobGuard::load(&t) .map_err(|e| StateError::Damaged("jobs.seen".into(), e.to_string())), Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(JobGuard::new()), Err(e) => Err(e.into()), } } /// Save the job guard. pub fn save_guard(&self, g: &JobGuard) -> Result<(), StateError> { write_atomic(&self.path("jobs.seen"), g.save().as_bytes(), false)?; Ok(()) } } /// Write through a temporary file renamed into place; `secret` files are 0600 on Unix. pub(crate) fn write_atomic(path: &Path, data: &[u8], secret: bool) -> io::Result<()> { let parent = path .parent() .ok_or_else(|| io::Error::other("no parent dir"))?; fs::create_dir_all(parent)?; let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("file"); let tmp = parent.join(format!(".{name}.tmp-{}", std::process::id())); let _ = fs::remove_file(&tmp); let mut o = fs::OpenOptions::new(); o.write(true).create_new(true); #[cfg(unix)] { use std::os::unix::fs::OpenOptionsExt; o.mode(if secret { 0o600 } else { 0o644 }); } #[cfg(not(unix))] let _ = secret; let mut f = o.open(&tmp)?; f.write_all(data)?; f.sync_all()?; drop(f); fs::rename(&tmp, path) }