Skip to main content

ldap_client/
tls_config.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Convenience types for building a [`rustls::ClientConfig`] without
4//! touching Rustls directly.
5
6use std::sync::Arc;
7
8use rustls::client::WantsClientCert;
9use rustls::{ClientConfig, ConfigBuilder, RootCertStore};
10use rustls_pki_types::{CertificateDer, PrivateKeyDer};
11
12/// Where to source trust anchors (root CA certificates).
13#[non_exhaustive]
14pub enum TrustAnchors {
15    /// Use the system/Mozilla roots **plus** any additional certs provided.
16    SystemPlusAdditional(Vec<CertificateDer<'static>>),
17    /// Trust **only** the supplied certificates (no system roots).
18    ExplicitOnly(Vec<CertificateDer<'static>>),
19}
20
21/// Minimum TLS version to accept.
22#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
23pub enum TlsVersion {
24    /// TLS 1.2
25    #[default]
26    Tls12,
27    /// TLS 1.3
28    Tls13,
29}
30
31/// High-level TLS configuration that can be converted into a
32/// [`rustls::ClientConfig`] via [`build`](Self::build).
33#[non_exhaustive]
34pub struct TlsConfig {
35    trust_anchors: TrustAnchors,
36    client_cert: Option<(Vec<CertificateDer<'static>>, PrivateKeyDer<'static>)>,
37    min_tls_version: TlsVersion,
38    #[cfg(feature = "danger-disable-verify")]
39    danger_disable_verification: bool,
40}
41
42impl Default for TlsConfig {
43    fn default() -> Self {
44        Self {
45            trust_anchors: TrustAnchors::SystemPlusAdditional(Vec::new()),
46            client_cert: None,
47            min_tls_version: TlsVersion::default(),
48            #[cfg(feature = "danger-disable-verify")]
49            danger_disable_verification: false,
50        }
51    }
52}
53
54impl TlsConfig {
55    pub fn trust_anchors(mut self, anchors: TrustAnchors) -> Self {
56        self.trust_anchors = anchors;
57        self
58    }
59
60    pub fn client_certificate(
61        mut self,
62        chain: Vec<CertificateDer<'static>>,
63        key: PrivateKeyDer<'static>,
64    ) -> Self {
65        self.client_cert = Some((chain, key));
66        self
67    }
68
69    pub fn min_tls_version(mut self, version: TlsVersion) -> Self {
70        self.min_tls_version = version;
71        self
72    }
73
74    #[cfg(feature = "danger-disable-verify")]
75    pub fn danger_disable_verification(mut self) -> Self {
76        self.danger_disable_verification = true;
77        self
78    }
79
80    /// Build a [`rustls::ClientConfig`] from these settings.
81    pub fn build(self) -> Result<Arc<ClientConfig>, rustls::Error> {
82        #[cfg(feature = "danger-disable-verify")]
83        if self.danger_disable_verification {
84            let config = crate::conn::danger_no_verify_tls_config();
85            return Ok(Arc::new(config));
86        }
87
88        let root_store = match self.trust_anchors {
89            TrustAnchors::SystemPlusAdditional(extra) => {
90                let mut store = webpki_root_store();
91                for cert in extra {
92                    store.add(cert)?;
93                }
94                store
95            }
96            TrustAnchors::ExplicitOnly(certs) => {
97                let mut store = RootCertStore::empty();
98                for cert in certs {
99                    store.add(cert)?;
100                }
101                store
102            }
103        };
104
105        let builder = config_builder(self.min_tls_version, root_store);
106        let config = match self.client_cert {
107            Some((certs, key)) => builder.with_client_auth_cert(certs, key)?,
108            None => builder.with_no_client_auth(),
109        };
110
111        Ok(Arc::new(config))
112    }
113}
114
115pub(crate) fn default_client_config() -> ClientConfig {
116    config_builder(TlsVersion::default(), webpki_root_store()).with_no_client_auth()
117}
118
119fn webpki_root_store() -> RootCertStore {
120    RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned())
121}
122
123/// The one place a minimum version becomes a set of protocol versions.
124fn config_builder(
125    min_version: TlsVersion,
126    roots: RootCertStore,
127) -> ConfigBuilder<ClientConfig, WantsClientCert> {
128    let versions: &[&rustls::SupportedProtocolVersion] = match min_version {
129        TlsVersion::Tls13 => &[&rustls::version::TLS13],
130        TlsVersion::Tls12 => &[&rustls::version::TLS12, &rustls::version::TLS13],
131    };
132    ClientConfig::builder_with_protocol_versions(versions).with_root_certificates(roots)
133}