From ae6d2edcbb80f551ef0256d3e284f95ca86f435d Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 17 Nov 2026 11:15:54 +0100 Subject: [PATCH] [pki] Tests: chains, expiry, wrong issuer, agent certificates, the root signer (red: the code follows) --- Cargo.toml | 29 ++++++ src/lib.rs | 5 + tests/agents.rs | 205 +++++++++++++++++++++++++++++++++++++++ tests/chains.rs | 227 ++++++++++++++++++++++++++++++++++++++++++++ tests/common/mod.rs | 82 ++++++++++++++++ tests/signer.rs | 196 ++++++++++++++++++++++++++++++++++++++ 6 files changed, 744 insertions(+) create mode 100644 Cargo.toml create mode 100644 src/lib.rs create mode 100644 tests/agents.rs create mode 100644 tests/chains.rs create mode 100644 tests/common/mod.rs create mode 100644 tests/signer.rs diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..0588499 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "domi-pki" +version = "1.0.0" +description = "The Domi CA: root certificate through a signer, intermediates, server, device and agent certificates, chain checks. Pure: no I/O." +edition = "2024" +rust-version = "1.89" +license = "MPL-2.0" +repository = "https://gitea.marek-novak.cz/mnovak/domi-pki" +publish = false + +[dependencies] +rcgen = { version = "0.14.5", default-features = false, features = ["ring", "pem", "crypto", "x509-parser"] } +x509-parser = { version = "0.18", features = ["verify"] } +webpki = { package = "rustls-webpki", version = "0.103", default-features = false, features = ["ring", "alloc"] } +rustls-pki-types = "1.12" +ring = "0.17.14" +base64 = "0.22.1" +thiserror = "2.0.17" +time = { version = "0.3", default-features = false } + +[lints.rust] +unsafe_code = "forbid" +missing_docs = "warn" + +[lints.clippy] +# Hostile input never meets unwrap(): non-test code must handle every Result. +unwrap_used = "deny" +expect_used = "deny" +panic = "deny" diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..ee9e599 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,5 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! The Domi CA (docs/01_domi_pki.md). Tests first: the code follows. diff --git a/tests/agents.rs b/tests/agents.rs new file mode 100644 index 0000000..38d79e2 --- /dev/null +++ b/tests/agents.rs @@ -0,0 +1,205 @@ +// 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/. + +//! Agent certificates (tests first, docs/01): issued from the agent's own CSR, only by the agents +//! intermediate; `verify_agent` names the agent, and refuses expired, foreign and mis-chained ones. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod common; + +use common::*; +use domi_pki::{self as pki, AGENT_DAYS, AgentIdentity, PkiError, Usage, VerifyError}; + +#[test] +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(); + assert_eq!(id.team, "acme"); + assert_eq!(id.agent, "build-box-1"); + assert_eq!(id.serial_hex, a.serial_hex); + assert_eq!(id.sha256_hex, a.sha256_hex); + 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()); + 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"); + // Client auth only. + assert_eq!( + pki::verify_chain(&ders(&a.chain_pem), &c.root_der(), NOW + DAY, Usage::Server), + Err(VerifyError::WrongUsage) + ); +} + +#[test] +fn an_expired_or_early_agent_certificate_is_refused() { + let c = ca(); + let (_, csr) = agent_csr("a1"); + let a = pki::issue_agent(&c.agents, &csr, "acme", "a1", NOW).unwrap(); + let chain = ders(&a.chain_pem); + assert_eq!( + pki::verify_agent(&chain, &c.root_der(), NOW + (AGENT_DAYS as i64 + 1) * DAY), + Err(VerifyError::Expired) + ); + assert_eq!( + pki::verify_agent(&chain, &c.root_der(), NOW - DAY), + Err(VerifyError::NotYetValid) + ); +} + +#[test] +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(); + assert_eq!( + pki::verify_agent(&ders(&dev.chain_pem), &c.root_der(), NOW + DAY), + Err(VerifyError::NotAnAgent) + ); + // A device certificate made by the agents intermediate still has no agent URI. + let dev2 = pki::issue_device(&c.agents, "phone", NOW).unwrap(); + assert_eq!( + pki::verify_agent(&ders(&dev2.chain_pem), &c.root_der(), NOW + DAY), + Err(VerifyError::NotAnAgent) + ); + let srv = pki::issue_server(&c.agents, "fabrica.home.test", NOW).unwrap(); + assert_eq!( + pki::verify_agent(&ders(&srv.chain_pem), &c.root_der(), NOW + DAY), + Err(VerifyError::WrongUsage) + ); +} + +#[test] +fn an_agent_under_the_wrong_intermediate_is_foreign() { + let c = ca(); + let (_, csr) = agent_csr("a1"); + // The CA refuses to issue an agent from Ianitor's intermediate... + assert!(matches!( + pki::issue_agent(&c.ianitor, &csr, "acme", "a1", NOW), + Err(PkiError::WrongIntermediate) + )); + // ...and one made there anyway (a compromised Ianitor) is refused as an agent. + let forged = pki::testing::agent_under_any(&c.ianitor, &csr, "acme", "a1", NOW).unwrap(); + pki::verify_chain(&ders(&forged), &c.root_der(), NOW + DAY, Usage::Client).unwrap(); + assert_eq!( + pki::verify_agent(&ders(&forged), &c.root_der(), NOW + DAY), + Err(VerifyError::WrongIntermediate) + ); +} + +#[test] +fn an_agent_of_another_root_is_foreign() { + let c = ca(); + let other = ca(); + 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:?}"); +} + +#[test] +fn an_agent_chain_must_be_exactly_leaf_and_agents_intermediate() { + let c = ca(); + let (_, csr) = agent_csr("a1"); + let a = pki::issue_agent(&c.agents, &csr, "acme", "a1", NOW).unwrap(); + let mut chain = ders(&a.chain_pem); + // The leaf alone. + assert_eq!( + pki::verify_agent(&chain[..1], &c.root_der(), NOW + DAY), + Err(VerifyError::UnknownIssuer) + ); + // Leaf, the right intermediate, and an extra certificate. + 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())) + ); + // 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)]; + assert!(pki::verify_agent(&mixed, &c.root_der(), NOW + DAY).is_err()); +} + +#[test] +fn the_csr_only_gives_its_public_key() { + let c = ca(); + let key = pki::generate_key().unwrap(); + // The CSR asks to be a CA, for a web name, for 50 years. + let greedy = pki::testing::greedy_csr(&key, "someone-else").unwrap(); + let a = pki::issue_agent(&c.agents, &greedy, "acme", "a1", NOW).unwrap(); + let info = pki::inspect(&a.cert_pem).unwrap(); + assert!(!info.is_ca); + assert!(info.dns_names.is_empty()); + assert_eq!(info.subject_cn, "a1"); + assert_eq!((info.not_after - NOW) / DAY, AGENT_DAYS as i64); + pki::verify_agent(&ders(&a.chain_pem), &c.root_der(), NOW + DAY).unwrap(); +} + +#[test] +fn a_tampered_or_wrong_kind_of_csr_is_refused() { + let c = ca(); + let (_, csr) = agent_csr("a1"); + let tampered = pki::testing::tamper_csr(&csr); + assert!(matches!( + pki::issue_agent(&c.agents, &tampered, "acme", "a1", NOW), + Err(PkiError::BadCsr) + )); + assert!(matches!( + pki::issue_agent(&c.agents, "not a csr", "acme", "a1", NOW), + Err(PkiError::BadCsr) + )); + let ed = pki::testing::ed25519_csr("a1").unwrap(); + assert!(matches!( + pki::issue_agent(&c.agents, &ed, "acme", "a1", NOW), + Err(PkiError::UnsupportedKey) + )); +} + +#[test] +fn agent_and_team_ids_are_checked() { + let c = ca(); + let (_, csr) = agent_csr("a1"); + for (team, agent) in [ + ("", "a1"), + ("acme", ""), + ("Acme", "a1"), + ("acme", "a 1"), + ("acme", "-a1"), + ("acme", "a1-"), + ("acme", "a:1"), + ("acme", &"x".repeat(41)), + ("ac/me", "a1"), + ] { + assert!( + matches!(pki::issue_agent(&c.agents, &csr, team, agent, NOW), Err(PkiError::BadName(_))), + "{team:?} {agent:?}" + ); + } + assert!(pki::valid_id("build-box-1")); + assert!(pki::valid_id(&"x".repeat(40))); + assert_eq!( + 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"] { + assert_eq!(pki::parse_agent_uri(bad), None, "{bad}"); + } +} + +#[test] +fn renewal_is_due_when_ten_days_are_left() { + let c = ca(); + let (_, csr) = agent_csr("a1"); + let a = pki::issue_agent(&c.agents, &csr, "acme", "a1", NOW).unwrap(); + assert!(!pki::agent_renewal_due(a.not_after, NOW + 19 * DAY)); + assert!(pki::agent_renewal_due(a.not_after, NOW + 21 * DAY)); +} diff --git a/tests/chains.rs b/tests/chains.rs new file mode 100644 index 0000000..f803d0c --- /dev/null +++ b/tests/chains.rs @@ -0,0 +1,227 @@ +// 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/. + +//! Chains, expiry and wrong issuers (tests first, docs/01): issued chains validate to the root, +//! a leaf cannot sign, pathLen 0 holds, expired and not-yet-valid certificates are refused, and a +//! certificate of another root is refused even when every name matches. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod common; + +use common::*; +use domi_pki::{ + self as pki, DEVICE_DAYS, INTERMEDIATE_DAYS, Intermediate, PkiError, ROOT_DAYS, SERVER_DAYS, + Usage, VerifyError, +}; + +#[test] +fn root_is_a_ten_year_ca_with_path_length_one() { + let c = ca(); + let info = pki::inspect(&c.root_pem).unwrap(); + assert!(info.is_ca); + assert_eq!(info.path_len, Some(1)); + 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"); +} + +#[test] +fn both_intermediates_are_one_year_path_length_zero_under_the_root() { + let c = ca(); + for int in [&c.ianitor, &c.agents] { + let info = pki::inspect(int.cert_pem()).unwrap(); + assert!(info.is_ca); + assert_eq!(info.path_len, Some(0)); + assert_eq!((info.not_after - NOW) / DAY, INTERMEDIATE_DAYS as i64); + assert!(pki::issued_by(int.cert_pem(), &c.root_pem).unwrap()); + 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), + None + ); + assert_eq!( + 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), + Some("not_ca") + ); +} + +#[test] +fn server_chain_validates_for_its_name_only() { + let c = ca(); + let leaf = pki::issue_server(&c.agents, "fabrica.home.test", NOW).unwrap(); + let chain = ders(&leaf.chain_pem); + pki::verify_chain(&chain, &c.root_der(), NOW + DAY, Usage::Server).unwrap(); + pki::verify_server(&chain, &c.root_der(), "fabrica.home.test", NOW + DAY).unwrap(); + assert!(matches!( + pki::verify_server(&chain, &c.root_der(), "other.home.test", NOW + DAY), + Err(VerifyError::WrongName) + )); + assert_eq!( + pki::verify_chain(&chain, &c.root_der(), NOW + DAY, Usage::Client), + Err(VerifyError::WrongUsage) + ); + 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()); +} + +#[test] +fn device_chain_validates_for_client_auth_only() { + let c = ca(); + let dev = pki::issue_device(&c.ianitor, "Mark's phone", NOW).unwrap(); + let chain = ders(&dev.chain_pem); + pki::verify_chain(&chain, &c.root_der(), NOW + DAY, Usage::Client).unwrap(); + assert_eq!( + pki::verify_chain(&chain, &c.root_der(), NOW + DAY, Usage::Server), + Err(VerifyError::WrongUsage) + ); + let info = pki::inspect(&dev.cert_pem).unwrap(); + assert_eq!(info.subject_cn, "Mark's phone"); + assert_eq!((info.not_after - NOW) / DAY, DEVICE_DAYS as i64); +} + +#[test] +fn a_leaf_cannot_sign() { + let c = ca(); + let leaf = pki::issue_server(&c.ianitor, "wiki.home.test", NOW).unwrap(); + let leaf_key = pki::KeyPair::from_pem(&leaf.key_pem).unwrap(); + assert!(matches!( + Intermediate::new(&leaf.cert_pem, leaf_key), + Err(PkiError::NotCa) + )); + let leaf_key = pki::KeyPair::from_pem(&leaf.key_pem).unwrap(); + 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:?}"); +} + +#[test] +fn an_intermediate_cannot_make_another_ca() { + let c = ca(); + let sub_key = pki::generate_key().unwrap(); + let sub = pki::testing::sub_ca(&c.ianitor, &sub_key, NOW).unwrap(); + let leaf = pki::testing::sign_as(&sub, sub_key, "deep.home.test", NOW).unwrap(); + let chain = ders(&format!("{leaf}{sub}{}", c.ianitor.cert_pem())); + assert!(pki::verify_chain(&chain, &c.root_der(), NOW + DAY, Usage::Server).is_err()); +} + +// ------------------------------------------------------------------ expiry + +#[test] +fn expired_and_not_yet_valid_leaves_are_refused() { + let c = ca(); + let leaf = pki::issue_server(&c.agents, "fabrica.home.test", NOW).unwrap(); + let chain = ders(&leaf.chain_pem); + let after = NOW + (SERVER_DAYS as i64 + 1) * DAY; + assert_eq!( + pki::verify_chain(&chain, &c.root_der(), after, Usage::Server), + Err(VerifyError::Expired) + ); + assert_eq!( + pki::verify_chain(&chain, &c.root_der(), NOW - DAY, Usage::Server), + Err(VerifyError::NotYetValid) + ); + // The backdating covers a client clock five minutes late, not more. + pki::verify_chain(&chain, &c.root_der(), NOW - 200, Usage::Server).unwrap(); +} + +#[test] +fn an_expired_intermediate_fails_the_chain_and_issues_nothing() { + let c = ca(); + 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"); + let gone = NOW + (INTERMEDIATE_DAYS as i64 + 1) * DAY; + assert!(matches!( + pki::issue_server(&c.agents, "fabrica.home.test", gone), + Err(PkiError::IssuerExpired) + )); + // 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), + Err(VerifyError::Expired) + ); + // The root refuses to sign once it has expired. + let key = pki::generate_key().unwrap(); + 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), + Err(PkiError::IssuerExpired) + )); +} + +// ------------------------------------------------------------------ wrong issuer + +#[test] +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:?}"); + 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), + Some("not_root") + ); +} + +#[test] +fn a_chain_without_its_intermediate_is_refused() { + let c = ca(); + let leaf = pki::issue_server(&c.agents, "fabrica.home.test", NOW).unwrap(); + let only_leaf = vec![ders(&leaf.cert_pem).remove(0)]; + assert_eq!( + pki::verify_chain(&only_leaf, &c.root_der(), NOW + DAY, Usage::Server), + Err(VerifyError::UnknownIssuer) + ); + // Nor does the wrong intermediate help. + let wrong = vec![only_leaf[0].clone(), ders(c.ianitor.cert_pem()).remove(0)]; + assert!(pki::verify_chain(&wrong, &c.root_der(), NOW + DAY, Usage::Server).is_err()); +} + +#[test] +fn a_self_signed_leaf_is_refused() { + let c = ca(); + let placeholder = pki::placeholder_leaf("nobody", NOW).unwrap(); + assert_eq!( + pki::verify_chain(&ders(&placeholder), &c.root_der(), NOW + DAY, Usage::Client), + Err(VerifyError::UnknownIssuer) + ); + let info = pki::inspect(&placeholder).unwrap(); + assert_eq!(info.subject_cn, "nobody"); + assert!(!info.is_ca); +} + +#[test] +fn an_empty_chain_or_garbage_root_is_an_error() { + let c = ca(); + assert_eq!( + pki::verify_chain(&[], &c.root_der(), NOW, Usage::Server), + Err(VerifyError::BadCertificate("the chain is empty".into())) + ); + let leaf = pki::issue_server(&c.agents, "fabrica.home.test", NOW).unwrap(); + assert!(matches!( + pki::verify_chain(&ders(&leaf.chain_pem), b"not a root", NOW, Usage::Server), + Err(VerifyError::BadCertificate(_)) + )); + assert!(pki::verify_chain(&[b"junk".to_vec()], &c.root_der(), NOW, Usage::Server).is_err()); + // Time before 1970 is refused, not wrapped. + assert!(pki::verify_chain(&ders(&leaf.chain_pem), &c.root_der(), -5, Usage::Server).is_err()); +} diff --git a/tests/common/mod.rs b/tests/common/mod.rs new file mode 100644 index 0000000..c87f777 --- /dev/null +++ b/tests/common/mod.rs @@ -0,0 +1,82 @@ +// 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/. + +#![allow(dead_code, clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::cell::Cell; + +use domi_pki::{self as pki, Intermediate, KeyPair, Signer, SignerError}; + +pub const NOW: i64 = 1_800_000_000; +pub const DAY: i64 = 86_400; + +/// A root key that only signs through the `Signer` trait (as Custos does), and counts how often. +pub struct CustosLike { + key: KeyPair, + pub signed: Cell, +} + +impl CustosLike { + pub fn new() -> CustosLike { + CustosLike { + key: pki::generate_key().unwrap(), + signed: Cell::new(0), + } + } +} + +impl Signer for CustosLike { + fn spki_der(&self) -> Vec { + self.key.spki_der() + } + fn sign(&self, msg: &[u8]) -> Result, SignerError> { + self.signed.set(self.signed.get() + 1); + self.key.sign(msg) + } +} + +/// A full CA: the root in a "Custos", one Ianitor and one agents intermediate. +pub struct Ca { + pub root: CustosLike, + pub root_pem: String, + pub ianitor: Intermediate, + pub agents: Intermediate, +} + +impl Ca { + pub fn root_der(&self) -> Vec { + pki::chain_der(&self.root_pem).unwrap().remove(0) + } +} + +pub fn intermediate(root: &dyn Signer, root_pem: &str, cn: &str) -> Intermediate { + let key = pki::generate_key().unwrap(); + let csr = pki::intermediate_csr(&key, cn).unwrap(); + let pem = pki::sign_intermediate(root_pem, root, &csr, cn, NOW).unwrap(); + Intermediate::new(&pem, key).unwrap() +} + +pub fn ca() -> Ca { + let root = CustosLike::new(); + let root_pem = pki::create_root(&root, NOW).unwrap(); + let ianitor = intermediate(&root, &root_pem, pki::IANITOR_INTERMEDIATE_CN); + let agents = intermediate(&root, &root_pem, pki::AGENTS_INTERMEDIATE_CN); + Ca { + root, + root_pem, + ianitor, + agents, + } +} + +/// An agent's own key and CSR, as Legatus makes them. +pub fn agent_csr(agent: &str) -> (KeyPair, String) { + let key = pki::generate_key().unwrap(); + let csr = pki::agent_csr(&key, agent).unwrap(); + (key, csr) +} + +pub fn ders(pem: &str) -> Vec> { + pki::chain_der(pem).unwrap() +} diff --git a/tests/signer.rs b/tests/signer.rs new file mode 100644 index 0000000..ab9053c --- /dev/null +++ b/tests/signer.rs @@ -0,0 +1,196 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! The root signs only through `Signer` (tests first, docs/01): once per operation, a signer whose +//! key is not the root's is refused, a lying signer is caught, and CSRs never steer the profile. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod common; + +use common::*; +use domi_pki::{self as pki, INTERMEDIATE_DAYS, PkiError, Signer, SignerError}; + +#[test] +fn the_root_signs_once_per_operation_through_the_signer() { + let root = CustosLike::new(); + let root_pem = pki::create_root(&root, NOW).unwrap(); + assert_eq!(root.signed.get(), 1, "the self-signature"); + let _ = intermediate(&root, &root_pem, pki::AGENTS_INTERMEDIATE_CN); + assert_eq!(root.signed.get(), 2, "one signature per intermediate"); + assert_eq!(pki::public_key_der(&root_pem).unwrap(), root.spki_der()); +} + +#[test] +fn issuing_leaves_never_asks_the_root() { + let c = ca(); + let before = c.root.signed.get(); + let (_, csr) = agent_csr("a1"); + pki::issue_agent(&c.agents, &csr, "acme", "a1", NOW).unwrap(); + pki::issue_server(&c.agents, "fabrica.home.test", NOW).unwrap(); + pki::issue_device(&c.ianitor, "phone", NOW).unwrap(); + assert_eq!(c.root.signed.get(), before); +} + +#[test] +fn a_signer_that_is_not_the_root_is_refused_before_signing() { + let c = ca(); + let impostor = CustosLike::new(); + 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), + Err(PkiError::KeyMismatch) + )); + assert_eq!(impostor.signed.get(), 0); +} + +struct Liar(CustosLike); +impl Signer for Liar { + fn spki_der(&self) -> Vec { + self.0.spki_der() + } + fn sign(&self, msg: &[u8]) -> Result, SignerError> { + let mut s = self.0.sign(msg)?; + if let Some(b) = s.last_mut() { + *b ^= 1; + } + Ok(s) + } +} + +struct Refuses(CustosLike); +impl Signer for Refuses { + fn spki_der(&self) -> Vec { + self.0.spki_der() + } + fn sign(&self, _: &[u8]) -> Result, SignerError> { + Err(SignerError::new("the approval was declined")) + } +} + +#[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(_)))); + let c = ca(); + let liar = Liar(c.root); + 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, &liar, &csr, pki::AGENTS_INTERMEDIATE_CN, NOW), + Err(PkiError::Signer(_)) + )); +} + +#[test] +fn a_declined_signature_is_reported_as_such() { + let r = Refuses(CustosLike::new()); + match pki::create_root(&r, NOW) { + Err(PkiError::Signer(m)) => assert!(m.contains("declined"), "{m}"), + other => panic!("{other:?}"), + } +} + +#[test] +fn a_signer_with_an_unsupported_key_is_refused() { + struct Garbage; + impl Signer for Garbage { + fn spki_der(&self) -> Vec { + b"not a key".to_vec() + } + fn sign(&self, _: &[u8]) -> Result, SignerError> { + Ok(vec![0; 64]) + } + } + assert!(matches!(pki::create_root(&Garbage, NOW), Err(PkiError::UnsupportedKey))); +} + +#[test] +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 info = pki::inspect(&pem).unwrap(); + assert_eq!(info.path_len, Some(0)); + assert!(info.dns_names.is_empty()); + assert_eq!((info.not_after - NOW) / DAY, INTERMEDIATE_DAYS as i64); + // The wrong subject is refused: not this intermediate's name, nor the other's. + for wrong in ["Some Other CA", pki::IANITOR_INTERMEDIATE_CN] { + let csr = pki::intermediate_csr(&key, wrong).unwrap(); + assert!(matches!( + pki::sign_intermediate(&c.root_pem, &c.root, &csr, pki::AGENTS_INTERMEDIATE_CN, NOW), + Err(PkiError::CsrSubject) + )); + } + 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()); +} + +#[test] +fn an_intermediate_must_match_its_key_and_be_a_ca() { + let c = ca(); + let other_key = pki::generate_key().unwrap(); + assert!(matches!( + pki::Intermediate::new(c.agents.cert_pem(), other_key), + Err(PkiError::KeyMismatch) + )); + assert!(matches!( + pki::Intermediate::new(&c.root_pem, pki::generate_key().unwrap()), + Err(PkiError::KeyMismatch) + )); +} + +#[test] +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(); + assert!(pki::issued_by(&pem, &root_pem).unwrap()); + // The openssl profile for the manual step matches. + assert!(pki::INTERMEDIATE_OPENSSL_EXT.contains("pathlen:0")); + assert!(pki::openssl_sign_command("int-2027").contains("-days 365")); +} + +#[test] +fn keys_and_match_codes() { + let k = pki::generate_key().unwrap(); + assert_eq!(format!("{k:?}"), "KeyPair(…)", "never printed"); + let back = pki::KeyPair::from_der(&k.serialize_der()).unwrap(); + assert_eq!(back.public_key_der(), k.public_key_der()); + assert!(pki::KeyPair::from_pem("nope").is_err()); + let a = pki::match_code(b"some csr"); + assert_eq!(a, pki::match_code(b"some csr")); + 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()))); +} + +#[test] +fn hostile_pem_and_der_never_panic() { + let c = ca(); + for bad in [ + "", + "-----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"), + "\u{0}\u{1}", + ] { + assert!(pki::inspect(bad).is_err()); + assert!(pki::issued_by(bad, bad).is_err()); + assert!(pki::public_key_der(bad).is_err()); + assert!(pki::csr_public_key_der(bad).is_err()); + assert!(pki::Intermediate::new(bad, pki::generate_key().unwrap()).is_err()); + assert!(pki::issue_agent(&c.agents, bad, "acme", "a1", NOW).is_err()); + } + for junk in [&b""[..], b"\x30\x03\x02\x01", &[0xff; 300]] { + assert!(pki::inspect_der(junk).is_err()); + assert!(pki::verify_agent(&[junk.to_vec()], &c.root_der(), NOW).is_err()); + } +}