Files
ianitor/crates/core/src/pki.rs
T

367 lines
14 KiB
Rust

// 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), as Ianitor uses it. The CA itself lives in the
//! shared crate `domi-pki` (Fabrica `docs/32_coherence.md`, T3a); this module is Ianitor's view of
//! it with Ianitor's names and messages, plus Ianitor's encrypted-key format. 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 in `domi-pki`.
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD;
use ring::rand::{SecureRandom, SystemRandom};
pub use domi_pki::{
CertInfo, DEVICE_DAYS, EkuInfo, INTERMEDIATE_DAYS, INTERMEDIATE_OPENSSL_EXT, KeyPair,
KeyUsageInfo, ORG, ROOT_CN, ROOT_DAYS, SERVER_DAYS, SERVER_RENEW_DAYS, der_to_pem, match_code,
openssl_sign_command, sha256_hex,
};
/// Subject CN of the intermediate. Signers refuse a CSR whose CN does not start with this.
pub const INTERMEDIATE_CN: &str = domi_pki::IANITOR_INTERMEDIATE_CN;
/// PBKDF2-HMAC-SHA256 iterations for encrypted keys (OWASP 2023 figure).
pub const KEY_KDF_ITERATIONS: u32 = 600_000;
// 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),
}
impl From<domi_pki::PkiError> for PkiError {
fn from(e: domi_pki::PkiError) -> PkiError {
use domi_pki::PkiError as D;
match e {
D::BadCertificate(s) => PkiError::BadCertificate(s),
D::BadCsr => PkiError::BadCsr,
D::CsrSubject => PkiError::CsrSubject,
D::BadKey | D::UnsupportedKey => PkiError::BadKey,
D::NotCa => PkiError::NotCa,
D::KeyMismatch => PkiError::KeyMismatch,
D::IssuerExpired => PkiError::IssuerExpired,
D::BadName(s) => PkiError::BadName(s),
D::Random => PkiError::Random,
D::Build(s) | D::Signer(s) => PkiError::Build(s),
other => PkiError::Build(other.to_string()),
}
}
}
pub fn generate_key() -> Result<KeyPair, PkiError> {
Ok(domi_pki::generate_key()?)
}
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)
}
// ------------------------------------------------------------------ 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> {
Ok(domi_pki::create_root_local(now)?)
}
/// 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 away, 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<String, PkiError> {
Ok(domi_pki::placeholder_leaf(NO_DEVICE_CN, now)?)
}
/// A CSR for a new intermediate key (made by control on the server).
pub fn intermediate_csr(key: &KeyPair, cn: &str) -> Result<String, PkiError> {
Ok(domi_pki::intermediate_csr(key, cn)?)
}
/// 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> {
Ok(domi_pki::sign_intermediate(
root_cert_pem,
root_key,
csr_pem,
INTERMEDIATE_CN,
now,
)?)
}
// ------------------------------------------------------------------ the intermediate
/// The intermediate as control holds it: its certificate and its key, checked to belong
/// together and to be a CA.
#[derive(Debug)]
pub struct Intermediate(domi_pki::Intermediate);
impl Intermediate {
pub fn new(cert_pem: &str, key: KeyPair) -> Result<Intermediate, PkiError> {
Ok(Intermediate(domi_pki::Intermediate::new(cert_pem, key)?))
}
pub fn cert_pem(&self) -> &str {
self.0.cert_pem()
}
pub fn not_after(&self) -> i64 {
self.0.not_after()
}
pub fn info(&self) -> &CertInfo {
self.0.info()
}
pub fn key(&self) -> &KeyPair {
self.0.key()
}
/// The shared crate's intermediate.
pub fn inner(&self) -> &domi_pki::Intermediate {
&self.0
}
}
pub use domi_pki::Issued;
/// 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> {
Ok(domi_pki::issue_server(&int.0, hostname, now)?)
}
/// A device certificate (mTLS client) for a named device.
pub fn issue_device(int: &Intermediate, name: &str, now: i64) -> Result<Issued, PkiError> {
Ok(domi_pki::issue_device(&int.0, name, now)?)
}
// ------------------------------------------------------------------ reading certificates
/// The DER of every certificate in a PEM chain, in order.
pub fn chain_der(pem: &str) -> Result<Vec<Vec<u8>>, PkiError> {
Ok(domi_pki::chain_der(pem)?)
}
/// The first certificate of a PEM chain, as PEM.
pub fn first_pem(pem: &str) -> Result<String, PkiError> {
Ok(domi_pki::first_pem(pem)?)
}
/// Read the first certificate of a PEM chain.
pub fn inspect(pem: &str) -> Result<CertInfo, PkiError> {
Ok(domi_pki::inspect(pem)?)
}
pub fn inspect_der(der: &[u8]) -> Result<CertInfo, PkiError> {
Ok(domi_pki::inspect_der(der)?)
}
/// 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> {
domi_pki::intermediate_problem(cert_pem, root_pem, INTERMEDIATE_CN, now)
}
/// SubjectPublicKeyInfo DER of the first certificate.
pub fn public_key_der(pem: &str) -> Result<Vec<u8>, PkiError> {
Ok(domi_pki::public_key_der(pem)?)
}
/// 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> {
Ok(domi_pki::issued_by(child_pem, issuer_pem)?)
}
/// SubjectPublicKeyInfo DER of a CSR (to match a signed certificate to its request).
pub fn csr_public_key_der(csr_pem: &str) -> Result<Vec<u8>, PkiError> {
Ok(domi_pki::csr_public_key_der(csr_pem)?)
}
/// DER of the first PEM block of a CSR (for the match code).
pub fn csr_der(csr_pem: &str) -> Result<Vec<u8>, PkiError> {
Ok(domi_pki::csr_der(csr_pem)?)
}
// ------------------------------------------------------------------ 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)?;
Ok(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<String, PkiError> {
Ok(domi_pki::testing::sign_as(issuer_pem, key, name, now)?)
}
/// A CA below the intermediate (which pathLen 0 forbids).
pub fn sub_ca(int: &Intermediate, key: &KeyPair, now: i64) -> Result<String, PkiError> {
Ok(domi_pki::testing::sub_ca(int.inner(), key, now)?)
}
/// A CSR that asks for far too much.
pub fn greedy_csr(key: &KeyPair, cn: &str) -> Result<String, PkiError> {
Ok(domi_pki::testing::greedy_csr(key, cn)?)
}
/// Flip one byte inside the CSR's signed part.
pub fn tamper_csr(csr_pem: &str) -> String {
domi_pki::testing::tamper_csr(csr_pem)
}
}