turnloop-tls 0.1.0-beta.2

Unbuffered sans-I/O TLS with host-supplied time
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! TLS record processing with caller-owned encrypted buffers and caller-supplied time.
//!
//! Handle every returned rustls state before calling `process` again, discard
//! `status.discard` input bytes only after handling it, and acknowledge
//! `TransmitTlsData` only after the host has completed all writes. Plaintext
//! records borrow rustls storage; consume them before advancing the state.
//!
//! # Configuration
//! [`ClientConfig::new`] and [`ServerConfig::new`] cover static TLS: roots or a
//! certificate chain, a key and ALPN. A host that needs a rustls decision those
//! constructors do not expose (client certificates, SNI resolvers, custom
//! verifiers, ticketers, protocol versions) builds the rustls config itself and
//! wraps it with [`ClientConfig::from_rustls`] / [`ServerConfig::from_rustls`],
//! passing [`HostTime::time_provider`] to `builder_with_details` so certificate
//! validity keeps following the time handed to `process`.
//!
//! # Crypto provider
//! The default `ring` feature makes `ring` the provider `new` uses when the host
//! names none. [`ClientOptions::provider`] and [`ServerConfig::with_provider`]
//! select any other rustls [`CryptoProvider`],
//! such as aws-lc-rs. With `default-features = false` this crate links no
//! provider of its own: `new` then uses the one the host passes, or the
//! process-default provider installed with rustls, and fails if there is neither.
//! Without `ring`, `tls_server_end_point` is unavailable; hash the certificate
//! with the algorithm [`tls_server_end_point_hash`] selects instead.
//!
//! # Getting started on turnloop
//! Enable the `turnloop` feature for the `asynchronous` module. The embedding
//! host owns `LocalExecutor` and calls `turn`; adapters await its streams and
//! deadline futures. See the crate README and turnloop-io for ownership, streaming
//! and cancellation examples. Default features retain the sans-I/O API.
#![deny(unsafe_op_in_unsafe_fn)]

use rustls::{
    CertificateError, DigitallySignedStruct, Error, SignatureScheme,
    client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier},
    crypto::CryptoProvider,
    pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime, pem::PemObject},
};
use std::{
    sync::{
        Arc,
        atomic::{AtomicU64, Ordering},
    },
    time::{Duration, Instant},
};

pub use rustls;
pub use rustls::unbuffered::{ConnectionState, UnbufferedStatus};

/// Wall time supplied by the host, never sampled from an operating-system clock.
#[derive(Debug)]
struct SuppliedTime(AtomicU64);

/// A shared wall clock that only the host advances.
///
/// Every connection made from a configuration stores the `unix_seconds` passed to
/// its `process` call here, and rustls reads it back through
/// [`time_provider`](Self::time_provider) when checking certificate validity.
/// Pass that provider to `rustls::ClientConfig::builder_with_details` (or the
/// server equivalent) before handing the result to `from_rustls`.
#[derive(Debug, Clone)]
pub struct HostTime(Arc<SuppliedTime>);
impl HostTime {
    pub fn new(unix_seconds: u64) -> Self {
        Self(Arc::new(SuppliedTime(AtomicU64::new(unix_seconds))))
    }
    pub fn set(&self, unix_seconds: u64) {
        self.0.0.store(unix_seconds, Ordering::Relaxed);
    }
    pub fn unix_seconds(&self) -> u64 {
        self.0.0.load(Ordering::Relaxed)
    }
    /// The rustls time provider backed by this clock.
    pub fn time_provider(&self) -> Arc<dyn rustls::time_provider::TimeProvider> {
        self.0.clone()
    }
}

/// The provider `new` uses when the host names none: `ring` when that feature is
/// enabled, otherwise the rustls process default.
fn default_provider() -> Result<Arc<CryptoProvider>, Error> {
    #[cfg(feature = "ring")]
    {
        Ok(Arc::new(rustls::crypto::ring::default_provider()))
    }
    #[cfg(not(feature = "ring"))]
    {
        CryptoProvider::get_default().cloned().ok_or_else(|| {
            Error::General(
                "no rustls crypto provider: pass one or install a process default".into(),
            )
        })
    }
}
impl rustls::time_provider::TimeProvider for SuppliedTime {
    fn current_time(&self) -> Option<UnixTime> {
        Some(UnixTime::since_unix_epoch(Duration::from_secs(
            self.0.load(Ordering::Relaxed),
        )))
    }
}

/// Node's explicit `ca` replaces default roots. Extra CA PEM augments Mozilla
/// roots only when explicit CA is absent. The host reads NODE_EXTRA_CA_CERTS
/// once at startup and supplies its contents; this crate never reads files/env.
#[derive(Debug, Clone)]
pub struct ClientOptions {
    pub alpn: Vec<Vec<u8>>,
    pub ca: Option<Vec<CertificateDer<'static>>>,
    pub extra_ca_pem: Vec<u8>,
    pub reject_unauthorized: bool,
    pub enable_sni: bool,
    /// The rustls crypto provider for handshakes and signature checks. `None`
    /// uses `ring` with the default `ring` feature, otherwise the process-default
    /// provider. Naming one lets a host link exactly one provider.
    pub provider: Option<Arc<CryptoProvider>>,
}
impl Default for ClientOptions {
    fn default() -> Self {
        Self {
            alpn: vec![b"http/1.1".to_vec()],
            ca: None,
            extra_ca_pem: Vec::new(),
            reject_unauthorized: true,
            enable_sni: true,
            provider: None,
        }
    }
}

