From 58c87547dbefddcdf317288ce6aba115c9e35d60 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 17 Nov 2026 12:09:57 +0100 Subject: [PATCH] [agent] Legatus agent: pinned-root TLS and mTLS, HTTP client, enroll, job pipeline, renewal, Linux target, CLI (21 tests) --- crates/agent/src/client.rs | 209 +++++++++++++++++++++ crates/agent/src/http.rs | 346 ++++++++++++++++++++++++++++++++++ crates/agent/src/lib.rs | 353 ++++++++++++++++++++++++++++++++++- crates/agent/src/main.rs | 110 ++++++++++- crates/agent/src/pipeline.rs | 316 +++++++++++++++++++++++++++++++ crates/agent/src/state.rs | 217 +++++++++++++++++++++ crates/agent/src/target.rs | 65 +++++++ crates/agent/src/tls.rs | 171 +++++++++++++++++ 8 files changed, 1785 insertions(+), 2 deletions(-) create mode 100644 crates/agent/src/client.rs create mode 100644 crates/agent/src/http.rs create mode 100644 crates/agent/src/pipeline.rs create mode 100644 crates/agent/src/state.rs create mode 100644 crates/agent/src/target.rs create mode 100644 crates/agent/src/tls.rs diff --git a/crates/agent/src/client.rs b/crates/agent/src/client.rs new file mode 100644 index 0000000..ecea18a --- /dev/null +++ b/crates/agent/src/client.rs @@ -0,0 +1,209 @@ +// 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 Fabrica server, as the agent talks to it (docs/02_protocol.md). + +use std::io::Write; +use std::sync::Arc; +use std::time::Duration; + +use legatus_protocol::msg::{ + EnrollRequest, EnrollResponse, ErrorBody, Hello, HostFacts, RenewRequest, Renewed, V, Welcome, +}; +use legatus_protocol::{EnrollmentCode, MAX_BODY, Report, decode, encode}; +use rustls::ClientConfig; + +use crate::http::{self, HttpError, Server}; +use crate::tls::{self, PinnedRoot, TlsError}; + +/// Why a call failed. +#[derive(Debug, thiserror::Error)] +pub enum ClientError { + /// The connection. + #[error("{0}")] + Http(#[from] HttpError), + /// TLS could not be set up. + #[error("{0}")] + Tls(#[from] TlsError), + /// The server said no. + #[error("the server refused ({status} {code}): {message}")] + Refused { + /// HTTP status. + status: u16, + /// Stable code. + code: String, + /// Its message. + message: String, + }, + /// The server's answer is not what the protocol says. + #[error("the server's answer cannot be used: {0}")] + BadAnswer(String), +} + +impl ClientError { + /// The stable code, when the server refused. + pub fn code(&self) -> Option<&str> { + match self { + ClientError::Refused { code, .. } => Some(code), + _ => None, + } + } +} + +fn refused(status: u16, body: &[u8]) -> ClientError { + match serde_json::from_slice::(body) { + Ok(e) => ClientError::Refused { + status, + code: e.error.chars().take(64).collect(), + message: e.message.chars().take(500).collect(), + }, + Err(_) => ClientError::Refused { + status, + code: "http".into(), + message: String::from_utf8_lossy(body.get(..body.len().min(200)).unwrap_or_default()) + .into_owned(), + }, + } +} + +const TIMEOUT: Duration = Duration::from_secs(30); + +/// Enroll: send the code's secret and the CSR to the server the code names, trusting only the +/// root the code pins. +pub fn enroll( + code: &EnrollmentCode, + csr_pem: &str, + host: HostFacts, +) -> Result { + let server = Server::parse(code.server())?; + let cfg = tls::enroll_config(PinnedRoot::by_hash(*code.root_sha256()))?; + let body = encode(&EnrollRequest { + v: V, + secret: code.secret_hex(), + csr: csr_pem.to_owned(), + host, + }); + let r = http::request( + &cfg, + &server, + "POST", + "/legatus/v1/enroll", + Some(&body), + MAX_BODY as u64, + TIMEOUT, + )?; + if r.status != 200 { + return Err(refused(r.status, &r.body)); + } + decode(&r.body).map_err(|e| ClientError::BadAnswer(e.to_string())) +} + +/// The server, over mTLS. +#[derive(Clone)] +pub struct Fabrica { + server: Server, + cfg: Arc, +} + +impl Fabrica { + /// A client for `server` with this mTLS configuration. + pub fn new(server_url: &str, cfg: Arc) -> Result { + Ok(Fabrica { + server: Server::parse(server_url)?, + cfg, + }) + } + + fn call( + &self, + method: &str, + path: &str, + body: Option<&[u8]>, + timeout: Duration, + ) -> Result { + Ok(http::request( + &self.cfg, + &self.server, + method, + path, + body, + MAX_BODY as u64, + timeout, + )?) + } + + /// `POST hello`. + pub fn hello(&self, hello: &Hello) -> Result { + let r = self.call("POST", "/legatus/v1/hello", Some(&encode(hello)), TIMEOUT)?; + if r.status != 200 { + return Err(refused(r.status, &r.body)); + } + decode(&r.body).map_err(|e| ClientError::BadAnswer(e.to_string())) + } + + /// `GET jobs?wait=`: the next job's bytes, or `None`. + pub fn next_job(&self, wait_seconds: u32) -> Result>, ClientError> { + let wait = wait_seconds.min(55); + let path = format!("/legatus/v1/jobs?wait={wait}"); + let r = self.call( + "GET", + &path, + None, + Duration::from_secs(u64::from(wait) + 20), + )?; + match r.status { + 200 => Ok(Some(r.body)), + 204 => Ok(None), + s => Err(refused(s, &r.body)), + } + } + + /// `POST reports`. + pub fn report(&self, report: &Report) -> Result<(), ClientError> { + let r = self.call( + "POST", + "/legatus/v1/reports", + Some(&encode(report)), + TIMEOUT, + )?; + match r.status { + 200 | 202 | 204 => Ok(()), + s => Err(refused(s, &r.body)), + } + } + + /// `POST renew`. + pub fn renew(&self, csr_pem: &str) -> Result { + let body = encode(&RenewRequest { + v: V, + csr: csr_pem.to_owned(), + }); + let r = self.call("POST", "/legatus/v1/renew", Some(&body), TIMEOUT)?; + if r.status != 200 { + return Err(refused(r.status, &r.body)); + } + decode(&r.body).map_err(|e| ClientError::BadAnswer(e.to_string())) + } + + /// `GET artifacts//` into `out`, at most `max` bytes. + pub fn artifact( + &self, + job: &str, + name: &str, + max: u64, + out: &mut dyn Write, + ) -> Result { + let path = format!("/legatus/v1/artifacts/{job}/{name}"); + let timeout = Duration::from_secs(300); + let (status, n) = http::download(&self.cfg, &self.server, &path, max, out, timeout)?; + if status != 200 { + return Err(ClientError::Refused { + status, + code: "download".into(), + message: "the artifact could not be downloaded".into(), + }); + } + Ok(n) + } +} diff --git a/crates/agent/src/http.rs b/crates/agent/src/http.rs new file mode 100644 index 0000000..7949b0f --- /dev/null +++ b/crates/agent/src/http.rs @@ -0,0 +1,346 @@ +// 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/. + +//! A small HTTP/1.1 client over rustls: one request per connection, bodies framed by +//! `Content-Length` or chunked encoding, every size bounded. The server's answers are hostile. + +use std::io::{self, Read, Write}; +use std::net::{TcpStream, ToSocketAddrs}; +use std::sync::Arc; +use std::time::Duration; + +use rustls::{ClientConfig, ClientConnection, StreamOwned}; +use rustls_pki_types::ServerName; + +const MAX_HEAD: usize = 16 * 1024; + +/// Why a request failed. +#[derive(Debug, thiserror::Error)] +pub enum HttpError { + /// The server address. + #[error("the server address cannot be used: {0}")] + Address(String), + /// Could not connect. + #[error("cannot reach the Fabrica server: {0}")] + Connect(String), + /// TLS failed (often: the server is not the one the code names, or a certificate is refused). + #[error("the secure connection failed: {0}")] + Tls(String), + /// The answer is not HTTP as expected. + #[error("the server's answer cannot be read: {0}")] + Protocol(String), + /// The body is larger than allowed. + #[error("the server's answer is too large")] + TooLarge, +} + +/// `https://host[:port]`, split. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Server { + host: String, + port: u16, +} + +impl Server { + /// Parse a server URL as an enrollment code carries it. + pub fn parse(url: &str) -> Result { + let bad = || HttpError::Address(url.chars().take(100).collect()); + let auth = url.strip_prefix("https://").ok_or_else(bad)?; + let (host, port) = if let Some(rest) = auth.strip_prefix('[') { + let (h, after) = rest.split_once(']').ok_or_else(bad)?; + match after.strip_prefix(':') { + Some(p) => (h, Some(p)), + None if after.is_empty() => (h, None), + None => return Err(bad()), + } + } else { + match auth.split_once(':') { + Some((h, p)) => (h, Some(p)), + None => (auth, None), + } + }; + let port = match port { + Some(p) => p.parse::().map_err(|_| bad())?, + None => 443, + }; + if host.is_empty() || host.contains('/') { + return Err(bad()); + } + Ok(Server { + host: host.to_owned(), + port, + }) + } + + /// Host name or address. + pub fn host(&self) -> &str { + &self.host + } + + /// Port. + pub fn port(&self) -> u16 { + self.port + } + + fn host_header(&self) -> String { + let h = if self.host.contains(':') { + format!("[{}]", self.host) + } else { + self.host.clone() + }; + if self.port == 443 { + h + } else { + format!("{h}:{}", self.port) + } + } +} + +type Tls = StreamOwned; + +fn open(cfg: &Arc, server: &Server, timeout: Duration) -> Result { + let name = ServerName::try_from(server.host.clone()) + .map_err(|_| HttpError::Address(server.host.clone()))?; + let addr = (server.host.as_str(), server.port) + .to_socket_addrs() + .map_err(|e| HttpError::Connect(e.to_string()))? + .next() + .ok_or_else(|| HttpError::Connect("no address".into()))?; + let tcp = TcpStream::connect_timeout(&addr, Duration::from_secs(10)) + .map_err(|e| HttpError::Connect(e.to_string()))?; + tcp.set_read_timeout(Some(timeout)) + .and_then(|()| tcp.set_write_timeout(Some(timeout))) + .map_err(|e| HttpError::Connect(e.to_string()))?; + let conn = + ClientConnection::new(cfg.clone(), name).map_err(|e| HttpError::Tls(e.to_string()))?; + let mut s = StreamOwned::new(conn, tcp); + // Finish the handshake now, so TLS refusals are reported as such. + while s.conn.is_handshaking() { + s.conn + .complete_io(&mut s.sock) + .map_err(|e| HttpError::Tls(tls_reason(&e)))?; + } + Ok(s) +} + +fn tls_reason(e: &io::Error) -> String { + match e.get_ref().and_then(|i| i.downcast_ref::()) { + Some(r) => r.to_string(), + None => e.to_string(), + } +} + +fn io_err(e: io::Error) -> HttpError { + if e.get_ref().is_some_and(|i| i.is::()) { + HttpError::Tls(tls_reason(&e)) + } else { + HttpError::Protocol(e.to_string()) + } +} + +struct Head { + status: u16, + framing: Framing, + rest: Vec, +} + +enum Framing { + Length(u64), + Chunked, +} + +fn send( + s: &mut Tls, + server: &Server, + method: &str, + path: &str, + body: Option<&[u8]>, +) -> Result { + let mut req = format!( + "{method} {path} HTTP/1.1\r\nHost: {}\r\nUser-Agent: legatus/{}\r\nAccept: application/json\r\nConnection: close\r\n", + server.host_header(), + env!("CARGO_PKG_VERSION") + ); + if let Some(b) = body { + req.push_str(&format!( + "Content-Type: application/json\r\nContent-Length: {}\r\n", + b.len() + )); + } + req.push_str("\r\n"); + s.write_all(req.as_bytes()).map_err(io_err)?; + if let Some(b) = body { + s.write_all(b).map_err(io_err)?; + } + s.flush().map_err(io_err)?; + read_head(s) +} + +fn read_head(s: &mut Tls) -> Result { + let mut buf = Vec::with_capacity(1024); + let mut chunk = [0u8; 2048]; + loop { + let n = s.read(&mut chunk).map_err(io_err)?; + if n == 0 { + return Err(HttpError::Protocol("the connection closed early".into())); + } + buf.extend_from_slice(chunk.get(..n).unwrap_or_default()); + let mut headers = [httparse::EMPTY_HEADER; 64]; + let mut resp = httparse::Response::new(&mut headers); + match resp.parse(&buf) { + Ok(httparse::Status::Complete(len)) => { + let status = resp + .code + .ok_or_else(|| HttpError::Protocol("no status".into()))?; + let mut framing = None; + for h in resp.headers.iter() { + let v = std::str::from_utf8(h.value).unwrap_or("").trim(); + if h.name.eq_ignore_ascii_case("content-length") { + let n = v + .parse::() + .map_err(|_| HttpError::Protocol("bad Content-Length".into()))?; + if matches!(framing, Some(Framing::Length(m)) if m != n) { + return Err(HttpError::Protocol("two Content-Lengths".into())); + } + framing.get_or_insert(Framing::Length(n)); + } else if h.name.eq_ignore_ascii_case("transfer-encoding") { + if !v.eq_ignore_ascii_case("chunked") { + return Err(HttpError::Protocol("unknown transfer encoding".into())); + } + framing = Some(Framing::Chunked); + } + } + let framing = match framing { + Some(f) => f, + None if status == 204 || status == 304 => Framing::Length(0), + None => return Err(HttpError::Protocol("no body length".into())), + }; + return Ok(Head { + status, + framing, + rest: buf.get(len..).unwrap_or_default().to_vec(), + }); + } + Ok(httparse::Status::Partial) if buf.len() < MAX_HEAD => {} + Ok(httparse::Status::Partial) => return Err(HttpError::TooLarge), + Err(e) => return Err(HttpError::Protocol(e.to_string())), + } + } +} + +/// Read the body after `head` into `out`, at most `max` bytes. +fn read_body(s: &mut Tls, head: Head, max: u64, out: &mut dyn Write) -> Result { + let mut src = io::Cursor::new(head.rest).chain(s); + match head.framing { + Framing::Length(n) => { + if n > max { + return Err(HttpError::TooLarge); + } + let got = io::copy(&mut (&mut src).take(n), out).map_err(io_err)?; + if got != n { + return Err(HttpError::Protocol("the body was cut short".into())); + } + Ok(n) + } + Framing::Chunked => { + let mut total = 0u64; + loop { + let line = read_line(&mut src)?; + let size_text = line.split(';').next().unwrap_or("").trim(); + if size_text.is_empty() || size_text.len() > 16 { + return Err(HttpError::Protocol("bad chunk size".into())); + } + let size = u64::from_str_radix(size_text, 16) + .map_err(|_| HttpError::Protocol("bad chunk size".into()))?; + if size == 0 { + // Trailers, then the empty line. + for _ in 0..64 { + if read_line(&mut src)?.is_empty() { + return Ok(total); + } + } + return Err(HttpError::Protocol("too many trailers".into())); + } + total = total.saturating_add(size); + if total > max { + return Err(HttpError::TooLarge); + } + let got = io::copy(&mut (&mut src).take(size), out).map_err(io_err)?; + if got != size || !read_line(&mut src)?.is_empty() { + return Err(HttpError::Protocol("a chunk was cut short".into())); + } + } + } + } +} + +fn read_line(r: &mut impl Read) -> Result { + let mut line = Vec::new(); + let mut b = [0u8; 1]; + loop { + let n = r.read(&mut b).map_err(io_err)?; + if n == 0 { + return Err(HttpError::Protocol("the connection closed early".into())); + } + if b[0] == b'\n' { + if line.last() == Some(&b'\r') { + line.pop(); + } + return String::from_utf8(line).map_err(|_| HttpError::Protocol("not text".into())); + } + line.push(b[0]); + if line.len() > 1024 { + return Err(HttpError::TooLarge); + } + } +} + +/// A response: its status and body. +#[derive(Debug)] +pub struct Response { + /// HTTP status. + pub status: u16, + /// The body. + pub body: Vec, +} + +/// One request: `body` as JSON, the answer at most `max` bytes. +pub fn request( + cfg: &Arc, + server: &Server, + method: &str, + path: &str, + body: Option<&[u8]>, + max: u64, + timeout: Duration, +) -> Result { + let mut s = open(cfg, server, timeout)?; + let head = send(&mut s, server, method, path, body)?; + let status = head.status; + let mut out = Vec::new(); + read_body(&mut s, head, max, &mut out)?; + Ok(Response { status, body: out }) +} + +/// A GET whose body (when the status is 200) is written to `out`, at most `max` bytes. Returns +/// the status and the bytes written; any other status's body is returned as an error message. +pub fn download( + cfg: &Arc, + server: &Server, + path: &str, + max: u64, + out: &mut dyn Write, + timeout: Duration, +) -> Result<(u16, u64), HttpError> { + let mut s = open(cfg, server, timeout)?; + let head = send(&mut s, server, "GET", path, None)?; + let status = head.status; + if status != 200 { + let mut sink = Vec::new(); + let _ = read_body(&mut s, head, 64 * 1024, &mut sink); + return Ok((status, 0)); + } + let n = read_body(&mut s, head, max, out)?; + Ok((status, n)) +} diff --git a/crates/agent/src/lib.rs b/crates/agent/src/lib.rs index 9a316a6..be056a0 100644 --- a/crates/agent/src/lib.rs +++ b/crates/agent/src/lib.rs @@ -1 +1,352 @@ -//! Legatus agent (code follows its tests). +// 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/. + +//! Legatus, the Fabrica Domi agent (docs/01_legatus.md): enroll with a one-time code, then +//! long-poll the Fabrica server over mTLS for jobs, and run them only when the release is signed +//! by the team. + +pub mod client; +pub mod http; +pub mod pipeline; +pub mod state; +pub mod target; +pub mod tls; + +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use legatus_protocol::msg::{Capabilities, Hello, HostFacts, V, Welcome}; +use legatus_protocol::{EnrollmentCode, JobGuard}; + +use crate::client::{ClientError, Fabrica}; +use crate::pipeline::{Context, Fetch, Target}; +use crate::state::{AgentFile, Enrolled, State, StateError}; +use crate::tls::PinnedRoot; + +/// This Legatus's version. +pub const VERSION: &str = env!("CARGO_PKG_VERSION"); + +/// Unix seconds now. +pub fn now() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX)) + .unwrap_or(0) +} + +/// Why the agent stopped or refused. +#[derive(Debug, thiserror::Error)] +pub enum AgentError { + /// The code. + #[error("{0}")] + Code(#[from] legatus_protocol::CodeError), + /// The server. + #[error("{0}")] + Client(#[from] ClientError), + /// The state dir. + #[error("{0}")] + State(#[from] StateError), + /// TLS. + #[error("{0}")] + Tls(#[from] tls::TlsError), + /// The CA. + #[error("{0}")] + Pki(#[from] domi_pki::PkiError), + /// Already enrolled. + #[error("this machine is already enrolled as {0}; use --force to enroll again")] + AlreadyEnrolled(String), + /// The server's answer does not hold up. + #[error("the server's answer cannot be trusted: {0}")] + Untrusted(String), +} + +/// This machine. +pub fn host_facts() -> HostFacts { + let hostname = std::env::var("HOSTNAME") + .ok() + .or_else(|| std::fs::read_to_string("/etc/hostname").ok()) + .or_else(|| std::env::var("COMPUTERNAME").ok()) + .unwrap_or_else(|| "unknown".into()); + HostFacts { + hostname: hostname.trim().chars().take(64).collect(), + os: std::env::consts::OS.into(), + arch: std::env::consts::ARCH.into(), + version: VERSION.into(), + } +} + +fn chain_der(pem: &str) -> Result>, AgentError> { + domi_pki::chain_der(pem).map_err(|e| AgentError::Untrusted(e.to_string())) +} + +/// Enroll this machine with a pasted code. The key is made here and never leaves; the server +/// must chain to the pinned root; what it sends back is checked before anything is saved. +pub fn enroll(state: &State, code_text: &str, force: bool) -> Result { + let code = EnrollmentCode::parse(code_text)?; + if state.is_enrolled() && !force { + let who = state + .load() + .map(|e| format!("{}/{}", e.file.team, e.file.agent)) + .unwrap_or_else(|_| "an agent".into()); + return Err(AgentError::AlreadyEnrolled(who)); + } + let key = domi_pki::generate_key()?; + let csr = domi_pki::agent_csr(&key, "legatus")?; + let resp = client::enroll(&code, &csr, host_facts())?; + // The root must be the one the code pins. + let roots = chain_der(&resp.root)?; + let [root_der] = roots.as_slice() else { + return Err(AgentError::Untrusted( + "the root is not one certificate".into(), + )); + }; + if PinnedRoot::with_der(*code.root_sha256(), root_der.clone()).is_none() { + return Err(AgentError::Untrusted( + "the root is not the one in the code".into(), + )); + } + // The certificate must be an agent certificate for our own key, under that root. + let chain = chain_der(&resp.chain)?; + let id = domi_pki::verify_agent(&chain, root_der, now()) + .map_err(|e| AgentError::Untrusted(format!("the agent certificate: {e}")))?; + if id.team != resp.team || id.agent != resp.agent { + return Err(AgentError::Untrusted( + "the certificate names another agent".into(), + )); + } + if domi_pki::public_key_der(&resp.chain)? != key.public_key_der() { + return Err(AgentError::Untrusted( + "the certificate is not for this machine's key".into(), + )); + } + if resp.release_keys.is_empty() || resp.release_keys.len() > 8 { + return Err(AgentError::Untrusted( + "1 to 8 release keys are needed".into(), + )); + } + for k in &resp.release_keys { + if minisign_key_ok(k).is_none() { + return Err(AgentError::Untrusted("a release key cannot be read".into())); + } + } + let file = AgentFile { + v: V, + server: code.server().to_owned(), + team: resp.team.clone(), + agent: resp.agent.clone(), + roles: resp.roles, + release_keys: resp.release_keys.clone(), + root_sha256: legatus_protocol::hex(code.root_sha256()), + poll_seconds: resp.poll_seconds.clamp(5, 55), + }; + state.save_enrollment(&file, &resp.root, &resp.chain, &key.serialize_pem())?; + Ok(file) +} + +fn minisign_key_ok(k: &str) -> Option<()> { + // `Ed` + 8-byte id + 32-byte key, base64. + let k = k.trim(); + (k.len() == 56 && k.starts_with("RW")).then_some(()) +} + +/// An enrolled agent's connection to Fabrica. +pub struct Session { + state: State, + enrolled: Enrolled, + fabrica: Fabrica, + ctx: Context, + guard: JobGuard, +} + +fn pinned(e: &Enrolled) -> Result { + let mut sha = [0u8; 32]; + let raw = (0..32) + .map(|i| u8::from_str_radix(e.file.root_sha256.get(2 * i..2 * i + 2).unwrap_or("zz"), 16)) + .collect::, _>>() + .map_err(|_| AgentError::Untrusted("the pinned root".into()))?; + sha.copy_from_slice(&raw); + PinnedRoot::with_der(sha, e.root_der.clone()) + .ok_or_else(|| AgentError::Untrusted("the pinned root".into())) +} + +impl Session { + /// Load the state and set up mTLS. + pub fn open(state: State) -> Result { + let enrolled = state.load()?; + let cfg = tls::agent_config(pinned(&enrolled)?, &enrolled.chain_pem, &enrolled.key_pem)?; + let fabrica = Fabrica::new(&enrolled.file.server, cfg)?; + let ctx = Context { + team: enrolled.file.team.clone(), + roles: enrolled.file.roles, + release_keys: enrolled.file.release_keys.clone(), + downloads: state.downloads(), + }; + let guard = state.load_guard()?; + Ok(Session { + state, + enrolled, + fabrica, + ctx, + guard, + }) + } + + /// Who this agent is: `team/agent`. + pub fn who(&self) -> String { + format!("{}/{}", self.enrolled.file.team, self.enrolled.file.agent) + } + + /// The current roles. + pub fn roles(&self) -> legatus_protocol::Roles { + self.ctx.roles + } + + /// `hello`: say what this machine is and runs; take the roles Fabrica holds. + pub fn hello(&mut self, target: &dyn Target) -> Result { + let h = host_facts(); + let w = self.fabrica.hello(&Hello { + v: V, + version: VERSION.into(), + os: h.os, + arch: h.arch, + hostname: h.hostname, + capabilities: Capabilities { + deploy: target.kinds(), + build: Vec::new(), + }, + deployed: target.deployed(), + })?; + if w.team != self.enrolled.file.team || w.agent != self.enrolled.file.agent { + return Err(AgentError::Untrusted( + "the server greets another agent".into(), + )); + } + self.set_roles(w.roles)?; + Ok(w) + } + + fn set_roles(&mut self, roles: legatus_protocol::Roles) -> Result<(), AgentError> { + if self.enrolled.file.roles != roles { + self.enrolled.file.roles = roles; + self.ctx.roles = roles; + self.state.save_file(&self.enrolled.file)?; + } + Ok(()) + } + + /// Wait for one job (long poll) and handle it. `true` when there was one. + pub fn poll_once(&mut self, target: &dyn Target) -> Result { + let Some(bytes) = self.fabrica.next_job(self.enrolled.file.poll_seconds)? else { + return Ok(false); + }; + let fabrica = self.fabrica.clone(); + let mut send = |r: legatus_protocol::Report| { + if let Err(e) = fabrica.report(&r) { + eprintln!("legatus: a report for job {} was not delivered: {e}", r.job); + } + }; + let done = pipeline::handle( + &bytes, + now(), + &mut self.ctx, + &mut self.guard, + &self.fabrica, + target, + &mut send, + ); + if done.guard_changed { + self.state.save_guard(&self.guard)?; + } + if done.roles_changed { + let roles = self.ctx.roles; + self.enrolled.file.roles = roles; + self.state.save_file(&self.enrolled.file)?; + } + Ok(true) + } + + /// Renew the certificate when it is due (or `force`): a new key, a CSR, the new chain checked + /// and stored, mTLS set up again. `true` when renewed. + pub fn renew_if_due(&mut self, force: bool) -> Result { + let leaf = domi_pki::inspect(&self.enrolled.chain_pem)?; + if !force && !domi_pki::agent_renewal_due(leaf.not_after, now()) { + return Ok(false); + } + let key = domi_pki::generate_key()?; + let csr = domi_pki::agent_csr(&key, "legatus")?; + let r = self.fabrica.renew(&csr)?; + let chain = chain_der(&r.chain)?; + let id = domi_pki::verify_agent(&chain, &self.enrolled.root_der, now()) + .map_err(|e| AgentError::Untrusted(format!("the renewed certificate: {e}")))?; + if id.team != self.enrolled.file.team || id.agent != self.enrolled.file.agent { + return Err(AgentError::Untrusted( + "the renewed certificate names another agent".into(), + )); + } + if domi_pki::public_key_der(&r.chain)? != key.public_key_der() { + return Err(AgentError::Untrusted( + "the renewed certificate is not for the new key".into(), + )); + } + let key_pem = key.serialize_pem(); + self.state.save_identity(&r.chain, &key_pem)?; + let cfg = tls::agent_config(pinned(&self.enrolled)?, &r.chain, &key_pem)?; + self.fabrica = Fabrica::new(&self.enrolled.file.server, cfg)?; + self.enrolled.chain_pem = r.chain; + self.enrolled.key_pem = key_pem; + Ok(true) + } +} + +impl Fetch for Fabrica { + fn fetch( + &self, + job: &str, + name: &str, + max: u64, + out: &mut dyn std::io::Write, + ) -> Result { + self.artifact(job, name, max, out) + .map_err(|e| e.to_string()) + } +} + +/// Run until stopped: hello, then jobs; reconnect with back-off on errors. +pub fn run(state: State, target: &dyn Target) -> Result<(), AgentError> { + let mut backoff = Duration::from_secs(5); + loop { + let mut s = match Session::open(state.clone()) { + Ok(s) => s, + // Not enrolled or damaged state: stop; systemd shows why. + Err(e @ (AgentError::State(_) | AgentError::Tls(_) | AgentError::Untrusted(_))) => { + return Err(e); + } + Err(e) => { + eprintln!("legatus: {e}"); + std::thread::sleep(backoff); + continue; + } + }; + let result = (|| -> Result<(), AgentError> { + let w = s.hello(target)?; + eprintln!( + "legatus: connected as {}; build {}, deploy {}", + s.who(), + if w.roles.build { "on" } else { "off" }, + if w.roles.deploy { "on" } else { "off" } + ); + s.renew_if_due(w.renew)?; + loop { + s.poll_once(target)?; + s.renew_if_due(false)?; + } + })(); + if let Err(e) = result { + eprintln!("legatus: {e}; trying again in {} s", backoff.as_secs()); + std::thread::sleep(backoff); + backoff = (backoff * 2).min(Duration::from_secs(60)); + } else { + backoff = Duration::from_secs(5); + } + } +} diff --git a/crates/agent/src/main.rs b/crates/agent/src/main.rs index f328e4d..4ec7457 100644 --- a/crates/agent/src/main.rs +++ b/crates/agent/src/main.rs @@ -1 +1,109 @@ -fn main() {} +// 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/. + +//! `legatus`: enroll, run, status. + +use std::path::PathBuf; +use std::process::ExitCode; + +use legatus::state::{State, default_dir}; +use legatus::target::Linux; + +const USAGE: &str = "legatus: the Fabrica Domi agent + +usage: + legatus enroll [--force] enroll this machine with the one-time code from Fabrica + legatus run connect to Fabrica and run jobs (the systemd service runs this) + legatus status who this agent is and what runs here + legatus version + +options: + --state state dir (default /var/lib/legatus, or $LEGATUS_STATE) + --apps where releases go (default /var/lib/legatus/apps) +"; + +fn main() -> ExitCode { + let mut args: Vec = std::env::args().skip(1).collect(); + let mut take = |flag: &str| -> Option { + let i = args.iter().position(|a| a == flag)?; + args.remove(i); + (i < args.len()).then(|| args.remove(i)) + }; + let state = State::new( + take("--state") + .map(PathBuf::from) + .unwrap_or_else(default_dir), + ); + let apps = take("--apps") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(legatus_linux::DEFAULT_ROOT)); + let force = match args.iter().position(|a| a == "--force") { + Some(i) => { + args.remove(i); + true + } + None => false, + }; + let words: Vec<&str> = args.iter().map(String::as_str).collect(); + match words.as_slice() { + ["enroll", code] => match legatus::enroll(&state, code, force) { + Ok(f) => { + println!( + "Enrolled as {}/{} with {}. Build here: {}. Deploy here: {}.", + f.team, + f.agent, + f.server, + if f.roles.build { "on" } else { "off" }, + if f.roles.deploy { "on" } else { "off" } + ); + ExitCode::SUCCESS + } + Err(e) => { + eprintln!("legatus: {e}"); + ExitCode::FAILURE + } + }, + ["run"] => { + let target = Linux::new(apps); + match legatus::run(state, &target) { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("legatus: {e}"); + ExitCode::FAILURE + } + } + } + ["status"] => match state.load() { + Ok(e) => { + let leaf = domi_pki::inspect(&e.chain_pem).ok(); + println!("agent {}/{}", e.file.team, e.file.agent); + println!("server {}", e.file.server); + println!( + "roles build {}, deploy {}", + e.file.roles.build, e.file.roles.deploy + ); + if let Some(l) = leaf { + println!("certificate valid until {} (unix)", l.not_after); + } + println!("release keys pinned: {}", e.file.release_keys.len()); + for d in legatus::pipeline::Target::deployed(&Linux::new(apps)) { + println!("running {} {}", d.app, d.version); + } + ExitCode::SUCCESS + } + Err(e) => { + eprintln!("legatus: {e}"); + ExitCode::FAILURE + } + }, + ["version"] | ["--version"] => { + println!("legatus {}", legatus::VERSION); + ExitCode::SUCCESS + } + _ => { + eprint!("{USAGE}"); + ExitCode::from(2) + } + } +} diff --git a/crates/agent/src/pipeline.rs b/crates/agent/src/pipeline.rs new file mode 100644 index 0000000..fa55da9 --- /dev/null +++ b/crates/agent/src/pipeline.rs @@ -0,0 +1,316 @@ +// 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/. + +//! One job, start to end: guard, role, signature and manifest, download, size and SHA-256, and +//! only then the target. Every refusal is reported; nothing unsigned reaches a target. + +use std::fs; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; + +use legatus_linux::{DeployError, Outcome, UnpackError}; +use legatus_protocol::msg::{DeployJob, Deployed, Target as JobTarget}; +use legatus_protocol::{ + Expected, JobBody, JobGuard, Report, Roles, Status, Step, check_artifact, parse_job, + verify_release, +}; + +/// Where artifacts come from (the Fabrica server over mTLS; a fake in tests). +pub trait Fetch { + /// Write the artifact `name` of job `job` into `out`, at most `max` bytes; the bytes written. + fn fetch(&self, job: &str, name: &str, max: u64, out: &mut dyn Write) -> Result; +} + +/// A place releases go (the Linux backend; a fake in tests). +pub trait Target { + /// Target kinds it handles (`linux`). + fn kinds(&self) -> Vec; + /// Deploy an artifact that already matches the signed manifest. + fn deploy( + &self, + job: &DeployJob, + artifact: &Path, + sha256: &str, + ) -> Result; + /// What runs here. + fn deployed(&self) -> Vec; +} + +/// What the pipeline needs to know about the agent. +#[derive(Debug, Clone)] +pub struct Context { + /// The agent's team. + pub team: String, + /// Current roles. + pub roles: Roles, + /// The pinned release keys. + pub release_keys: Vec, + /// Where downloads go while checked. + pub downloads: PathBuf, +} + +/// What handling a job changed in the agent. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct Handled { + /// The roles changed (save them). + pub roles_changed: bool, + /// The guard remembered a new id (save it). + pub guard_changed: bool, +} + +struct Hashing<'a> { + out: &'a mut dyn Write, + ctx: ring::digest::Context, +} + +impl Write for Hashing<'_> { + fn write(&mut self, buf: &[u8]) -> io::Result { + let n = self.out.write(buf)?; + self.ctx.update(buf.get(..n).unwrap_or_default()); + Ok(n) + } + fn flush(&mut self) -> io::Result<()> { + self.out.flush() + } +} + +/// Handle one job's bytes at `now`. Reports go to `report` as they happen. +pub fn handle( + bytes: &[u8], + now: i64, + ctx: &mut Context, + guard: &mut JobGuard, + fetch: &dyn Fetch, + target: &dyn Target, + report: &mut dyn FnMut(Report), +) -> Handled { + let mut done = Handled::default(); + let job = match parse_job(bytes) { + Ok(j) => j, + // Not even the id can be trusted: nothing to report to. + Err(_) => return done, + }; + let id = job.header.id.clone(); + if let Err(e) = guard.check(&job.header, now) { + report(Report::refused( + &id, + now, + Step::Guard, + e.code(), + &e.to_string(), + )); + return done; + } + done.guard_changed = true; + match job.body { + JobBody::Unsupported(kind) => report(Report::refused( + &id, + now, + Step::Guard, + "unsupported", + &format!("this Legatus cannot run {kind} jobs"), + )), + JobBody::Invalid(why) => { + report(Report::refused(&id, now, Step::Guard, "bad_request", &why)) + } + JobBody::Config(c) => { + ctx.roles = c.roles; + done.roles_changed = true; + report(Report::succeeded( + &id, + now, + &format!( + "roles: build {}, deploy {}", + on(c.roles.build), + on(c.roles.deploy) + ), + None, + )); + } + JobBody::Deploy(d) if !ctx.roles.deploy => { + let _ = d; + report(Report::refused( + &id, + now, + Step::Role, + "role_off", + "deploy here is off for this agent in Fabrica", + )); + } + JobBody::Deploy(d) => deploy(&id, &d, now, ctx, fetch, target, report), + } + done +} + +fn on(b: bool) -> &'static str { + if b { "on" } else { "off" } +} + +fn deploy( + id: &str, + d: &DeployJob, + now: i64, + ctx: &Context, + fetch: &dyn Fetch, + target: &dyn Target, + report: &mut dyn FnMut(Report), +) { + let kind = match &d.target { + JobTarget::Linux(_) => "linux", + }; + if !target.kinds().iter().any(|k| k == kind) { + report(Report::refused( + id, + now, + Step::Guard, + "unsupported", + &format!("this machine has no {kind} target"), + )); + return; + } + // 1. The signature and the manifest, before anything is downloaded. + let expect = Expected { + team: &ctx.team, + app: &d.app, + version: &d.version, + artifact: &d.artifact, + }; + let approved = match verify_release( + d.release.manifest.as_bytes(), + &d.release.signature, + &ctx.release_keys, + &expect, + ) { + Ok(a) => a, + Err(e) => { + report(Report::refused( + id, + now, + Step::Verify, + e.code(), + &e.to_string(), + )); + return; + } + }; + report(Report { + status: Status::Accepted, + ..Report::running( + id, + now, + Step::Download, + &format!("{} {} is signed by the team; downloading", d.app, d.version), + ) + }); + // 2. The artifact, bounded by the signed size, hashed as it arrives. + let path = ctx.downloads.join(format!("{id}.part")); + let result = download(&path, id, &approved.name, approved.size, fetch); + let (len, sha) = match result { + Ok(x) => x, + Err(why) => { + let _ = fs::remove_file(&path); + report(Report::failed(id, now, Step::Download, &why, false)); + return; + } + }; + if let Err(e) = check_artifact(&approved, &sha, len) { + let _ = fs::remove_file(&path); + report(Report::refused( + id, + now, + Step::Download, + e.code(), + &e.to_string(), + )); + return; + } + // 3. Only now does the target see it. + let outcome = target.deploy(d, &path, &sha); + let _ = fs::remove_file(&path); + report(match outcome { + Ok(Outcome::Succeeded { previous }) => Report::succeeded( + id, + now, + &match previous { + Some(p) => format!("{} {} is running (was {p})", d.app, d.version), + None => format!("{} {} is running", d.app, d.version), + }, + Some(Deployed { + app: d.app.clone(), + version: d.version.clone(), + }), + ), + Ok(Outcome::RolledBack { + to, + healthy, + reason, + }) => { + let state = if healthy { + "and it is healthy" + } else { + "but it is not healthy either" + }; + let mut r = Report::failed( + id, + now, + Step::Health, + &format!("{reason}; rolled back to {to}, {state}"), + true, + ); + r.deployed = Some(Deployed { + app: d.app.clone(), + version: to, + }); + r + } + Ok(Outcome::Failed { reason }) => Report::failed( + id, + now, + Step::Health, + &format!("{reason}; there was no earlier release to roll back to"), + false, + ), + Err(DeployError::Unpack(UnpackError::Archive(e))) => { + Report::refused(id, now, Step::Unpack, e.code(), &e.to_string()) + } + Err(DeployError::Unpack(e)) => { + Report::refused(id, now, Step::Unpack, "bad_archive", &e.to_string()) + } + Err(DeployError::Unit) => Report::refused( + id, + now, + Step::Unpack, + "bad_request", + "the unit name is not valid", + ), + Err(DeployError::Switch(e)) => Report::failed(id, now, Step::Switch, &e, false), + }); +} + +fn download( + path: &Path, + id: &str, + name: &str, + size: u64, + fetch: &dyn Fetch, +) -> Result<(u64, String), String> { + if let Some(dir) = path.parent() { + fs::create_dir_all(dir).map_err(|e| e.to_string())?; + } + let _ = fs::remove_file(path); + let mut file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(path) + .map_err(|e| e.to_string())?; + let mut h = Hashing { + out: &mut file, + ctx: ring::digest::Context::new(&ring::digest::SHA256), + }; + // One byte more than signed, so a longer artifact is seen as such. + let n = fetch.fetch(id, name, size.saturating_add(1), &mut h)?; + let sha = legatus_protocol::hex(h.ctx.finish().as_ref()); + file.sync_all().map_err(|e| e.to_string())?; + Ok((n, sha)) +} diff --git a/crates/agent/src/state.rs b/crates/agent/src/state.rs new file mode 100644 index 0000000..87306e9 --- /dev/null +++ b/crates/agent/src/state.rs @@ -0,0 +1,217 @@ +// 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) +} diff --git a/crates/agent/src/target.rs b/crates/agent/src/target.rs new file mode 100644 index 0000000..24cd794 --- /dev/null +++ b/crates/agent/src/target.rs @@ -0,0 +1,65 @@ +// 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 targets this machine offers: Linux (systemd) on Linux, none elsewhere in v0.1. + +use std::path::Path; +use std::time::Duration; + +use legatus_linux::{DeployError, HttpHealth, Layout, LinuxBackend, Outcome, Plan, Systemctl}; +use legatus_protocol::msg::{DeployJob, Deployed, Target as JobTarget}; + +use crate::pipeline::Target; + +/// The Linux target with real systemd. +pub struct Linux { + backend: LinuxBackend, +} + +impl Linux { + /// Apps under `root` (normally `/var/lib/legatus/apps`). + pub fn new(root: impl Into) -> Linux { + Linux { + backend: LinuxBackend::new(Layout::new(root), Systemctl, HttpHealth), + } + } +} + +impl Target for Linux { + fn kinds(&self) -> Vec { + if cfg!(target_os = "linux") { + vec!["linux".into()] + } else { + Vec::new() + } + } + + fn deploy( + &self, + job: &DeployJob, + artifact: &Path, + sha256: &str, + ) -> Result { + let JobTarget::Linux(t) = &job.target; + let file = std::fs::File::open(artifact).map_err(|e| DeployError::Switch(e.to_string()))?; + let plan = Plan { + app: &job.app, + version: &job.version, + unit: &t.unit, + health_url: t.health_url.as_deref(), + health_timeout: Duration::from_secs(u64::from(t.health_timeout_seconds)), + keep: t.keep, + }; + self.backend + .deploy(&plan, std::io::BufReader::new(file), sha256) + } + + fn deployed(&self) -> Vec { + self.backend + .deployed() + .into_iter() + .map(|(app, version)| Deployed { app, version }) + .collect() + } +} diff --git a/crates/agent/src/tls.rs b/crates/agent/src/tls.rs new file mode 100644 index 0000000..434aba9 --- /dev/null +++ b/crates/agent/src/tls.rs @@ -0,0 +1,171 @@ +// 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/. + +//! TLS to the Fabrica server: the server is accepted only when its chain ends at the pinned Domi +//! root and its leaf is valid for the server's name; the agent presents its own certificate +//! (mTLS) on every connection after enrollment. + +use std::sync::Arc; + +use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}; +use rustls::crypto::{CryptoProvider, WebPkiSupportedAlgorithms}; +use rustls::{ClientConfig, DigitallySignedStruct, SignatureScheme}; +use rustls_pki_types::pem::PemObject; +use rustls_pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime}; + +/// The Domi root, pinned by its SHA-256 (from the enrollment code) and, once known, its DER. +#[derive(Debug, Clone)] +pub struct PinnedRoot { + sha256: [u8; 32], + der: Option>, +} + +impl PinnedRoot { + /// Pinned by fingerprint only (enrollment: the server must present the root itself). + pub fn by_hash(sha256: [u8; 32]) -> PinnedRoot { + PinnedRoot { sha256, der: None } + } + + /// Pinned by the stored certificate (after enrollment). `None` if it does not hash to `sha256`. + pub fn with_der(sha256: [u8; 32], der: Vec) -> Option { + (digest(&der) == sha256).then_some(PinnedRoot { + sha256, + der: Some(der), + }) + } +} + +fn digest(b: &[u8]) -> [u8; 32] { + let d = ring::digest::digest(&ring::digest::SHA256, b); + let mut out = [0u8; 32]; + out.copy_from_slice(d.as_ref()); + out +} + +fn provider() -> Arc { + Arc::new(rustls::crypto::ring::default_provider()) +} + +#[derive(Debug)] +struct Verifier { + root: PinnedRoot, + algs: WebPkiSupportedAlgorithms, +} + +fn tls_err(e: domi_pki::VerifyError) -> rustls::Error { + use domi_pki::VerifyError as V; + use rustls::CertificateError as C; + rustls::Error::InvalidCertificate(match e { + V::Expired => C::Expired, + V::NotYetValid => C::NotValidYet, + V::UnknownIssuer => C::UnknownIssuer, + V::BadSignature => C::BadSignature, + V::WrongName => C::NotValidForName, + V::WrongUsage => C::InvalidPurpose, + other => C::Other(rustls::OtherError(Arc::new(other))), + }) +} + +impl ServerCertVerifier for Verifier { + fn verify_server_cert( + &self, + end_entity: &CertificateDer<'_>, + intermediates: &[CertificateDer<'_>], + server_name: &ServerName<'_>, + _ocsp: &[u8], + now: UnixTime, + ) -> Result { + // The root: the stored one, or the presented certificate that hashes to the pin. + let root = match &self.root.der { + Some(d) => d.clone(), + None => intermediates + .iter() + .find(|c| digest(c.as_ref()) == self.root.sha256) + .map(|c| c.as_ref().to_vec()) + .ok_or(rustls::Error::InvalidCertificate( + rustls::CertificateError::UnknownIssuer, + ))?, + }; + let mut chain = vec![end_entity.as_ref().to_vec()]; + chain.extend( + intermediates + .iter() + .filter(|c| c.as_ref() != root.as_slice()) + .take(4) + .map(|c| c.as_ref().to_vec()), + ); + let secs = i64::try_from(now.as_secs()).unwrap_or(i64::MAX); + domi_pki::verify_server(&chain, &root, &server_name.to_str(), secs).map_err(tls_err)?; + Ok(ServerCertVerified::assertion()) + } + + fn verify_tls12_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &DigitallySignedStruct, + ) -> Result { + rustls::crypto::verify_tls12_signature(message, cert, dss, &self.algs) + } + + fn verify_tls13_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &DigitallySignedStruct, + ) -> Result { + rustls::crypto::verify_tls13_signature(message, cert, dss, &self.algs) + } + + fn supported_verify_schemes(&self) -> Vec { + self.algs.supported_schemes() + } +} + +/// Why a TLS configuration could not be made. +#[derive(Debug, thiserror::Error)] +pub enum TlsError { + /// The agent's certificate or key cannot be read. + #[error("the agent's certificate or key cannot be read: {0}")] + Identity(String), + /// rustls refused the configuration. + #[error("TLS could not be set up: {0}")] + Config(String), +} + +/// A client configuration that trusts only `root`, without a client certificate (enrollment). +pub fn enroll_config(root: PinnedRoot) -> Result, TlsError> { + let p = provider(); + let algs = p.signature_verification_algorithms; + let cfg = ClientConfig::builder_with_provider(p) + .with_safe_default_protocol_versions() + .map_err(|e| TlsError::Config(e.to_string()))? + .dangerous() + .with_custom_certificate_verifier(Arc::new(Verifier { root, algs })) + .with_no_client_auth(); + Ok(Arc::new(cfg)) +} + +/// A client configuration that trusts only `root` and presents the agent's chain and key (mTLS). +pub fn agent_config( + root: PinnedRoot, + chain_pem: &str, + key_pem: &str, +) -> Result, TlsError> { + let chain: Vec> = CertificateDer::pem_slice_iter(chain_pem.as_bytes()) + .collect::>() + .map_err(|e| TlsError::Identity(e.to_string()))?; + let key = PrivateKeyDer::from_pem_slice(key_pem.as_bytes()) + .map_err(|_| TlsError::Identity("the key".into()))?; + let p = provider(); + let algs = p.signature_verification_algorithms; + let cfg = ClientConfig::builder_with_provider(p) + .with_safe_default_protocol_versions() + .map_err(|e| TlsError::Config(e.to_string()))? + .dangerous() + .with_custom_certificate_verifier(Arc::new(Verifier { root, algs })) + .with_client_auth_cert(chain, key) + .map_err(|e| TlsError::Identity(e.to_string()))?; + Ok(Arc::new(cfg)) +}