Skip to main content

trillium_rustls/
client.rs

1use crate::crypto_provider;
2use RustlsClientTransportInner::{Tcp, Tls};
3#[cfg(feature = "dangerous")]
4use futures_rustls::rustls::{
5    DigitallySignedStruct, SignatureScheme,
6    client::danger::{HandshakeSignatureValid, ServerCertVerified},
7    crypto::{verify_tls12_signature, verify_tls13_signature},
8    pki_types::UnixTime,
9};
10use futures_rustls::{
11    TlsConnector,
12    client::TlsStream,
13    rustls::{
14        ClientConfig, ClientConnection, RootCertStore,
15        client::{WebPkiServerVerifier, danger::ServerCertVerifier},
16        crypto::CryptoProvider,
17        pki_types::{CertificateDer, ServerName, pem::PemObject},
18    },
19};
20use std::{
21    fmt::{self, Debug, Formatter},
22    io::{Error, ErrorKind, IoSlice, Result},
23    net::SocketAddr,
24    pin::Pin,
25    sync::Arc,
26    task::{Context, Poll},
27};
28use trillium_server_common::{AsyncRead, AsyncWrite, Connector, Destination, Transport, Url};
29
30/// Rustls [`ClientConfig`] wrapper used by [`RustlsConfig`].
31///
32/// [`RustlsClientConfig::default`] trusts the platform or webpki roots (depending on the
33/// `platform-verifier` feature). Use [`RustlsClientConfig::from_root_cert_pem`] to trust a specific
34/// private or self-signed certificate instead, or convert an existing [`ClientConfig`] via
35/// [`From`].
36#[derive(Clone, Debug)]
37pub struct RustlsClientConfig(Arc<ClientConfig>);
38
39/// Client configuration for RustlsConnector
40#[derive(Clone, Default)]
41pub struct RustlsConfig<Config> {
42    /// configuration for rustls itself
43    pub rustls_config: RustlsClientConfig,
44
45    /// configuration for the inner transport
46    pub tcp_config: Config,
47}
48
49impl<C: Connector> RustlsConfig<C> {
50    /// build a new default rustls config with this tcp config
51    pub fn new(rustls_config: impl Into<RustlsClientConfig>, tcp_config: C) -> Self {
52        Self {
53            rustls_config: rustls_config.into(),
54            tcp_config,
55        }
56    }
57}
58
59impl Default for RustlsClientConfig {
60    /// Verifies servers with
61    /// [`rustls-platform-verifier`](https://docs.rs/rustls-platform-verifier) when the
62    /// `platform-verifier` feature is enabled (the default), and against the
63    /// [WebPKI](https://github.com/rustls/webpki-roots) roots compiled into the binary otherwise.
64    ///
65    /// The platform verifier uses the operating system's verifier and trust store on macOS, iOS,
66    /// Windows, and Android. On Linux and other Unix systems it verifies against the system CA
67    /// bundle — or, when `SSL_CERT_FILE` or `SSL_CERT_DIR` is set, against only the certificates
68    /// those name.
69    ///
70    /// # Panics
71    ///
72    /// With the platform verifier on Linux and other Unix systems, panics if no CA certificates
73    /// can be loaded: no system bundle is installed, or `SSL_CERT_FILE` and `SSL_CERT_DIR` name no
74    /// readable certificates.
75    fn default() -> Self {
76        Self(Arc::new(default_client_config()))
77    }
78}
79
80#[cfg(feature = "platform-verifier")]
81fn verifier(provider: Arc<CryptoProvider>) -> Arc<dyn ServerCertVerifier> {
82    Arc::new(
83        rustls_platform_verifier::Verifier::new(provider).unwrap_or_else(|e| {
84            panic!(
85                "could not build the platform certificate verifier ({e}). If SSL_CERT_FILE or \
86                 SSL_CERT_DIR is set, it must name readable PEM certificates; otherwise install \
87                 the system CA certificates (often the `ca-certificates` package), or disable \
88                 trillium-rustls's `platform-verifier` feature to use the WebPKI roots compiled \
89                 into the binary"
90            )
91        }),
92    )
93}
94
95#[cfg(not(feature = "platform-verifier"))]
96fn verifier(provider: Arc<CryptoProvider>) -> Arc<dyn ServerCertVerifier> {
97    let roots = Arc::new(RootCertStore::from_iter(
98        webpki_roots::TLS_SERVER_ROOTS.iter().cloned(),
99    ));
100    WebPkiServerVerifier::builder_with_provider(roots, provider)
101        .build()
102        .unwrap()
103}
104
105fn client_config_with_verifier(verifier: Arc<dyn ServerCertVerifier>) -> ClientConfig {
106    let mut config = ClientConfig::builder_with_provider(crypto_provider())
107        .with_safe_default_protocol_versions()
108        .expect("crypto provider did not support safe default protocol versions")
109        .dangerous()
110        .with_custom_certificate_verifier(verifier)
111        .with_no_client_auth();
112
113    config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
114
115    config
116}
117
118fn default_client_config() -> ClientConfig {
119    client_config_with_verifier(verifier(crypto_provider()))
120}
121
122impl RustlsClientConfig {
123    /// Build a client configuration that trusts exactly the certificate(s) in `pem`.
124    ///
125    /// Unlike [`RustlsClientConfig::default`], this consults neither the platform trust store nor
126    /// the webpki root bundle — the provided roots are the only trust anchors. Server
127    /// authentication is otherwise unchanged: certificate chains, signatures, expiry, and server
128    /// name are all still verified against these roots. This is the right tool for talking to a
129    /// service that presents a private or self-signed certificate.
130    ///
131    /// The crate's configured crypto provider and default ALPN protocol list (`h2`, `http/1.1`)
132    /// are reused.
133    ///
134    /// # Errors
135    ///
136    /// Returns an error if `pem` contains no certificates or cannot be parsed, or if the resulting
137    /// trust anchors are rejected by the verifier builder.
138    pub fn from_root_cert_pem(pem: &[u8]) -> Result<Self> {
139        let mut roots = RootCertStore::empty();
140        for cert in CertificateDer::pem_slice_iter(pem) {
141            let cert = cert.map_err(|e| Error::new(ErrorKind::InvalidData, e))?;
142            roots.add(cert).map_err(Error::other)?;
143        }
144
145        if roots.is_empty() {
146            return Err(Error::new(
147                ErrorKind::InvalidInput,
148                "no certificates found in pem",
149            ));
150        }
151
152        let verifier =
153            WebPkiServerVerifier::builder_with_provider(Arc::new(roots), crypto_provider())
154                .build()
155                .map_err(Error::other)?;
156
157        Ok(Self(Arc::new(client_config_with_verifier(verifier))))
158    }
159}
160
161impl From<ClientConfig> for RustlsClientConfig {
162    fn from(rustls_config: ClientConfig) -> Self {
163        Self(Arc::new(rustls_config))
164    }
165}
166
167impl From<Arc<ClientConfig>> for RustlsClientConfig {
168    fn from(rustls_config: Arc<ClientConfig>) -> Self {
169        Self(rustls_config)
170    }
171}
172
173#[cfg(feature = "dangerous")]
174#[derive(Debug)]
175struct AcceptAnyServerCert(Arc<CryptoProvider>);
176
177#[cfg(feature = "dangerous")]
178impl ServerCertVerifier for AcceptAnyServerCert {
179    fn verify_server_cert(
180        &self,
181        _end_entity: &CertificateDer<'_>,
182        _intermediates: &[CertificateDer<'_>],
183        _server_name: &ServerName<'_>,
184        _ocsp_response: &[u8],
185        _now: UnixTime,
186    ) -> std::result::Result<ServerCertVerified, futures_rustls::rustls::Error> {
187        Ok(ServerCertVerified::assertion())
188    }
189
190    fn verify_tls12_signature(
191        &self,
192        message: &[u8],
193        cert: &CertificateDer<'_>,
194        dss: &DigitallySignedStruct,
195    ) -> std::result::Result<HandshakeSignatureValid, futures_rustls::rustls::Error> {
196        verify_tls12_signature(
197            message,
198            cert,
199            dss,
200            &self.0.signature_verification_algorithms,
201        )
202    }
203
204    fn verify_tls13_signature(
205        &self,
206        message: &[u8],
207        cert: &CertificateDer<'_>,
208        dss: &DigitallySignedStruct,
209    ) -> std::result::Result<HandshakeSignatureValid, futures_rustls::rustls::Error> {
210        verify_tls13_signature(
211            message,
212            cert,
213            dss,
214            &self.0.signature_verification_algorithms,
215        )
216    }
217
218    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
219        self.0.signature_verification_algorithms.supported_schemes()
220    }
221}
222
223#[cfg(feature = "dangerous")]
224#[cfg_attr(docsrs, doc(cfg(feature = "dangerous")))]
225impl RustlsClientConfig {
226    /// Build a client configuration that accepts **any** server certificate without verification.
227    ///
228    /// ⚠️ This disables server authentication entirely: handshake signatures are still checked,
229    /// but the certificate is never validated against any trust anchor, so the connection is
230    /// vulnerable to man-in-the-middle attacks. It exists for development against throwaway
231    /// self-signed certificates and for `--insecure`-style CLI flags. For talking to a service
232    /// with a known private certificate, prefer [`RustlsClientConfig::from_root_cert_pem`], which
233    /// keeps authentication intact.
234    ///
235    /// This constructor is only available with the `dangerous` crate feature enabled, and logs a
236    /// warning when called.
237    pub fn dangerously_accept_any_cert() -> Self {
238        log::warn!(
239            "constructing a rustls client config that accepts any server certificate; server \
240             authentication is disabled and connections are vulnerable to interception"
241        );
242        let verifier = Arc::new(AcceptAnyServerCert(crypto_provider()));
243        Self(Arc::new(client_config_with_verifier(verifier)))
244    }
245}
246
247impl<C: Connector> RustlsConfig<C> {
248    /// replace the tcp config
249    pub fn with_tcp_config(mut self, config: C) -> Self {
250        self.tcp_config = config;
251        self
252    }
253
254    /// Drop `h2` from the ALPN protocol list, forcing HTTP/1.1 over TLS.
255    ///
256    /// `RustlsConfig::default()` advertises `[h2, http/1.1]` so HTTP/2 is the preferred
257    /// protocol when the server supports it. Call this to opt out and pin the connection to
258    /// HTTP/1.1.
259    #[must_use]
260    pub fn without_http2(mut self) -> Self {
261        let config = Arc::make_mut(&mut self.rustls_config.0);
262        config.alpn_protocols.retain(|p| p != b"h2");
263        self
264    }
265}
266
267impl<Config: Debug> Debug for RustlsConfig<Config> {
268    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
269        f.debug_struct("RustlsConfig")
270            .field("rustls_config", &format_args!(".."))
271            .field("tcp_config", &self.tcp_config)
272            .finish()
273    }
274}
275
276mod connector;
277
278#[derive(Debug)]
279enum RustlsClientTransportInner<T> {
280    Tcp(T),
281    Tls(Box<TlsStream<T>>),
282}
283
284/// Transport for the rustls connector
285///
286/// This may represent either an encrypted tls connection or a plaintext
287/// connection, depending on the request schema
288#[derive(Debug)]
289pub struct RustlsClientTransport<T>(RustlsClientTransportInner<T>);
290impl<T> From<T> for RustlsClientTransport<T> {
291    fn from(value: T) -> Self {
292        Self(Tcp(value))
293    }
294}
295
296impl<T> From<TlsStream<T>> for RustlsClientTransport<T> {
297    fn from(value: TlsStream<T>) -> Self {
298        Self(Tls(Box::new(value)))
299    }
300}
301
302impl<C> AsyncRead for RustlsClientTransport<C>
303where
304    C: AsyncWrite + AsyncRead + Unpin,
305{
306    fn poll_read(
307        mut self: Pin<&mut Self>,
308        cx: &mut Context<'_>,
309        buf: &mut [u8],
310    ) -> Poll<Result<usize>> {
311        match &mut self.0 {
312            Tcp(c) => Pin::new(c).poll_read(cx, buf),
313            Tls(c) => Pin::new(c).poll_read(cx, buf),
314        }
315    }
316
317    fn poll_read_vectored(
318        mut self: Pin<&mut Self>,
319        cx: &mut Context<'_>,
320        bufs: &mut [std::io::IoSliceMut<'_>],
321    ) -> Poll<Result<usize>> {
322        match &mut self.0 {
323            Tcp(c) => Pin::new(c).poll_read_vectored(cx, bufs),
324            Tls(c) => Pin::new(c).poll_read_vectored(cx, bufs),
325        }
326    }
327}
328
329impl<C> AsyncWrite for RustlsClientTransport<C>
330where
331    C: AsyncRead + AsyncWrite + Unpin,
332{
333    fn poll_write(
334        mut self: Pin<&mut Self>,
335        cx: &mut Context<'_>,
336        buf: &[u8],
337    ) -> Poll<Result<usize>> {
338        match &mut self.0 {
339            Tcp(c) => Pin::new(c).poll_write(cx, buf),
340            Tls(c) => Pin::new(&mut *c).poll_write(cx, buf),
341        }
342    }
343
344    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
345        match &mut self.0 {
346            Tcp(c) => Pin::new(c).poll_flush(cx),
347            Tls(c) => Pin::new(&mut *c).poll_flush(cx),
348        }
349    }
350
351    fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
352        match &mut self.0 {
353            Tcp(c) => Pin::new(c).poll_close(cx),
354            Tls(c) => Pin::new(&mut *c).poll_close(cx),
355        }
356    }
357
358    fn poll_write_vectored(
359        mut self: Pin<&mut Self>,
360        cx: &mut Context<'_>,
361        bufs: &[IoSlice<'_>],
362    ) -> Poll<Result<usize>> {
363        match &mut self.0 {
364            Tcp(c) => Pin::new(c).poll_write_vectored(cx, bufs),
365            Tls(c) => Pin::new(&mut *c).poll_write_vectored(cx, bufs),
366        }
367    }
368}
369
370impl<T: Transport> Transport for RustlsClientTransport<T> {
371    fn peer_addr(&self) -> Result<Option<SocketAddr>> {
372        self.as_ref().peer_addr()
373    }
374
375    fn negotiated_alpn(&self) -> Option<std::borrow::Cow<'_, [u8]>> {
376        self.tls_state()
377            .and_then(|conn| conn.alpn_protocol())
378            .map(std::borrow::Cow::Borrowed)
379    }
380}
381
382impl<T> AsRef<T> for RustlsClientTransport<T> {
383    fn as_ref(&self) -> &T {
384        match &self.0 {
385            Tcp(x) => x,
386            Tls(x) => x.get_ref().0,
387        }
388    }
389}
390
391impl<T> RustlsClientTransport<T> {
392    /// Retrieve the tls [`ClientConnection`] if this transport is Tls
393    pub fn tls_state_mut(&mut self) -> Option<&mut ClientConnection> {
394        match &mut self.0 {
395            Tls(x) => Some(x.get_mut().1),
396            _ => None,
397        }
398    }
399
400    /// Retrieve the tls [`ClientConnection`] if this transport is Tls
401    pub fn tls_state(&self) -> Option<&ClientConnection> {
402        match &self.0 {
403            Tls(x) => Some(x.get_ref().1),
404            _ => None,
405        }
406    }
407}