#[derive(Clone)]
pub struct ClientConfig {
    config: Arc<rustls::ClientConfig>,
    time: HostTime,
}
impl ClientConfig {
    pub fn new(options: ClientOptions, unix_seconds: u64) -> Result<Self, Error> {
        let provider = match options.provider {
            Some(provider) => provider,
            None => default_provider()?,
        };
        let time = HostTime::new(unix_seconds);
        let mut roots = rustls::RootCertStore::empty();
        if let Some(ca) = options.ca {
            for cert in ca {
                roots.add(cert)?;
            }
        } else {
            roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
            for cert in CertificateDer::pem_slice_iter(&options.extra_ca_pem) {
                roots.add(cert.map_err(|e| Error::General(e.to_string()))?)?;
            }
        }
        let mut config =
            rustls::ClientConfig::builder_with_details(provider.clone(), time.time_provider())
                .with_safe_default_protocol_versions()?
                .with_root_certificates(roots)
                .with_no_client_auth();
        if !options.reject_unauthorized {
            config
                .dangerous()
                .set_certificate_verifier(Arc::new(Unverified { provider }));
        }
        config.alpn_protocols = options.alpn;
        config.enable_sni = options.enable_sni;
        Ok(Self::from_rustls(Arc::new(config), time))
    }
    /// Wrap a rustls configuration the host built itself. Build it with
    /// `builder_with_details(provider, time.time_provider())` so certificate
    /// validity follows the time passed to `process`; with any other time
    /// provider rustls keeps using that one, and `process` only updates `time`.
    pub fn from_rustls(config: Arc<rustls::ClientConfig>, time: HostTime) -> Self {
        Self { config, time }
    }
    pub fn rustls_config(&self) -> &Arc<rustls::ClientConfig> {
        &self.config
    }
    /// The same roots, verifier and host time, offering `alpn` instead. A hop
    /// that only speaks one protocol (an HTTP/1.1 proxy) must not let the peer
    /// pick another; the copy has its own session cache.
    pub fn with_alpn(&self, alpn: Vec<Vec<u8>>) -> Self {
        let mut config = (*self.config).clone();
        config.alpn_protocols = alpn;
        Self::from_rustls(Arc::new(config), self.time.clone())
    }
    /// Reuse this configuration across connections to share the session cache.
    pub fn connect(&self, name: ServerName<'static>) -> Result<Client, Error> {
        Ok(Client {
            inner: rustls::client::UnbufferedClientConnection::new(self.config.clone(), name)?,
            time: self.time.clone(),
            deadline: None,
            timed_out: false,
        })
    }
}

#[derive(Clone)]
pub struct ServerConfig {
    config: Arc<rustls::ServerConfig>,
    time: HostTime,
}
impl ServerConfig {
    /// Uses `ring` with the default `ring` feature, otherwise the process-default
    /// provider; see [`with_provider`](Self::with_provider).
    pub fn new(
        chain: Vec<CertificateDer<'static>>,
        key: PrivateKeyDer<'static>,
        alpn: Vec<Vec<u8>>,
        unix_seconds: u64,
    ) -> Result<Self, Error> {
        Self::with_provider(default_provider()?, chain, key, alpn, unix_seconds)
    }
    /// [`new`](Self::new) with an explicit rustls crypto provider.
    pub fn with_provider(
        provider: Arc<CryptoProvider>,
        chain: Vec<CertificateDer<'static>>,
        key: PrivateKeyDer<'static>,
        alpn: Vec<Vec<u8>>,
        unix_seconds: u64,
    ) -> Result<Self, Error> {
        let time = HostTime::new(unix_seconds);
        let mut config = rustls::ServerConfig::builder_with_details(provider, time.time_provider())
            .with_safe_default_protocol_versions()?
            .with_no_client_auth()
            .with_single_cert(chain, key)?;
        config.alpn_protocols = alpn;
        // Rustls's default stateful session cache avoids a clock-reading ticketer.
        Ok(Self::from_rustls(Arc::new(config), time))
    }
    /// Wrap a rustls configuration the host built itself; see
    /// [`ClientConfig::from_rustls`] for how `time` reaches certificate checks.
    /// A ticketer the host configures may read its own clock.
    pub fn from_rustls(config: Arc<rustls::ServerConfig>, time: HostTime) -> Self {
        Self { config, time }
    }
    pub fn rustls_config(&self) -> &Arc<rustls::ServerConfig> {
        &self.config
    }
    pub fn accept(&self) -> Result<Server, Error> {
        Ok(Server {
            inner: rustls::server::UnbufferedServerConnection::new(self.config.clone())?,
            time: self.time.clone(),
            deadline: None,
            timed_out: false,
        })
    }
}

