[pki] CA: the Domi CA from Ianitor core behind a Signer, agent certificates, webpki chain checks (34 tests)
This commit is contained in:
@@ -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<const N: usize>() -> Result<[u8; N], PkiError> {
|
||||
let mut b = [0u8; N];
|
||||
SystemRandom::new()
|
||||
.fill(&mut b)
|
||||
.map_err(|_| PkiError::Random)?;
|
||||
Ok(b)
|
||||
}
|
||||
|
||||
fn serial() -> Result<SerialNumber, PkiError> {
|
||||
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, PkiError> {
|
||||
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<CertificateParams, PkiError> {
|
||||
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<String, PkiError> {
|
||||
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<String, PkiError> {
|
||||
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<String, PkiError> {
|
||||
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 <this>`.
|
||||
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<String> {
|
||||
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<String, PkiError> {
|
||||
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<S: Signer = KeyPair> {
|
||||
cert_pem: String,
|
||||
key: S,
|
||||
info: CertInfo,
|
||||
}
|
||||
|
||||
impl<S: Signer> fmt::Debug for Intermediate<S> {
|
||||
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<S: Signer> Intermediate<S> {
|
||||
/// 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<Intermediate<S>, 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<IssuedCert, PkiError> {
|
||||
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<Issued, PkiError> {
|
||||
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<S: Signer>(
|
||||
int: &Intermediate<S>,
|
||||
hostname: &str,
|
||||
now: i64,
|
||||
) -> Result<Issued, PkiError> {
|
||||
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<S: Signer>(
|
||||
int: &Intermediate<S>,
|
||||
name: &str,
|
||||
now: i64,
|
||||
) -> Result<Issued, PkiError> {
|
||||
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<String, PkiError> {
|
||||
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<CertificateParams, PkiError> {
|
||||
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<rcgen::PublicKey, PkiError> {
|
||||
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<S: Signer> Intermediate<S> {
|
||||
pub(crate) fn issue_agent_unchecked(
|
||||
&self,
|
||||
csr_pem: &str,
|
||||
team: &str,
|
||||
agent: &str,
|
||||
now: i64,
|
||||
) -> Result<IssuedCert, PkiError> {
|
||||
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<S: Signer>(
|
||||
int: &Intermediate<S>,
|
||||
csr_pem: &str,
|
||||
team: &str,
|
||||
agent: &str,
|
||||
now: i64,
|
||||
) -> Result<IssuedCert, PkiError> {
|
||||
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
|
||||
}
|
||||
+293
@@ -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<u32>,
|
||||
/// DNS subject alternative names.
|
||||
pub dns_names: Vec<String>,
|
||||
/// URI subject alternative names.
|
||||
pub uris: Vec<String>,
|
||||
/// 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<KeyUsageInfo>,
|
||||
/// extendedKeyUsage: `None` when the extension is absent (any use).
|
||||
pub eku: Option<EkuInfo>,
|
||||
}
|
||||
|
||||
/// 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<Vec<Vec<u8>>, 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<Vec<u8>, 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<Vec<Vec<u8>>, PkiError> {
|
||||
ders(pem)
|
||||
}
|
||||
|
||||
/// The first certificate of a PEM chain, as PEM.
|
||||
pub fn first_pem(pem: &str) -> Result<String, PkiError> {
|
||||
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<x509_parser::certificate::X509Certificate<'_>, 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<CertInfo, PkiError> {
|
||||
inspect_der(&first_der(pem)?)
|
||||
}
|
||||
|
||||
/// Read one DER certificate.
|
||||
pub fn inspect_der(der: &[u8]) -> Result<CertInfo, PkiError> {
|
||||
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<Vec<u8>, 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<bool, PkiError> {
|
||||
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<bool, PkiError> {
|
||||
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<Vec<u8>, 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<Vec<u8>, 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)
|
||||
}
|
||||
+118
-1
@@ -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
|
||||
//! │ ├ <hostname> 90 days, serverAuth
|
||||
//! │ └ <device name> 1 year, clientAuth
|
||||
//! └ Fabrica Domi Agents Intermediate 1 year, pathLen 0
|
||||
//! ├ <fabrica server name> 90 days, serverAuth
|
||||
//! └ <agent id> 30 days, clientAuth, URI urn:domi:agent:<team>:<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,
|
||||
}
|
||||
|
||||
+185
@@ -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<String>) -> 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<u8>;
|
||||
/// Sign `msg`. ECDSA P-256: SHA-256, the signature ASN.1 DER encoded. Ed25519: the raw 64 bytes.
|
||||
fn sign(&self, msg: &[u8]) -> Result<Vec<u8>, SignerError>;
|
||||
}
|
||||
|
||||
impl<S: Signer + ?Sized> Signer for &S {
|
||||
fn spki_der(&self) -> Vec<u8> {
|
||||
(**self).spki_der()
|
||||
}
|
||||
fn sign(&self, msg: &[u8]) -> Result<Vec<u8>, 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<u8> {
|
||||
self.0.serialize_der()
|
||||
}
|
||||
|
||||
/// Read a PKCS#8 PEM key.
|
||||
pub fn from_pem(pem: &str) -> Result<KeyPair, PkiError> {
|
||||
rcgen::KeyPair::from_pem(pem)
|
||||
.map(KeyPair)
|
||||
.map_err(|_| PkiError::BadKey)
|
||||
}
|
||||
|
||||
/// Read a PKCS#8 DER key.
|
||||
pub fn from_der(der: &[u8]) -> Result<KeyPair, PkiError> {
|
||||
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<u8> {
|
||||
self.0.subject_public_key_info()
|
||||
}
|
||||
}
|
||||
|
||||
impl Signer for KeyPair {
|
||||
fn spki_der(&self) -> Vec<u8> {
|
||||
self.public_key_der()
|
||||
}
|
||||
fn sign(&self, msg: &[u8]) -> Result<Vec<u8>, 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<KeyPair, PkiError> {
|
||||
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<u8>), 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<u8>,
|
||||
error: RefCell<Option<SignerError>>,
|
||||
}
|
||||
|
||||
impl<'a> Adapter<'a> {
|
||||
pub(crate) fn new(signer: &'a dyn Signer) -> Result<Adapter<'a>, 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<Vec<u8>, rcgen::Error> {
|
||||
self.signer.sign(msg).map_err(|e| {
|
||||
*self.error.borrow_mut() = Some(e);
|
||||
rcgen::Error::RemoteKeyError
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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, PkiError> {
|
||||
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<String, PkiError> {
|
||||
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<String, PkiError> {
|
||||
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<String, PkiError> {
|
||||
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<S: Signer>(
|
||||
int: &Intermediate<S>,
|
||||
csr_pem: &str,
|
||||
team: &str,
|
||||
agent: &str,
|
||||
now: i64,
|
||||
) -> Result<String, PkiError> {
|
||||
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<String, PkiError> {
|
||||
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)
|
||||
}
|
||||
+224
@@ -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<UnixTime, VerifyError> {
|
||||
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<u8>],
|
||||
root_der: &[u8],
|
||||
now: i64,
|
||||
usage: Usage,
|
||||
) -> Result<(), VerifyError> {
|
||||
with_leaf(chain, root_der, now, usage, |_| Ok(()))
|
||||
}
|
||||
|
||||
fn with_leaf<T>(
|
||||
chain: &[Vec<u8>],
|
||||
root_der: &[u8],
|
||||
now: i64,
|
||||
usage: Usage,
|
||||
then: impl FnOnce(&EndEntityCert<'_>) -> Result<T, VerifyError>,
|
||||
) -> Result<T, VerifyError> {
|
||||
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<CertificateDer<'_>> = 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<u8>],
|
||||
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:<team>:<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<u8>],
|
||||
root_der: &[u8],
|
||||
now: i64,
|
||||
) -> Result<AgentIdentity, VerifyError> {
|
||||
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,
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user