trillium-rustls 0.11.2

rustls adapter for trillium.rs
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
use crate::crypto_provider;
use RustlsClientTransportInner::{Tcp, Tls};
#[cfg(feature = "dangerous")]
use futures_rustls::rustls::{
    DigitallySignedStruct, SignatureScheme,
    client::danger::{HandshakeSignatureValid, ServerCertVerified},
    crypto::{verify_tls12_signature, verify_tls13_signature},
    pki_types::{CertificateDer, UnixTime},
};
use futures_rustls::{
    TlsConnector,
    client::TlsStream,
    rustls::{
        ClientConfig, ClientConnection, RootCertStore,
        client::{WebPkiServerVerifier, danger::ServerCertVerifier},
        crypto::CryptoProvider,
        pki_types::ServerName,
    },
};
use std::{
    fmt::{self, Debug, Formatter},
    io::{Error, ErrorKind, IoSlice, Result},
    net::SocketAddr,
    pin::Pin,
    sync::Arc,
    task::{Context, Poll},
};
use trillium_server_common::{AsyncRead, AsyncWrite, Connector, Transport, Url, url::Host};

/// Rustls [`ClientConfig`] wrapper used by [`RustlsConfig`].
///
/// [`RustlsClientConfig::default`] trusts the platform or webpki roots (depending on the
/// `platform-verifier` feature). Use [`RustlsClientConfig::from_root_cert_pem`] to trust a specific
/// private or self-signed certificate instead, or convert an existing [`ClientConfig`] via
/// [`From`].
#[derive(Clone, Debug)]
pub struct RustlsClientConfig(Arc<ClientConfig>);

/// Client configuration for RustlsConnector
#[derive(Clone, Default)]
pub struct RustlsConfig<Config> {
    /// configuration for rustls itself
    pub rustls_config: RustlsClientConfig,

    /// configuration for the inner transport
    pub tcp_config: Config,
}

impl<C: Connector> RustlsConfig<C> {
    /// build a new default rustls config with this tcp config
    pub fn new(rustls_config: impl Into<RustlsClientConfig>, tcp_config: C) -> Self {
        Self {
            rustls_config: rustls_config.into(),
            tcp_config,
        }
    }
}

impl Default for RustlsClientConfig {
    fn default() -> Self {
        Self(Arc::new(default_client_config()))
    }
}

#[cfg(feature = "platform-verifier")]
fn verifier(provider: Arc<CryptoProvider>) -> Arc<dyn ServerCertVerifier> {
    Arc::new(rustls_platform_verifier::Verifier::new(provider).unwrap())
}

#[cfg(not(feature = "platform-verifier"))]
fn verifier(provider: Arc<CryptoProvider>) -> Arc<dyn ServerCertVerifier> {
    let roots = Arc::new(RootCertStore::from_iter(
        webpki_roots::TLS_SERVER_ROOTS.iter().cloned(),
    ));
    WebPkiServerVerifier::builder_with_provider(roots, provider)
        .build()
        .unwrap()
}

fn client_config_with_verifier(verifier: Arc<dyn ServerCertVerifier>) -> ClientConfig {
    let mut config = ClientConfig::builder_with_provider(crypto_provider())
        .with_safe_default_protocol_versions()
        .expect("crypto provider did not support safe default protocol versions")
        .dangerous()
        .with_custom_certificate_verifier(verifier)
        .with_no_client_auth();

    config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];

    config
}

fn default_client_config() -> ClientConfig {
    client_config_with_verifier(verifier(crypto_provider()))
}

impl RustlsClientConfig {
    /// Build a client configuration that trusts exactly the certificate(s) in `pem`.
    ///
    /// Unlike [`RustlsClientConfig::default`], this consults neither the platform trust store nor
    /// the webpki root bundle — the provided roots are the only trust anchors. Server
    /// authentication is otherwise unchanged: certificate chains, signatures, expiry, and server
    /// name are all still verified against these roots. This is the right tool for talking to a
    /// service that presents a private or self-signed certificate.
    ///
    /// The crate's configured crypto provider and default ALPN protocol list (`h2`, `http/1.1`)
    /// are reused.
    ///
    /// # Errors
    ///
    /// Returns an error if `pem` contains no certificates or cannot be parsed, or if the resulting
    /// trust anchors are rejected by the verifier builder.
    pub fn from_root_cert_pem(pem: &[u8]) -> Result<Self> {
        let mut roots = RootCertStore::empty();
        let mut reader = pem;
        for cert in rustls_pemfile::certs(&mut reader) {
            roots.add(cert?).map_err(Error::other)?;
        }

        if roots.is_empty() {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                "no certificates found in pem",
            ));
        }

        let verifier =
            WebPkiServerVerifier::builder_with_provider(Arc::new(roots), crypto_provider())
                .build()
                .map_err(Error::other)?;

        Ok(Self(Arc::new(client_config_with_verifier(verifier))))
    }
}

