// 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) }