// 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 (ROADMAP §1.1, §1.2, §1.8, §3): a small CA on rcgen. Pure: the caller passes //! the time in and does every file read and write. Keys are ECDSA P-256 everywhere. //! //! ```text //! Domi PKI Root 10 years, pathLen 1 created offline, never on the server //! └ Ianitor Domi Intermediate 1 year, pathLen 0 key encrypted at rest on the server //! ├ 90 days, serverAuth tls = "domi" hosts //! └ 1 year, clientAuth mTLS for hosts with device_certs //! ``` //! //! Lifetimes (decided in phase 3): //! - Server certificates: 90 days, renewed by control when 30 days are left. Control renews //! them by itself, so a short life costs nothing and bounds the damage of a key read from the //! certificate directory; 30 days of slack survive a long control outage. //! - Device certificates: 1 year. Installing one is a deliberate, manual step on a phone or a //! laptop (ROADMAP §4 accepts a 4th click for it), so it should not come round more than //! once a year; revocation (the allow list edge and Caddy check) covers a lost device. //! - No certificate is ever issued past its issuer's `notAfter`. //! //! The intermediate is never made from what a CSR asks for: only its public key and its //! subject CN are taken; every extension comes from the profile here. use std::fmt; use base64::Engine as _; use base64::engine::general_purpose::STANDARD; use rcgen::{ BasicConstraints, CertificateParams, CertificateSigningRequestParams, DistinguishedName, DnType, ExtendedKeyUsagePurpose, IsCa, Issuer, KeyUsagePurpose, PKCS_ECDSA_P256_SHA256, SerialNumber, }; use ring::rand::{SecureRandom, SystemRandom}; use time::OffsetDateTime; /// Root: about 10 years. pub const ROOT_DAYS: u32 = 3653; /// Intermediate: about 1 year. pub const INTERMEDIATE_DAYS: u32 = 365; /// Server (tls = "domi") certificates. pub const SERVER_DAYS: u32 = 90; /// Renew a server certificate when fewer than this many days are left. pub const SERVER_RENEW_DAYS: u32 = 30; /// Device (mTLS client) certificates. pub const DEVICE_DAYS: u32 = 365; /// Subject CN of the root. pub const ROOT_CN: &str = "Domi PKI Root"; /// Subject CN of the intermediate. Signers refuse a CSR whose CN does not start with this. pub const INTERMEDIATE_CN: &str = "Ianitor Domi Intermediate"; /// Organisation on every certificate. pub const ORG: &str = "Fabrica Domi"; /// PBKDF2-HMAC-SHA256 iterations for encrypted keys (OWASP 2023 figure). pub const KEY_KDF_ITERATIONS: u32 = 600_000; /// Backdating of `notBefore`, for clocks that run a little late. const BACKDATE_SECS: i64 = 300; const DAY: i64 = 86_400; // Split so that this file does not match the pre-commit hook itself. const ARMOR_BEGIN: &str = concat!("-----BEGIN IANITOR ENCRYPTED ", "PRIVATE KEY-----"); const ARMOR_END: &str = concat!("-----END IANITOR ENCRYPTED ", "PRIVATE KEY-----"); const KEY_MAGIC: &[u8; 4] = b"IEK1"; const KEY_AAD: &[u8] = b"ianitor encrypted key v1"; #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum PkiError { #[error("the certificate cannot be read: {0}")] BadCertificate(String), #[error("the certificate signing request cannot be read or its signature is wrong")] BadCsr, #[error("the request's subject must start with \"{INTERMEDIATE_CN}\"")] CsrSubject, #[error("the private key cannot be read")] BadKey, #[error("the certificate is not a CA certificate")] NotCa, #[error("the private key does not belong to the certificate")] KeyMismatch, #[error("the issuing certificate has expired or is not valid yet")] IssuerExpired, #[error("the name cannot be used in a certificate: {0}")] BadName(String), #[error("the encrypted key cannot be read")] BadSealedKey, #[error("the password does not open the encrypted key")] WrongPassword, #[error("no randomness available")] Random, #[error("the certificate could not be made: {0}")] Build(String), } fn build(e: rcgen::Error) -> PkiError { PkiError::Build(e.to_string()) } /// An ECDSA P-256 key pair. Never printed. pub struct KeyPair(rcgen::KeyPair); impl fmt::Debug for KeyPair { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("KeyPair(…)") } } impl KeyPair { /// PKCS#8 PEM. Callers write it only to files with mode 0600 (or encrypt it). pub fn serialize_pem(&self) -> String { self.0.serialize_pem() } pub fn serialize_der(&self) -> Vec { self.0.serialize_der() } pub fn from_pem(pem: &str) -> Result { rcgen::KeyPair::from_pem(pem) .map(KeyPair) .map_err(|_| PkiError::BadKey) } pub fn from_der(der: &[u8]) -> Result { rcgen::KeyPair::try_from(der) .map(KeyPair) .map_err(|_| PkiError::BadKey) } /// SubjectPublicKeyInfo DER. pub fn public_key_der(&self) -> Vec { use rcgen::PublicKeyData as _; self.0.subject_public_key_info() } } pub fn generate_key() -> Result { rcgen::KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256) .map(KeyPair) .map_err(build) } 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())) } fn dn(cn: &str) -> DistinguishedName { let mut d = DistinguishedName::new(); d.push(DnType::CommonName, cn); d.push(DnType::OrganizationName, ORG); d } /// A certificate name a person typed: 1 to 64 printable characters, no control characters. fn check_display_name(name: &str) -> Result<(), PkiError> { let n = name.chars().count(); if n == 0 || n > 64 || name.chars().any(char::is_control) || name.trim() != name { return Err(PkiError::BadName( "use 1 to 64 visible characters, no leading or trailing spaces".into(), )); } Ok(()) } // ------------------------------------------------------------------ root (offline) /// Create the root: a self-signed CA, `pathLenConstraint 1`, about 10 years. For the offline /// machine only (`ianitor-control ca init`); control never calls this on the server. pub fn create_root(now: i64) -> Result<(String, KeyPair), PkiError> { let key = generate_key()?; let mut p = CertificateParams::default(); p.distinguished_name = dn(ROOT_CN); p.is_ca = IsCa::Ca(BasicConstraints::Constrained(1)); p.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign]; p.not_before = time(now - BACKDATE_SECS)?; p.not_after = time(now + i64::from(ROOT_DAYS) * DAY)?; p.serial_number = Some(serial()?); let cert = p.self_signed(&key.0).map_err(build)?; Ok((cert.pem(), key)) } /// Common name of [`no_device_placeholder`]. pub const NO_DEVICE_CN: &str = "Ianitor placeholder: no device is allowed"; /// The allow list's only entry while no device is enrolled. Caddy refuses to load an empty /// leaf list (and with it the whole config), so the list is never empty: this self-signed /// certificate's key is dropped right here, so no client can ever present it, and it is not /// issued by the Domi intermediate, so edge refuses it too. pub fn no_device_placeholder(now: i64) -> Result { let key = generate_key()?; let mut p = CertificateParams::default(); p.distinguished_name = dn(NO_DEVICE_CN); p.is_ca = IsCa::ExplicitNoCa; p.key_usages = vec![KeyUsagePurpose::DigitalSignature]; p.not_before = time(now - BACKDATE_SECS)?; p.not_after = time(now + 100 * 365 * DAY)?; p.serial_number = Some(serial()?); let cert = p.self_signed(&key.0).map_err(build)?; drop(key); Ok(cert.pem()) } /// A CSR for a new intermediate key (made by control on the server). pub fn intermediate_csr(key: &KeyPair, cn: &str) -> Result { let mut p = CertificateParams::default(); p.distinguished_name = dn(cn); p.serialize_request(&key.0) .map_err(build)? .pem() .map_err(build) } /// The extensions for signing an intermediate with openssl on the offline machine (the /// accepted manual step until Custos can sign, docs/pki.md): the same profile as /// [`sign_intermediate`]. Use with `openssl x509 -req … -days 365 -extfile `. pub const INTERMEDIATE_OPENSSL_EXT: &str = "basicConstraints = critical, CA:TRUE, pathlen:0\n\ keyUsage = critical, keyCertSign, cRLSign, digitalSignature\n\ subjectKeyIdentifier = hash\n\ authorityKeyIdentifier = keyid:always\n"; /// The openssl command that signs a renewal on the offline machine (files named after the /// request). OpenSSL 3 picks a random serial. pub fn openssl_sign_command(base: &str) -> String { format!( "openssl x509 -req -in {base}.csr -CA domi-root.crt -CAkey domi-root.key -days {INTERMEDIATE_DAYS} -sha256 -extfile {base}.ext -out {base}.crt" ) } /// Sign an intermediate CSR with the root (offline, or in Custos once it can). Only the CSR's /// public key and CN are used; the CN must start with [`INTERMEDIATE_CN`]. pub fn sign_intermediate( root_cert_pem: &str, root_key: &KeyPair, csr_pem: &str, now: i64, ) -> Result { let root = inspect(root_cert_pem)?; if !root.is_ca { return Err(PkiError::NotCa); } if public_key_der(root_cert_pem)? != root_key.public_key_der() { return Err(PkiError::KeyMismatch); } if now < root.not_before || now >= root.not_after { return Err(PkiError::IssuerExpired); } let csr = CertificateSigningRequestParams::from_pem(csr_pem).map_err(|_| PkiError::BadCsr)?; let cn = csr .params .distinguished_name .get(&DnType::CommonName) .and_then(dn_text) .ok_or(PkiError::CsrSubject)?; if !cn.starts_with(INTERMEDIATE_CN) || cn.chars().count() > 64 || cn.chars().any(char::is_control) { return Err(PkiError::CsrSubject); } let mut p = CertificateParams::default(); p.distinguished_name = dn(&cn); p.is_ca = IsCa::Ca(BasicConstraints::Constrained(0)); p.key_usages = vec![ KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign, KeyUsagePurpose::DigitalSignature, ]; p.not_before = time(now - BACKDATE_SECS)?; p.not_after = time((now + i64::from(INTERMEDIATE_DAYS) * DAY).min(root.not_after))?; p.serial_number = Some(serial()?); p.use_authority_key_identifier_extension = true; let fresh = CertificateSigningRequestParams { params: p, public_key: csr.public_key, }; let issuer = Issuer::from_ca_cert_pem(root_cert_pem, &root_key.0).map_err(build)?; Ok(fresh.signed_by(&issuer).map_err(build)?.pem()) } fn dn_text(v: &rcgen::DnValue) -> Option { match v { rcgen::DnValue::Utf8String(s) => Some(s.clone()), rcgen::DnValue::PrintableString(s) => Some(s.as_str().to_owned()), _ => None, } } // ------------------------------------------------------------------ the intermediate /// The intermediate as control holds it: its certificate and its key, checked to belong /// together and to be a CA. pub struct Intermediate { cert_pem: String, key: KeyPair, info: CertInfo, } impl fmt::Debug for Intermediate { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Intermediate") .field("subject", &self.info.subject_cn) .field("not_after", &self.info.not_after) .finish() } } impl Intermediate { pub fn new(cert_pem: &str, key: KeyPair) -> Result { let first = first_pem(cert_pem)?; let info = inspect(&first)?; if !info.is_ca { return Err(PkiError::NotCa); } if public_key_der(&first)? != key.public_key_der() { return Err(PkiError::KeyMismatch); } Ok(Intermediate { cert_pem: first, key, info, }) } pub fn cert_pem(&self) -> &str { &self.cert_pem } pub fn not_after(&self) -> i64 { self.info.not_after } pub fn info(&self) -> &CertInfo { &self.info } pub fn key(&self) -> &KeyPair { &self.key } fn issue(&self, mut p: CertificateParams, days: u32, now: i64) -> Result { if now < self.info.not_before || now >= self.info.not_after { return Err(PkiError::IssuerExpired); } let key = generate_key()?; p.is_ca = IsCa::ExplicitNoCa; p.not_before = time(now - BACKDATE_SECS)?; p.not_after = time((now + i64::from(days) * DAY).min(self.info.not_after))?; p.serial_number = Some(serial()?); p.use_authority_key_identifier_extension = true; let issuer = Issuer::from_ca_cert_pem(&self.cert_pem, &self.key.0).map_err(build)?; let cert = p.signed_by(&key.0, &issuer).map_err(build)?; let cert_pem = cert.pem(); let info = inspect(&cert_pem)?; Ok(Issued { chain_pem: format!("{cert_pem}{}", self.cert_pem), key_pem: key.serialize_pem(), key, serial_hex: info.serial_hex.clone(), sha256_hex: info.sha256_hex.clone(), not_before: info.not_before, not_after: info.not_after, cert_pem, }) } } /// A freshly issued leaf. pub struct Issued { /// The leaf alone. pub cert_pem: String, /// Leaf, then the intermediate (what a server or a device presents). pub chain_pem: String, /// PKCS#8 PEM of the leaf's key. pub key_pem: String, pub key: KeyPair, pub serial_hex: String, /// SHA-256 of the leaf's DER, lowercase hex. pub sha256_hex: String, pub not_before: i64, pub not_after: i64, } impl fmt::Debug for Issued { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Issued") .field("serial", &self.serial_hex) .field("not_after", &self.not_after) .finish() } } /// A server certificate for one hostname (`tls = "domi"`). The hostname must already be /// validated by the schema; it is checked again here. pub fn issue_server(int: &Intermediate, hostname: &str, now: i64) -> Result { let mut p = CertificateParams::new(vec![hostname.to_owned()]) .map_err(|e| PkiError::BadName(e.to_string()))?; p.distinguished_name = dn(hostname); p.key_usages = vec![KeyUsagePurpose::DigitalSignature]; p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth]; int.issue(p, SERVER_DAYS, now) } /// A device certificate (mTLS client) for a named device. pub fn issue_device(int: &Intermediate, name: &str, now: i64) -> Result { check_display_name(name)?; let mut p = CertificateParams::default(); let mut d = DistinguishedName::new(); d.push(DnType::CommonName, name); d.push(DnType::OrganizationName, ORG); d.push(DnType::OrganizationalUnitName, "Domi devices"); p.distinguished_name = d; p.key_usages = vec![KeyUsagePurpose::DigitalSignature]; p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth]; int.issue(p, DEVICE_DAYS, now) } // ------------------------------------------------------------------ reading certificates /// What Ianitor needs to know about a certificate. #[derive(Debug, Clone, PartialEq, Eq)] pub struct CertInfo { pub subject_cn: String, pub issuer_cn: String, pub not_before: i64, pub not_after: i64, pub is_ca: bool, pub path_len: Option, pub dns_names: Vec, pub serial_hex: String, pub sha256_hex: String, /// keyUsage: `None` when the extension is absent. pub key_usage: Option, /// extendedKeyUsage: `None` when the extension is absent (any use). pub eku: Option, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct KeyUsageInfo { pub key_cert_sign: bool, pub crl_sign: bool, pub digital_signature: bool, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct EkuInfo { pub any: bool, pub server_auth: bool, pub client_auth: bool, } fn ders(pem: &str) -> Result>, PkiError> { let mut out = Vec::new(); for p in x509_parser::pem::Pem::iter_from_buffer(pem.as_bytes()) { let p = p.map_err(|e| PkiError::BadCertificate(e.to_string()))?; if p.label != "CERTIFICATE" { return Err(PkiError::BadCertificate(format!( "unexpected PEM block {}", p.label ))); } out.push(p.contents); } if out.is_empty() { return Err(PkiError::BadCertificate("no certificate in it".into())); } Ok(out) } /// The DER of every certificate in a PEM chain, in order. pub fn chain_der(pem: &str) -> Result>, PkiError> { ders(pem) } /// The first certificate of a PEM chain, as PEM. pub fn first_pem(pem: &str) -> Result { let first = ders(pem)? .into_iter() .next() .ok_or_else(|| PkiError::BadCertificate("no certificate in it".into()))?; Ok(der_to_pem(&first)) } pub fn der_to_pem(der: &[u8]) -> String { let b = STANDARD.encode(der); let mut s = String::from("-----BEGIN CERTIFICATE-----\n"); for chunk in b.as_bytes().chunks(64) { s.push_str(&String::from_utf8_lossy(chunk)); s.push('\n'); } s.push_str("-----END CERTIFICATE-----\n"); s } fn parse(der: &[u8]) -> Result, PkiError> { let (rest, c) = x509_parser::parse_x509_certificate(der) .map_err(|e| PkiError::BadCertificate(e.to_string()))?; if !rest.is_empty() { return Err(PkiError::BadCertificate("trailing bytes".into())); } Ok(c) } fn cn_of(name: &x509_parser::x509::X509Name<'_>) -> String { name.iter_common_name() .next() .and_then(|c| c.as_str().ok()) .unwrap_or_default() .to_owned() } fn hex(b: &[u8]) -> String { b.iter().map(|x| format!("{x:02x}")).collect() } /// SHA-256 of a DER blob, lowercase hex. pub fn sha256_hex(der: &[u8]) -> String { hex(ring::digest::digest(&ring::digest::SHA256, der).as_ref()) } /// Read the first certificate of a PEM chain. pub fn inspect(pem: &str) -> Result { let der = ders(pem)? .into_iter() .next() .ok_or_else(|| PkiError::BadCertificate("no certificate in it".into()))?; inspect_der(&der) } pub fn inspect_der(der: &[u8]) -> Result { let c = parse(der)?; let bc = c .basic_constraints() .map_err(|e| PkiError::BadCertificate(e.to_string()))?; let (is_ca, path_len) = match bc { Some(b) => (b.value.ca, b.value.path_len_constraint), None => (false, None), }; let dns_names = match c .subject_alternative_name() .map_err(|e| PkiError::BadCertificate(e.to_string()))? { Some(san) => san .value .general_names .iter() .filter_map(|g| match g { x509_parser::extensions::GeneralName::DNSName(n) => Some((*n).to_owned()), _ => None, }) .collect(), None => Vec::new(), }; Ok(CertInfo { subject_cn: cn_of(c.subject()), issuer_cn: cn_of(c.issuer()), not_before: c.validity().not_before.timestamp(), not_after: c.validity().not_after.timestamp(), is_ca, path_len, dns_names, serial_hex: hex(c.raw_serial()), sha256_hex: sha256_hex(der), key_usage: c .key_usage() .map_err(|e| PkiError::BadCertificate(e.to_string()))? .map(|k| KeyUsageInfo { key_cert_sign: k.value.key_cert_sign(), crl_sign: k.value.crl_sign(), digital_signature: k.value.digital_signature(), }), eku: c .extended_key_usage() .map_err(|e| PkiError::BadCertificate(e.to_string()))? .map(|e| EkuInfo { any: e.value.any, server_auth: e.value.server_auth, client_auth: e.value.client_auth, }), }) } /// Why a signed certificate cannot be the Domi intermediate, or `None` when it can. It must /// be signed by the root, a CA with path length 0 that may sign certificates (keyCertSign), /// allowed to issue both server and device certificates (no extendedKeyUsage, or one that /// allows both), valid now, and no longer than the root. pub fn intermediate_problem(cert_pem: &str, root_pem: &str, now: i64) -> Option<&'static str> { let Ok(info) = inspect(cert_pem) else { return Some("not_certificate"); }; let Ok(root) = inspect(root_pem) else { return Some("not_root"); }; if !issued_by(cert_pem, root_pem).unwrap_or(false) { return Some("not_root"); } if !info.is_ca || info.path_len != Some(0) || !info.subject_cn.starts_with(INTERMEDIATE_CN) { return Some("not_ca"); } if !info .key_usage .is_some_and(|k| k.key_cert_sign && k.crl_sign) { return Some("not_ca"); } if info .eku .is_some_and(|e| !e.any && !(e.server_auth && e.client_auth)) { return Some("eku"); } if info.not_before > now + 300 || info.not_after <= now || info.not_after > root.not_after || info.not_before < root.not_before - 300 { return Some("dates"); } None } /// SubjectPublicKeyInfo DER of the first certificate. pub fn public_key_der(pem: &str) -> Result, PkiError> { let der = ders(pem)? .into_iter() .next() .ok_or_else(|| PkiError::BadCertificate("no certificate in it".into()))?; let c = parse(&der)?; Ok(c.public_key().raw.to_vec()) } /// Is `child` (first certificate) signed by the key of `issuer` (first certificate), and /// does its issuer name match? A CA flag on the issuer is required. pub fn issued_by(child_pem: &str, issuer_pem: &str) -> Result { let cd = ders(child_pem)? .into_iter() .next() .ok_or(PkiError::BadCertificate(String::new()))?; let id = ders(issuer_pem)? .into_iter() .next() .ok_or(PkiError::BadCertificate(String::new()))?; let child = parse(&cd)?; let issuer = parse(&id)?; let ca = matches!(issuer.basic_constraints(), Ok(Some(b)) if b.value.ca); Ok(ca && child.issuer() == issuer.subject() && child.verify_signature(Some(issuer.public_key())).is_ok()) } // ------------------------------------------------------------------ match codes /// The code both screens show for one request: SHA-256 of the request, first three bytes, /// each mod 100, as `47 19 83` (see docs/custos-ticket.md). pub fn match_code(request: &[u8]) -> String { let d = ring::digest::digest(&ring::digest::SHA256, request); let b = d.as_ref(); format!( "{:02} {:02} {:02}", b.first().copied().unwrap_or(0) % 100, b.get(1).copied().unwrap_or(0) % 100, b.get(2).copied().unwrap_or(0) % 100 ) } /// SubjectPublicKeyInfo DER of a CSR (to match a signed certificate to its request). pub fn csr_public_key_der(csr_pem: &str) -> Result, PkiError> { use x509_parser::prelude::FromDer; let der = csr_der(csr_pem)?; let (_, csr) = x509_parser::certification_request::X509CertificationRequest::from_der(&der) .map_err(|_| PkiError::BadCsr)?; Ok(csr.certification_request_info.subject_pki.raw.to_vec()) } /// DER of the first PEM block of a CSR (for the match code). pub fn csr_der(csr_pem: &str) -> Result, PkiError> { for p in x509_parser::pem::Pem::iter_from_buffer(csr_pem.as_bytes()) { let p = p.map_err(|_| PkiError::BadCsr)?; if p.label == "CERTIFICATE REQUEST" { return Ok(p.contents); } } Err(PkiError::BadCsr) } // ------------------------------------------------------------------ encrypted keys fn derive( password: &[u8], salt: &[u8], iterations: u32, ) -> Result { let n = std::num::NonZeroU32::new(iterations).ok_or(PkiError::BadSealedKey)?; let mut k = [0u8; 32]; ring::pbkdf2::derive(ring::pbkdf2::PBKDF2_HMAC_SHA256, n, salt, password, &mut k); let unbound = ring::aead::UnboundKey::new(&ring::aead::AES_256_GCM, &k) .map_err(|_| PkiError::BadSealedKey)?; Ok(ring::aead::LessSafeKey::new(unbound)) } /// Encrypt a key with a password: PBKDF2-HMAC-SHA256 ([`KEY_KDF_ITERATIONS`]) and /// AES-256-GCM, armoured as `IANITOR ENCRYPTED PRIVATE KEY` (so the pre-commit hook blocks it). pub fn encrypt_key(key: &KeyPair, password: &[u8]) -> Result { encrypt_key_with(key, password, KEY_KDF_ITERATIONS) } /// [`encrypt_key`] with another iteration count (tests). pub fn encrypt_key_with( key: &KeyPair, password: &[u8], iterations: u32, ) -> Result { if password.is_empty() { return Err(PkiError::WrongPassword); } let salt = random::<16>()?; let nonce = random::<12>()?; let k = derive(password, &salt, iterations)?; let mut data = key.serialize_der(); k.seal_in_place_append_tag( ring::aead::Nonce::assume_unique_for_key(nonce), ring::aead::Aad::from(KEY_AAD), &mut data, ) .map_err(|_| PkiError::BadSealedKey)?; let mut blob = Vec::with_capacity(36 + data.len()); blob.extend_from_slice(KEY_MAGIC); blob.extend_from_slice(&iterations.to_be_bytes()); blob.extend_from_slice(&salt); blob.extend_from_slice(&nonce); blob.extend_from_slice(&data); let b = STANDARD.encode(blob); let mut s = format!("{ARMOR_BEGIN}\n"); for chunk in b.as_bytes().chunks(64) { s.push_str(&String::from_utf8_lossy(chunk)); s.push('\n'); } s.push_str(ARMOR_END); s.push('\n'); Ok(s) } /// Open a key made by [`encrypt_key`]. pub fn decrypt_key(sealed: &str, password: &[u8]) -> Result { let body = sealed .trim() .strip_prefix(ARMOR_BEGIN) .and_then(|r| r.strip_suffix(ARMOR_END)) .ok_or(PkiError::BadSealedKey)?; let b64: String = body.chars().filter(|c| !c.is_ascii_whitespace()).collect(); let blob = STANDARD.decode(b64).map_err(|_| PkiError::BadSealedKey)?; if blob.len() < 4 + 4 + 16 + 12 + 16 || &blob[..4] != KEY_MAGIC { return Err(PkiError::BadSealedKey); } let iterations = u32::from_be_bytes([blob[4], blob[5], blob[6], blob[7]]); if !(1..=10_000_000).contains(&iterations) { return Err(PkiError::BadSealedKey); } let salt = &blob[8..24]; let mut nonce = [0u8; 12]; nonce.copy_from_slice(&blob[24..36]); let mut data = blob[36..].to_vec(); let k = derive(password, salt, iterations)?; let plain = k .open_in_place( ring::aead::Nonce::assume_unique_for_key(nonce), ring::aead::Aad::from(KEY_AAD), &mut data, ) .map_err(|_| PkiError::WrongPassword)?; KeyPair::from_der(plain) } // ------------------------------------------------------------------ for tests /// Helpers for tests that need certificates Ianitor itself would never make. #[doc(hidden)] pub mod testing { use super::*; /// 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 - BACKDATE_SECS)?; p.not_after = time(now + 30 * DAY)?; let issuer = Issuer::from_ca_cert_pem(&first_pem(issuer_pem)?, key.0).map_err(build)?; Ok(p.signed_by(&leaf_key.0, &issuer).map_err(build)?.pem()) } /// A CA below the intermediate (which pathLen 0 forbids). pub fn sub_ca(int: &Intermediate, key: &KeyPair, now: i64) -> Result { let mut p = CertificateParams::default(); p.distinguished_name = dn("Sub CA"); p.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); p.key_usages = vec![KeyUsagePurpose::KeyCertSign]; p.not_before = time(now - BACKDATE_SECS)?; p.not_after = time(now + 30 * DAY)?; let issuer = Issuer::from_ca_cert_pem(int.cert_pem(), &int.key.0).map_err(build)?; Ok(p.signed_by(&key.0, &issuer).map_err(build)?.pem()) } /// A CSR that asks for far too much. pub fn greedy_csr(key: &KeyPair, cn: &str) -> Result { let mut p = CertificateParams::new(vec!["www.example.com".to_owned()]).map_err(build)?; p.distinguished_name = dn(cn); p.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); p.not_after = time(4_000_000_000)?; p.serialize_request(&key.0) .map_err(build)? .pem() .map_err(build) } /// Flip one byte inside the CSR's signed part. pub fn tamper_csr(csr_pem: &str) -> String { let Ok(mut der) = csr_der(csr_pem) else { return csr_pem.to_owned(); }; if let Some(b) = der.get_mut(40) { *b ^= 0x01; } let b = STANDARD.encode(der); let mut s = String::from("-----BEGIN CERTIFICATE REQUEST-----\n"); for chunk in b.as_bytes().chunks(64) { s.push_str(&String::from_utf8_lossy(chunk)); s.push('\n'); } s.push_str("-----END CERTIFICATE REQUEST-----\n"); s } }