Skip to main content

turnloop_tls/
lib.rs

1//! TLS record processing with caller-owned encrypted buffers and caller-supplied time.
2//!
3//! Handle every returned rustls state before calling `process` again, discard
4//! `status.discard` input bytes only after handling it, and acknowledge
5//! `TransmitTlsData` only after the host has completed all writes. Plaintext
6//! records borrow rustls storage; consume them before advancing the state.
7//!
8//! # Configuration
9//! [`ClientConfig::new`] and [`ServerConfig::new`] cover static TLS: roots or a
10//! certificate chain, a key and ALPN. A host that needs a rustls decision those
11//! constructors do not expose (client certificates, SNI resolvers, custom
12//! verifiers, ticketers, protocol versions) builds the rustls config itself and
13//! wraps it with [`ClientConfig::from_rustls`] / [`ServerConfig::from_rustls`],
14//! passing [`HostTime::time_provider`] to `builder_with_details` so certificate
15//! validity keeps following the time handed to `process`.
16//!
17//! # Crypto provider
18//! The default `ring` feature makes `ring` the provider `new` uses when the host
19//! names none. [`ClientOptions::provider`] and [`ServerConfig::with_provider`]
20//! select any other rustls [`CryptoProvider`],
21//! such as aws-lc-rs. With `default-features = false` this crate links no
22//! provider of its own: `new` then uses the one the host passes, or the
23//! process-default provider installed with rustls, and fails if there is neither.
24//! Without `ring`, `tls_server_end_point` is unavailable; hash the certificate
25//! with the algorithm [`tls_server_end_point_hash`] selects instead.
26//!
27//! # Getting started on turnloop
28//! Enable the `turnloop` feature for the `asynchronous` module. The embedding
29//! host owns `LocalExecutor` and calls `turn`; adapters await its streams and
30//! deadline futures. See the crate README and turnloop-io for ownership, streaming
31//! and cancellation examples. Default features retain the sans-I/O API.
32#![deny(unsafe_op_in_unsafe_fn)]
33
34use rustls::{
35    CertificateError, DigitallySignedStruct, Error, SignatureScheme,
36    client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier},
37    crypto::CryptoProvider,
38    pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime, pem::PemObject},
39};
40use std::{
41    sync::{
42        Arc,
43        atomic::{AtomicU64, Ordering},
44    },
45    time::{Duration, Instant},
46};
47
48pub use rustls;
49pub use rustls::unbuffered::{ConnectionState, UnbufferedStatus};
50
51/// Wall time supplied by the host, never sampled from an operating-system clock.
52#[derive(Debug)]
53struct SuppliedTime(AtomicU64);
54
55/// A shared wall clock that only the host advances.
56///
57/// Every connection made from a configuration stores the `unix_seconds` passed to
58/// its `process` call here, and rustls reads it back through
59/// [`time_provider`](Self::time_provider) when checking certificate validity.
60/// Pass that provider to `rustls::ClientConfig::builder_with_details` (or the
61/// server equivalent) before handing the result to `from_rustls`.
62#[derive(Debug, Clone)]
63pub struct HostTime(Arc<SuppliedTime>);
64impl HostTime {
65    pub fn new(unix_seconds: u64) -> Self {
66        Self(Arc::new(SuppliedTime(AtomicU64::new(unix_seconds))))
67    }
68    pub fn set(&self, unix_seconds: u64) {
69        self.0.0.store(unix_seconds, Ordering::Relaxed);
70    }
71    pub fn unix_seconds(&self) -> u64 {
72        self.0.0.load(Ordering::Relaxed)
73    }
74    /// The rustls time provider backed by this clock.
75    pub fn time_provider(&self) -> Arc<dyn rustls::time_provider::TimeProvider> {
76        self.0.clone()
77    }
78}
79
80/// The provider `new` uses when the host names none: `ring` when that feature is
81/// enabled, otherwise the rustls process default.
82fn default_provider() -> Result<Arc<CryptoProvider>, Error> {
83    #[cfg(feature = "ring")]
84    {
85        Ok(Arc::new(rustls::crypto::ring::default_provider()))
86    }
87    #[cfg(not(feature = "ring"))]
88    {
89        CryptoProvider::get_default().cloned().ok_or_else(|| {
90            Error::General(
91                "no rustls crypto provider: pass one or install a process default".into(),
92            )
93        })
94    }
95}
96impl rustls::time_provider::TimeProvider for SuppliedTime {
97    fn current_time(&self) -> Option<UnixTime> {
98        Some(UnixTime::since_unix_epoch(Duration::from_secs(
99            self.0.load(Ordering::Relaxed),
100        )))
101    }
102}
103
104/// Node's explicit `ca` replaces default roots. Extra CA PEM augments Mozilla
105/// roots only when explicit CA is absent. The host reads NODE_EXTRA_CA_CERTS
106/// once at startup and supplies its contents; this crate never reads files/env.
107#[derive(Debug, Clone)]
108pub struct ClientOptions {
109    pub alpn: Vec<Vec<u8>>,
110    pub ca: Option<Vec<CertificateDer<'static>>>,
111    pub extra_ca_pem: Vec<u8>,
112    pub reject_unauthorized: bool,
113    pub enable_sni: bool,
114    /// The rustls crypto provider for handshakes and signature checks. `None`
115    /// uses `ring` with the default `ring` feature, otherwise the process-default
116    /// provider. Naming one lets a host link exactly one provider.
117    pub provider: Option<Arc<CryptoProvider>>,
118}
119impl Default for ClientOptions {
120    fn default() -> Self {
121        Self {
122            alpn: vec![b"http/1.1".to_vec()],
123            ca: None,
124            extra_ca_pem: Vec::new(),
125            reject_unauthorized: true,
126            enable_sni: true,
127            provider: None,
128        }
129    }
130}
131
132#[derive(Clone)]
133pub struct ClientConfig {
134    config: Arc<rustls::ClientConfig>,
135    time: HostTime,
136}
137impl ClientConfig {
138    pub fn new(options: ClientOptions, unix_seconds: u64) -> Result<Self, Error> {
139        let provider = match options.provider {
140            Some(provider) => provider,
141            None => default_provider()?,
142        };
143        let time = HostTime::new(unix_seconds);
144        let mut roots = rustls::RootCertStore::empty();
145        if let Some(ca) = options.ca {
146            for cert in ca {
147                roots.add(cert)?;
148            }
149        } else {
150            roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
151            for cert in CertificateDer::pem_slice_iter(&options.extra_ca_pem) {
152                roots.add(cert.map_err(|e| Error::General(e.to_string()))?)?;
153            }
154        }
155        let mut config =
156            rustls::ClientConfig::builder_with_details(provider.clone(), time.time_provider())
157                .with_safe_default_protocol_versions()?
158                .with_root_certificates(roots)
159                .with_no_client_auth();
160        if !options.reject_unauthorized {
161            config
162                .dangerous()
163                .set_certificate_verifier(Arc::new(Unverified { provider }));
164        }
165        config.alpn_protocols = options.alpn;
166        config.enable_sni = options.enable_sni;
167        Ok(Self::from_rustls(Arc::new(config), time))
168    }
169    /// Wrap a rustls configuration the host built itself. Build it with
170    /// `builder_with_details(provider, time.time_provider())` so certificate
171    /// validity follows the time passed to `process`; with any other time
172    /// provider rustls keeps using that one, and `process` only updates `time`.
173    pub fn from_rustls(config: Arc<rustls::ClientConfig>, time: HostTime) -> Self {
174        Self { config, time }
175    }
176    pub fn rustls_config(&self) -> &Arc<rustls::ClientConfig> {
177        &self.config
178    }
179    /// The same roots, verifier and host time, offering `alpn` instead. A hop
180    /// that only speaks one protocol (an HTTP/1.1 proxy) must not let the peer
181    /// pick another; the copy has its own session cache.
182    pub fn with_alpn(&self, alpn: Vec<Vec<u8>>) -> Self {
183        let mut config = (*self.config).clone();
184        config.alpn_protocols = alpn;
185        Self::from_rustls(Arc::new(config), self.time.clone())
186    }
187    /// Reuse this configuration across connections to share the session cache.
188    pub fn connect(&self, name: ServerName<'static>) -> Result<Client, Error> {
189        Ok(Client {
190            inner: rustls::client::UnbufferedClientConnection::new(self.config.clone(), name)?,
191            time: self.time.clone(),
192            deadline: None,
193            timed_out: false,
194        })
195    }
196}
197
198#[derive(Clone)]
199pub struct ServerConfig {
200    config: Arc<rustls::ServerConfig>,
201    time: HostTime,
202}
203impl ServerConfig {
204    /// Uses `ring` with the default `ring` feature, otherwise the process-default
205    /// provider; see [`with_provider`](Self::with_provider).
206    pub fn new(
207        chain: Vec<CertificateDer<'static>>,
208        key: PrivateKeyDer<'static>,
209        alpn: Vec<Vec<u8>>,
210        unix_seconds: u64,
211    ) -> Result<Self, Error> {
212        Self::with_provider(default_provider()?, chain, key, alpn, unix_seconds)
213    }
214    /// [`new`](Self::new) with an explicit rustls crypto provider.
215    pub fn with_provider(
216        provider: Arc<CryptoProvider>,
217        chain: Vec<CertificateDer<'static>>,
218        key: PrivateKeyDer<'static>,
219        alpn: Vec<Vec<u8>>,
220        unix_seconds: u64,
221    ) -> Result<Self, Error> {
222        let time = HostTime::new(unix_seconds);
223        let mut config = rustls::ServerConfig::builder_with_details(provider, time.time_provider())
224            .with_safe_default_protocol_versions()?
225            .with_no_client_auth()
226            .with_single_cert(chain, key)?;
227        config.alpn_protocols = alpn;
228        // Rustls's default stateful session cache avoids a clock-reading ticketer.
229        Ok(Self::from_rustls(Arc::new(config), time))
230    }
231    /// Wrap a rustls configuration the host built itself; see
232    /// [`ClientConfig::from_rustls`] for how `time` reaches certificate checks.
233    /// A ticketer the host configures may read its own clock.
234    pub fn from_rustls(config: Arc<rustls::ServerConfig>, time: HostTime) -> Self {
235        Self { config, time }
236    }
237    pub fn rustls_config(&self) -> &Arc<rustls::ServerConfig> {
238        &self.config
239    }
240    pub fn accept(&self) -> Result<Server, Error> {
241        Ok(Server {
242            inner: rustls::server::UnbufferedServerConnection::new(self.config.clone())?,
243            time: self.time.clone(),
244            deadline: None,
245            timed_out: false,
246        })
247    }
248}
249
250mod channel_binding;
251#[cfg(feature = "ring")]
252pub use channel_binding::tls_server_end_point;
253pub use channel_binding::{EndPointHash, tls_server_end_point_hash};
254
255macro_rules! endpoint {
256    ($name:ident, $connection:ty, $data:ty) => {
257        pub struct $name {
258            inner: $connection,
259            time: HostTime,
260            deadline: Option<Instant>,
261            timed_out: bool,
262        }
263        impl $name {
264            /// No input/output staging copies are introduced by this wrapper.
265            pub fn process<'c, 'i>(
266                &'c mut self,
267                incoming: &'i mut [u8],
268                unix_seconds: u64,
269            ) -> UnbufferedStatus<'c, 'i, $data> {
270                self.time.set(unix_seconds);
271                if self.timed_out {
272                    return UnbufferedStatus {
273                        discard: 0,
274                        state: Err(Error::General("TLS handshake timeout".into())),
275                    };
276                }
277                self.inner.process_tls_records(incoming)
278            }
279            pub fn alpn_protocol(&self) -> Option<&[u8]> {
280                self.inner.alpn_protocol()
281            }
282            /// Peer chain, leaf first. Verification follows the configured verifier;
283            /// consume it only after a successful handshake.
284            pub fn peer_certificates(
285                &self,
286            ) -> Option<&[rustls::pki_types::CertificateDer<'static>]> {
287                self.inner.peer_certificates()
288            }
289            pub fn is_handshaking(&self) -> bool {
290                self.inner.is_handshaking()
291            }
292            pub fn handshake_kind(&self) -> Option<rustls::HandshakeKind> {
293                self.inner.handshake_kind()
294            }
295            pub fn set_handshake_deadline(&mut self, deadline: Option<Instant>) {
296                self.deadline = deadline;
297            }
298            pub fn next_timeout(&self) -> Option<Instant> {
299                if self.inner.is_handshaking() && !self.timed_out {
300                    self.deadline
301                } else {
302                    None
303                }
304            }
305            /// Returns a terminal timeout event exactly once.
306            pub fn handle_timeout(&mut self, now: Instant) -> Option<&'static str> {
307                if self.next_timeout().is_some_and(|d| now >= d) {
308                    self.timed_out = true;
309                    self.deadline = None;
310                    Some("ERR_TLS_HANDSHAKE_TIMEOUT")
311                } else {
312                    None
313                }
314            }
315        }
316    };
317}
318endpoint!(
319    Client,
320    rustls::client::UnbufferedClientConnection,
321    rustls::client::ClientConnectionData
322);
323endpoint!(
324    Server,
325    rustls::server::UnbufferedServerConnection,
326    rustls::server::ServerConnectionData
327);
328
329/// Stable Node-style cause code. Rustls cannot distinguish a missing intermediate
330/// from an untrusted root; both map to UNABLE_TO_VERIFY_LEAF_SIGNATURE.
331pub fn node_error_code(error: &Error) -> &'static str {
332    match error {
333        Error::InvalidCertificate(
334            CertificateError::Expired | CertificateError::ExpiredContext { .. },
335        ) => "CERT_HAS_EXPIRED",
336        Error::InvalidCertificate(
337            CertificateError::NotValidYet | CertificateError::NotValidYetContext { .. },
338        ) => "CERT_NOT_YET_VALID",
339        Error::InvalidCertificate(
340            CertificateError::NotValidForName | CertificateError::NotValidForNameContext { .. },
341        ) => "ERR_TLS_CERT_ALTNAME_INVALID",
342        Error::InvalidCertificate(CertificateError::UnknownIssuer) => {
343            "UNABLE_TO_VERIFY_LEAF_SIGNATURE"
344        }
345        Error::InvalidCertificate(CertificateError::Revoked) => "CERT_REVOKED",
346        Error::NoApplicationProtocol => "ERR_SSL_TLSV1_ALERT_NO_APPLICATION_PROTOCOL",
347        _ => "ERR_SSL_PROTOCOL_ERROR",
348    }
349}
350
351#[derive(Debug)]
352struct Unverified {
353    provider: Arc<CryptoProvider>,
354}
355impl ServerCertVerifier for Unverified {
356    fn verify_server_cert(
357        &self,
358        _: &CertificateDer<'_>,
359        _: &[CertificateDer<'_>],
360        _: &ServerName<'_>,
361        _: &[u8],
362        _: UnixTime,
363    ) -> Result<ServerCertVerified, Error> {
364        Ok(ServerCertVerified::assertion())
365    }
366    // rejectUnauthorized disables trust/name validation, not proof of possession.
367    fn verify_tls12_signature(
368        &self,
369        message: &[u8],
370        cert: &CertificateDer<'_>,
371        dss: &DigitallySignedStruct,
372    ) -> Result<HandshakeSignatureValid, Error> {
373        rustls::crypto::verify_tls12_signature(
374            message,
375            cert,
376            dss,
377            &self.provider.signature_verification_algorithms,
378        )
379    }
380    fn verify_tls13_signature(
381        &self,
382        message: &[u8],
383        cert: &CertificateDer<'_>,
384        dss: &DigitallySignedStruct,
385    ) -> Result<HandshakeSignatureValid, Error> {
386        rustls::crypto::verify_tls13_signature(
387            message,
388            cert,
389            dss,
390            &self.provider.signature_verification_algorithms,
391        )
392    }
393    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
394        self.provider
395            .signature_verification_algorithms
396            .supported_schemes()
397    }
398}
399
400#[cfg(feature = "turnloop")]
401pub mod asynchronous;
402#[cfg(feature = "turnloop")]
403pub use asynchronous::TlsStream;