impl From<ClientConfig> for RustlsClientConfig {
    fn from(rustls_config: ClientConfig) -> Self {
        Self(Arc::new(rustls_config))
    }
}

impl From<Arc<ClientConfig>> for RustlsClientConfig {
    fn from(rustls_config: Arc<ClientConfig>) -> Self {
        Self(rustls_config)
    }
}

#[cfg(feature = "dangerous")]
#[derive(Debug)]
struct AcceptAnyServerCert(Arc<CryptoProvider>);

#[cfg(feature = "dangerous")]
impl ServerCertVerifier for AcceptAnyServerCert {
    fn verify_server_cert(
        &self,
        _end_entity: &CertificateDer<'_>,
        _intermediates: &[CertificateDer<'_>],
        _server_name: &ServerName<'_>,
        _ocsp_response: &[u8],
        _now: UnixTime,
    ) -> std::result::Result<ServerCertVerified, futures_rustls::rustls::Error> {
        Ok(ServerCertVerified::assertion())
    }

    fn verify_tls12_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> std::result::Result<HandshakeSignatureValid, futures_rustls::rustls::Error> {
        verify_tls12_signature(
            message,
            cert,
            dss,
            &self.0.signature_verification_algorithms,
        )
    }

    fn verify_tls13_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> std::result::Result<HandshakeSignatureValid, futures_rustls::rustls::Error> {
        verify_tls13_signature(
            message,
            cert,
            dss,
            &self.0.signature_verification_algorithms,
        )
    }

    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
        self.0.signature_verification_algorithms.supported_schemes()
    }
}

#[cfg(feature = "dangerous")]
#[cfg_attr(docsrs, doc(cfg(feature = "dangerous")))]
impl RustlsClientConfig {
    /// Build a client configuration that accepts **any** server certificate without verification.
    ///
    /// ⚠️ This disables server authentication entirely: handshake signatures are still checked,
    /// but the certificate is never validated against any trust anchor, so the connection is
    /// vulnerable to man-in-the-middle attacks. It exists for development against throwaway
    /// self-signed certificates and for `--insecure`-style CLI flags. For talking to a service
    /// with a known private certificate, prefer [`RustlsClientConfig::from_root_cert_pem`], which
    /// keeps authentication intact.
    ///
    /// This constructor is only available with the `dangerous` crate feature enabled, and logs a
    /// warning when called.
    pub fn dangerously_accept_any_cert() -> Self {
        log::warn!(
            "constructing a rustls client config that accepts any server certificate; server \
             authentication is disabled and connections are vulnerable to interception"
        );
        let verifier = Arc::new(AcceptAnyServerCert(crypto_provider()));
        Self(Arc::new(client_config_with_verifier(verifier)))
    }
}

impl<C: Connector> RustlsConfig<C> {
    /// replace the tcp config
    pub fn with_tcp_config(mut self, config: C) -> Self {
        self.tcp_config = config;
        self
    }

    /// Drop `h2` from the ALPN protocol list, forcing HTTP/1.1 over TLS.
    ///
    /// `RustlsConfig::default()` advertises `[h2, http/1.1]` so HTTP/2 is the preferred
    /// protocol when the server supports it. Call this to opt out and pin the connection to
    /// HTTP/1.1.
    #[must_use]
    pub fn without_http2(mut self) -> Self {
        let config = Arc::make_mut(&mut self.rustls_config.0);
        config.alpn_protocols.retain(|p| p != b"h2");
        self
    }
}

impl<Config: Debug> Debug for RustlsConfig<Config> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("RustlsConfig")
            .field("rustls_config", &format_args!(".."))
            .field("tcp_config", &self.tcp_config)
            .finish()
    }
}

impl<C: Connector> Connector for RustlsConfig<C> {
    type Runtime = C::Runtime;
    type Transport = RustlsClientTransport<C::Transport>;
    type Udp = C::Udp;

    async fn connect(&self, url: &Url) -> Result<Self::Transport> {
        match url.scheme() {
            "https" => {
                let mut http = url.clone();
                http.set_scheme("http").ok();
                http.set_port(url.port_or_known_default()).ok();

                let connector: TlsConnector = Arc::clone(&self.rustls_config.0).into();
                // Derive the TLS server name from the URL host. A domain becomes a DNS
                // `ServerName` (sent via SNI); an IP literal becomes an `IpAddress` server
                // name (no SNI, validated against the certificate's IP SAN) — `url.domain()`
                // returns `None` for IPs, so matching on `host()` is what lets us connect to
                // an IP address over TLS at all.
                let domain = match url.host() {
                    Some(Host::Domain(domain)) => {
                        ServerName::try_from(domain.to_owned()).map_err(|e| {
                            Error::other(format!("invalid server name {domain:?}: {e}"))
                        })?
                    }
                    Some(Host::Ipv4(ip)) => ServerName::IpAddress(std::net::IpAddr::V4(ip).into()),
                    Some(Host::Ipv6(ip)) => ServerName::IpAddress(std::net::IpAddr::V6(ip).into()),
                    None => return Err(Error::other("url has no host")),
                };

                connector
                    .connect(domain, self.tcp_config.connect(&http).await?)
                    .await
                    .map_err(|e| Error::other(e.to_string()))
                    .map(Into::into)
            }

            "http" => self.tcp_config.connect(url).await.map(Into::into),

            unknown => Err(Error::new(
                ErrorKind::InvalidInput,
                format!("unknown scheme {unknown}"),
            )),
        }
    }

