// 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/. //! Checking chains (rustls-webpki) and agent certificates. Everything presented is hostile. use std::time::Duration; use rustls_pki_types::{CertificateDer, ServerName, UnixTime}; use webpki::{EndEntityCert, KeyUsage, anchor_from_trusted_cert}; use crate::inspect::{inspect_der, parse}; use crate::{AGENTS_INTERMEDIATE_CN, valid_id}; /// What a certificate is checked for. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Usage { /// A TLS server (serverAuth). Server, /// A TLS client (clientAuth): devices and agents. Client, } /// Why a certificate or chain is refused. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum VerifyError { /// A certificate in the chain has expired. #[error("the certificate has expired")] Expired, /// A certificate in the chain is not valid yet. #[error("the certificate is not valid yet")] NotYetValid, /// The chain does not lead to the trusted root. #[error("the certificate was not issued under the trusted root")] UnknownIssuer, /// A signature in the chain does not verify. #[error("a signature in the chain does not verify")] BadSignature, /// The certificate is not for this use (server or client). #[error("the certificate is not for this use")] WrongUsage, /// A CA was presented as the leaf, or a leaf as a CA. #[error("a CA and a leaf are mixed up in the chain")] NotCa, /// The server certificate is not for this host name. #[error("the certificate is not for this host name")] WrongName, /// A valid client certificate that does not name an agent. #[error("the certificate does not name a Domi agent")] NotAnAgent, /// An agent certificate not issued by the agents intermediate. #[error("the agent certificate was not issued by the agents intermediate")] WrongIntermediate, /// Unreadable or otherwise refused. #[error("the certificate cannot be used: {0}")] BadCertificate(String), } fn map(e: webpki::Error) -> VerifyError { use webpki::Error as E; match e { E::CertExpired { .. } => VerifyError::Expired, E::CertNotValidYet { .. } => VerifyError::NotYetValid, E::UnknownIssuer => VerifyError::UnknownIssuer, E::InvalidSignatureForPublicKey | E::UnsupportedSignatureAlgorithmContext(_) | E::UnsupportedSignatureAlgorithmForPublicKeyContext(_) | E::SignatureAlgorithmMismatch => VerifyError::BadSignature, E::RequiredEkuNotFoundContext(_) => VerifyError::WrongUsage, E::CaUsedAsEndEntity | E::EndEntityUsedAsCa | E::PathLenConstraintViolated => { VerifyError::NotCa } other => VerifyError::BadCertificate(format!("{other:?}")), } } fn unix(now: i64) -> Result { let secs = u64::try_from(now) .map_err(|_| VerifyError::BadCertificate("the time is before 1970".into()))?; Ok(UnixTime::since_unix_epoch(Duration::from_secs(secs))) } /// Check `chain` (leaf first, then intermediates, DER) against `root_der` at `now`, for `usage`. pub fn verify_chain( chain: &[Vec], root_der: &[u8], now: i64, usage: Usage, ) -> Result<(), VerifyError> { with_leaf(chain, root_der, now, usage, |_| Ok(())) } fn with_leaf( chain: &[Vec], root_der: &[u8], now: i64, usage: Usage, then: impl FnOnce(&EndEntityCert<'_>) -> Result, ) -> Result { let Some((leaf, rest)) = chain.split_first() else { return Err(VerifyError::BadCertificate("the chain is empty".into())); }; let time = unix(now)?; let root = CertificateDer::from(root_der); let anchor = anchor_from_trusted_cert(&root) .map_err(|_| VerifyError::BadCertificate("the root cannot be read".into()))?; let leaf = CertificateDer::from(leaf.as_slice()); let ee = EndEntityCert::try_from(&leaf).map_err(map)?; let ints: Vec> = rest .iter() .map(|d| CertificateDer::from(d.as_slice())) .collect(); let ku = match usage { Usage::Server => KeyUsage::server_auth(), Usage::Client => KeyUsage::client_auth(), }; ee.verify_for_usage( webpki::ALL_VERIFICATION_ALGS, &[anchor], &ints, time, ku, None, None, ) .map_err(map)?; then(&ee) } /// [`verify_chain`] for a server, and the leaf must be valid for `host` (a DNS name or IP). pub fn verify_server( chain: &[Vec], root_der: &[u8], host: &str, now: i64, ) -> Result<(), VerifyError> { let name = ServerName::try_from(host).map_err(|_| VerifyError::WrongName)?; with_leaf(chain, root_der, now, Usage::Server, |ee| { ee.verify_is_valid_for_subject_name(&name) .map_err(|_| VerifyError::WrongName) }) } /// Who an accepted agent certificate names. #[derive(Debug, Clone, PartialEq, Eq)] pub struct AgentIdentity { /// The team id. pub team: String, /// The agent id. pub agent: String, /// The leaf's serial, lowercase hex (the registry keeps the current one per agent). pub serial_hex: String, /// SHA-256 of the leaf's DER, lowercase hex. pub sha256_hex: String, /// notAfter of the leaf, unix seconds. pub not_after: i64, } /// `urn:domi:agent::`. pub fn agent_uri(team: &str, agent: &str) -> String { format!("urn:domi:agent:{team}:{agent}") } /// The `(team, agent)` of an agent URI, or `None` when it is not one. pub fn parse_agent_uri(uri: &str) -> Option<(String, String)> { let rest = uri.strip_prefix("urn:domi:agent:")?; let (team, agent) = rest.split_once(':')?; (valid_id(team) && valid_id(agent)).then(|| (team.to_owned(), agent.to_owned())) } /// Check an agent's chain as presented in its TLS handshake (leaf, then the agents intermediate) /// against the root at `now`, and say which agent it is. The caller still checks that the agent is /// registered and that this is its current serial. pub fn verify_agent( chain: &[Vec], root_der: &[u8], now: i64, ) -> Result { if chain.len() > 2 { return Err(VerifyError::BadCertificate( "an agent presents its certificate and the agents intermediate".into(), )); } verify_chain(chain, root_der, now, Usage::Client)?; let (Some(leaf), Some(int)) = (chain.first(), chain.get(1)) else { return Err(VerifyError::UnknownIssuer); }; let bad = |e: crate::PkiError| VerifyError::BadCertificate(e.to_string()); let info = inspect_der(leaf).map_err(bad)?; let ids: Vec<(String, String)> = info .uris .iter() .filter_map(|u| parse_agent_uri(u)) .collect(); let [(team, agent)] = ids.as_slice() else { return Err(VerifyError::NotAnAgent); }; if info.uris.len() != 1 || info.is_ca || info.subject_cn != *agent || !info.dns_names.is_empty() { return Err(VerifyError::NotAnAgent); } // Only one intermediate was offered and webpki accepted the path, so it issued the leaf; // checked again here so this never rests on how webpki builds paths. if !crate::inspect::issued_by_der(leaf, int).map_err(bad)? { return Err(VerifyError::UnknownIssuer); } let int_cert = parse(int).map_err(bad)?; let int_cn = int_cert .subject() .iter_common_name() .next() .and_then(|c| c.as_str().ok()) .unwrap_or_default(); if !int_cn.starts_with(AGENTS_INTERMEDIATE_CN) { return Err(VerifyError::WrongIntermediate); } Ok(AgentIdentity { team: team.clone(), agent: agent.clone(), serial_hex: info.serial_hex, sha256_hex: info.sha256_hex, not_after: info.not_after, }) }