Skip to main content

kute_protocol/
tls.rs

1//! Authenticated, encrypted transport for the exchange protocol: TLS 1.3
2//! with a certificate on both sides (mutual TLS), through `rustls`.
3//!
4//! The protocol itself carries no credentials. `HELLO` has a `peer` name,
5//! and that name is a claim. Who the other side is comes from here: the
6//! SHA-256 of the certificate it proved possession of during the handshake.
7//! [`Access`] maps that fingerprint to a [`Policy`]; a peer that is not
8//! listed is refused before any protocol message is read, even when its
9//! certificate chains to a trusted authority.
10//!
11//! ```text
12//! let (stream, who) = tls::accept(&config, tcp)?;      // handshake done
13//! let policy = access.policy_for(&who)?;               // or refused
14//! let peer = Peer::new("plant-b", engine, policy);
15//! Session::new(peer, Framed::new(stream, max_frame)).serve()?;
16//! ```
17
18use crate::Policy;
19use kute::{KuteError, Result};
20use rustls::pki_types::pem::PemObject;
21use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName};
22use rustls::server::WebPkiClientVerifier;
23use rustls::{ClientConfig, ClientConnection, ConnectionCommon, RootCertStore, ServerConfig, ServerConnection, SideData, StreamOwned};
24use sha2::{Digest, Sha256};
25use std::collections::BTreeMap;
26use std::io::{Read, Write};
27use std::net::TcpStream;
28use std::ops::DerefMut;
29use std::path::Path;
30use std::sync::Arc;
31
32fn tls_error(what: &str, e: impl std::fmt::Display) -> KuteError {
33    KuteError::Backend(format!("tls: {what}: {e}"))
34}
35
36/// Who the other side proved to be.
37#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
38pub struct PeerIdentity {
39    /// `sha256:` and the hex SHA-256 of the peer's own certificate (DER).
40    pub fingerprint: String,
41}
42
43/// The fingerprint [`PeerIdentity`] carries, for a certificate in hand.
44pub fn fingerprint(certificate: &CertificateDer<'_>) -> String {
45    format!("sha256:{}", kute::hex(&Sha256::digest(certificate.as_ref())))
46}
47
48/// Which peers may connect, and what each may do. Nobody is listed at first.
49#[derive(Clone, Debug, Default)]
50pub struct Access {
51    peers: BTreeMap<String, Policy>,
52}
53
54impl Access {
55    pub fn new() -> Self {
56        Self::default()
57    }
58
59    /// Let the holder of the certificate with this fingerprint connect,
60    /// under `policy`.
61    pub fn allow(&mut self, fingerprint: &str, policy: Policy) -> Result<()> {
62        let hex = fingerprint.strip_prefix("sha256:").unwrap_or("");
63        if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) {
64            return Err(KuteError::InvalidConfig(format!("{fingerprint:?} is not a certificate fingerprint (sha256: and 64 lowercase hex digits)")));
65        }
66        self.peers.insert(fingerprint.to_string(), policy);
67        Ok(())
68    }
69
70    /// The policy for an authenticated peer, or the refusal.
71    pub fn policy_for(&self, who: &PeerIdentity) -> Result<Policy> {
72        self.peers
73            .get(&who.fingerprint)
74            .cloned()
75            .ok_or_else(|| KuteError::Backend(format!("peer {} is authenticated but not authorized here", who.fingerprint)))
76    }
77
78    pub fn len(&self) -> usize {
79        self.peers.len()
80    }
81
82    pub fn is_empty(&self) -> bool {
83        self.peers.is_empty()
84    }
85}
86
87/// Certificates from a PEM file, in order.
88pub fn load_certificates(path: &Path) -> Result<Vec<CertificateDer<'static>>> {
89    let certs = CertificateDer::pem_file_iter(path)
90        .map_err(|e| tls_error(&format!("reading {}", path.display()), e))?
91        .collect::<std::result::Result<Vec<_>, _>>()
92        .map_err(|e| tls_error(&format!("reading {}", path.display()), e))?;
93    if certs.is_empty() {
94        return Err(KuteError::InvalidConfig(format!("{} holds no certificate", path.display())));
95    }
96    Ok(certs)
97}
98
99/// The private key in a PEM file.
100pub fn load_private_key(path: &Path) -> Result<PrivateKeyDer<'static>> {
101    PrivateKeyDer::from_pem_file(path).map_err(|e| tls_error(&format!("reading the key in {}", path.display()), e))
102}
103
104fn roots(authorities: Vec<CertificateDer<'static>>) -> Result<RootCertStore> {
105    let mut store = RootCertStore::empty();
106    for authority in authorities {
107        store.add(authority).map_err(|e| tls_error("a trusted authority certificate is not usable", e))?;
108    }
109    if store.is_empty() {
110        return Err(KuteError::InvalidConfig("no trusted authority was given".into()));
111    }
112    Ok(store)
113}
114
115fn provider() -> Arc<rustls::crypto::CryptoProvider> {
116    Arc::new(rustls::crypto::ring::default_provider())
117}
118
119/// A listening side that requires a client certificate issued by one of
120/// `client_authorities`. TLS 1.3 only.
121pub fn server_config(
122    chain: Vec<CertificateDer<'static>>,
123    key: PrivateKeyDer<'static>,
124    client_authorities: Vec<CertificateDer<'static>>,
125) -> Result<Arc<ServerConfig>> {
126    let verifier = WebPkiClientVerifier::builder_with_provider(Arc::new(roots(client_authorities)?), provider())
127        .build()
128        .map_err(|e| tls_error("client verification", e))?;
129    let config = ServerConfig::builder_with_provider(provider())
130        .with_protocol_versions(&[&rustls::version::TLS13])
131        .map_err(|e| tls_error("protocol versions", e))?
132        .with_client_cert_verifier(verifier)
133        .with_single_cert(chain, key)
134        .map_err(|e| tls_error("the server certificate and key", e))?;
135    Ok(Arc::new(config))
136}
137
138/// A connecting side that presents `chain` and trusts servers issued by one
139/// of `server_authorities`. TLS 1.3 only.
140pub fn client_config(
141    chain: Vec<CertificateDer<'static>>,
142    key: PrivateKeyDer<'static>,
143    server_authorities: Vec<CertificateDer<'static>>,
144) -> Result<Arc<ClientConfig>> {
145    let config = ClientConfig::builder_with_provider(provider())
146        .with_protocol_versions(&[&rustls::version::TLS13])
147        .map_err(|e| tls_error("protocol versions", e))?
148        .with_root_certificates(roots(server_authorities)?)
149        .with_client_auth_cert(chain, key)
150        .map_err(|e| tls_error("the client certificate and key", e))?;
151    Ok(Arc::new(config))
152}
153
154/// An encrypted connection. Dropping it tells the other side that the
155/// stream ends here (TLS `close_notify`), so the other side can tell a
156/// finished conversation from one that was cut: a connection that ends
157/// without that notice is reported as an error by whoever is reading it.
158pub struct Secured<C, S>(StreamOwned<C, TcpStream>)
159where
160    C: DerefMut<Target = ConnectionCommon<S>>,
161    S: SideData;
162
163/// The listening side's connection.
164pub type ServerStream = Secured<ServerConnection, rustls::server::ServerConnectionData>;
165/// The connecting side's connection.
166pub type ClientStream = Secured<ClientConnection, rustls::client::ClientConnectionData>;
167
168impl<C: DerefMut<Target = ConnectionCommon<S>>, S: SideData> Read for Secured<C, S> {
169    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
170        self.0.read(buf)
171    }
172}
173
174impl<C: DerefMut<Target = ConnectionCommon<S>>, S: SideData> Write for Secured<C, S> {
175    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
176        self.0.write(buf)
177    }
178    fn flush(&mut self) -> std::io::Result<()> {
179        self.0.flush()
180    }
181}
182
183impl<C: DerefMut<Target = ConnectionCommon<S>>, S: SideData> Drop for Secured<C, S> {
184    fn drop(&mut self) {
185        self.0.conn.send_close_notify();
186        let _ = self.0.flush();
187    }
188}
189
190fn identity(certificates: Option<&[CertificateDer<'_>]>) -> Result<PeerIdentity> {
191    let own = certificates.and_then(|c| c.first()).ok_or_else(|| KuteError::Backend("tls: the peer presented no certificate".into()))?;
192    Ok(PeerIdentity { fingerprint: fingerprint(own) })
193}
194
195/// Listening side: complete the handshake on an accepted connection.
196/// Returns the encrypted stream and who the client proved to be. Fails, and
197/// nothing of the protocol is read, if the client has no certificate from a
198/// trusted authority.
199pub fn accept(config: &Arc<ServerConfig>, mut tcp: TcpStream) -> Result<(ServerStream, PeerIdentity)> {
200    let mut connection = ServerConnection::new(config.clone()).map_err(|e| tls_error("starting the handshake", e))?;
201    while connection.is_handshaking() {
202        connection.complete_io(&mut tcp).map_err(|e| tls_error("handshake", e))?;
203    }
204    let who = identity(connection.peer_certificates())?;
205    Ok((Secured(StreamOwned::new(connection, tcp)), who))
206}
207
208/// Connecting side: complete the handshake with the server named
209/// `server_name` (it must be in the server's certificate). Returns the
210/// encrypted stream and the server's identity, for a caller that wants to
211/// accept one particular server and not any the authority issued.
212pub fn connect(config: &Arc<ClientConfig>, server_name: &str, mut tcp: TcpStream) -> Result<(ClientStream, PeerIdentity)> {
213    let name = ServerName::try_from(server_name.to_string()).map_err(|e| tls_error(&format!("server name {server_name:?}"), e))?;
214    let mut connection = ClientConnection::new(config.clone(), name).map_err(|e| tls_error("starting the handshake", e))?;
215    while connection.is_handshaking() {
216        connection.complete_io(&mut tcp).map_err(|e| tls_error("handshake", e))?;
217    }
218    let who = identity(connection.peer_certificates())?;
219    Ok((Secured(StreamOwned::new(connection, tcp)), who))
220}