    fn runtime(&self) -> Self::Runtime {
        self.tcp_config.runtime()
    }

    async fn resolve(&self, host: &str, port: u16) -> Result<Vec<SocketAddr>> {
        self.tcp_config.resolve(host, port).await
    }
}

#[derive(Debug)]
enum RustlsClientTransportInner<T> {
    Tcp(T),
    Tls(Box<TlsStream<T>>),
}

/// Transport for the rustls connector
///
/// This may represent either an encrypted tls connection or a plaintext
/// connection, depending on the request schema
#[derive(Debug)]
pub struct RustlsClientTransport<T>(RustlsClientTransportInner<T>);
impl<T> From<T> for RustlsClientTransport<T> {
    fn from(value: T) -> Self {
        Self(Tcp(value))
    }
}

impl<T> From<TlsStream<T>> for RustlsClientTransport<T> {
    fn from(value: TlsStream<T>) -> Self {
        Self(Tls(Box::new(value)))
    }
}

impl<C> AsyncRead for RustlsClientTransport<C>
where
    C: AsyncWrite + AsyncRead + Unpin,
{
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<Result<usize>> {
        match &mut self.0 {
            Tcp(c) => Pin::new(c).poll_read(cx, buf),
            Tls(c) => Pin::new(c).poll_read(cx, buf),
        }
    }

    fn poll_read_vectored(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        bufs: &mut [std::io::IoSliceMut<'_>],
    ) -> Poll<Result<usize>> {
        match &mut self.0 {
            Tcp(c) => Pin::new(c).poll_read_vectored(cx, bufs),
            Tls(c) => Pin::new(c).poll_read_vectored(cx, bufs),
        }
    }
}

impl<C> AsyncWrite for RustlsClientTransport<C>
where
    C: AsyncRead + AsyncWrite + Unpin,
{
    fn poll_write(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<Result<usize>> {
        match &mut self.0 {
            Tcp(c) => Pin::new(c).poll_write(cx, buf),
            Tls(c) => Pin::new(&mut *c).poll_write(cx, buf),
        }
    }

    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
        match &mut self.0 {
            Tcp(c) => Pin::new(c).poll_flush(cx),
            Tls(c) => Pin::new(&mut *c).poll_flush(cx),
        }
    }

    fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
        match &mut self.0 {
            Tcp(c) => Pin::new(c).poll_close(cx),
            Tls(c) => Pin::new(&mut *c).poll_close(cx),
        }
    }

    fn poll_write_vectored(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        bufs: &[IoSlice<'_>],
    ) -> Poll<Result<usize>> {
        match &mut self.0 {
            Tcp(c) => Pin::new(c).poll_write_vectored(cx, bufs),
            Tls(c) => Pin::new(&mut *c).poll_write_vectored(cx, bufs),
        }
    }
}

impl<T: Transport> Transport for RustlsClientTransport<T> {
    fn peer_addr(&self) -> Result<Option<SocketAddr>> {
        self.as_ref().peer_addr()
    }

    fn negotiated_alpn(&self) -> Option<std::borrow::Cow<'_, [u8]>> {
        self.tls_state()
            .and_then(|conn| conn.alpn_protocol())
            .map(std::borrow::Cow::Borrowed)
    }
}

impl<T> AsRef<T> for RustlsClientTransport<T> {
    fn as_ref(&self) -> &T {
        match &self.0 {
            Tcp(x) => x,
            Tls(x) => x.get_ref().0,
        }
    }
}

impl<T> RustlsClientTransport<T> {
    /// Retrieve the tls [`ClientConnection`] if this transport is Tls
    pub fn tls_state_mut(&mut self) -> Option<&mut ClientConnection> {
        match &mut self.0 {
            Tls(x) => Some(x.get_mut().1),
            _ => None,
        }
    }

    /// Retrieve the tls [`ClientConnection`] if this transport is Tls
    pub fn tls_state(&self) -> Option<&ClientConnection> {
        match &self.0 {
            Tls(x) => Some(x.get_ref().1),
            _ => None,
        }
    }
}