smgw_sec/tls.rs
1//! Provision a certificate chain and its OpenSSL signing key for a TLS endpoint.
2
3use ::openssl::{
4 error::ErrorStack,
5 pkey::{PKey, Private},
6 ssl::{SslContextBuilder, SslMethod},
7 x509::X509,
8};
9use std::io;
10
11/// A leaf certificate, its intermediates in issuer order, and a matching signing
12/// key. The key can be a provider handle whose private material stays on a token.
13pub struct TlsIdentity {
14 leaf: X509,
15 intermediates: Vec<X509>,
16 key: PKey<Private>,
17}
18
19impl TlsIdentity {
20 /// Bind an already provisioned signing key using its public component.
21 /// The leaf is presented first and the root belongs in the peer's trust store.
22 pub fn new(leaf: X509, intermediates: Vec<X509>, key: PKey<Private>) -> io::Result<Self> {
23 if !leaf.public_key()?.public_eq(&key) {
24 return Err(io::Error::new(
25 io::ErrorKind::InvalidInput,
26 "TLS certificate and signing key do not match",
27 ));
28 }
29 Ok(Self {
30 leaf,
31 intermediates,
32 key,
33 })
34 }
35
36 /// Read a leaf-first PEM certificate chain and an unencrypted PEM key or
37 /// provider key reference. To use a PKCS#11 reference PEM, configure the
38 /// OpenSSL provider and token login before constructing the identity.
39 /// An already unlocked key handle can be supplied directly to [`Self::new`].
40 pub fn from_pem(chain: &[u8], key: &[u8]) -> io::Result<Self> {
41 let mut chain = X509::stack_from_pem(chain)?.into_iter();
42 let leaf = chain.next().ok_or_else(|| {
43 io::Error::new(io::ErrorKind::InvalidInput, "empty TLS certificate chain")
44 })?;
45 // Endpoint provisioning is noninteractive. The deployment supplies any
46 // token login through its provider configuration.
47 let key = PKey::private_key_from_pem_callback(key, |_| Ok(0)).map_err(|_| {
48 // Provider errors can include the configured locator or PIN source.
49 io::Error::new(
50 io::ErrorKind::InvalidInput,
51 "unable to load TLS signing key",
52 )
53 })?;
54 Self::new(leaf, chain.collect(), key)
55 }
56
57 /// Start a fresh OpenSSL context with this local identity. The transport
58 /// configures its TLS profile, trust anchors and peer authentication on it.
59 pub fn into_context_builder(self, method: SslMethod) -> Result<SslContextBuilder, ErrorStack> {
60 let mut context = SslContextBuilder::new(method)?;
61 context.set_certificate(&self.leaf)?;
62 for intermediate in self.intermediates {
63 context.add_extra_chain_cert(intermediate)?;
64 }
65 context.set_private_key(&self.key)?;
66 context.check_private_key()?;
67 Ok(context)
68 }
69}