[core] Domi CA: offline root (10 y, pathLen 1), intermediate from a CSR (1 y, pathLen 0), server (90 d) and device (1 y) leaves, encrypted keys, match codes

This commit is contained in:
2026-11-07 22:41:29 +01:00
parent cde0c3ea3b
commit dc23bfe842
3 changed files with 763 additions and 62 deletions
+1 -1
View File
@@ -10,9 +10,9 @@
pub mod compile;
pub mod edge_config;
pub mod pki;
mod error;
mod model;
pub mod pki;
pub mod routes;
pub mod share;
pub mod time;
+701 -42
View File
@@ -2,74 +2,733 @@
// 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. Interface only; the implementation follows the tests (red commit).
//! 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
//! ├ <hostname> 90 days, serverAuth tls = "domi" hosts
//! └ <device name> 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";
pub const KEY_KDF_ITERATIONS: u32 = 0;
/// 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("not built yet")]
NotBuilt,
#[error("bad certificate")]
#[error("the certificate cannot be read: {0}")]
BadCertificate(String),
#[error("bad csr")]
#[error("the certificate signing request cannot be read or its signature is wrong")]
BadCsr,
#[error("csr subject")]
#[error("the request's subject must start with \"{INTERMEDIATE_CN}\"")]
CsrSubject,
#[error("bad key")]
#[error("the private key cannot be read")]
BadKey,
#[error("not a ca")]
#[error("the certificate is not a CA certificate")]
NotCa,
#[error("key mismatch")]
#[error("the private key does not belong to the certificate")]
KeyMismatch,
#[error("issuer expired")]
#[error("the issuing certificate has expired or is not valid yet")]
IssuerExpired,
#[error("wrong password")]
#[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(…)")
}
}
#[derive(Debug)]
pub struct KeyPair;
impl KeyPair {
pub fn serialize_pem(&self) -> String { String::new() }
pub fn from_pem(_: &str) -> Result<KeyPair, PkiError> { Err(PkiError::NotBuilt) }
pub fn public_key_der(&self) -> Vec<u8> { Vec::new() }
/// 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<u8> {
self.0.serialize_der()
}
pub fn from_pem(pem: &str) -> Result<KeyPair, PkiError> {
rcgen::KeyPair::from_pem(pem)
.map(KeyPair)
.map_err(|_| PkiError::BadKey)
}
pub fn from_der(der: &[u8]) -> Result<KeyPair, PkiError> {
rcgen::KeyPair::try_from(der)
.map(KeyPair)
.map_err(|_| PkiError::BadKey)
}
/// SubjectPublicKeyInfo DER.
pub fn public_key_der(&self) -> Vec<u8> {
use rcgen::PublicKeyData as _;
self.0.subject_public_key_info()
}
}
pub fn generate_key() -> Result<KeyPair, PkiError> { Err(PkiError::NotBuilt) }
pub fn create_root(_: i64) -> Result<(String, KeyPair), PkiError> { Err(PkiError::NotBuilt) }
pub fn intermediate_csr(_: &KeyPair, _: &str) -> Result<String, PkiError> { Err(PkiError::NotBuilt) }
pub fn sign_intermediate(_: &str, _: &KeyPair, _: &str, _: i64) -> Result<String, PkiError> { Err(PkiError::NotBuilt) }
#[derive(Debug)]
pub struct Intermediate;
pub fn generate_key() -> Result<KeyPair, PkiError> {
rcgen::KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256)
.map(KeyPair)
.map_err(build)
}
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()))
}
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))
}
/// A CSR for a new intermediate key (made by control on the server).
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)
}
/// 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<String, PkiError> {
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<String> {
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(_: &str, _: KeyPair) -> Result<Intermediate, PkiError> { Err(PkiError::NotBuilt) }
pub fn cert_pem(&self) -> &str { "" }
pub fn not_after(&self) -> i64 { 0 }
pub fn new(cert_pem: &str, key: KeyPair) -> Result<Intermediate, 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.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<Issued, PkiError> {
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,
})
}
}
#[derive(Debug)]
pub struct Issued { pub cert_pem: String, pub chain_pem: String, pub key_pem: String }
pub fn issue_server(_: &Intermediate, _: &str, _: i64) -> Result<Issued, PkiError> { Err(PkiError::NotBuilt) }
pub fn issue_device(_: &Intermediate, _: &str, _: i64) -> Result<Issued, PkiError> { Err(PkiError::NotBuilt) }
#[derive(Debug)]
pub struct CertInfo { pub subject_cn: String, pub not_after: i64, pub is_ca: bool, pub path_len: Option<u32>, pub dns_names: Vec<String> }
pub fn inspect(_: &str) -> Result<CertInfo, PkiError> { Err(PkiError::NotBuilt) }
pub fn public_key_der(_: &str) -> Result<Vec<u8>, PkiError> { Err(PkiError::NotBuilt) }
pub fn issued_by(_: &str, _: &str) -> Result<bool, PkiError> { Err(PkiError::NotBuilt) }
pub fn match_code(_: &[u8]) -> String { String::new() }
pub fn encrypt_key_with(_: &KeyPair, _: &[u8], _: u32) -> Result<String, PkiError> { Err(PkiError::NotBuilt) }
pub fn decrypt_key(_: &str, _: &[u8]) -> Result<KeyPair, PkiError> { Err(PkiError::NotBuilt) }
/// 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<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(p, SERVER_DAYS, now)
}
/// A device certificate (mTLS client) for a named device.
pub fn issue_device(int: &Intermediate, 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(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<u32>,
pub dns_names: Vec<String>,
pub serial_hex: String,
pub sha256_hex: String,
}
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)
}
/// 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> {
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<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> {
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<CertInfo, PkiError> {
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),
})
}
/// SubjectPublicKeyInfo DER of the first certificate.
pub fn public_key_der(pem: &str) -> Result<Vec<u8>, 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<bool, PkiError> {
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
)
}
/// DER of the first PEM block of a CSR (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)
}
// ------------------------------------------------------------------ encrypted keys
fn derive(
password: &[u8],
salt: &[u8],
iterations: u32,
) -> Result<ring::aead::LessSafeKey, PkiError> {
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<String, PkiError> {
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<String, PkiError> {
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<KeyPair, PkiError> {
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::*;
pub fn sign_as(_: &str, _: KeyPair, _: &str, _: i64) -> Result<String, PkiError> { Err(PkiError::NotBuilt) }
pub fn sub_ca(_: &Intermediate, _: &KeyPair, _: i64) -> Result<String, PkiError> { Err(PkiError::NotBuilt) }
pub fn greedy_csr(_: &KeyPair, _: &str) -> Result<String, PkiError> { Err(PkiError::NotBuilt) }
pub fn tamper_csr(s: &str) -> String { s.to_owned() }
/// 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 - 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<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 - 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<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;
}
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
}
}