mod channel_binding;
#[cfg(feature = "ring")]
pub use channel_binding::tls_server_end_point;
pub use channel_binding::{EndPointHash, tls_server_end_point_hash};

macro_rules! endpoint {
    ($name:ident, $connection:ty, $data:ty) => {
        pub struct $name {
            inner: $connection,
            time: HostTime,
            deadline: Option<Instant>,
            timed_out: bool,
        }
        impl $name {
            /// No input/output staging copies are introduced by this wrapper.
            pub fn process<'c, 'i>(
                &'c mut self,
                incoming: &'i mut [u8],
                unix_seconds: u64,
            ) -> UnbufferedStatus<'c, 'i, $data> {
                self.time.set(unix_seconds);
                if self.timed_out {
                    return UnbufferedStatus {
                        discard: 0,
                        state: Err(Error::General("TLS handshake timeout".into())),
                    };
                }
                self.inner.process_tls_records(incoming)
            }
            pub fn alpn_protocol(&self) -> Option<&[u8]> {
                self.inner.alpn_protocol()
            }
            /// Peer chain, leaf first. Verification follows the configured verifier;
            /// consume it only after a successful handshake.
            pub fn peer_certificates(
                &self,
            ) -> Option<&[rustls::pki_types::CertificateDer<'static>]> {
                self.inner.peer_certificates()
            }
            pub fn is_handshaking(&self) -> bool {
                self.inner.is_handshaking()
            }
            pub fn handshake_kind(&self) -> Option<rustls::HandshakeKind> {
                self.inner.handshake_kind()
            }
            pub fn set_handshake_deadline(&mut self, deadline: Option<Instant>) {
                self.deadline = deadline;
            }
            pub fn next_timeout(&self) -> Option<Instant> {
                if self.inner.is_handshaking() && !self.timed_out {
                    self.deadline
                } else {
                    None
                }
            }
            /// Returns a terminal timeout event exactly once.
            pub fn handle_timeout(&mut self, now: Instant) -> Option<&'static str> {
                if self.next_timeout().is_some_and(|d| now >= d) {
                    self.timed_out = true;
                    self.deadline = None;
                    Some("ERR_TLS_HANDSHAKE_TIMEOUT")
                } else {
                    None
                }
            }
        }
    };
}
endpoint!(
    Client,
    rustls::client::UnbufferedClientConnection,
    rustls::client::ClientConnectionData
);
endpoint!(
    Server,
    rustls::server::UnbufferedServerConnection,
    rustls::server::ServerConnectionData
);

/// Stable Node-style cause code. Rustls cannot distinguish a missing intermediate
/// from an untrusted root; both map to UNABLE_TO_VERIFY_LEAF_SIGNATURE.
pub fn node_error_code(error: &Error) -> &'static str {
    match error {
        Error::InvalidCertificate(
            CertificateError::Expired | CertificateError::ExpiredContext { .. },
        ) => "CERT_HAS_EXPIRED",
        Error::InvalidCertificate(
            CertificateError::NotValidYet | CertificateError::NotValidYetContext { .. },
        ) => "CERT_NOT_YET_VALID",
        Error::InvalidCertificate(
            CertificateError::NotValidForName | CertificateError::NotValidForNameContext { .. },
        ) => "ERR_TLS_CERT_ALTNAME_INVALID",
        Error::InvalidCertificate(CertificateError::UnknownIssuer) => {
            "UNABLE_TO_VERIFY_LEAF_SIGNATURE"
        }
        Error::InvalidCertificate(CertificateError::Revoked) => "CERT_REVOKED",
        Error::NoApplicationProtocol => "ERR_SSL_TLSV1_ALERT_NO_APPLICATION_PROTOCOL",
        _ => "ERR_SSL_PROTOCOL_ERROR",
    }
}

#[derive(Debug)]
struct Unverified {
    provider: Arc<CryptoProvider>,
}
impl ServerCertVerifier for Unverified {
    fn verify_server_cert(
        &self,
        _: &CertificateDer<'_>,
        _: &[CertificateDer<'_>],
        _: &ServerName<'_>,
        _: &[u8],
        _: UnixTime,
    ) -> Result<ServerCertVerified, Error> {
        Ok(ServerCertVerified::assertion())
    }
    // rejectUnauthorized disables trust/name validation, not proof of possession.
    fn verify_tls12_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, Error> {
        rustls::crypto::verify_tls12_signature(
            message,
            cert,
            dss,
            &self.provider.signature_verification_algorithms,
        )
    }
    fn verify_tls13_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, Error> {
        rustls::crypto::verify_tls13_signature(
            message,
            cert,
            dss,
            &self.provider.signature_verification_algorithms,
        )
    }
    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
        self.provider
            .signature_verification_algorithms
            .supported_schemes()
    }
}

#[cfg(feature = "turnloop")]
pub mod asynchronous;
#[cfg(feature = "turnloop")]
pub use asynchronous::TlsStream;