From bd796d475b325cd26c1aa4f3ff745d954b83f4dd Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 17 Nov 2026 11:21:21 +0100 Subject: [PATCH] [pki] CA: the Domi CA from Ianitor core behind a Signer, agent certificates, webpki chain checks (34 tests) --- Cargo.lock | 565 ++++++++++++++++++++++++++++++++++++++++++++++++ src/ca.rs | 483 +++++++++++++++++++++++++++++++++++++++++ src/inspect.rs | 293 +++++++++++++++++++++++++ src/lib.rs | 119 +++++++++- src/signer.rs | 185 ++++++++++++++++ src/testing.rs | 93 ++++++++ src/verify.rs | 224 +++++++++++++++++++ tests/agents.rs | 52 ++++- tests/chains.rs | 82 +++++-- tests/signer.rs | 101 ++++++++- 10 files changed, 2163 insertions(+), 34 deletions(-) create mode 100644 Cargo.lock create mode 100644 src/ca.rs create mode 100644 src/inspect.rs create mode 100644 src/signer.rs create mode 100644 src/testing.rs create mode 100644 src/verify.rs diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..df9e8f7 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,565 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "asn1-rs" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom", + "num-traits", + "rusticata-macros", + "thiserror", + "time", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "asn1-rs-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bit-vec" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +dependencies = [ + "serde", +] + +[[package]] +name = "cc" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "der-parser" +version = "10.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" +dependencies = [ + "asn1-rs", + "displaydoc", + "nom", + "num-bigint", + "num-traits", + "rusticata-macros", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "domi-pki" +version = "1.0.0" +dependencies = [ + "base64 0.22.1", + "rcgen", + "ring", + "rustls-pki-types", + "rustls-webpki", + "thiserror", + "time", + "x509-parser", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "oid-registry" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" +dependencies = [ + "asn1-rs", +] + +[[package]] +name = "pem" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120" +dependencies = [ + "base64 0.23.1", + "serde_core", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rcgen" +version = "0.14.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8" +dependencies = [ + "pem", + "ring", + "rustls-pki-types", + "time", + "x509-parser", + "yasna", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom", + "libc", + "untrusted", + "windows-sys", +] + +[[package]] +name = "rusticata-macros" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" +dependencies = [ + "nom", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "x509-parser" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202" +dependencies = [ + "asn1-rs", + "data-encoding", + "der-parser", + "lazy_static", + "nom", + "oid-registry", + "ring", + "rusticata-macros", + "thiserror", + "time", +] + +[[package]] +name = "yasna" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282" +dependencies = [ + "bit-vec", + "time", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" diff --git a/src/ca.rs b/src/ca.rs new file mode 100644 index 0000000..e217d97 --- /dev/null +++ b/src/ca.rs @@ -0,0 +1,483 @@ +// 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/. + +//! Making certificates: the root's (through a [`Signer`]), intermediates from CSRs, and the +//! leaves an [`Intermediate`] issues (server, device, agent). + +use std::fmt; + +use rcgen::{ + BasicConstraints, CertificateParams, CertificateSigningRequestParams, DistinguishedName, + DnType, ExtendedKeyUsagePurpose, IsCa, Issuer, KeyUsagePurpose, SanType, SerialNumber, +}; +use ring::rand::{SecureRandom, SystemRandom}; +use time::OffsetDateTime; + +use crate::inspect::{CertInfo, first_pem, inspect, issued_by, public_key_der}; +use crate::signer::{Adapter, KeyPair, Signer, generate_key, key_kind}; +use crate::*; + +/// Backdating of `notBefore`, for clocks that run a little late. +const BACKDATE_SECS: i64 = 300; + +fn build(e: rcgen::Error) -> PkiError { + PkiError::Build(e.to_string()) +} + +fn random() -> Result<[u8; N], PkiError> { + let mut b = [0u8; N]; + SystemRandom::new() + .fill(&mut b) + .map_err(|_| PkiError::Random)?; + 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())) +} + +pub(crate) 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(()) +} + +// ------------------------------------------------------------------ the root + +fn root_params(now: i64) -> Result { + 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()?); + Ok(p) +} + +/// The root's self-signed certificate (`pathLenConstraint 1`, about 10 years), signed once by +/// `root` (Custos). The signature is checked before the PEM is returned. +pub fn create_root(root: &dyn Signer, now: i64) -> Result { + let key = Adapter::new(root)?; + let cert = root_params(now)? + .self_signed(&key) + .map_err(|e| key.fail(e))?; + let pem = cert.pem(); + if !issued_by(&pem, &pem)? { + return Err(PkiError::Signer( + "the signer's signature does not verify".into(), + )); + } + Ok(pem) +} + +/// A root with a new local key: for tests and the offline machine (`ianitor-control ca init`). In +/// production the root key is in Custos and [`create_root`] is used. +pub fn create_root_local(now: i64) -> Result<(String, KeyPair), PkiError> { + let key = generate_key()?; + let pem = create_root(&key, now)?; + Ok((pem, key)) +} + +/// A self-signed leaf whose key is dropped at once, so nobody can ever present it, and which no +/// Domi intermediate issued. Caddy refuses an empty allow list; this fills it with nobody. +pub fn placeholder_leaf(cn: &str, now: i64) -> Result { + let key = generate_key()?; + let mut p = CertificateParams::default(); + p.distinguished_name = dn(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()) +} + +// ------------------------------------------------------------------ intermediates + +/// A CSR for a new intermediate key, with subject `cn`. +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 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 an intermediate 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" + ) +} + +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, + } +} + +/// Sign an intermediate CSR with the root. `root` is the root's [`Signer`] (Custos); it is asked +/// once. Only the CSR's public key and CN are used; the CN must start with `cn_prefix` +/// ([`IANITOR_INTERMEDIATE_CN`] or [`AGENTS_INTERMEDIATE_CN`]). The signature is checked before +/// the PEM is returned. +pub fn sign_intermediate( + root_cert_pem: &str, + root: &dyn Signer, + csr_pem: &str, + cn_prefix: &str, + now: i64, +) -> Result { + let root_pem = first_pem(root_cert_pem)?; + let info = inspect(&root_pem)?; + if !info.is_ca { + return Err(PkiError::NotCa); + } + if public_key_der(&root_pem)? != root.spki_der() { + return Err(PkiError::KeyMismatch); + } + if now < info.not_before || now >= info.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_prefix.is_empty() + || !cn.starts_with(cn_prefix) + || 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(info.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 key = Adapter::new(root)?; + let issuer = Issuer::from_ca_cert_pem(&root_pem, &key).map_err(build)?; + let pem = fresh.signed_by(&issuer).map_err(|e| key.fail(e))?.pem(); + if !issued_by(&pem, &root_pem)? { + return Err(PkiError::Signer( + "the signer's signature does not verify".into(), + )); + } + Ok(pem) +} + +/// An intermediate as its holder keeps it: the certificate and its signer (a local [`KeyPair`] +/// by default), checked to belong together and to be a CA. +pub struct Intermediate { + cert_pem: String, + key: S, + 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() + } +} + +impl Intermediate { + /// The first certificate of `cert_pem` with its signer. Refused unless it is a CA and the + /// signer's public key is the certificate's. + pub fn new(cert_pem: &str, key: S) -> Result, PkiError> { + let first = first_pem(cert_pem)?; + let info = inspect(&first)?; + if !info.is_ca { + return Err(PkiError::NotCa); + } + if public_key_der(&first)? != key.spki_der() { + return Err(PkiError::KeyMismatch); + } + Ok(Intermediate { + cert_pem: first, + key, + info, + }) + } + + /// The intermediate's certificate. + pub fn cert_pem(&self) -> &str { + &self.cert_pem + } + + /// notAfter, unix seconds. + pub fn not_after(&self) -> i64 { + self.info.not_after + } + + /// What the certificate says. + pub fn info(&self) -> &CertInfo { + &self.info + } + + /// The signer (the key, for a local intermediate). + pub fn key(&self) -> &S { + &self.key + } + + fn sign_leaf( + &self, + mut p: CertificateParams, + leaf_key: &impl rcgen::PublicKeyData, + days: u32, + now: i64, + ) -> Result { + if now < self.info.not_before || now >= self.info.not_after { + return Err(PkiError::IssuerExpired); + } + 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 signer = Adapter::new(&self.key)?; + let issuer = Issuer::from_ca_cert_pem(&self.cert_pem, &signer).map_err(build)?; + let cert = p.signed_by(leaf_key, &issuer).map_err(|e| signer.fail(e))?; + let cert_pem = cert.pem(); + if !issued_by(&cert_pem, &self.cert_pem)? { + return Err(PkiError::Signer( + "the signer's signature does not verify".into(), + )); + } + let info = inspect(&cert_pem)?; + Ok(IssuedCert { + chain_pem: format!("{cert_pem}{}", self.cert_pem), + serial_hex: info.serial_hex, + sha256_hex: info.sha256_hex, + not_before: info.not_before, + not_after: info.not_after, + cert_pem, + }) + } + + fn issue_with_new_key( + &self, + p: CertificateParams, + days: u32, + now: i64, + ) -> Result { + let key = generate_key()?; + let c = self.sign_leaf(p, &key.0, days, now)?; + Ok(Issued { + key_pem: key.serialize_pem(), + key, + cert_pem: c.cert_pem, + chain_pem: c.chain_pem, + serial_hex: c.serial_hex, + sha256_hex: c.sha256_hex, + not_before: c.not_before, + not_after: c.not_after, + }) + } +} + +/// A freshly issued leaf with the key the CA made for it (server and device certificates). +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, + /// The leaf's key. + pub key: KeyPair, + /// Serial, lowercase hex. + pub serial_hex: String, + /// SHA-256 of the leaf's DER, lowercase hex. + pub sha256_hex: String, + /// notBefore, unix seconds. + pub not_before: i64, + /// notAfter, unix seconds. + 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() + } +} + +/// A freshly issued leaf for a key the CA never saw (agent certificates, from a CSR). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct IssuedCert { + /// The leaf alone. + pub cert_pem: String, + /// Leaf, then the intermediate (what the agent presents). + pub chain_pem: String, + /// Serial, lowercase hex. + pub serial_hex: String, + /// SHA-256 of the leaf's DER, lowercase hex. + pub sha256_hex: String, + /// notBefore, unix seconds. + pub not_before: i64, + /// notAfter, unix seconds. + pub not_after: i64, +} + +/// A server certificate for one hostname (90 days, serverAuth). The hostname should already be +/// validated by the caller; rcgen refuses what is not a name. +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_with_new_key(p, SERVER_DAYS, now) +} + +/// A device certificate (mTLS client, 1 year) 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_with_new_key(p, DEVICE_DAYS, now) +} + +// ------------------------------------------------------------------ agents + +/// An agent's CSR: its own key, subject CN = the agent id. Made by Legatus; the key stays there. +pub fn agent_csr(key: &KeyPair, agent: &str) -> Result { + if !valid_id(agent) { + return Err(bad_id()); + } + intermediate_csr(key, agent) +} + +fn bad_id() -> PkiError { + PkiError::BadName("ids are 1 to 40 of a-z, 0-9 and '-', not starting or ending with '-'".into()) +} + +pub(crate) fn agent_params(team: &str, agent: &str) -> Result { + if !valid_id(team) || !valid_id(agent) { + return Err(bad_id()); + } + let mut p = CertificateParams::default(); + let mut d = DistinguishedName::new(); + d.push(DnType::CommonName, agent); + d.push(DnType::OrganizationName, ORG); + d.push(DnType::OrganizationalUnitName, "Domi agents"); + p.distinguished_name = d; + let uri = rcgen::string::Ia5String::try_from(agent_uri(team, agent)) + .map_err(|e| PkiError::BadName(e.to_string()))?; + p.subject_alt_names = vec![SanType::URI(uri)]; + p.key_usages = vec![KeyUsagePurpose::DigitalSignature]; + p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth]; + Ok(p) +} + +/// Read an agent's CSR: its signature must verify (the agent holds the key), its key must be +/// ECDSA P-256. Nothing else in it is used. +pub(crate) fn agent_key_from_csr(csr_pem: &str) -> Result { + let csr = CertificateSigningRequestParams::from_pem(csr_pem).map_err(|_| PkiError::BadCsr)?; + let spki = crate::inspect::csr_public_key_der(csr_pem)?; + let (alg, _) = key_kind(&spki)?; + if alg != &rcgen::PKCS_ECDSA_P256_SHA256 { + return Err(PkiError::UnsupportedKey); + } + Ok(csr.public_key) +} + +impl Intermediate { + pub(crate) fn issue_agent_unchecked( + &self, + csr_pem: &str, + team: &str, + agent: &str, + now: i64, + ) -> Result { + let p = agent_params(team, agent)?; + let key = agent_key_from_csr(csr_pem)?; + self.sign_leaf(p, &key, AGENT_DAYS, now) + } +} + +/// An agent certificate (mTLS client, [`AGENT_DAYS`]) for the key in the agent's CSR. Only the +/// agents intermediate ([`AGENTS_INTERMEDIATE_CN`]) issues agents. +pub fn issue_agent( + int: &Intermediate, + csr_pem: &str, + team: &str, + agent: &str, + now: i64, +) -> Result { + if !int.info().subject_cn.starts_with(AGENTS_INTERMEDIATE_CN) { + return Err(PkiError::WrongIntermediate); + } + int.issue_agent_unchecked(csr_pem, team, agent, now) +} + +/// Is an agent certificate ending at `not_after` due for renewal at `now`? +pub fn agent_renewal_due(not_after: i64, now: i64) -> bool { + not_after - now <= i64::from(AGENT_RENEW_DAYS) * DAY +} diff --git a/src/inspect.rs b/src/inspect.rs new file mode 100644 index 0000000..c0b28fd --- /dev/null +++ b/src/inspect.rs @@ -0,0 +1,293 @@ +// 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/. + +//! Reading certificates and CSRs (hostile input): what they say, who signed them, match codes. + +use base64::Engine as _; +use base64::engine::general_purpose::STANDARD; + +use crate::PkiError; + +/// What the Domi CA needs to know about a certificate. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CertInfo { + /// Subject common name ("" when absent). + pub subject_cn: String, + /// Issuer common name ("" when absent). + pub issuer_cn: String, + /// notBefore, unix seconds. + pub not_before: i64, + /// notAfter, unix seconds. + pub not_after: i64, + /// basicConstraints CA flag. + pub is_ca: bool, + /// basicConstraints pathLenConstraint. + pub path_len: Option, + /// DNS subject alternative names. + pub dns_names: Vec, + /// URI subject alternative names. + pub uris: Vec, + /// Serial number, lowercase hex. + pub serial_hex: String, + /// SHA-256 of the DER, lowercase hex. + 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, +} + +/// The keyUsage bits the CA cares about. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct KeyUsageInfo { + /// keyCertSign. + pub key_cert_sign: bool, + /// cRLSign. + pub crl_sign: bool, + /// digitalSignature. + pub digital_signature: bool, +} + +/// The extendedKeyUsage purposes the CA cares about. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct EkuInfo { + /// anyExtendedKeyUsage. + pub any: bool, + /// serverAuth. + pub server_auth: bool, + /// clientAuth. + 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) +} + +fn first_der(pem: &str) -> Result, PkiError> { + ders(pem)? + .into_iter() + .next() + .ok_or_else(|| PkiError::BadCertificate("no certificate in it".into())) +} + +/// The DER of every certificate in a PEM chain, in order. +pub fn chain_der(pem: &str) -> Result>, PkiError> { + ders(pem) +} + +/// The first certificate of a PEM chain, as PEM. +pub fn first_pem(pem: &str) -> Result { + Ok(der_to_pem(&first_der(pem)?)) +} + +/// One certificate as PEM. +pub fn der_to_pem(der: &[u8]) -> String { + armor("CERTIFICATE", der) +} + +pub(crate) fn armor(label: &str, der: &[u8]) -> String { + let b = STANDARD.encode(der); + let mut s = format!("-----BEGIN {label}-----\n"); + for chunk in b.as_bytes().chunks(64) { + s.push_str(&String::from_utf8_lossy(chunk)); + s.push('\n'); + } + s.push_str(&format!("-----END {label}-----\n")); + s +} + +pub(crate) 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()) +} + +/// Read the first certificate of a PEM chain. +pub fn inspect(pem: &str) -> Result { + inspect_der(&first_der(pem)?) +} + +/// Read one DER certificate. +pub fn inspect_der(der: &[u8]) -> Result { + use x509_parser::extensions::GeneralName; + let c = parse(der)?; + let bad = |e: x509_parser::error::X509Error| PkiError::BadCertificate(e.to_string()); + let (is_ca, path_len) = match c.basic_constraints().map_err(bad)? { + Some(b) => (b.value.ca, b.value.path_len_constraint), + None => (false, None), + }; + let mut dns_names = Vec::new(); + let mut uris = Vec::new(); + if let Some(san) = c.subject_alternative_name().map_err(bad)? { + for g in &san.value.general_names { + match g { + GeneralName::DNSName(n) => dns_names.push((*n).to_owned()), + GeneralName::URI(u) => uris.push((*u).to_owned()), + _ => {} + } + } + } + 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, + uris, + serial_hex: hex(c.raw_serial()), + sha256_hex: sha256_hex(der), + key_usage: c.key_usage().map_err(bad)?.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(bad)?.map(|e| EkuInfo { + any: e.value.any, + server_auth: e.value.server_auth, + client_auth: e.value.client_auth, + }), + }) +} + +/// Why a signed certificate cannot be the intermediate named `cn_prefix`, or `None` when it can. +/// It must be signed by the root, a CA with path length 0 whose CN starts with `cn_prefix`, that may +/// sign certificates (keyCertSign, cRLSign), allowed to issue both server and client 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, + cn_prefix: &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 cn_prefix.is_empty() + || !info.is_ca + || info.path_len != Some(0) + || !info.subject_cn.starts_with(cn_prefix) + { + 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 +} + +/// SubjectPublicKeyInfo DER of the first certificate. +pub fn public_key_der(pem: &str) -> Result, PkiError> { + let der = first_der(pem)?; + let c = parse(&der)?; + Ok(c.public_key().raw.to_vec()) +} + +/// 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 = first_der(child_pem)?; + let id = first_der(issuer_pem)?; + issued_by_der(&cd, &id) +} + +pub(crate) fn issued_by_der(child_der: &[u8], issuer_der: &[u8]) -> Result { + let child = parse(child_der)?; + let issuer = parse(issuer_der)?; + 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()) +} + +/// The code both screens show for one request: SHA-256 of the request, first three bytes, each +/// mod 100, as `47 19 83`. +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 + ) +} + +/// SubjectPublicKeyInfo DER of a CSR (to match a signed certificate to its request). Does not +/// check the CSR's signature. +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()) +} + +/// DER of the first `CERTIFICATE REQUEST` PEM block (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) +} diff --git a/src/lib.rs b/src/lib.rs index ee9e599..9dbc400 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,4 +2,121 @@ // 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 (docs/01_domi_pki.md). Tests first: the code follows. +//! The Domi CA (docs/01_domi_pki.md): a small CA on rcgen, checked with rustls-webpki. Pure: the +//! caller passes the time in and does every file read and write. Keys are ECDSA P-256; a root +//! [`Signer`] may also be Ed25519. +//! +//! ```text +//! Domi PKI Root 10 years, pathLen 1 key in Custos, signs through Signer +//! ├ Ianitor Domi Intermediate 1 year, pathLen 0 +//! │ ├ 90 days, serverAuth +//! │ └ 1 year, clientAuth +//! └ Fabrica Domi Agents Intermediate 1 year, pathLen 0 +//! ├ 90 days, serverAuth +//! └ 30 days, clientAuth, URI urn:domi:agent:: +//! ``` +//! +//! No certificate is ever issued past its issuer's `notAfter`. An 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. The same holds for agents: only the CSR's public key is used. + +mod ca; +mod inspect; +mod signer; +#[doc(hidden)] +pub mod testing; +mod verify; + +pub use ca::{ + INTERMEDIATE_OPENSSL_EXT, Intermediate, Issued, IssuedCert, agent_csr, agent_renewal_due, + create_root, create_root_local, intermediate_csr, issue_agent, issue_device, issue_server, + openssl_sign_command, placeholder_leaf, sign_intermediate, +}; +pub use inspect::{ + CertInfo, EkuInfo, KeyUsageInfo, chain_der, csr_der, csr_public_key_der, der_to_pem, first_pem, + inspect, inspect_der, intermediate_problem, issued_by, match_code, public_key_der, sha256_hex, +}; +pub use signer::{KeyPair, Signer, SignerError, generate_key}; +pub use verify::{ + AgentIdentity, Usage, VerifyError, agent_uri, parse_agent_uri, verify_agent, verify_chain, + verify_server, +}; + +/// Seconds in a day. +pub const DAY: i64 = 86_400; +/// Root: about 10 years. +pub const ROOT_DAYS: u32 = 3653; +/// Intermediates: about 1 year. +pub const INTERMEDIATE_DAYS: u32 = 365; +/// Server 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; +/// Agent (mTLS client) certificates. +pub const AGENT_DAYS: u32 = 30; +/// Renew an agent certificate when this many days or fewer are left. +pub const AGENT_RENEW_DAYS: u32 = 10; +/// Subject CN of the root. +pub const ROOT_CN: &str = "Domi PKI Root"; +/// Subject CN (prefix) of Ianitor's intermediate. +pub const IANITOR_INTERMEDIATE_CN: &str = "Ianitor Domi Intermediate"; +/// Subject CN (prefix) of the intermediate that issues Legatus agents (held by the Fabrica server). +pub const AGENTS_INTERMEDIATE_CN: &str = "Fabrica Domi Agents Intermediate"; +/// Organisation on every certificate. +pub const ORG: &str = "Fabrica Domi"; + +/// Is `id` a team or agent id: 1 to 40 of `a-z`, `0-9`, `-`, not starting or ending with `-`. +pub fn valid_id(id: &str) -> bool { + (1..=40).contains(&id.len()) + && id + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') + && !id.starts_with('-') + && !id.ends_with('-') +} + +/// Why the CA did not make a certificate or could not read one. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum PkiError { + /// A certificate cannot be read. + #[error("the certificate cannot be read: {0}")] + BadCertificate(String), + /// A CSR cannot be read or its signature is wrong. + #[error("the certificate signing request cannot be read or its signature is wrong")] + BadCsr, + /// The CSR's subject is not the name of the intermediate being made. + #[error("the request's subject is not the name of the intermediate being made")] + CsrSubject, + /// A private key cannot be read. + #[error("the private key cannot be read")] + BadKey, + /// Not a CA certificate. + #[error("the certificate is not a CA certificate")] + NotCa, + /// Key and certificate do not belong together. + #[error("the private key does not belong to the certificate")] + KeyMismatch, + /// The issuer is outside its validity. + #[error("the issuing certificate has expired or is not valid yet")] + IssuerExpired, + /// A name that cannot go in a certificate. + #[error("the name cannot be used in a certificate: {0}")] + BadName(String), + /// No randomness. + #[error("no randomness available")] + Random, + /// rcgen could not build the certificate. + #[error("the certificate could not be made: {0}")] + Build(String), + /// The signer did not sign, or its signature does not verify. + #[error("the signer did not sign: {0}")] + Signer(String), + /// A key type the Domi CA does not use. + #[error("the key type is not supported (ECDSA P-256, or Ed25519 for a root signer)")] + UnsupportedKey, + /// Only the agents intermediate issues agent certificates. + #[error("only the agents intermediate issues agent certificates")] + WrongIntermediate, +} diff --git a/src/signer.rs b/src/signer.rs new file mode 100644 index 0000000..2d5049b --- /dev/null +++ b/src/signer.rs @@ -0,0 +1,185 @@ +// 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/. + +//! Who signs: the [`Signer`] trait (the root lives in Custos and signs through it) and the local +//! [`KeyPair`] (intermediates, tests, the offline machine). + +use std::cell::RefCell; +use std::fmt; + +use rcgen::{PKCS_ECDSA_P256_SHA256, PKCS_ED25519, PublicKeyData, SignatureAlgorithm, SigningKey}; +use x509_parser::oid_registry::{OID_EC_P256, OID_KEY_TYPE_EC_PUBLIC_KEY, OID_SIG_ED25519}; +use x509_parser::prelude::FromDer; + +use crate::PkiError; + +/// Why a [`Signer`] did not sign (declined, timed out, unreachable). Shown to people as it is. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SignerError(String); + +impl SignerError { + /// A signer error with a plain-English reason. + pub fn new(reason: impl Into) -> SignerError { + SignerError(reason.into()) + } + + /// The reason. + pub fn reason(&self) -> &str { + &self.0 + } +} + +impl fmt::Display for SignerError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for SignerError {} + +/// A key that signs on the crate's behalf without handing the private key over. +/// +/// Custos implements this for the Domi root (after a match-code approval); [`KeyPair`] implements +/// it for local keys. The crate checks every signature it gets back, so a faulty or lying signer +/// yields [`PkiError::Signer`], never a bad certificate. +pub trait Signer { + /// SubjectPublicKeyInfo DER of the signing key: ECDSA P-256 or Ed25519. + fn spki_der(&self) -> Vec; + /// Sign `msg`. ECDSA P-256: SHA-256, the signature ASN.1 DER encoded. Ed25519: the raw 64 bytes. + fn sign(&self, msg: &[u8]) -> Result, SignerError>; +} + +impl Signer for &S { + fn spki_der(&self) -> Vec { + (**self).spki_der() + } + fn sign(&self, msg: &[u8]) -> Result, SignerError> { + (**self).sign(msg) + } +} + +/// An ECDSA P-256 key pair held in memory. Never printed. +pub struct KeyPair(pub(crate) 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() + } + + /// PKCS#8 DER. + pub fn serialize_der(&self) -> Vec { + self.0.serialize_der() + } + + /// Read a PKCS#8 PEM key. + pub fn from_pem(pem: &str) -> Result { + rcgen::KeyPair::from_pem(pem) + .map(KeyPair) + .map_err(|_| PkiError::BadKey) + } + + /// Read a PKCS#8 DER key. + pub fn from_der(der: &[u8]) -> Result { + rcgen::KeyPair::try_from(der) + .map(KeyPair) + .map_err(|_| PkiError::BadKey) + } + + /// SubjectPublicKeyInfo DER (the same as [`Signer::spki_der`]). + pub fn public_key_der(&self) -> Vec { + self.0.subject_public_key_info() + } +} + +impl Signer for KeyPair { + fn spki_der(&self) -> Vec { + self.public_key_der() + } + fn sign(&self, msg: &[u8]) -> Result, SignerError> { + SigningKey::sign(&self.0, msg).map_err(|e| SignerError::new(e.to_string())) + } +} + +/// A new ECDSA P-256 key. +pub fn generate_key() -> Result { + rcgen::KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256) + .map(KeyPair) + .map_err(|e| PkiError::Build(e.to_string())) +} + +/// The algorithm of a SubjectPublicKeyInfo: ECDSA P-256 (signing with SHA-256) or Ed25519, and the +/// raw public key bits. Anything else is [`PkiError::UnsupportedKey`]. +pub(crate) fn key_kind( + spki_der: &[u8], +) -> Result<(&'static SignatureAlgorithm, Vec), PkiError> { + let (rest, spki) = x509_parser::x509::SubjectPublicKeyInfo::from_der(spki_der) + .map_err(|_| PkiError::UnsupportedKey)?; + if !rest.is_empty() { + return Err(PkiError::UnsupportedKey); + } + let alg = &spki.algorithm; + let raw = spki.subject_public_key.data.to_vec(); + if alg.algorithm == OID_KEY_TYPE_EC_PUBLIC_KEY { + let curve = alg.parameters.as_ref().and_then(|p| p.as_oid().ok()); + if curve.as_ref() == Some(&OID_EC_P256) && raw.len() == 65 { + return Ok((&PKCS_ECDSA_P256_SHA256, raw)); + } + } else if alg.algorithm == OID_SIG_ED25519 && alg.parameters.is_none() && raw.len() == 32 { + return Ok((&PKCS_ED25519, raw)); + } + Err(PkiError::UnsupportedKey) +} + +/// A [`Signer`] seen through rcgen's eyes. Keeps the signer's own error, which rcgen would lose. +pub(crate) struct Adapter<'a> { + signer: &'a dyn Signer, + alg: &'static SignatureAlgorithm, + raw: Vec, + error: RefCell>, +} + +impl<'a> Adapter<'a> { + pub(crate) fn new(signer: &'a dyn Signer) -> Result, PkiError> { + let (alg, raw) = key_kind(&signer.spki_der())?; + Ok(Adapter { + signer, + alg, + raw, + error: RefCell::new(None), + }) + } + + /// The signer's own error if it had one, else rcgen's. + pub(crate) fn fail(&self, e: rcgen::Error) -> PkiError { + match self.error.borrow_mut().take() { + Some(s) => PkiError::Signer(s.reason().to_owned()), + None => PkiError::Build(e.to_string()), + } + } +} + +impl PublicKeyData for Adapter<'_> { + fn der_bytes(&self) -> &[u8] { + &self.raw + } + fn algorithm(&self) -> &'static SignatureAlgorithm { + self.alg + } +} + +impl SigningKey for Adapter<'_> { + fn sign(&self, msg: &[u8]) -> Result, rcgen::Error> { + self.signer.sign(msg).map_err(|e| { + *self.error.borrow_mut() = Some(e); + rcgen::Error::RemoteKeyError + }) + } +} diff --git a/src/testing.rs b/src/testing.rs new file mode 100644 index 0000000..8ff7e29 --- /dev/null +++ b/src/testing.rs @@ -0,0 +1,93 @@ +// 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/. + +//! Helpers for tests that need certificates the Domi CA itself would never make. + +use rcgen::{ + BasicConstraints, CertificateParams, ExtendedKeyUsagePurpose, IsCa, Issuer, KeyUsagePurpose, +}; + +use crate::ca::dn; +use crate::inspect::{armor, csr_der, first_pem}; +use crate::*; + +fn build(e: rcgen::Error) -> PkiError { + PkiError::Build(e.to_string()) +} + +fn time(unix: i64) -> Result { + time::OffsetDateTime::from_unix_timestamp(unix).map_err(|e| PkiError::Build(e.to_string())) +} + +/// A server certificate for `name`, signed with `key` as if the first certificate of +/// `issuer_pem` were a CA (for "a leaf cannot sign"). +pub fn sign_as(issuer_pem: &str, key: KeyPair, 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 - 300)?; + 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()) +} + +/// 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 - 300)?; + 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()) +} + +/// A CSR that asks for far too much: a CA, no path limit, a web name, 50 years. +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) +} + +/// 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; + } + armor("CERTIFICATE REQUEST", &der) +} + +/// An agent certificate made by any intermediate (a compromised Ianitor), chain PEM. +pub fn agent_under_any( + int: &Intermediate, + csr_pem: &str, + team: &str, + agent: &str, + now: i64, +) -> Result { + Ok(int + .issue_agent_unchecked(csr_pem, team, agent, now)? + .chain_pem) +} + +/// A CSR for an Ed25519 key (agents must use P-256). +pub fn ed25519_csr(cn: &str) -> Result { + let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ED25519).map_err(build)?; + let mut p = CertificateParams::default(); + p.distinguished_name = dn(cn); + p.serialize_request(&key) + .map_err(build)? + .pem() + .map_err(build) +} diff --git a/src/verify.rs b/src/verify.rs new file mode 100644 index 0000000..cda36b5 --- /dev/null +++ b/src/verify.rs @@ -0,0 +1,224 @@ +// 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, + }) +} diff --git a/tests/agents.rs b/tests/agents.rs index 38d79e2..c2cc5b7 100644 --- a/tests/agents.rs +++ b/tests/agents.rs @@ -17,7 +17,8 @@ fn an_agent_certificate_names_the_agent_and_its_team() { let c = ca(); let (key, csr) = agent_csr("build-box-1"); let a = pki::issue_agent(&c.agents, &csr, "acme", "build-box-1", NOW).unwrap(); - let id: AgentIdentity = pki::verify_agent(&ders(&a.chain_pem), &c.root_der(), NOW + DAY).unwrap(); + let id: AgentIdentity = + pki::verify_agent(&ders(&a.chain_pem), &c.root_der(), NOW + DAY).unwrap(); assert_eq!(id.team, "acme"); assert_eq!(id.agent, "build-box-1"); assert_eq!(id.serial_hex, a.serial_hex); @@ -25,12 +26,21 @@ fn an_agent_certificate_names_the_agent_and_its_team() { assert_eq!(id.not_after, a.not_after); assert_eq!((a.not_after - NOW) / DAY, AGENT_DAYS as i64); // The certificate carries the agent's own key: the CA never made or saw a private key. - assert_eq!(pki::public_key_der(&a.cert_pem).unwrap(), key.public_key_der()); + assert_eq!( + pki::public_key_der(&a.cert_pem).unwrap(), + key.public_key_der() + ); let info = pki::inspect(&a.cert_pem).unwrap(); assert_eq!(info.subject_cn, "build-box-1"); assert!(!info.is_ca); - assert_eq!(info.eku.map(|e| (e.client_auth, e.server_auth)), Some((true, false))); - assert_eq!(pki::agent_uri("acme", "build-box-1"), "urn:domi:agent:acme:build-box-1"); + assert_eq!( + info.eku.map(|e| (e.client_auth, e.server_auth)), + Some((true, false)) + ); + assert_eq!( + pki::agent_uri("acme", "build-box-1"), + "urn:domi:agent:acme:build-box-1" + ); // Client auth only. assert_eq!( pki::verify_chain(&ders(&a.chain_pem), &c.root_der(), NOW + DAY, Usage::Server), @@ -59,7 +69,13 @@ fn a_device_or_server_certificate_is_not_an_agent() { let c = ca(); // A phone's device certificate: same root, client auth, but Ianitor's intermediate. let dev = pki::issue_device(&c.ianitor, "phone", NOW).unwrap(); - pki::verify_chain(&ders(&dev.chain_pem), &c.root_der(), NOW + DAY, Usage::Client).unwrap(); + pki::verify_chain( + &ders(&dev.chain_pem), + &c.root_der(), + NOW + DAY, + Usage::Client, + ) + .unwrap(); assert_eq!( pki::verify_agent(&ders(&dev.chain_pem), &c.root_der(), NOW + DAY), Err(VerifyError::NotAnAgent) @@ -102,7 +118,10 @@ fn an_agent_of_another_root_is_foreign() { let (_, csr) = agent_csr("a1"); let a = pki::issue_agent(&other.agents, &csr, "acme", "a1", NOW).unwrap(); let e = pki::verify_agent(&ders(&a.chain_pem), &c.root_der(), NOW + DAY).unwrap_err(); - assert!(matches!(e, VerifyError::UnknownIssuer | VerifyError::BadSignature), "{e:?}"); + assert!( + matches!(e, VerifyError::UnknownIssuer | VerifyError::BadSignature), + "{e:?}" + ); } #[test] @@ -120,12 +139,17 @@ fn an_agent_chain_must_be_exactly_leaf_and_agents_intermediate() { chain.push(ders(c.ianitor.cert_pem()).remove(0)); assert_eq!( pki::verify_agent(&chain, &c.root_der(), NOW + DAY), - Err(VerifyError::BadCertificate("an agent presents its certificate and the agents intermediate".into())) + Err(VerifyError::BadCertificate( + "an agent presents its certificate and the agents intermediate".into() + )) ); // The agents intermediate presented, but a different one (another Fabrica server) signed the leaf. let other_agents = intermediate(&c.root, &c.root_pem, pki::AGENTS_INTERMEDIATE_CN); let b = pki::issue_agent(&other_agents, &csr, "acme", "a1", NOW).unwrap(); - let mixed = vec![ders(&b.cert_pem).remove(0), ders(c.agents.cert_pem()).remove(0)]; + let mixed = vec![ + ders(&b.cert_pem).remove(0), + ders(c.agents.cert_pem()).remove(0), + ]; assert!(pki::verify_agent(&mixed, &c.root_der(), NOW + DAY).is_err()); } @@ -180,7 +204,10 @@ fn agent_and_team_ids_are_checked() { ("ac/me", "a1"), ] { assert!( - matches!(pki::issue_agent(&c.agents, &csr, team, agent, NOW), Err(PkiError::BadName(_))), + matches!( + pki::issue_agent(&c.agents, &csr, team, agent, NOW), + Err(PkiError::BadName(_)) + ), "{team:?} {agent:?}" ); } @@ -190,7 +217,12 @@ fn agent_and_team_ids_are_checked() { pki::parse_agent_uri("urn:domi:agent:acme:a1"), Some(("acme".to_owned(), "a1".to_owned())) ); - for bad in ["urn:domi:agent:acme", "urn:domi:agent:acme:a1:x", "urn:domi:device:acme:a1", "urn:domi:agent::a1"] { + for bad in [ + "urn:domi:agent:acme", + "urn:domi:agent:acme:a1:x", + "urn:domi:device:acme:a1", + "urn:domi:agent::a1", + ] { assert_eq!(pki::parse_agent_uri(bad), None, "{bad}"); } } diff --git a/tests/chains.rs b/tests/chains.rs index f803d0c..7eb2df5 100644 --- a/tests/chains.rs +++ b/tests/chains.rs @@ -25,8 +25,14 @@ fn root_is_a_ten_year_ca_with_path_length_one() { assert_eq!(info.subject_cn, pki::ROOT_CN); assert_eq!(info.issuer_cn, pki::ROOT_CN); let days = (info.not_after - NOW) / DAY; - assert!((ROOT_DAYS as i64 - 1..=ROOT_DAYS as i64).contains(&days), "{days}"); - assert!(pki::issued_by(&c.root_pem, &c.root_pem).unwrap(), "self-signed"); + assert!( + (ROOT_DAYS as i64 - 1..=ROOT_DAYS as i64).contains(&days), + "{days}" + ); + assert!( + pki::issued_by(&c.root_pem, &c.root_pem).unwrap(), + "self-signed" + ); } #[test] @@ -41,16 +47,31 @@ fn both_intermediates_are_one_year_path_length_zero_under_the_root() { assert!(!pki::issued_by(&c.root_pem, int.cert_pem()).unwrap()); } assert_eq!( - pki::intermediate_problem(c.agents.cert_pem(), &c.root_pem, pki::AGENTS_INTERMEDIATE_CN, NOW), + pki::intermediate_problem( + c.agents.cert_pem(), + &c.root_pem, + pki::AGENTS_INTERMEDIATE_CN, + NOW + ), None ); assert_eq!( - pki::intermediate_problem(c.ianitor.cert_pem(), &c.root_pem, pki::IANITOR_INTERMEDIATE_CN, NOW), + pki::intermediate_problem( + c.ianitor.cert_pem(), + &c.root_pem, + pki::IANITOR_INTERMEDIATE_CN, + NOW + ), None ); // Each is only the intermediate it is named for. assert_eq!( - pki::intermediate_problem(c.ianitor.cert_pem(), &c.root_pem, pki::AGENTS_INTERMEDIATE_CN, NOW), + pki::intermediate_problem( + c.ianitor.cert_pem(), + &c.root_pem, + pki::AGENTS_INTERMEDIATE_CN, + NOW + ), Some("not_ca") ); } @@ -73,7 +94,10 @@ fn server_chain_validates_for_its_name_only() { let info = pki::inspect(&leaf.cert_pem).unwrap(); assert_eq!((info.not_after - NOW) / DAY, SERVER_DAYS as i64); let k = pki::KeyPair::from_pem(&leaf.key_pem).unwrap(); - assert_eq!(pki::public_key_der(&leaf.cert_pem).unwrap(), k.public_key_der()); + assert_eq!( + pki::public_key_der(&leaf.cert_pem).unwrap(), + k.public_key_der() + ); } #[test] @@ -104,7 +128,10 @@ fn a_leaf_cannot_sign() { let forged = pki::testing::sign_as(&leaf.cert_pem, leaf_key, "evil.home.test", NOW).unwrap(); let chain = ders(&format!("{forged}{}", leaf.chain_pem)); let e = pki::verify_chain(&chain, &c.root_der(), NOW + DAY, Usage::Server).unwrap_err(); - assert!(matches!(e, VerifyError::NotCa | VerifyError::UnknownIssuer), "{e:?}"); + assert!( + matches!(e, VerifyError::NotCa | VerifyError::UnknownIssuer), + "{e:?}" + ); } #[test] @@ -143,7 +170,10 @@ fn an_expired_intermediate_fails_the_chain_and_issues_nothing() { let late = NOW + (INTERMEDIATE_DAYS as i64 - 10) * DAY; let dev = pki::issue_device(&c.ianitor, "tablet", late).unwrap(); let info = pki::inspect(&dev.cert_pem).unwrap(); - assert!(info.not_after <= c.ianitor.not_after(), "no leaf outlives its issuer"); + assert!( + info.not_after <= c.ianitor.not_after(), + "no leaf outlives its issuer" + ); let gone = NOW + (INTERMEDIATE_DAYS as i64 + 1) * DAY; assert!(matches!( pki::issue_server(&c.agents, "fabrica.home.test", gone), @@ -151,7 +181,12 @@ fn an_expired_intermediate_fails_the_chain_and_issues_nothing() { )); // A chain whose intermediate expired is refused even inside the leaf's own validity. assert_eq!( - pki::verify_chain(&ders(&dev.chain_pem), &c.root_der(), c.ianitor.not_after() + 1, Usage::Client), + pki::verify_chain( + &ders(&dev.chain_pem), + &c.root_der(), + c.ianitor.not_after() + 1, + Usage::Client + ), Err(VerifyError::Expired) ); // The root refuses to sign once it has expired. @@ -159,7 +194,13 @@ fn an_expired_intermediate_fails_the_chain_and_issues_nothing() { let csr = pki::intermediate_csr(&key, pki::AGENTS_INTERMEDIATE_CN).unwrap(); let past_root = NOW + (ROOT_DAYS as i64 + 1) * DAY; assert!(matches!( - pki::sign_intermediate(&c.root_pem, &c.root, &csr, pki::AGENTS_INTERMEDIATE_CN, past_root), + pki::sign_intermediate( + &c.root_pem, + &c.root, + &csr, + pki::AGENTS_INTERMEDIATE_CN, + past_root + ), Err(PkiError::IssuerExpired) )); } @@ -171,13 +212,26 @@ fn another_root_with_the_same_names_is_refused() { let c = ca(); let other = ca(); let leaf = pki::issue_server(&other.agents, "fabrica.home.test", NOW).unwrap(); - let e = pki::verify_chain(&ders(&leaf.chain_pem), &c.root_der(), NOW + DAY, Usage::Server) - .unwrap_err(); - assert!(matches!(e, VerifyError::UnknownIssuer | VerifyError::BadSignature), "{e:?}"); + let e = pki::verify_chain( + &ders(&leaf.chain_pem), + &c.root_der(), + NOW + DAY, + Usage::Server, + ) + .unwrap_err(); + assert!( + matches!(e, VerifyError::UnknownIssuer | VerifyError::BadSignature), + "{e:?}" + ); assert!(!pki::issued_by(&leaf.cert_pem, other.ianitor.cert_pem()).unwrap()); assert!(!pki::issued_by(other.agents.cert_pem(), &c.root_pem).unwrap()); assert_eq!( - pki::intermediate_problem(other.agents.cert_pem(), &c.root_pem, pki::AGENTS_INTERMEDIATE_CN, NOW), + pki::intermediate_problem( + other.agents.cert_pem(), + &c.root_pem, + pki::AGENTS_INTERMEDIATE_CN, + NOW + ), Some("not_root") ); } diff --git a/tests/signer.rs b/tests/signer.rs index ab9053c..213ffe5 100644 --- a/tests/signer.rs +++ b/tests/signer.rs @@ -40,7 +40,13 @@ fn a_signer_that_is_not_the_root_is_refused_before_signing() { let key = pki::generate_key().unwrap(); let csr = pki::intermediate_csr(&key, pki::AGENTS_INTERMEDIATE_CN).unwrap(); assert!(matches!( - pki::sign_intermediate(&c.root_pem, &impostor, &csr, pki::AGENTS_INTERMEDIATE_CN, NOW), + pki::sign_intermediate( + &c.root_pem, + &impostor, + &csr, + pki::AGENTS_INTERMEDIATE_CN, + NOW + ), Err(PkiError::KeyMismatch) )); assert_eq!(impostor.signed.get(), 0); @@ -73,7 +79,10 @@ impl Signer for Refuses { #[test] fn a_bad_signature_from_the_signer_is_caught() { let liar = Liar(CustosLike::new()); - assert!(matches!(pki::create_root(&liar, NOW), Err(PkiError::Signer(_)))); + assert!(matches!( + pki::create_root(&liar, NOW), + Err(PkiError::Signer(_)) + )); let c = ca(); let liar = Liar(c.root); let key = pki::generate_key().unwrap(); @@ -104,7 +113,10 @@ fn a_signer_with_an_unsupported_key_is_refused() { Ok(vec![0; 64]) } } - assert!(matches!(pki::create_root(&Garbage, NOW), Err(PkiError::UnsupportedKey))); + assert!(matches!( + pki::create_root(&Garbage, NOW), + Err(PkiError::UnsupportedKey) + )); } #[test] @@ -112,7 +124,14 @@ fn the_intermediate_ignores_what_the_csr_asks_for() { let c = ca(); let key = pki::generate_key().unwrap(); let greedy = pki::testing::greedy_csr(&key, pki::AGENTS_INTERMEDIATE_CN).unwrap(); - let pem = pki::sign_intermediate(&c.root_pem, &c.root, &greedy, pki::AGENTS_INTERMEDIATE_CN, NOW).unwrap(); + let pem = pki::sign_intermediate( + &c.root_pem, + &c.root, + &greedy, + pki::AGENTS_INTERMEDIATE_CN, + NOW, + ) + .unwrap(); let info = pki::inspect(&pem).unwrap(); assert_eq!(info.path_len, Some(0)); assert!(info.dns_names.is_empty()); @@ -126,8 +145,26 @@ fn the_intermediate_ignores_what_the_csr_asks_for() { )); } let csr = pki::intermediate_csr(&key, pki::AGENTS_INTERMEDIATE_CN).unwrap(); - assert!(pki::sign_intermediate(&c.root_pem, &c.root, &pki::testing::tamper_csr(&csr), pki::AGENTS_INTERMEDIATE_CN, NOW).is_err()); - assert!(pki::sign_intermediate(&c.root_pem, &c.root, "not a csr", pki::AGENTS_INTERMEDIATE_CN, NOW).is_err()); + assert!( + pki::sign_intermediate( + &c.root_pem, + &c.root, + &pki::testing::tamper_csr(&csr), + pki::AGENTS_INTERMEDIATE_CN, + NOW + ) + .is_err() + ); + assert!( + pki::sign_intermediate( + &c.root_pem, + &c.root, + "not a csr", + pki::AGENTS_INTERMEDIATE_CN, + NOW + ) + .is_err() + ); } #[test] @@ -149,7 +186,14 @@ fn a_local_root_works_for_the_offline_machine_and_tests() { let (root_pem, root_key) = pki::create_root_local(NOW).unwrap(); let key = pki::generate_key().unwrap(); let csr = pki::intermediate_csr(&key, pki::IANITOR_INTERMEDIATE_CN).unwrap(); - let pem = pki::sign_intermediate(&root_pem, &root_key, &csr, pki::IANITOR_INTERMEDIATE_CN, NOW).unwrap(); + let pem = pki::sign_intermediate( + &root_pem, + &root_key, + &csr, + pki::IANITOR_INTERMEDIATE_CN, + NOW, + ) + .unwrap(); assert!(pki::issued_by(&pem, &root_pem).unwrap()); // The openssl profile for the manual step matches. assert!(pki::INTERMEDIATE_OPENSSL_EXT.contains("pathlen:0")); @@ -168,7 +212,11 @@ fn keys_and_match_codes() { assert_ne!(a, pki::match_code(b"other csr")); let parts: Vec<&str> = a.split(' ').collect(); assert_eq!(parts.len(), 3); - assert!(parts.iter().all(|p| p.len() == 2 && p.bytes().all(|b| b.is_ascii_digit()))); + assert!( + parts + .iter() + .all(|p| p.len() == 2 && p.bytes().all(|b| b.is_ascii_digit())) + ); } #[test] @@ -179,7 +227,11 @@ fn hostile_pem_and_der_never_panic() { "-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----\n", "-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n", // Split so that this file does not match the pre-commit hook. - concat!("-----BEGIN PRIVATE", " KEY-----\nAAAA\n-----END PRIVATE", " KEY-----\n"), + concat!( + "-----BEGIN PRIVATE", + " KEY-----\nAAAA\n-----END PRIVATE", + " KEY-----\n" + ), "\u{0}\u{1}", ] { assert!(pki::inspect(bad).is_err()); @@ -194,3 +246,34 @@ fn hostile_pem_and_der_never_panic() { assert!(pki::verify_agent(&[junk.to_vec()], &c.root_der(), NOW).is_err()); } } + +/// A root held as Ed25519 (Custos's minisign-style keys are Ed25519). +struct EdRoot(ring::signature::Ed25519KeyPair); +impl Signer for EdRoot { + fn spki_der(&self) -> Vec { + use ring::signature::KeyPair as _; + // SubjectPublicKeyInfo: SEQUENCE { SEQUENCE { OID 1.3.101.112 }, BIT STRING key }. + let mut d = vec![ + 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00, + ]; + d.extend_from_slice(self.0.public_key().as_ref()); + d + } + fn sign(&self, msg: &[u8]) -> Result, SignerError> { + Ok(self.0.sign(msg).as_ref().to_vec()) + } +} + +#[test] +fn an_ed25519_root_signer_works_end_to_end() { + let rng = ring::rand::SystemRandom::new(); + let pkcs8 = ring::signature::Ed25519KeyPair::generate_pkcs8(&rng).unwrap(); + let root = EdRoot(ring::signature::Ed25519KeyPair::from_pkcs8(pkcs8.as_ref()).unwrap()); + let root_pem = pki::create_root(&root, NOW).unwrap(); + let agents = intermediate(&root, &root_pem, pki::AGENTS_INTERMEDIATE_CN); + let (_, csr) = agent_csr("a1"); + let a = pki::issue_agent(&agents, &csr, "acme", "a1", NOW).unwrap(); + let root_der = pki::chain_der(&root_pem).unwrap().remove(0); + let id = pki::verify_agent(&ders(&a.chain_pem), &root_der, NOW + DAY).unwrap(); + assert_eq!((id.team.as_str(), id.agent.as_str()), ("acme", "a1")); +}