diff --git a/CLAUDE.md b/CLAUDE.md index 0f0c340..3495676 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,8 @@ Ianitor is a reverse proxy built on Cloudflare's Pingora, with a small Domi CA, NixOS-native, with Caddy as a tested fallback. MPL-2.0. Plan, decisions and status: docs/ROADMAP.md — read it first. ## Layout -crates/core config model, schema, compilers (Pingora runtime + Caddy JSON), CA. Pure: no I/O, no network. +crates/core config model, schema, compilers (Pingora runtime + Caddy JSON), CA (Ianitor's view of the shared + crate domi-pki, pinned by tag). Pure: no I/O, no network. crates/edge Pingora data plane. Reads compiled config, serves traffic. Never decides policy. crates/control API, git routes repo, apply/rollback, share links, PKI flows. Loopback only. Never serves public traffic. apps/web Svelte 5 (runes, TypeScript strict). A client of the API; no logic. diff --git a/Cargo.lock b/Cargo.lock index 68ea429..98d5207 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -859,6 +859,21 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "domi-pki" +version = "1.0.0" +source = "git+https://gitea.marek-novak.cz/mnovak/domi-pki?tag=v1.0.0#b1ec5b3196fc22355270f381e5a7748c50e3380d" +dependencies = [ + "base64 0.22.1", + "rcgen", + "ring", + "rustls-pki-types", + "rustls-webpki", + "thiserror 2.0.21", + "time", + "x509-parser 0.18.1", +] + [[package]] name = "equivalent" version = "1.0.3" @@ -1319,18 +1334,16 @@ name = "ianitor-core" version = "0.1.0" dependencies = [ "base64 0.22.1", - "rcgen", + "domi-pki", "ring", "rustls-pki-types", "rustls-webpki", "serde", "serde_json", "thiserror 2.0.21", - "time", "toml", "unicode-normalization", "url", - "x509-parser 0.18.1", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index e479f4e..0cc6979 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,6 +22,8 @@ publish = false ianitor-core = { path = "crates/core" } ianitor-edge = { path = "crates/edge" } ianitor-testkit = { path = "tests/support" } +# The Domi CA, shared with Fabrica (docs/32_coherence.md T3a); pinned by tag. +domi-pki = { git = "https://gitea.marek-novak.cz/mnovak/domi-pki", tag = "v1.0.0" } serde = { version = "1.0.228", features = ["derive"] } serde_json = "1.0.145" toml = "1.2.1" diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index ff25605..9c487bb 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -16,9 +16,7 @@ url.workspace = true ring.workspace = true base64.workspace = true unicode-normalization = "0.1.24" -rcgen = { workspace = true, features = ["x509-parser"] } -x509-parser = { version = "0.18", features = ["verify"] } -time = { version = "0.3", default-features = false } +domi-pki.workspace = true [dev-dependencies] rustls-pki-types.workspace = true diff --git a/crates/core/src/pki.rs b/crates/core/src/pki.rs index 72e4445..39383e8 100644 --- a/crates/core/src/pki.rs +++ b/crates/core/src/pki.rs @@ -2,8 +2,10 @@ // 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 Domi CA (ROADMAP §1.1, §1.2, §1.8, §3): a small CA on rcgen. Pure: the caller passes -//! the time in and does every file read and write. Keys are ECDSA P-256 everywhere. +//! The Domi CA (ROADMAP §1.1, §1.2, §1.8, §3), as Ianitor uses it. The CA itself lives in the +//! shared crate `domi-pki` (Fabrica `docs/32_coherence.md`, T3a); this module is Ianitor's view of +//! it with Ianitor's names and messages, plus Ianitor's encrypted-key format. Pure: the caller +//! passes the time in and does every file read and write. Keys are ECDSA P-256 everywhere. //! //! ```text //! Domi PKI Root 10 years, pathLen 1 created offline, never on the server @@ -22,41 +24,22 @@ //! - No certificate is ever issued past its issuer's `notAfter`. //! //! The intermediate is never made from what a CSR asks for: only its public key and its -//! subject CN are taken; every extension comes from the profile here. - -use std::fmt; +//! subject CN are taken; every extension comes from the profile in `domi-pki`. use base64::Engine as _; use base64::engine::general_purpose::STANDARD; -use rcgen::{ - BasicConstraints, CertificateParams, CertificateSigningRequestParams, DistinguishedName, - DnType, ExtendedKeyUsagePurpose, IsCa, Issuer, KeyUsagePurpose, PKCS_ECDSA_P256_SHA256, - SerialNumber, -}; use ring::rand::{SecureRandom, SystemRandom}; -use time::OffsetDateTime; -/// Root: about 10 years. -pub const ROOT_DAYS: u32 = 3653; -/// Intermediate: about 1 year. -pub const INTERMEDIATE_DAYS: u32 = 365; -/// Server (tls = "domi") certificates. -pub const SERVER_DAYS: u32 = 90; -/// Renew a server certificate when fewer than this many days are left. -pub const SERVER_RENEW_DAYS: u32 = 30; -/// Device (mTLS client) certificates. -pub const DEVICE_DAYS: u32 = 365; -/// Subject CN of the root. -pub const ROOT_CN: &str = "Domi PKI Root"; +pub use domi_pki::{ + CertInfo, DEVICE_DAYS, EkuInfo, INTERMEDIATE_DAYS, INTERMEDIATE_OPENSSL_EXT, KeyPair, + KeyUsageInfo, ORG, ROOT_CN, ROOT_DAYS, SERVER_DAYS, SERVER_RENEW_DAYS, der_to_pem, + match_code, openssl_sign_command, sha256_hex, +}; + /// Subject CN of the intermediate. Signers refuse a CSR whose CN does not start with this. -pub const INTERMEDIATE_CN: &str = "Ianitor Domi Intermediate"; -/// Organisation on every certificate. -pub const ORG: &str = "Fabrica Domi"; +pub const INTERMEDIATE_CN: &str = domi_pki::IANITOR_INTERMEDIATE_CN; /// PBKDF2-HMAC-SHA256 iterations for encrypted keys (OWASP 2023 figure). pub const KEY_KDF_ITERATIONS: u32 = 600_000; -/// Backdating of `notBefore`, for clocks that run a little late. -const BACKDATE_SECS: i64 = 300; -const DAY: i64 = 86_400; // Split so that this file does not match the pre-commit hook itself. const ARMOR_BEGIN: &str = concat!("-----BEGIN IANITOR ENCRYPTED ", "PRIVATE KEY-----"); const ARMOR_END: &str = concat!("-----END IANITOR ENCRYPTED ", "PRIVATE KEY-----"); @@ -91,52 +74,27 @@ pub enum PkiError { Build(String), } -fn build(e: rcgen::Error) -> PkiError { - PkiError::Build(e.to_string()) -} - -/// An ECDSA P-256 key pair. Never printed. -pub struct KeyPair(rcgen::KeyPair); - -impl fmt::Debug for KeyPair { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str("KeyPair(…)") - } -} - -impl KeyPair { - /// PKCS#8 PEM. Callers write it only to files with mode 0600 (or encrypt it). - pub fn serialize_pem(&self) -> String { - self.0.serialize_pem() - } - - pub fn serialize_der(&self) -> Vec { - self.0.serialize_der() - } - - pub fn from_pem(pem: &str) -> Result { - rcgen::KeyPair::from_pem(pem) - .map(KeyPair) - .map_err(|_| PkiError::BadKey) - } - - pub fn from_der(der: &[u8]) -> Result { - rcgen::KeyPair::try_from(der) - .map(KeyPair) - .map_err(|_| PkiError::BadKey) - } - - /// SubjectPublicKeyInfo DER. - pub fn public_key_der(&self) -> Vec { - use rcgen::PublicKeyData as _; - self.0.subject_public_key_info() +impl From for PkiError { + fn from(e: domi_pki::PkiError) -> PkiError { + use domi_pki::PkiError as D; + match e { + D::BadCertificate(s) => PkiError::BadCertificate(s), + D::BadCsr => PkiError::BadCsr, + D::CsrSubject => PkiError::CsrSubject, + D::BadKey | D::UnsupportedKey => PkiError::BadKey, + D::NotCa => PkiError::NotCa, + D::KeyMismatch => PkiError::KeyMismatch, + D::IssuerExpired => PkiError::IssuerExpired, + D::BadName(s) => PkiError::BadName(s), + D::Random => PkiError::Random, + D::Build(s) | D::Signer(s) => PkiError::Build(s), + other => PkiError::Build(other.to_string()), + } } } pub fn generate_key() -> Result { - rcgen::KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256) - .map(KeyPair) - .map_err(build) + Ok(domi_pki::generate_key()?) } fn random() -> Result<[u8; N], PkiError> { @@ -147,50 +105,12 @@ fn random() -> Result<[u8; N], PkiError> { Ok(b) } -fn serial() -> Result { - let mut b = random::<16>()?; - // Positive and never shortened by DER (leading byte 0x01..=0x7f). - b[0] = (b[0] & 0x7f) | 0x01; - Ok(SerialNumber::from_slice(&b)) -} - -fn time(unix: i64) -> Result { - OffsetDateTime::from_unix_timestamp(unix).map_err(|e| PkiError::Build(e.to_string())) -} - -fn dn(cn: &str) -> DistinguishedName { - let mut d = DistinguishedName::new(); - d.push(DnType::CommonName, cn); - d.push(DnType::OrganizationName, ORG); - d -} - -/// A certificate name a person typed: 1 to 64 printable characters, no control characters. -fn check_display_name(name: &str) -> Result<(), PkiError> { - let n = name.chars().count(); - if n == 0 || n > 64 || name.chars().any(char::is_control) || name.trim() != name { - return Err(PkiError::BadName( - "use 1 to 64 visible characters, no leading or trailing spaces".into(), - )); - } - Ok(()) -} - // ------------------------------------------------------------------ root (offline) /// Create the root: a self-signed CA, `pathLenConstraint 1`, about 10 years. For the offline /// machine only (`ianitor-control ca init`); control never calls this on the server. pub fn create_root(now: i64) -> Result<(String, KeyPair), PkiError> { - let key = generate_key()?; - let mut p = CertificateParams::default(); - p.distinguished_name = dn(ROOT_CN); - p.is_ca = IsCa::Ca(BasicConstraints::Constrained(1)); - p.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign]; - p.not_before = time(now - BACKDATE_SECS)?; - p.not_after = time(now + i64::from(ROOT_DAYS) * DAY)?; - p.serial_number = Some(serial()?); - let cert = p.self_signed(&key.0).map_err(build)?; - Ok((cert.pem(), key)) + Ok(domi_pki::create_root_local(now)?) } /// Common name of [`no_device_placeholder`]. @@ -198,46 +118,15 @@ pub const NO_DEVICE_CN: &str = "Ianitor placeholder: no device is allowed"; /// The allow list's only entry while no device is enrolled. Caddy refuses to load an empty /// leaf list (and with it the whole config), so the list is never empty: this self-signed -/// certificate's key is dropped right here, so no client can ever present it, and it is not +/// certificate's key is dropped right away, so no client can ever present it, and it is not /// issued by the Domi intermediate, so edge refuses it too. pub fn no_device_placeholder(now: i64) -> Result { - let key = generate_key()?; - let mut p = CertificateParams::default(); - p.distinguished_name = dn(NO_DEVICE_CN); - p.is_ca = IsCa::ExplicitNoCa; - p.key_usages = vec![KeyUsagePurpose::DigitalSignature]; - p.not_before = time(now - BACKDATE_SECS)?; - p.not_after = time(now + 100 * 365 * DAY)?; - p.serial_number = Some(serial()?); - let cert = p.self_signed(&key.0).map_err(build)?; - drop(key); - Ok(cert.pem()) + Ok(domi_pki::placeholder_leaf(NO_DEVICE_CN, now)?) } /// A CSR for a new intermediate key (made by control on the server). pub fn intermediate_csr(key: &KeyPair, cn: &str) -> Result { - let mut p = CertificateParams::default(); - p.distinguished_name = dn(cn); - p.serialize_request(&key.0) - .map_err(build)? - .pem() - .map_err(build) -} - -/// The extensions for signing an intermediate with openssl on the offline machine (the -/// accepted manual step until Custos can sign, docs/pki.md): the same profile as -/// [`sign_intermediate`]. Use with `openssl x509 -req … -days 365 -extfile `. -pub const INTERMEDIATE_OPENSSL_EXT: &str = "basicConstraints = critical, CA:TRUE, pathlen:0\n\ -keyUsage = critical, keyCertSign, cRLSign, digitalSignature\n\ -subjectKeyIdentifier = hash\n\ -authorityKeyIdentifier = keyid:always\n"; - -/// The openssl command that signs a renewal on the offline machine (files named after the -/// request). OpenSSL 3 picks a random serial. -pub fn openssl_sign_command(base: &str) -> String { - format!( - "openssl x509 -req -in {base}.csr -CA domi-root.crt -CAkey domi-root.key -days {INTERMEDIATE_DAYS} -sha256 -extfile {base}.ext -out {base}.crt" - ) + Ok(domi_pki::intermediate_csr(key, cn)?) } /// Sign an intermediate CSR with the root (offline, or in Custos once it can). Only the CSR's @@ -248,349 +137,81 @@ pub fn sign_intermediate( csr_pem: &str, now: i64, ) -> Result { - let root = inspect(root_cert_pem)?; - if !root.is_ca { - return Err(PkiError::NotCa); - } - if public_key_der(root_cert_pem)? != root_key.public_key_der() { - return Err(PkiError::KeyMismatch); - } - if now < root.not_before || now >= root.not_after { - return Err(PkiError::IssuerExpired); - } - let csr = CertificateSigningRequestParams::from_pem(csr_pem).map_err(|_| PkiError::BadCsr)?; - let cn = csr - .params - .distinguished_name - .get(&DnType::CommonName) - .and_then(dn_text) - .ok_or(PkiError::CsrSubject)?; - if !cn.starts_with(INTERMEDIATE_CN) - || cn.chars().count() > 64 - || cn.chars().any(char::is_control) - { - return Err(PkiError::CsrSubject); - } - let mut p = CertificateParams::default(); - p.distinguished_name = dn(&cn); - p.is_ca = IsCa::Ca(BasicConstraints::Constrained(0)); - p.key_usages = vec![ - KeyUsagePurpose::KeyCertSign, - KeyUsagePurpose::CrlSign, - KeyUsagePurpose::DigitalSignature, - ]; - p.not_before = time(now - BACKDATE_SECS)?; - p.not_after = time((now + i64::from(INTERMEDIATE_DAYS) * DAY).min(root.not_after))?; - p.serial_number = Some(serial()?); - p.use_authority_key_identifier_extension = true; - let fresh = CertificateSigningRequestParams { - params: p, - public_key: csr.public_key, - }; - let issuer = Issuer::from_ca_cert_pem(root_cert_pem, &root_key.0).map_err(build)?; - Ok(fresh.signed_by(&issuer).map_err(build)?.pem()) -} - -fn dn_text(v: &rcgen::DnValue) -> Option { - match v { - rcgen::DnValue::Utf8String(s) => Some(s.clone()), - rcgen::DnValue::PrintableString(s) => Some(s.as_str().to_owned()), - _ => None, - } + Ok(domi_pki::sign_intermediate( + root_cert_pem, + root_key, + csr_pem, + INTERMEDIATE_CN, + now, + )?) } // ------------------------------------------------------------------ the intermediate /// The intermediate as control holds it: its certificate and its key, checked to belong /// together and to be a CA. -pub struct Intermediate { - cert_pem: String, - key: KeyPair, - info: CertInfo, -} - -impl fmt::Debug for Intermediate { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Intermediate") - .field("subject", &self.info.subject_cn) - .field("not_after", &self.info.not_after) - .finish() - } -} +#[derive(Debug)] +pub struct Intermediate(domi_pki::Intermediate); impl Intermediate { pub fn new(cert_pem: &str, key: KeyPair) -> Result { - let first = first_pem(cert_pem)?; - let info = inspect(&first)?; - if !info.is_ca { - return Err(PkiError::NotCa); - } - if public_key_der(&first)? != key.public_key_der() { - return Err(PkiError::KeyMismatch); - } - Ok(Intermediate { - cert_pem: first, - key, - info, - }) + Ok(Intermediate(domi_pki::Intermediate::new(cert_pem, key)?)) } pub fn cert_pem(&self) -> &str { - &self.cert_pem + self.0.cert_pem() } pub fn not_after(&self) -> i64 { - self.info.not_after + self.0.not_after() } pub fn info(&self) -> &CertInfo { - &self.info + self.0.info() } pub fn key(&self) -> &KeyPair { - &self.key + self.0.key() } - fn issue(&self, mut p: CertificateParams, days: u32, now: i64) -> Result { - if now < self.info.not_before || now >= self.info.not_after { - return Err(PkiError::IssuerExpired); - } - let key = generate_key()?; - p.is_ca = IsCa::ExplicitNoCa; - p.not_before = time(now - BACKDATE_SECS)?; - p.not_after = time((now + i64::from(days) * DAY).min(self.info.not_after))?; - p.serial_number = Some(serial()?); - p.use_authority_key_identifier_extension = true; - let issuer = Issuer::from_ca_cert_pem(&self.cert_pem, &self.key.0).map_err(build)?; - let cert = p.signed_by(&key.0, &issuer).map_err(build)?; - let cert_pem = cert.pem(); - let info = inspect(&cert_pem)?; - Ok(Issued { - chain_pem: format!("{cert_pem}{}", self.cert_pem), - key_pem: key.serialize_pem(), - key, - serial_hex: info.serial_hex.clone(), - sha256_hex: info.sha256_hex.clone(), - not_before: info.not_before, - not_after: info.not_after, - cert_pem, - }) + /// The shared crate's intermediate. + pub fn inner(&self) -> &domi_pki::Intermediate { + &self.0 } } -/// A freshly issued leaf. -pub struct Issued { - /// The leaf alone. - pub cert_pem: String, - /// Leaf, then the intermediate (what a server or a device presents). - pub chain_pem: String, - /// PKCS#8 PEM of the leaf's key. - pub key_pem: String, - pub key: KeyPair, - pub serial_hex: String, - /// SHA-256 of the leaf's DER, lowercase hex. - pub sha256_hex: String, - pub not_before: i64, - pub not_after: i64, -} - -impl fmt::Debug for Issued { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Issued") - .field("serial", &self.serial_hex) - .field("not_after", &self.not_after) - .finish() - } -} +pub use domi_pki::Issued; /// A server certificate for one hostname (`tls = "domi"`). The hostname must already be /// validated by the schema; it is checked again here. pub fn issue_server(int: &Intermediate, hostname: &str, now: i64) -> Result { - let mut p = CertificateParams::new(vec![hostname.to_owned()]) - .map_err(|e| PkiError::BadName(e.to_string()))?; - p.distinguished_name = dn(hostname); - p.key_usages = vec![KeyUsagePurpose::DigitalSignature]; - p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth]; - int.issue(p, SERVER_DAYS, now) + Ok(domi_pki::issue_server(&int.0, hostname, now)?) } /// A device certificate (mTLS client) for a named device. pub fn issue_device(int: &Intermediate, name: &str, now: i64) -> Result { - check_display_name(name)?; - let mut p = CertificateParams::default(); - let mut d = DistinguishedName::new(); - d.push(DnType::CommonName, name); - d.push(DnType::OrganizationName, ORG); - d.push(DnType::OrganizationalUnitName, "Domi devices"); - p.distinguished_name = d; - p.key_usages = vec![KeyUsagePurpose::DigitalSignature]; - p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth]; - int.issue(p, DEVICE_DAYS, now) + Ok(domi_pki::issue_device(&int.0, name, now)?) } // ------------------------------------------------------------------ reading certificates -/// What Ianitor needs to know about a certificate. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct CertInfo { - pub subject_cn: String, - pub issuer_cn: String, - pub not_before: i64, - pub not_after: i64, - pub is_ca: bool, - pub path_len: Option, - pub dns_names: Vec, - pub serial_hex: String, - pub sha256_hex: String, - /// keyUsage: `None` when the extension is absent. - pub key_usage: Option, - /// extendedKeyUsage: `None` when the extension is absent (any use). - pub eku: Option, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct KeyUsageInfo { - pub key_cert_sign: bool, - pub crl_sign: bool, - pub digital_signature: bool, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct EkuInfo { - pub any: bool, - pub server_auth: bool, - pub client_auth: bool, -} - -fn ders(pem: &str) -> Result>, PkiError> { - let mut out = Vec::new(); - for p in x509_parser::pem::Pem::iter_from_buffer(pem.as_bytes()) { - let p = p.map_err(|e| PkiError::BadCertificate(e.to_string()))?; - if p.label != "CERTIFICATE" { - return Err(PkiError::BadCertificate(format!( - "unexpected PEM block {}", - p.label - ))); - } - out.push(p.contents); - } - if out.is_empty() { - return Err(PkiError::BadCertificate("no certificate in it".into())); - } - Ok(out) -} - /// The DER of every certificate in a PEM chain, in order. pub fn chain_der(pem: &str) -> Result>, PkiError> { - ders(pem) + Ok(domi_pki::chain_der(pem)?) } /// The first certificate of a PEM chain, as PEM. pub fn first_pem(pem: &str) -> Result { - let first = ders(pem)? - .into_iter() - .next() - .ok_or_else(|| PkiError::BadCertificate("no certificate in it".into()))?; - Ok(der_to_pem(&first)) -} - -pub fn der_to_pem(der: &[u8]) -> String { - let b = STANDARD.encode(der); - let mut s = String::from("-----BEGIN CERTIFICATE-----\n"); - for chunk in b.as_bytes().chunks(64) { - s.push_str(&String::from_utf8_lossy(chunk)); - s.push('\n'); - } - s.push_str("-----END CERTIFICATE-----\n"); - s -} - -fn parse(der: &[u8]) -> Result, PkiError> { - let (rest, c) = x509_parser::parse_x509_certificate(der) - .map_err(|e| PkiError::BadCertificate(e.to_string()))?; - if !rest.is_empty() { - return Err(PkiError::BadCertificate("trailing bytes".into())); - } - Ok(c) -} - -fn cn_of(name: &x509_parser::x509::X509Name<'_>) -> String { - name.iter_common_name() - .next() - .and_then(|c| c.as_str().ok()) - .unwrap_or_default() - .to_owned() -} - -fn hex(b: &[u8]) -> String { - b.iter().map(|x| format!("{x:02x}")).collect() -} - -/// SHA-256 of a DER blob, lowercase hex. -pub fn sha256_hex(der: &[u8]) -> String { - hex(ring::digest::digest(&ring::digest::SHA256, der).as_ref()) + Ok(domi_pki::first_pem(pem)?) } /// Read the first certificate of a PEM chain. pub fn inspect(pem: &str) -> Result { - let der = ders(pem)? - .into_iter() - .next() - .ok_or_else(|| PkiError::BadCertificate("no certificate in it".into()))?; - inspect_der(&der) + Ok(domi_pki::inspect(pem)?) } pub fn inspect_der(der: &[u8]) -> Result { - let c = parse(der)?; - let bc = c - .basic_constraints() - .map_err(|e| PkiError::BadCertificate(e.to_string()))?; - let (is_ca, path_len) = match bc { - Some(b) => (b.value.ca, b.value.path_len_constraint), - None => (false, None), - }; - let dns_names = match c - .subject_alternative_name() - .map_err(|e| PkiError::BadCertificate(e.to_string()))? - { - Some(san) => san - .value - .general_names - .iter() - .filter_map(|g| match g { - x509_parser::extensions::GeneralName::DNSName(n) => Some((*n).to_owned()), - _ => None, - }) - .collect(), - None => Vec::new(), - }; - Ok(CertInfo { - subject_cn: cn_of(c.subject()), - issuer_cn: cn_of(c.issuer()), - not_before: c.validity().not_before.timestamp(), - not_after: c.validity().not_after.timestamp(), - is_ca, - path_len, - dns_names, - serial_hex: hex(c.raw_serial()), - sha256_hex: sha256_hex(der), - key_usage: c - .key_usage() - .map_err(|e| PkiError::BadCertificate(e.to_string()))? - .map(|k| KeyUsageInfo { - key_cert_sign: k.value.key_cert_sign(), - crl_sign: k.value.crl_sign(), - digital_signature: k.value.digital_signature(), - }), - eku: c - .extended_key_usage() - .map_err(|e| PkiError::BadCertificate(e.to_string()))? - .map(|e| EkuInfo { - any: e.value.any, - server_auth: e.value.server_auth, - client_auth: e.value.client_auth, - }), - }) + Ok(domi_pki::inspect_der(der)?) } /// Why a signed certificate cannot be the Domi intermediate, or `None` when it can. It must @@ -598,102 +219,28 @@ pub fn inspect_der(der: &[u8]) -> Result { /// allowed to issue both server and device certificates (no extendedKeyUsage, or one that /// allows both), valid now, and no longer than the root. pub fn intermediate_problem(cert_pem: &str, root_pem: &str, now: i64) -> Option<&'static str> { - let Ok(info) = inspect(cert_pem) else { - return Some("not_certificate"); - }; - let Ok(root) = inspect(root_pem) else { - return Some("not_root"); - }; - if !issued_by(cert_pem, root_pem).unwrap_or(false) { - return Some("not_root"); - } - if !info.is_ca || info.path_len != Some(0) || !info.subject_cn.starts_with(INTERMEDIATE_CN) { - return Some("not_ca"); - } - if !info - .key_usage - .is_some_and(|k| k.key_cert_sign && k.crl_sign) - { - return Some("not_ca"); - } - if info - .eku - .is_some_and(|e| !e.any && !(e.server_auth && e.client_auth)) - { - return Some("eku"); - } - if info.not_before > now + 300 - || info.not_after <= now - || info.not_after > root.not_after - || info.not_before < root.not_before - 300 - { - return Some("dates"); - } - None + domi_pki::intermediate_problem(cert_pem, root_pem, INTERMEDIATE_CN, now) } /// SubjectPublicKeyInfo DER of the first certificate. pub fn public_key_der(pem: &str) -> Result, PkiError> { - let der = ders(pem)? - .into_iter() - .next() - .ok_or_else(|| PkiError::BadCertificate("no certificate in it".into()))?; - let c = parse(&der)?; - Ok(c.public_key().raw.to_vec()) + Ok(domi_pki::public_key_der(pem)?) } /// Is `child` (first certificate) signed by the key of `issuer` (first certificate), and /// does its issuer name match? A CA flag on the issuer is required. pub fn issued_by(child_pem: &str, issuer_pem: &str) -> Result { - let cd = ders(child_pem)? - .into_iter() - .next() - .ok_or(PkiError::BadCertificate(String::new()))?; - let id = ders(issuer_pem)? - .into_iter() - .next() - .ok_or(PkiError::BadCertificate(String::new()))?; - let child = parse(&cd)?; - let issuer = parse(&id)?; - let ca = matches!(issuer.basic_constraints(), Ok(Some(b)) if b.value.ca); - Ok(ca - && child.issuer() == issuer.subject() - && child.verify_signature(Some(issuer.public_key())).is_ok()) -} - -// ------------------------------------------------------------------ match codes - -/// The code both screens show for one request: SHA-256 of the request, first three bytes, -/// each mod 100, as `47 19 83` (see docs/custos-ticket.md). -pub fn match_code(request: &[u8]) -> String { - let d = ring::digest::digest(&ring::digest::SHA256, request); - let b = d.as_ref(); - format!( - "{:02} {:02} {:02}", - b.first().copied().unwrap_or(0) % 100, - b.get(1).copied().unwrap_or(0) % 100, - b.get(2).copied().unwrap_or(0) % 100 - ) + Ok(domi_pki::issued_by(child_pem, issuer_pem)?) } /// SubjectPublicKeyInfo DER of a CSR (to match a signed certificate to its request). pub fn csr_public_key_der(csr_pem: &str) -> Result, PkiError> { - use x509_parser::prelude::FromDer; - let der = csr_der(csr_pem)?; - let (_, csr) = x509_parser::certification_request::X509CertificationRequest::from_der(&der) - .map_err(|_| PkiError::BadCsr)?; - Ok(csr.certification_request_info.subject_pki.raw.to_vec()) + Ok(domi_pki::csr_public_key_der(csr_pem)?) } /// DER of the first PEM block of a CSR (for the match code). pub fn csr_der(csr_pem: &str) -> Result, PkiError> { - for p in x509_parser::pem::Pem::iter_from_buffer(csr_pem.as_bytes()) { - let p = p.map_err(|_| PkiError::BadCsr)?; - if p.label == "CERTIFICATE REQUEST" { - return Ok(p.contents); - } - } - Err(PkiError::BadCsr) + Ok(domi_pki::csr_der(csr_pem)?) } // ------------------------------------------------------------------ encrypted keys @@ -781,7 +328,7 @@ pub fn decrypt_key(sealed: &str, password: &[u8]) -> Result { &mut data, ) .map_err(|_| PkiError::WrongPassword)?; - KeyPair::from_der(plain) + Ok(KeyPair::from_der(plain)?) } // ------------------------------------------------------------------ for tests @@ -799,55 +346,21 @@ pub mod testing { name: &str, now: i64, ) -> Result { - let leaf_key = generate_key()?; - let mut p = CertificateParams::new(vec![name.to_owned()]).map_err(build)?; - p.distinguished_name = dn(name); - p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth]; - p.not_before = time(now - BACKDATE_SECS)?; - p.not_after = time(now + 30 * DAY)?; - let issuer = Issuer::from_ca_cert_pem(&first_pem(issuer_pem)?, key.0).map_err(build)?; - Ok(p.signed_by(&leaf_key.0, &issuer).map_err(build)?.pem()) + Ok(domi_pki::testing::sign_as(issuer_pem, key, name, now)?) } /// A CA below the intermediate (which pathLen 0 forbids). pub fn sub_ca(int: &Intermediate, key: &KeyPair, now: i64) -> Result { - let mut p = CertificateParams::default(); - p.distinguished_name = dn("Sub CA"); - p.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); - p.key_usages = vec![KeyUsagePurpose::KeyCertSign]; - p.not_before = time(now - BACKDATE_SECS)?; - p.not_after = time(now + 30 * DAY)?; - let issuer = Issuer::from_ca_cert_pem(int.cert_pem(), &int.key.0).map_err(build)?; - Ok(p.signed_by(&key.0, &issuer).map_err(build)?.pem()) + Ok(domi_pki::testing::sub_ca(int.inner(), key, now)?) } /// A CSR that asks for far too much. pub fn greedy_csr(key: &KeyPair, cn: &str) -> Result { - let mut p = CertificateParams::new(vec!["www.example.com".to_owned()]).map_err(build)?; - p.distinguished_name = dn(cn); - p.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); - p.not_after = time(4_000_000_000)?; - p.serialize_request(&key.0) - .map_err(build)? - .pem() - .map_err(build) + Ok(domi_pki::testing::greedy_csr(key, cn)?) } /// Flip one byte inside the CSR's signed part. pub fn tamper_csr(csr_pem: &str) -> String { - let Ok(mut der) = csr_der(csr_pem) else { - return csr_pem.to_owned(); - }; - if let Some(b) = der.get_mut(40) { - *b ^= 0x01; - } - let b = STANDARD.encode(der); - let mut s = String::from("-----BEGIN CERTIFICATE REQUEST-----\n"); - for chunk in b.as_bytes().chunks(64) { - s.push_str(&String::from_utf8_lossy(chunk)); - s.push('\n'); - } - s.push_str("-----END CERTIFICATE REQUEST-----\n"); - s + domi_pki::testing::tamper_csr(csr_pem) } } diff --git a/deploy/nixos/package.nix b/deploy/nixos/package.nix index 5874f2b..5bdceed 100644 --- a/deploy/nixos/package.nix +++ b/deploy/nixos/package.nix @@ -25,7 +25,11 @@ rustPlatform.buildRustPackage { ]; }; - cargoLock.lockFile = ../../Cargo.lock; + cargoLock = { + lockFile = ../../Cargo.lock; + # domi-pki, the shared Domi CA (Cargo.toml pins tag v1.0.0): the NAR hash of its tree at that tag. + outputHashes."domi-pki-1.0.0" = "sha256-JdknFJ5cxsI1/MtWmvsItoE6f7znJjUr4C/rwUEz9i4="; + }; # libz-ng-sys (Pingora's compression) builds zlib-ng with CMake. nativeBuildInputs = [ cmake ]; dontUseCmakeConfigure = true; diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index b758381..7d3079a 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -169,6 +169,20 @@ Identity gate, tunnel, Domi templates, ACME server, HTTP/3, migrating public sit ## 10. Handover (Rewritten at the end of every session: what changed, what was not verified, which build is deployed, the next step.) +**2026-11-17: The Domi CA moved to the shared crate domi-pki (Fabrica docs/32_coherence.md, T3a).** +- **Changed:** `crates/core/src/pki.rs` is now Ianitor's view of [domi-pki](https://gitea.marek-novak.cz/mnovak/domi-pki) + v1.0.0 (git tag in Cargo.toml): the same public API, the same error messages and the same encrypted-key format + (which stays here: it is Ianitor's storage). Fabrica issues Legatus agent certificates from the same crate under a + second intermediate. `deploy/nixos/package.nix` gets `cargoLock.outputHashes."domi-pki-1.0.0"` (the NAR hash of the + tag's tree, computed with a script checked against a known flake.lock narHash). core no longer depends on rcgen, + x509-parser and time directly. +- **Verified:** Rust on Windows only (WSL2 Debian has no disk: `E:\WSL\Debian\ext4.vhdx` is missing): core 103 + (pki 15, unchanged tests), control 21, edge 31 and diff 2 (the Linux-only targets are skip stubs there), testkit 1: + the same counts as before the move. +- **Not verified:** `nix build .#ianitor`, `nix flake check`, the Linux-only Rust suites. +- **Deployed:** nothing. +- **Next step:** T4 (its own session) runs the Linux suites and the Nix build first. + **2026-11-09: Release notes and screenshots for Fabrica.** - **Changed:** `.fabrica/artifex/release.yaml` (on a `v*` tag, Windows runner: version check, web check and tests, `fabrica notes`, the screenshots, Custos approval, publish to the tag's Gitea release with `sums: domi-release`);