1
0
mirror of https://github.com/aziascreations/BakaShrot.git synced 2026-11-23 20:58:46 +01:00

Moved the PureBasic version to OldSource/, Started the Rust rewrite in Source/

The rewrite's plan and decisions are in revamp.md. Steps 0 to 10 are done:
the workspace and checks, bakashrot-proto, bakashrot-pki and
bakashrot-cert, bakashrot-config, bakashrot-storage (schema v9), the
server and the client library (every request but replication's,
attachments and retention included), the C DLL with its C, PureBasic and
Python bindings, and the bakashrot tool. Step 11 (replication) is next.

OldSource/ is the old implementation, kept building and passing as the
reference.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RwFeVTGs2SsufaH6zquzcb
This commit is contained in:
2026-11-14 12:47:40 +01:00
parent d0048b17c8
commit e044fcf359
225 changed files with 21849 additions and 123 deletions
+25
View File
@@ -0,0 +1,25 @@
[package]
name = "bakashrot-pki"
description = "BakaShrot's certificates: issuing them and CRLs, reading identities, the TLS setup of servers and clients."
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
authors.workspace = true
repository.workspace = true
publish.workspace = true
[dependencies]
bakashrot-proto = { path = "../bakashrot-proto" }
# Issuing certificates and CRLs, P-384 keys through aws-lc.
rcgen = { version = "0.14.10", default-features = false, features = ["x509-parser", "pem", "aws_lc_rs"] }
# TLS 1.3 only, through aws-lc (the one with ML-KEM).
rustls = { version = "0.23.46", default-features = false, features = ["aws_lc_rs", "std"] }
time = "0.3.55"
# Reading certificates and CRLs, a CRL's signature checked through aws-lc.
x509-parser = { version = "0.18.1", features = ["verify-aws"] }
# The identity extension's DER (rcgen's own DER library).
yasna = "0.6.0"
[lints]
workspace = true
+238
View File
@@ -0,0 +1,238 @@
//! A CA: issuing client and server certificates, and CRLs.
//!
//! Every key is ECDSA P-384, every signature SHA-384. A server certificate
//! is for servers and clients both (servers are their peers' clients), and
//! has the DNS name [`SERVER_NAME`] its clients ask for.
use crate::{Error, IDENTITY_OID, Identity, Result, SERVER_NAME, parse_certificate, pem_der};
use rcgen::{
BasicConstraints, CertificateParams, CertificateRevocationListParams, CustomExtension,
DistinguishedName, DnType, ExtendedKeyUsagePurpose, IsCa, Issuer, KeyIdMethod, KeyPair,
KeyUsagePurpose, PKCS_ECDSA_P384_SHA384, PublicKeyData, RevokedCertParams, SanType,
SerialNumber,
};
use time::{Duration, OffsetDateTime};
use x509_parser::x509::X509Name;
/// What a certificate is for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Usage {
/// A client's: it connects to servers.
Client,
/// A server's: clients and peers connect to it, and it connects to its
/// peers.
Server,
}
/// A certificate and its private key, PEM.
#[derive(Debug, Clone)]
pub struct Issued {
/// The certificate: public, goes wherever it's needed.
pub certificate: String,
/// Its private key: stays with its owner.
pub key: String,
}
/// A CA, loaded from its certificate and its key.
pub struct Ca {
certificate: Vec<u8>,
issuer: Issuer<'static, KeyPair>,
}
fn rcgen_error(what: &str) -> impl Fn(rcgen::Error) -> Error + '_ {
move |error| Error::new(format!("{what}: {error}"))
}
fn new_key() -> Result<KeyPair> {
KeyPair::generate_for(&PKCS_ECDSA_P384_SHA384).map_err(rcgen_error("making a key"))
}
/// Parameters valid from now on, for `days`, with `name` as the CN.
fn params(name: &str, days: u32) -> CertificateParams {
let mut params = CertificateParams::default();
let mut subject = DistinguishedName::new();
subject.push(DnType::CommonName, name);
params.distinguished_name = subject;
let now = OffsetDateTime::now_utc();
params.not_before = now;
params.not_after = now + Duration::days(days.into());
params
}
impl Ca {
/// Makes a new CA named `name` (its CN), valid `days`: its certificate
/// and its key. Keep the key off the servers: whoever has it can make
/// any identity.
pub fn create(name: &str, days: u32) -> Result<Issued> {
if name.trim().is_empty() {
return Err(Error::new("a CA needs a name"));
}
let key = new_key()?;
let mut params = params(name, days);
params.is_ca = IsCa::Ca(BasicConstraints::Constrained(0));
params.key_usages = vec![
KeyUsagePurpose::KeyCertSign,
KeyUsagePurpose::CrlSign,
KeyUsagePurpose::DigitalSignature,
];
let certificate = params
.self_signed(&key)
.map_err(rcgen_error("making the CA"))?;
Ok(Issued {
certificate: certificate.pem(),
key: key.serialize_pem(),
})
}
/// Loads a CA from its certificate and its key (PEM). Fails if the
/// certificate isn't a CA's, or the key isn't its.
pub fn load(certificate: &str, key: &str) -> Result<Ca> {
let key = KeyPair::from_pem(key).map_err(rcgen_error("the CA's key"))?;
let der = pem_der(certificate, "CERTIFICATE")?;
{
let parsed = parse_certificate(&der)?;
if !parsed.is_ca() {
return Err(Error::new("the certificate isn't a CA's"));
}
if parsed.public_key().raw != key.subject_public_key_info() {
return Err(Error::new("the key isn't the CA certificate's"));
}
}
let issuer = Issuer::from_ca_cert_pem(certificate, key)
.map_err(rcgen_error("the CA's certificate"))?;
Ok(Ca {
certificate: der,
issuer,
})
}
/// Issues a certificate for `identity`, valid `days`: its certificate and
/// a new key.
pub fn issue(&self, identity: &Identity, usage: Usage, days: u32) -> Result<Issued> {
let key = new_key()?;
let mut params = params(&identity.name, days);
params.key_usages = vec![KeyUsagePurpose::DigitalSignature];
params.use_authority_key_identifier_extension = true;
params.custom_extensions = vec![CustomExtension::from_oid_content(
IDENTITY_OID,
identity.to_der(),
)];
match usage {
Usage::Client => {
params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth];
}
Usage::Server => {
params.extended_key_usages = vec![
ExtendedKeyUsagePurpose::ServerAuth,
ExtendedKeyUsagePurpose::ClientAuth,
];
let name = SERVER_NAME
.try_into()
.map_err(rcgen_error("the server name"))?;
params.subject_alt_names = vec![SanType::DnsName(name)];
}
}
let certificate = params
.signed_by(&key, &self.issuer)
.map_err(rcgen_error("issuing the certificate"))?;
Ok(Issued {
certificate: certificate.pem(),
key: key.serialize_pem(),
})
}
/// Whether this CA issued `certificate` (PEM): its signature checks out
/// with the CA's key.
pub fn issued(&self, certificate: &str) -> Result<bool> {
let ca = parse_certificate(&self.certificate)?;
let der = pem_der(certificate, "CERTIFICATE")?;
let certificate = parse_certificate(&der)?;
Ok(certificate.verify_signature(Some(ca.public_key())).is_ok())
}
/// A CRL revoking the certificates of these serial numbers (as
/// [`Summary::serial`] gives them), PEM. It says to expect the next one
/// within `days`; servers don't hold it against an older one.
pub fn revocation_list(&self, serials: &[Vec<u8>], days: u32) -> Result<String> {
let now = OffsetDateTime::now_utc();
let params = CertificateRevocationListParams {
this_update: now,
next_update: now + Duration::days(days.max(1).into()),
crl_number: SerialNumber::from(now.unix_timestamp().max(1) as u64),
issuing_distribution_point: None,
revoked_certs: serials
.iter()
.map(|serial| RevokedCertParams {
serial_number: SerialNumber::from_slice(serial),
revocation_time: now,
reason_code: None,
invalidity_date: None,
})
.collect(),
key_identifier_method: KeyIdMethod::Sha256,
};
let list = params
.signed_by(&self.issuer)
.map_err(rcgen_error("making the CRL"))?;
list.pem().map_err(rcgen_error("writing the CRL"))
}
}
/// What a certificate says, for people (and the tool).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Summary {
/// Its subject's CN.
pub subject: String,
/// Its issuer's CN.
pub issuer: String,
/// Its serial number, as it's written (what a CRL lists).
pub serial: Vec<u8>,
/// Valid from, as written in it.
pub not_before: String,
/// Valid until, as written in it.
pub not_after: String,
/// Whether it's a CA's.
pub is_ca: bool,
/// What it's for, if it's one of ours.
pub usage: Option<Usage>,
/// Who it is, if it has an identity.
pub identity: Option<Identity>,
}
impl Summary {
/// The serial number in hex.
pub fn serial_hex(&self) -> String {
self.serial
.iter()
.map(|byte| format!("{byte:02x}"))
.collect()
}
}
/// What a certificate (PEM) says.
pub fn summarize(certificate: &str) -> Result<Summary> {
let der = pem_der(certificate, "CERTIFICATE")?;
let parsed = parse_certificate(&der)?;
let common_name = |name: &X509Name<'_>| {
name.iter_common_name()
.next()
.and_then(|cn| cn.as_str().ok())
.unwrap_or("")
.to_owned()
};
let usage = match parsed.extended_key_usage() {
Ok(Some(eku)) if eku.value.server_auth => Some(Usage::Server),
Ok(Some(eku)) if eku.value.client_auth => Some(Usage::Client),
_ => None,
};
Ok(Summary {
subject: common_name(parsed.subject()),
issuer: common_name(parsed.issuer()),
serial: parsed.raw_serial().to_vec(),
not_before: parsed.validity().not_before.to_string(),
not_after: parsed.validity().not_after.to_string(),
is_ca: parsed.is_ca(),
usage,
identity: Identity::from_certificate(&der).ok(),
})
}
+147
View File
@@ -0,0 +1,147 @@
//! The identity extension: who a certificate is.
//!
//! ```text
//! BakaShrotIdentity ::= SEQUENCE {
//! version INTEGER, -- 1
//! name UTF8String, -- the node: "kitchen"
//! roles SEQUENCE OF UTF8String -- free: "sensor", "peer"...
//! }
//! ```
//!
//! Non-critical (rustls refuses critical extensions it doesn't know), read
//! by BakaShrot only. Names and roles follow the name rules
//! (`bakashrot_proto::names`).
use crate::{Error, IDENTITY_OID, Result, parse_certificate};
use bakashrot_proto::names::is_valid_name;
use x509_parser::oid_registry::Oid;
/// The version written, the only one read.
const VERSION: u32 = 1;
/// The most roles a certificate may have.
pub const MAX_ROLES: usize = 64;
/// Who a certificate is: a node, and its roles (their meaning is the
/// server's config's).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Identity {
/// The node's name.
pub name: String,
/// Its roles, in order.
pub roles: Vec<String>,
}
impl Identity {
/// An identity, checked: a name, roles that are names too.
pub fn new(name: &str, roles: &[&str]) -> Result<Identity> {
let identity = Identity {
name: name.to_owned(),
roles: roles.iter().map(|role| (*role).to_owned()).collect(),
};
identity.check()?;
Ok(identity)
}
/// Whether it has `role` (roles compare without case, like names).
pub fn has_role(&self, role: &str) -> bool {
self.roles.iter().any(|own| own.eq_ignore_ascii_case(role))
}
fn check(&self) -> Result<()> {
if !is_valid_name(&self.name) {
return Err(Error::new(format!("'{}' isn't a valid name", self.name)));
}
if self.roles.len() > MAX_ROLES {
return Err(Error::new(format!("more than {MAX_ROLES} roles")));
}
if let Some(role) = self.roles.iter().find(|role| !is_valid_name(role)) {
return Err(Error::new(format!("'{role}' isn't a valid role")));
}
Ok(())
}
/// The extension's value, DER.
pub(crate) fn to_der(&self) -> Vec<u8> {
yasna::construct_der(|writer| {
writer.write_sequence(|writer| {
writer.next().write_u32(VERSION);
writer.next().write_utf8_string(&self.name);
writer.next().write_sequence_of(|writer| {
for role in &self.roles {
writer.next().write_utf8_string(role);
}
});
});
})
}
/// Reads the extension's value, DER.
pub(crate) fn from_der(der: &[u8]) -> Result<Identity> {
let (version, name, roles) = yasna::parse_der(der, |reader| {
reader.read_sequence(|reader| {
let version = reader.next().read_u32()?;
let name = reader.next().read_utf8string()?;
let roles = reader
.next()
.collect_sequence_of(|reader| reader.read_utf8string())?;
Ok((version, name, roles))
})
})
.map_err(|error| Error::new(format!("the identity extension isn't readable: {error}")))?;
if version != VERSION {
return Err(Error::new(format!(
"identity version {version}, this one reads {VERSION}"
)));
}
let identity = Identity { name, roles };
identity.check()?;
Ok(identity)
}
/// The identity of a certificate (DER), the one the TLS connection
/// presented once verified.
pub fn from_certificate(der: &[u8]) -> Result<Identity> {
let certificate = parse_certificate(der)?;
let oid = Oid::from(IDENTITY_OID).map_err(|_| Error::new("the identity OID is invalid"))?;
let extension = certificate
.get_extension_unique(&oid)
.map_err(|error| Error::new(format!("the identity extension: {error}")))?
.ok_or_else(|| Error::new("the certificate has no BakaShrot identity"))?;
Identity::from_der(extension.value)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trip() {
let identity = Identity::new("kitchen", &["sensor", "Reader"]).unwrap();
assert_eq!(Identity::from_der(&identity.to_der()), Ok(identity.clone()));
assert!(identity.has_role("reader"));
assert!(!identity.has_role("peer"));
let alone = Identity::new("kitchen", &[]).unwrap();
assert_eq!(Identity::from_der(&alone.to_der()), Ok(alone));
}
#[test]
fn refused() {
assert!(Identity::new("12", &[]).is_err());
assert!(Identity::new("a b", &[]).is_err());
assert!(Identity::new("kitchen", &["bad role"]).is_err());
assert!(Identity::new("kitchen", &["r"; MAX_ROLES + 1]).is_err());
assert!(Identity::from_der(b"garbage").is_err());
// Another version.
let other = yasna::construct_der(|writer| {
writer.write_sequence(|writer| {
writer.next().write_u32(2);
writer.next().write_utf8_string("kitchen");
writer.next().write_sequence_of(|_| {});
});
});
assert!(Identity::from_der(&other).is_err());
}
}
+87
View File
@@ -0,0 +1,87 @@
//! BakaShrot's certificates, and the TLS they're used with.
//!
//! - [`Identity`]: who a certificate is (a node's name, its roles), in an
//! extension of BakaShrot's own.
//! - [`Ca`]: a CA issuing client and server certificates, and CRLs.
//! - [`Revocations`]: the certificates a CRL revokes, for servers to check
//! (and reload when the CRL file changes).
//! - [`tls`]: the server's and the client's rustls configurations, at the
//! strongest settings rustls has.
//!
//! Everything is PEM text in and out, as files hold it. The profile and the
//! reasons behind it: `Source/docs/certificates.md`.
mod ca;
mod identity;
mod revocation;
pub mod tls;
pub use ca::{Ca, Issued, Summary, Usage, summarize};
pub use identity::Identity;
pub use revocation::{Revocations, SharedRevocations, serial};
use std::fmt;
use x509_parser::certificate::X509Certificate;
/// The identity extension's OID.
///
/// **A placeholder** ([`IDENTITY_OID_IS_PLACEHOLDER`]): under PEN 32473,
/// which RFC 5612 reserves for documentation. Replace it with one under
/// NibblePoker's own PEN once IANA gave it (`Source/docs/oid.md`), before
/// issuing certificates for real: certificates made with this one stop
/// being read once it changes.
pub const IDENTITY_OID: &[u64] = &[1, 3, 6, 1, 4, 1, 32473, 1, 1];
/// Whether [`IDENTITY_OID`] is still the placeholder: `bakashrot-cert`
/// warns when it makes a CA or a certificate then. Set it to `false` with
/// the real OID.
pub const IDENTITY_OID_IS_PLACEHOLDER: bool = true;
/// The DNS name every server certificate has, and every client asks for:
/// a label, not a host. Servers are known by their certificate, wherever
/// they are.
pub const SERVER_NAME: &str = "bakashrot-server";
/// Default lifetimes, in days.
pub const CA_DAYS: u32 = 3650;
/// See [`CA_DAYS`].
pub const CERTIFICATE_DAYS: u32 = 365;
/// What went wrong, in words: everything here fails on a file or a value
/// that isn't right, which people fix.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Error(String);
impl Error {
pub(crate) fn new(what: impl fmt::Display) -> Self {
Error(what.to_string())
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for Error {}
/// A result of this crate.
pub type Result<T> = std::result::Result<T, Error>;
/// Reads one PEM block of `label`, its DER.
fn pem_der(text: &str, label: &str) -> Result<Vec<u8>> {
let (_, pem) = x509_parser::pem::parse_x509_pem(text.as_bytes())
.map_err(|error| Error::new(format!("not PEM: {error}")))?;
if pem.label != label {
return Err(Error::new(format!("a {}, not a {label}", pem.label)));
}
Ok(pem.contents)
}
/// Reads a certificate (DER).
fn parse_certificate(der: &[u8]) -> Result<X509Certificate<'_>> {
let (_, certificate) = x509_parser::parse_x509_certificate(der)
.map_err(|error| Error::new(format!("not a certificate: {error}")))?;
Ok(certificate)
}
@@ -0,0 +1,91 @@
//! The certificates a CRL revokes.
//!
//! A server loads its CRL file into [`Revocations`], shares it with its TLS
//! setup ([`SharedRevocations`]), and replaces what's inside when the file
//! changes: new connections are checked against the new list at once, and
//! the server checks the open ones itself ([`Revocations::revokes_serial`],
//! their serials read once with [`serial`]).
//!
//! A CRL is only taken if it's the CA's: issued by it, its signature
//! checked. Its "next update" isn't held against it: CRLs are pushed by
//! hand, an old one still revokes what it lists.
use crate::{Error, Result, parse_certificate, pem_der};
use std::collections::HashSet;
use std::sync::{Arc, RwLock};
/// The serial numbers of the certificates a CRL revokes.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Revocations {
serials: HashSet<Vec<u8>>,
}
/// Revocations shared between a server's TLS setup and whatever reloads
/// them.
pub type SharedRevocations = Arc<RwLock<Revocations>>;
impl Revocations {
/// Nothing revoked: no CRL file.
pub fn none() -> Revocations {
Revocations::default()
}
/// Reads a CRL (PEM), which must be the CA's (its certificate, PEM).
pub fn load(crl: &str, ca_certificate: &str) -> Result<Revocations> {
let crl_der = pem_der(crl, "X509 CRL")?;
let ca_der = pem_der(ca_certificate, "CERTIFICATE")?;
let (_, list) = x509_parser::parse_x509_crl(&crl_der)
.map_err(|error| Error::new(format!("not a CRL: {error}")))?;
let ca = parse_certificate(&ca_der)
.map_err(|error| Error::new(format!("the CA's certificate: {error}")))?;
if list.issuer().as_raw() != ca.subject().as_raw() {
return Err(Error::new("the CRL is another CA's"));
}
list.verify_signature(ca.public_key())
.map_err(|_| Error::new("the CRL's signature isn't the CA's"))?;
Ok(Revocations {
serials: list
.iter_revoked_certificates()
.map(|revoked| revoked.raw_serial().to_vec())
.collect(),
})
}
/// Whether it revokes this certificate (DER). One that can't be read is
/// taken as revoked.
pub fn revokes(&self, certificate: &[u8]) -> bool {
serial(certificate).map_or(true, |serial| self.revokes_serial(&serial))
}
/// Whether it revokes the certificate with this serial number
/// ([`serial`]): checking an open connection without reading its
/// certificate again.
pub fn revokes_serial(&self, serial: &[u8]) -> bool {
self.serials.contains(serial)
}
/// The serial numbers it revokes.
pub fn serials(&self) -> impl Iterator<Item = &[u8]> {
self.serials.iter().map(Vec::as_slice)
}
/// How many it revokes.
pub fn len(&self) -> usize {
self.serials.len()
}
/// Whether it revokes none.
pub fn is_empty(&self) -> bool {
self.serials.is_empty()
}
/// Wraps it for sharing.
pub fn shared(self) -> SharedRevocations {
Arc::new(RwLock::new(self))
}
}
/// A certificate's (DER) serial number, as CRLs list them.
pub fn serial(certificate: &[u8]) -> Result<Vec<u8>> {
Ok(parse_certificate(certificate)?.raw_serial().to_vec())
}
+254
View File
@@ -0,0 +1,254 @@
//! The TLS setup of servers and clients: TLS 1.3 only, AES-256-GCM-SHA384
//! only, the X25519MLKEM768 key exchange only, ALPN `bakashrot`, and a
//! certificate from the CA on both ends.
//!
//! Each end checks the other with rustls' own verifier (a server's
//! certificate for the name they all have, [`SERVER_NAME`]: no host names
//! or IPs), then that it isn't revoked and has an identity. Both ends take
//! [`SharedRevocations`]: a server dialing its peer is that peer's client,
//! so servers block each other the same way. Once connected, either end
//! reads the other's [`Identity`] with [`peer_identity`].
use crate::{Error, Identity, Result, SERVER_NAME, SharedRevocations};
use bakashrot_proto::limits::ALPN;
use rustls::client::WebPkiServerVerifier;
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::crypto::{CryptoProvider, aws_lc_rs};
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime};
use rustls::server::WebPkiClientVerifier;
use rustls::server::danger::{ClientCertVerified, ClientCertVerifier};
use rustls::{
CertificateError, ClientConfig, DigitallySignedStruct, DistinguishedName, RootCertStore,
ServerConfig, SignatureScheme,
};
use std::sync::Arc;
/// aws-lc, with only the strongest cipher suite and key exchange.
pub fn provider() -> Arc<CryptoProvider> {
Arc::new(CryptoProvider {
cipher_suites: vec![aws_lc_rs::cipher_suite::TLS13_AES_256_GCM_SHA384],
kx_groups: vec![aws_lc_rs::kx_group::X25519MLKEM768],
..aws_lc_rs::default_provider()
})
}
/// The name a client asks for: [`SERVER_NAME`].
pub fn server_name() -> ServerName<'static> {
ServerName::try_from(SERVER_NAME).expect("SERVER_NAME is a DNS name")
}
/// A server's configuration: its certificate and key (PEM), the CA it takes
/// clients from (PEM), and the revocations it checks them against.
pub fn server_config(
ca: &str,
certificate: &str,
key: &str,
revocations: SharedRevocations,
) -> Result<Arc<ServerConfig>> {
let provider = provider();
let webpki = WebPkiClientVerifier::builder_with_provider(roots(ca)?, provider.clone())
.build()
.map_err(|error| Error::new(format!("the CA: {error}")))?;
let mut config = ServerConfig::builder_with_provider(provider)
.with_protocol_versions(&[&rustls::version::TLS13])
.map_err(tls_error)?
.with_client_cert_verifier(Arc::new(ClientCheck {
webpki,
revocations,
}))
.with_single_cert(chain(certificate)?, private_key(key)?)
.map_err(tls_error)?;
config.alpn_protocols = vec![ALPN.to_vec()];
Ok(Arc::new(config))
}
/// A client's configuration: its certificate and key (PEM), the CA it takes
/// servers from (PEM), and the revocations it checks them against
/// (`Revocations::none()` without a CRL). Connect with [`server_name`].
pub fn client_config(
ca: &str,
certificate: &str,
key: &str,
revocations: SharedRevocations,
) -> Result<Arc<ClientConfig>> {
let provider = provider();
let webpki = WebPkiServerVerifier::builder_with_provider(roots(ca)?, provider.clone())
.build()
.map_err(|error| Error::new(format!("the CA: {error}")))?;
let mut config = ClientConfig::builder_with_provider(provider)
.with_protocol_versions(&[&rustls::version::TLS13])
.map_err(tls_error)?
.dangerous()
.with_custom_certificate_verifier(Arc::new(ServerCheck {
webpki,
revocations,
}))
.with_client_auth_cert(chain(certificate)?, private_key(key)?)
.map_err(tls_error)?;
config.alpn_protocols = vec![ALPN.to_vec()];
Ok(Arc::new(config))
}
/// The identity of the other end, from its certificates once connected
/// (`peer_certificates()` of a rustls connection).
pub fn peer_identity(certificates: Option<&[CertificateDer<'_>]>) -> Result<Identity> {
let certificate = certificates
.and_then(<[_]>::first)
.ok_or_else(|| Error::new("no certificate from the other end"))?;
Identity::from_certificate(certificate)
}
fn tls_error(error: rustls::Error) -> Error {
Error::new(format!("TLS: {error}"))
}
fn roots(ca: &str) -> Result<Arc<RootCertStore>> {
let mut roots = RootCertStore::empty();
for certificate in CertificateDer::pem_slice_iter(ca.as_bytes()) {
let certificate = certificate.map_err(|error| Error::new(format!("the CA: {error}")))?;
roots.add(certificate).map_err(tls_error)?;
}
if roots.is_empty() {
return Err(Error::new("the CA: no certificate"));
}
Ok(Arc::new(roots))
}
fn chain(certificate: &str) -> Result<Vec<CertificateDer<'static>>> {
let chain = CertificateDer::pem_slice_iter(certificate.as_bytes())
.collect::<std::result::Result<Vec<_>, _>>()
.map_err(|error| Error::new(format!("the certificate: {error}")))?;
if chain.is_empty() {
return Err(Error::new("the certificate: none in it"));
}
Ok(chain)
}
fn private_key(key: &str) -> Result<PrivateKeyDer<'static>> {
PrivateKeyDer::from_pem_slice(key.as_bytes())
.map_err(|error| Error::new(format!("the key: {error}")))
}
/// What both ends check once rustls' verifier took the other's certificate:
/// not revoked, an identity.
fn ours(
certificate: &CertificateDer<'_>,
revocations: &SharedRevocations,
) -> std::result::Result<(), rustls::Error> {
// A poisoned lock: refuse rather than guess.
let revoked = revocations
.read()
.map_or(true, |revocations| revocations.revokes(certificate));
if revoked {
return Err(rustls::Error::InvalidCertificate(CertificateError::Revoked));
}
if Identity::from_certificate(certificate).is_err() {
return Err(rustls::Error::InvalidCertificate(
CertificateError::ApplicationVerificationFailure,
));
}
Ok(())
}
/// The server's check of clients: rustls', then [`ours`].
#[derive(Debug)]
struct ClientCheck {
webpki: Arc<dyn ClientCertVerifier>,
revocations: SharedRevocations,
}
impl ClientCertVerifier for ClientCheck {
fn root_hint_subjects(&self) -> &[DistinguishedName] {
self.webpki.root_hint_subjects()
}
fn verify_client_cert(
&self,
end_entity: &CertificateDer<'_>,
intermediates: &[CertificateDer<'_>],
now: UnixTime,
) -> std::result::Result<ClientCertVerified, rustls::Error> {
let verified = self
.webpki
.verify_client_cert(end_entity, intermediates, now)?;
ours(end_entity, &self.revocations)?;
Ok(verified)
}
fn verify_tls12_signature(
&self,
message: &[u8],
certificate: &CertificateDer<'_>,
signature: &DigitallySignedStruct,
) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
self.webpki
.verify_tls12_signature(message, certificate, signature)
}
fn verify_tls13_signature(
&self,
message: &[u8],
certificate: &CertificateDer<'_>,
signature: &DigitallySignedStruct,
) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
self.webpki
.verify_tls13_signature(message, certificate, signature)
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
self.webpki.supported_verify_schemes()
}
}
/// The client's check of servers: rustls', then [`ours`].
#[derive(Debug)]
struct ServerCheck {
webpki: Arc<WebPkiServerVerifier>,
revocations: SharedRevocations,
}
impl ServerCertVerifier for ServerCheck {
fn verify_server_cert(
&self,
end_entity: &CertificateDer<'_>,
intermediates: &[CertificateDer<'_>],
server_name: &ServerName<'_>,
ocsp_response: &[u8],
now: UnixTime,
) -> std::result::Result<ServerCertVerified, rustls::Error> {
let verified = self.webpki.verify_server_cert(
end_entity,
intermediates,
server_name,
ocsp_response,
now,
)?;
ours(end_entity, &self.revocations)?;
Ok(verified)
}
fn verify_tls12_signature(
&self,
message: &[u8],
certificate: &CertificateDer<'_>,
signature: &DigitallySignedStruct,
) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
self.webpki
.verify_tls12_signature(message, certificate, signature)
}
fn verify_tls13_signature(
&self,
message: &[u8],
certificate: &CertificateDer<'_>,
signature: &DigitallySignedStruct,
) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
self.webpki
.verify_tls13_signature(message, certificate, signature)
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
self.webpki.supported_verify_schemes()
}
}
+235
View File
@@ -0,0 +1,235 @@
//! Issuing: what certificates and CRLs hold, and OpenSSL agreeing.
use bakashrot_pki::{Ca, Identity, Revocations, Usage, summarize};
use std::path::PathBuf;
use std::process::Command;
fn ca() -> (Ca, String) {
let issued = Ca::create("Test CA", 30).unwrap();
(
Ca::load(&issued.certificate, &issued.key).unwrap(),
issued.certificate,
)
}
#[test]
fn certificates_say_who_and_what_for() {
let (ca, ca_certificate) = ca();
let identity = Identity::new("kitchen", &["sensor", "reader"]).unwrap();
let client = ca.issue(&identity, Usage::Client, 365).unwrap();
let server = ca
.issue(
&Identity::new("server-1", &["peer"]).unwrap(),
Usage::Server,
365,
)
.unwrap();
let summary = summarize(&client.certificate).unwrap();
assert_eq!(summary.identity, Some(identity));
assert_eq!(summary.subject, "kitchen");
assert_eq!(summary.issuer, "Test CA");
assert_eq!(summary.usage, Some(Usage::Client));
assert!(!summary.is_ca);
assert!(!summary.serial.is_empty());
assert_eq!(
summarize(&server.certificate).unwrap().usage,
Some(Usage::Server)
);
let ca_summary = summarize(&ca_certificate).unwrap();
assert!(ca_summary.is_ca);
assert_eq!(ca_summary.identity, None);
assert!(ca.issued(&client.certificate).unwrap());
let (other, _) = self::ca();
assert!(!other.issued(&client.certificate).unwrap());
}
#[test]
fn a_ca_needs_its_own_key() {
let first = Ca::create("First", 30).unwrap();
let second = Ca::create("Second", 30).unwrap();
assert!(Ca::load(&first.certificate, &second.key).is_err());
assert!(Ca::load(&first.certificate, &first.key).is_ok());
let ca = Ca::load(&first.certificate, &first.key).unwrap();
let client = ca
.issue(&Identity::new("kitchen", &[]).unwrap(), Usage::Client, 30)
.unwrap();
assert!(
Ca::load(&client.certificate, &client.key).is_err(),
"not a CA"
);
assert!(Ca::create(" ", 30).is_err());
}
#[test]
fn crls_revoke_what_they_list() {
let (ca, ca_certificate) = ca();
let certificates: Vec<String> = (0..8)
.map(|n| {
let identity = Identity::new(&format!("node-{n}"), &[]).unwrap();
ca.issue(&identity, Usage::Client, 30).unwrap().certificate
})
.collect();
let serials: Vec<Vec<u8>> = certificates[..4]
.iter()
.map(|certificate| summarize(certificate).unwrap().serial)
.collect();
let crl = ca.revocation_list(&serials, 30).unwrap();
let revocations = Revocations::load(&crl, &ca_certificate).unwrap();
assert_eq!(revocations.len(), 4);
for (n, certificate) in certificates.iter().enumerate() {
assert_eq!(revocations.revokes(&der(certificate)), n < 4, "node-{n}");
}
assert!(Revocations::none().is_empty());
assert!(!Revocations::none().revokes(&der(&certificates[0])));
let empty = ca.revocation_list(&[], 30).unwrap();
assert!(
Revocations::load(&empty, &ca_certificate)
.unwrap()
.is_empty()
);
}
#[test]
fn only_the_cas_crls_are_taken() {
let (ca, ca_certificate) = ca();
let (other, other_certificate) = self::ca();
let crl = other.revocation_list(&[vec![1]], 30).unwrap();
assert!(
Revocations::load(&crl, &ca_certificate).is_err(),
"another CA's"
);
assert!(Revocations::load(&crl, &other_certificate).is_ok());
// Tampered: a character of its Base64 changed.
let crl = ca.revocation_list(&[vec![1]], 30).unwrap();
let at = crl.len() / 2;
let swapped = if &crl[at..=at] == "A" { "B" } else { "A" };
let tampered = format!("{}{}{}", &crl[..at], swapped, &crl[at + 1..]);
assert!(Revocations::load(&tampered, &ca_certificate).is_err());
assert!(Revocations::load("not a CRL", &ca_certificate).is_err());
assert!(
Revocations::load(&ca_certificate, &ca_certificate).is_err(),
"a certificate"
);
}
fn der(certificate: &str) -> Vec<u8> {
use rustls::pki_types::{CertificateDer, pem::PemObject};
CertificateDer::from_pem_slice(certificate.as_bytes())
.unwrap()
.to_vec()
}
/// OpenSSL, from the PATH or Git for Windows'.
fn openssl() -> Option<PathBuf> {
let candidates = [
PathBuf::from("openssl"),
PathBuf::from(r"C:\Program Files\Git\ucrt64\bin\openssl.exe"),
PathBuf::from(r"C:\Program Files\Git\mingw64\bin\openssl.exe"),
PathBuf::from(r"C:\Program Files\Git\usr\bin\openssl.exe"),
];
candidates.into_iter().find(|candidate| {
Command::new(candidate)
.arg("version")
.output()
.is_ok_and(|output| output.status.success())
})
}
#[test]
fn openssl_agrees() {
let Some(openssl) = openssl() else {
eprintln!("SKIP: no openssl");
return;
};
let folder = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("pki-openssl");
let _ = std::fs::remove_dir_all(&folder);
std::fs::create_dir_all(&folder).unwrap();
let issued = Ca::create("Test CA", 30).unwrap();
let ca = Ca::load(&issued.certificate, &issued.key).unwrap();
let client = ca
.issue(
&Identity::new("kitchen", &["sensor"]).unwrap(),
Usage::Client,
30,
)
.unwrap();
let server = ca
.issue(&Identity::new("server-1", &[]).unwrap(), Usage::Server, 30)
.unwrap();
let serial = summarize(&client.certificate).unwrap().serial;
let files = [
("ca.crt", issued.certificate.clone()),
("client.crt", client.certificate),
("server.crt", server.certificate),
("ca.crl", ca.revocation_list(&[serial], 30).unwrap()),
];
for (name, text) in &files {
std::fs::write(folder.join(name), text).unwrap();
}
let run = |args: &[&str]| {
let output = Command::new(&openssl)
.args(args)
.current_dir(&folder)
.output()
.unwrap();
let text = format!(
"{}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
(output.status.success(), text)
};
let (ok, text) = run(&[
"verify",
"-CAfile",
"ca.crt",
"-purpose",
"sslclient",
"client.crt",
]);
assert!(ok, "{text}");
let (ok, text) = run(&[
"verify",
"-CAfile",
"ca.crt",
"-purpose",
"sslserver",
"server.crt",
]);
assert!(ok, "{text}");
let (ok, _) = run(&[
"verify",
"-CAfile",
"ca.crt",
"-purpose",
"sslserver",
"client.crt",
]);
assert!(!ok, "a client's certificate isn't a server's");
let (ok, text) = run(&["crl", "-in", "ca.crl", "-CAfile", "ca.crt", "-noout"]);
assert!(ok && text.contains("verify OK"), "{text}");
let (ok, text) = run(&[
"verify",
"-CAfile",
"ca.crt",
"-CRLfile",
"ca.crl",
"-crl_check",
"client.crt",
]);
assert!(!ok && text.contains("revoked"), "{text}");
let (ok, text) = run(&["x509", "-in", "server.crt", "-noout", "-text"]);
assert!(
ok && text.contains("NIST CURVE: P-384") && text.contains("DNS:bakashrot-server"),
"{text}"
);
}
+388
View File
@@ -0,0 +1,388 @@
//! Handshakes in memory, no sockets: what's accepted and what's refused.
use bakashrot_pki::tls::{self, peer_identity};
use bakashrot_pki::{Ca, Identity, Issued, Revocations, SharedRevocations, Usage, summarize};
use bakashrot_proto::limits::ALPN;
use rustls::{ClientConfig, ClientConnection, ConnectionCommon, ServerConfig, ServerConnection};
use std::io::{Read, Write};
use std::sync::Arc;
struct Pki {
ca: Ca,
ca_certificate: String,
ca_key: String,
}
impl Pki {
fn new(name: &str) -> Pki {
let issued = Ca::create(name, 30).unwrap();
Pki {
ca: Ca::load(&issued.certificate, &issued.key).unwrap(),
ca_certificate: issued.certificate,
ca_key: issued.key,
}
}
fn issue(&self, name: &str, roles: &[&str], usage: Usage) -> Issued {
self.ca
.issue(&Identity::new(name, roles).unwrap(), usage, 30)
.unwrap()
}
fn server(&self, issued: &Issued, revocations: SharedRevocations) -> Arc<ServerConfig> {
tls::server_config(
&self.ca_certificate,
&issued.certificate,
&issued.key,
revocations,
)
.unwrap()
}
fn client(&self, issued: &Issued) -> Arc<ClientConfig> {
self.client_checking(issued, Revocations::none().shared())
}
fn client_checking(
&self,
issued: &Issued,
revocations: SharedRevocations,
) -> Arc<ClientConfig> {
tls::client_config(
&self.ca_certificate,
&issued.certificate,
&issued.key,
revocations,
)
.unwrap()
}
/// Revocations listing these certificates.
fn revoking(&self, certificates: &[&Issued]) -> SharedRevocations {
let serials: Vec<Vec<u8>> = certificates
.iter()
.map(|issued| summarize(&issued.certificate).unwrap().serial)
.collect();
let crl = self.ca.revocation_list(&serials, 30).unwrap();
Revocations::load(&crl, &self.ca_certificate)
.unwrap()
.shared()
}
}
fn transfer<A, B>(from: &mut ConnectionCommon<A>, to: &mut ConnectionCommon<B>) {
while from.wants_write() {
let mut bytes = Vec::new();
from.write_tls(&mut bytes).unwrap();
let mut rest = &bytes[..];
while !rest.is_empty() {
to.read_tls(&mut rest).unwrap();
}
}
}
/// A handshake, then a byte each way: the connections, or which end
/// refused and why.
fn connect(
client: Arc<ClientConfig>,
server: Arc<ServerConfig>,
) -> Result<(ClientConnection, ServerConnection), String> {
let mut client = ClientConnection::new(client, tls::server_name()).unwrap();
let mut server = ServerConnection::new(server).unwrap();
for _ in 0..10 {
transfer(&mut client, &mut server);
server
.process_new_packets()
.map_err(|e| format!("server: {e}"))?;
transfer(&mut server, &mut client);
client
.process_new_packets()
.map_err(|e| format!("client: {e}"))?;
if !client.is_handshaking() && !server.is_handshaking() {
break;
}
}
client.writer().write_all(b"c").unwrap();
transfer(&mut client, &mut server);
server
.process_new_packets()
.map_err(|e| format!("server: {e}"))?;
server.writer().write_all(b"s").unwrap();
transfer(&mut server, &mut client);
client
.process_new_packets()
.map_err(|e| format!("client: {e}"))?;
let mut byte = [0];
server
.reader()
.read_exact(&mut byte)
.map_err(|e| format!("server read: {e}"))?;
assert_eq!(&byte, b"c");
client
.reader()
.read_exact(&mut byte)
.map_err(|e| format!("client read: {e}"))?;
assert_eq!(&byte, b"s");
Ok((client, server))
}
#[test]
fn connected_at_the_strongest_settings() {
let pki = Pki::new("Test CA");
let server = pki.issue("server-1", &["peer"], Usage::Server);
let client = pki.issue("kitchen", &["sensor"], Usage::Client);
let (client, server) = connect(
pki.client(&client),
pki.server(&server, Revocations::none().shared()),
)
.unwrap();
assert_eq!(
client.protocol_version(),
Some(rustls::ProtocolVersion::TLSv1_3)
);
assert_eq!(
client.negotiated_cipher_suite().unwrap().suite(),
rustls::CipherSuite::TLS13_AES_256_GCM_SHA384
);
assert_eq!(
client.negotiated_key_exchange_group().unwrap().name(),
rustls::NamedGroup::X25519MLKEM768
);
assert_eq!(client.alpn_protocol(), Some(ALPN));
assert_eq!(server.alpn_protocol(), Some(ALPN));
// Each end knows who the other is.
let client_identity = peer_identity(server.peer_certificates()).unwrap();
assert_eq!(
client_identity,
Identity::new("kitchen", &["sensor"]).unwrap()
);
let server_identity = peer_identity(client.peer_certificates()).unwrap();
assert_eq!(server_identity.name, "server-1");
assert!(server_identity.has_role("peer"));
}
#[test]
fn servers_connect_to_their_peers() {
let pki = Pki::new("Test CA");
let first = pki.issue("server-1", &["peer"], Usage::Server);
let second = pki.issue("server-2", &["peer"], Usage::Server);
// A server's certificate is a client's too.
let (_, server) = connect(
pki.client(&first),
pki.server(&second, Revocations::none().shared()),
)
.unwrap();
assert_eq!(
peer_identity(server.peer_certificates()).unwrap().name,
"server-1"
);
}
#[test]
fn a_client_of_another_ca_is_refused() {
let pki = Pki::new("Test CA");
let other = Pki::new("Other CA");
let server = pki.server(
&pki.issue("server-1", &[], Usage::Server),
Revocations::none().shared(),
);
let stranger = other.issue("kitchen", &[], Usage::Client);
let client = tls::client_config(
&pki.ca_certificate,
&stranger.certificate,
&stranger.key,
Revocations::none().shared(),
)
.unwrap();
let error = connect(client, server).unwrap_err();
assert!(error.starts_with("server:"), "{error}");
}
#[test]
fn a_server_of_another_ca_is_refused() {
let pki = Pki::new("Test CA");
let other = Pki::new("Other CA");
let client = pki.client(&pki.issue("kitchen", &[], Usage::Client));
let impostor = other.issue("server-1", &[], Usage::Server);
let server = tls::server_config(
&pki.ca_certificate,
&impostor.certificate,
&impostor.key,
Revocations::none().shared(),
)
.unwrap();
let error = connect(client, server).unwrap_err();
assert!(error.starts_with("client:"), "{error}");
}
#[test]
fn a_clients_certificate_isnt_a_servers() {
let pki = Pki::new("Test CA");
let client = pki.client(&pki.issue("kitchen", &[], Usage::Client));
let posing = pki.issue("server-1", &[], Usage::Client);
let error = connect(client, pki.server(&posing, Revocations::none().shared())).unwrap_err();
assert!(error.starts_with("client:"), "{error}");
}
#[test]
fn revoked_clients_are_refused_and_reloading_takes_effect() {
let pki = Pki::new("Test CA");
let revocations = Revocations::none().shared();
let server = pki.server(
&pki.issue("server-1", &[], Usage::Server),
revocations.clone(),
);
let kitchen = pki.issue("kitchen", &[], Usage::Client);
let garage = pki.issue("garage", &[], Usage::Client);
assert!(connect(pki.client(&kitchen), server.clone()).is_ok());
// The CRL changes: the same server configuration refuses at once.
let serial = summarize(&kitchen.certificate).unwrap().serial;
let crl = pki.ca.revocation_list(&[serial], 30).unwrap();
*revocations.write().unwrap() = Revocations::load(&crl, &pki.ca_certificate).unwrap();
let error = connect(pki.client(&kitchen), server.clone()).unwrap_err();
assert!(
error.starts_with("server:") && error.contains("Revoked"),
"{error}"
);
assert!(
connect(pki.client(&garage), server.clone()).is_ok(),
"only kitchen"
);
*revocations.write().unwrap() = Revocations::none();
assert!(connect(pki.client(&kitchen), server).is_ok());
}
#[test]
fn a_certificate_without_an_identity_is_refused() {
let pki = Pki::new("Test CA");
let server = pki.server(
&pki.issue("server-1", &[], Usage::Server),
Revocations::none().shared(),
);
// Signed by the right CA, but not by Ca::issue: no identity extension.
let ca_key = rcgen::KeyPair::from_pem(&pki.ca_key).unwrap();
let issuer = rcgen::Issuer::from_ca_cert_pem(&pki.ca_certificate, ca_key).unwrap();
let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P384_SHA384).unwrap();
let mut params = rcgen::CertificateParams::default();
params.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::ClientAuth];
let certificate = params.signed_by(&key, &issuer).unwrap().pem();
let client = tls::client_config(
&pki.ca_certificate,
&certificate,
&key.serialize_pem(),
Revocations::none().shared(),
)
.unwrap();
let error = connect(client, server).unwrap_err();
assert!(error.starts_with("server:"), "{error}");
}
#[test]
fn another_protocol_is_refused() {
let pki = Pki::new("Test CA");
let server = pki.server(
&pki.issue("server-1", &[], Usage::Server),
Revocations::none().shared(),
);
let client = pki.issue("kitchen", &[], Usage::Client);
let mut config = (*pki.client(&client)).clone();
config.alpn_protocols = vec![b"http/1.1".to_vec()];
let error = connect(Arc::new(config), server).unwrap_err();
assert!(error.starts_with("server:"), "{error}");
}
#[test]
fn bad_files_are_told() {
let pki = Pki::new("Test CA");
let client = pki.issue("kitchen", &[], Usage::Client);
let none = || Revocations::none().shared();
assert!(tls::client_config("", &client.certificate, &client.key, none()).is_err());
assert!(tls::client_config(&pki.ca_certificate, "", &client.key, none()).is_err());
assert!(tls::client_config(&pki.ca_certificate, &client.certificate, "", none()).is_err());
assert!(peer_identity(None).is_err());
}
#[test]
fn clients_given_a_crl_refuse_revoked_servers() {
let pki = Pki::new("Test CA");
let server = pki.issue("server-1", &[], Usage::Server);
let client = pki.issue("kitchen", &[], Usage::Client);
let config = pki.server(&server, Revocations::none().shared());
assert!(connect(pki.client(&client), config.clone()).is_ok());
let error = connect(
pki.client_checking(&client, pki.revoking(&[&server])),
config,
)
.unwrap_err();
assert!(
error.starts_with("client:") && error.contains("Revoked"),
"{error}"
);
}
#[test]
fn servers_block_each_other() {
let pki = Pki::new("Test CA");
let first = pki.issue("server-1", &["peer"], Usage::Server);
let second = pki.issue("server-2", &["peer"], Usage::Server);
let crl = pki.revoking(&[&second]);
// server-1 has the CRL: it refuses server-2 both ways.
let error = connect(pki.client(&second), pki.server(&first, crl.clone())).unwrap_err();
assert!(
error.starts_with("server:") && error.contains("Revoked"),
"{error}"
);
let error = connect(
pki.client_checking(&first, crl),
pki.server(&second, Revocations::none().shared()),
)
.unwrap_err();
assert!(
error.starts_with("client:") && error.contains("Revoked"),
"{error}"
);
}
#[test]
fn same_named_servers_have_their_own_certificates() {
let pki = Pki::new("Test CA");
let first = pki.issue("server-1", &["peer"], Usage::Server);
let second = pki.issue("server-1", &["peer"], Usage::Server);
assert_ne!(first.certificate, second.certificate);
assert_ne!(
summarize(&first.certificate).unwrap().serial,
summarize(&second.certificate).unwrap().serial
);
let client = pki.issue("kitchen", &[], Usage::Client);
for server in [&first, &second] {
assert!(
connect(
pki.client(&client),
pki.server(server, Revocations::none().shared())
)
.is_ok()
);
}
// Revoking one leaves the other alone, as a server and as a client.
let crl = pki.revoking(&[&first]);
let checking = pki.client_checking(&client, crl.clone());
assert!(
connect(
checking.clone(),
pki.server(&first, Revocations::none().shared())
)
.is_err()
);
assert!(connect(checking, pki.server(&second, Revocations::none().shared())).is_ok());
let gate = pki.server(&pki.issue("server-2", &[], Usage::Server), crl);
assert!(connect(pki.client(&first), gate.clone()).is_err());
assert!(connect(pki.client(&second), gate).is_ok());
}