Skip to main content

kube_client/client/
tls.rs

1#[cfg(feature = "rustls-tls")]
2pub mod rustls_tls {
3    use std::{
4        path::PathBuf,
5        sync::{Arc, RwLock},
6        time::Duration,
7    };
8    use tokio::time::Instant;
9
10    // Only the webpki-roots fallback uses this; the default platform-verifier path does not.
11    #[cfg(feature = "webpki-roots")] use hyper_rustls::ConfigBuilderExt;
12    use rustls::{
13        self, ClientConfig, DigitallySignedStruct, RootCertStore,
14        client::{
15            WebPkiServerVerifier,
16            danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier},
17        },
18        pki_types::{CertificateDer, InvalidDnsNameError, PrivateKeyDer, ServerName},
19    };
20    use thiserror::Error;
21
22    /// Errors from Rustls
23    #[derive(Debug, Error)]
24    pub enum Error {
25        /// Identity PEM is invalid
26        #[error("identity PEM is invalid: {0}")]
27        InvalidIdentityPem(#[source] rustls::pki_types::pem::Error),
28
29        /// Identity PEM is missing a private key: the key must be PKCS8 or RSA/PKCS1
30        #[error("identity PEM is missing a private key: the key must be PKCS8 or RSA/PKCS1")]
31        MissingPrivateKey,
32
33        /// Identity PEM is missing certificate
34        #[error("identity PEM is missing certificate")]
35        MissingCertificate,
36
37        /// Invalid private key
38        #[error("invalid private key: {0}")]
39        InvalidPrivateKey(#[source] rustls::Error),
40
41        /// Unknown private key format
42        #[error("unknown private key format")]
43        UnknownPrivateKeyFormat,
44
45        // Using type-erased error to avoid depending on webpki
46        /// Failed to add a root certificate
47        #[error("failed to add a root certificate: {0}")]
48        AddRootCertificate(#[source] Box<dyn std::error::Error + Send + Sync>),
49
50        /// No valid native root CA certificates found
51        #[error("no valid native root CA certificates found: {0}")]
52        NoValidNativeRootCA(#[source] std::io::Error),
53
54        /// Invalid server name
55        #[error("invalid server name: {0}")]
56        InvalidServerName(#[source] InvalidDnsNameError),
57    }
58
59    /// Create `rustls::ClientConfig`.
60    pub fn rustls_client_config(
61        identity_pem: Option<&[u8]>,
62        root_certs: Option<&[Vec<u8>]>,
63        accept_invalid: bool,
64    ) -> Result<ClientConfig, Error> {
65        let config_builder = if let Some(certs) = root_certs {
66            ClientConfig::builder().with_root_certificates(root_store(certs)?)
67        } else {
68            // No CA was configured (e.g. the kubeconfig has no `certificate-authority`),
69            // so defer to the trust store, mirroring how client-go leaves `RootCAs`
70            // nil to use the OS roots.
71            #[cfg(feature = "webpki-roots")]
72            {
73                // Opt-in override: use the bundled WebPKI (Mozilla) roots.
74                ClientConfig::builder().with_webpki_roots()
75            }
76            #[cfg(not(feature = "webpki-roots"))]
77            {
78                // Default: delegate to the OS-native verifier (macOS Security
79                // framework, Windows CryptoAPI, native roots on Linux/Android/iOS),
80                // honouring OS trust policies such as per-certificate trust settings.
81                use rustls_platform_verifier::BuilderVerifierExt;
82                ClientConfig::builder()
83                    .with_platform_verifier()
84                    // Reuse the type-erased trust-setup error variant to keep the
85                    // public `Error` enum stable.
86                    .map_err(|e| Error::AddRootCertificate(Box::new(e)))?
87            }
88        };
89
90        let mut client_config = if let Some((chain, pkey)) = identity_pem.map(client_auth).transpose()? {
91            config_builder
92                .with_client_auth_cert(chain, pkey)
93                .map_err(Error::InvalidPrivateKey)?
94        } else {
95            config_builder.with_no_client_auth()
96        };
97
98        if accept_invalid {
99            client_config
100                .dangerous()
101                .set_certificate_verifier(std::sync::Arc::new(NoCertificateVerification {}));
102        }
103        Ok(client_config)
104    }
105
106    fn root_store(root_certs: &[Vec<u8>]) -> Result<rustls::RootCertStore, Error> {
107        let mut root_store = rustls::RootCertStore::empty();
108        for der in root_certs {
109            root_store
110                .add(CertificateDer::from(der.to_owned()))
111                .map_err(|e| Error::AddRootCertificate(Box::new(e)))?;
112        }
113        Ok(root_store)
114    }
115
116    /// A [`ServerCertVerifier`] that re-reads the CA bundle file roughly once
117    /// per minute to pick up CA rotation.
118    ///
119    /// This mirrors the token-file reload behaviour in
120    /// [`crate::client::auth::TokenFile`]: the service-account `ca.crt` lives
121    /// in the same projected volume and rotates under the same mechanism.
122    /// Existing TLS connections are unaffected (they already handshook); new
123    /// connections use the freshly loaded roots.
124    ///
125    /// If a reload fails (file missing, parse error), the last successfully
126    /// loaded verifier is retained — same policy as `TokenFile`, per
127    /// <https://github.com/kubernetes/kubernetes/issues/68164>.
128    #[derive(Debug)]
129    pub(crate) struct ReloadingVerifier {
130        path: PathBuf,
131        inner: RwLock<(Arc<WebPkiServerVerifier>, Instant)>,
132    }
133
134    impl ReloadingVerifier {
135        const RELOAD_INTERVAL: Duration = Duration::from_secs(60);
136
137        pub(crate) fn new(path: PathBuf) -> Result<Self, Error> {
138            let verifier = Self::load(&path)?;
139            Ok(Self {
140                path,
141                inner: RwLock::new((verifier, Instant::now())),
142            })
143        }
144
145        fn load(path: &PathBuf) -> Result<Arc<WebPkiServerVerifier>, Error> {
146            let pem = std::fs::read(path).map_err(|e| Error::AddRootCertificate(Box::new(e)))?;
147            let ders = crate::config::certs(&pem).map_err(|e| Error::AddRootCertificate(Box::new(e)))?;
148            let mut store = RootCertStore::empty();
149            for der in ders {
150                store
151                    .add(CertificateDer::from(der))
152                    .map_err(|e| Error::AddRootCertificate(Box::new(e)))?;
153            }
154            WebPkiServerVerifier::builder(Arc::new(store))
155                .build()
156                .map_err(|e| Error::AddRootCertificate(Box::new(e)))
157        }
158
159        fn current(&self) -> Arc<WebPkiServerVerifier> {
160            {
161                let guard = self.inner.read().unwrap_or_else(|e| e.into_inner());
162                if guard.1.elapsed() < Self::RELOAD_INTERVAL {
163                    return guard.0.clone();
164                }
165            }
166            let mut guard = self.inner.write().unwrap_or_else(|e| e.into_inner());
167            if guard.1.elapsed() < Self::RELOAD_INTERVAL {
168                return guard.0.clone();
169            }
170            if let Ok(fresh) = Self::load(&self.path) {
171                guard.0 = fresh;
172            } else {
173                tracing::warn!(path = ?self.path, "failed to reload CA bundle; keeping stale roots");
174            }
175            guard.1 = Instant::now();
176            guard.0.clone()
177        }
178    }
179
180    impl ServerCertVerifier for ReloadingVerifier {
181        fn verify_server_cert(
182            &self,
183            end_entity: &CertificateDer,
184            intermediates: &[CertificateDer],
185            server_name: &ServerName,
186            ocsp_response: &[u8],
187            now: rustls::pki_types::UnixTime,
188        ) -> Result<ServerCertVerified, rustls::Error> {
189            self.current()
190                .verify_server_cert(end_entity, intermediates, server_name, ocsp_response, now)
191        }
192
193        fn verify_tls12_signature(
194            &self,
195            message: &[u8],
196            cert: &CertificateDer,
197            dss: &DigitallySignedStruct,
198        ) -> Result<HandshakeSignatureValid, rustls::Error> {
199            self.current().verify_tls12_signature(message, cert, dss)
200        }
201
202        fn verify_tls13_signature(
203            &self,
204            message: &[u8],
205            cert: &CertificateDer,
206            dss: &DigitallySignedStruct,
207        ) -> Result<HandshakeSignatureValid, rustls::Error> {
208            self.current().verify_tls13_signature(message, cert, dss)
209        }
210
211        fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
212            self.current().supported_verify_schemes()
213        }
214    }
215
216    fn client_auth(data: &[u8]) -> Result<(Vec<CertificateDer<'static>>, PrivateKeyDer<'static>), Error> {
217        use rustls::pki_types::pem::{self, SectionKind};
218
219        let mut cert_chain = Vec::new();
220        let mut pkcs8_key = None;
221        let mut pkcs1_key = None;
222        let mut sec1_key = None;
223        let mut reader = std::io::Cursor::new(data);
224        while let Some((kind, der)) = pem::from_buf(&mut reader).map_err(Error::InvalidIdentityPem)? {
225            match kind {
226                SectionKind::Certificate => cert_chain.push(der.into()),
227                SectionKind::PrivateKey => pkcs8_key = Some(PrivateKeyDer::Pkcs8(der.into())),
228                SectionKind::RsaPrivateKey => pkcs1_key = Some(PrivateKeyDer::Pkcs1(der.into())),
229                SectionKind::EcPrivateKey => sec1_key = Some(PrivateKeyDer::Sec1(der.into())),
230                _ => return Err(Error::UnknownPrivateKeyFormat),
231            }
232        }
233
234        let private_key = pkcs8_key
235            .or(pkcs1_key)
236            .or(sec1_key)
237            .ok_or(Error::MissingPrivateKey)?;
238        if cert_chain.is_empty() {
239            return Err(Error::MissingCertificate);
240        }
241        Ok((cert_chain, private_key))
242    }
243
244    #[derive(Debug)]
245    struct NoCertificateVerification {}
246
247    impl ServerCertVerifier for NoCertificateVerification {
248        fn verify_server_cert(
249            &self,
250            _end_entity: &CertificateDer,
251            _intermediates: &[CertificateDer],
252            _server_name: &ServerName,
253            _ocsp_response: &[u8],
254            _now: rustls::pki_types::UnixTime,
255        ) -> Result<ServerCertVerified, rustls::Error> {
256            tracing::warn!("Server cert bypassed");
257            Ok(ServerCertVerified::assertion())
258        }
259
260        fn verify_tls13_signature(
261            &self,
262            _message: &[u8],
263            _cert: &CertificateDer,
264            _dss: &DigitallySignedStruct,
265        ) -> Result<HandshakeSignatureValid, rustls::Error> {
266            Ok(HandshakeSignatureValid::assertion())
267        }
268
269        fn verify_tls12_signature(
270            &self,
271            _message: &[u8],
272            _cert: &CertificateDer,
273            _dss: &DigitallySignedStruct,
274        ) -> Result<HandshakeSignatureValid, rustls::Error> {
275            Ok(HandshakeSignatureValid::assertion())
276        }
277
278        fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
279            use rustls::SignatureScheme;
280            vec![
281                SignatureScheme::RSA_PKCS1_SHA1,
282                SignatureScheme::ECDSA_SHA1_Legacy,
283                SignatureScheme::RSA_PKCS1_SHA256,
284                SignatureScheme::ECDSA_NISTP256_SHA256,
285                SignatureScheme::RSA_PKCS1_SHA384,
286                SignatureScheme::ECDSA_NISTP384_SHA384,
287                SignatureScheme::RSA_PKCS1_SHA512,
288                SignatureScheme::ECDSA_NISTP521_SHA512,
289                SignatureScheme::RSA_PSS_SHA256,
290                SignatureScheme::RSA_PSS_SHA384,
291                SignatureScheme::RSA_PSS_SHA512,
292                SignatureScheme::ED25519,
293                SignatureScheme::ED448,
294            ]
295        }
296    }
297
298    #[cfg(test)]
299    mod tests {
300        use super::*;
301
302        // EC P-256 self-signed CAs, valid until 2126. Regenerate with:
303        //   openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes \
304        //     -keyout /dev/null -out ca.pem -days 36500 -subj "/CN=test-ca-N"
305        const CA1: &str = "-----BEGIN CERTIFICATE-----
306MIIBgDCCASWgAwIBAgIUVrQf5d//S01a0fbXxYRIx9wc0VQwCgYIKoZIzj0EAwIw
307FDESMBAGA1UEAwwJdGVzdC1jYS0xMCAXDTI2MDMwNDEzMDk1MFoYDzIxMjYwMjA4
308MTMwOTUwWjAUMRIwEAYDVQQDDAl0ZXN0LWNhLTEwWTATBgcqhkjOPQIBBggqhkjO
309PQMBBwNCAARg57mWJPDsAIEQAgXqMOOfjMQP+PE9HqcZobycO8z94r/uRuV0wKx/
3100SvMsKFtnreut0bjgFtmZaWY+6d87Is9o1MwUTAdBgNVHQ4EFgQUjtGuhkM7LtHB
311gMPCJIxMwbY69OQwHwYDVR0jBBgwFoAUjtGuhkM7LtHBgMPCJIxMwbY69OQwDwYD
312VR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAgNJADBGAiEAj/WzNVJDg/cBtLqQVM77
313tkB+QyIXLG3Vi9Xj1YfW9QECIQDDFW8yFtgLeCg2Zhr4xQNq3/24r/01kI2rjFPO
314xBkDMw==
315-----END CERTIFICATE-----
316";
317        const CA2: &str = "-----BEGIN CERTIFICATE-----
318MIIBfjCCASWgAwIBAgIUZ7Qsiwan2joRz01p25/cy1XNNiwwCgYIKoZIzj0EAwIw
319FDESMBAGA1UEAwwJdGVzdC1jYS0yMCAXDTI2MDMwNDEzMDk1MFoYDzIxMjYwMjA4
320MTMwOTUwWjAUMRIwEAYDVQQDDAl0ZXN0LWNhLTIwWTATBgcqhkjOPQIBBggqhkjO
321PQMBBwNCAARJle2/yiOD5zp0UkjZg9Yy6ZHBItTLrqv/uzB2YMQg03frnqEUMzSV
322mFinosBcGpX/dPGfHNPhBMOpHmlocZu9o1MwUTAdBgNVHQ4EFgQUsqG0hSGDYsz2
323eGIsLIwJnCR5SFIwHwYDVR0jBBgwFoAUsqG0hSGDYsz2eGIsLIwJnCR5SFIwDwYD
324VR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAgNHADBEAiApvLu9DIC3/K/+G9ooOm75
325a72Cjw62aM8NfPe7ILs8SgIgL0VHe6ksTyB176RECCm3MJVnlhOop6b1tNvxjrru
326FRU=
327-----END CERTIFICATE-----
328";
329
330        fn expire(v: &ReloadingVerifier) {
331            // Can't move Instant backwards; instead, reach past the guard.
332            // The test pokes private state the same way auth::tests::token_file does.
333            v.inner.write().unwrap().1 = Instant::now().checked_sub(Duration::from_secs(120)).unwrap();
334        }
335
336        #[test]
337        fn reloading_verifier() {
338            #[cfg(feature = "aws-lc-rs")]
339            let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
340
341            let file = tempfile::NamedTempFile::new().unwrap();
342            std::fs::write(file.path(), CA1).unwrap();
343
344            let verifier = ReloadingVerifier::new(file.path().to_path_buf()).unwrap();
345            let first = verifier.current();
346
347            // File changed but we're still within the reload interval: no reload.
348            std::fs::write(file.path(), CA2).unwrap();
349            assert!(Arc::ptr_eq(&verifier.current(), &first));
350
351            // Force expiry: reload picks up CA2.
352            expire(&verifier);
353            let second = verifier.current();
354            assert!(!Arc::ptr_eq(&second, &first));
355
356            // File gone, expired again: keep stale verifier.
357            drop(file);
358            expire(&verifier);
359            assert!(Arc::ptr_eq(&verifier.current(), &second));
360        }
361    }
362
363    #[cfg(all(test, not(feature = "webpki-roots")))]
364    mod platform_verifier_tests {
365        use super::*;
366
367        // With no kubeconfig CA, the client config must fall back to the OS-native
368        // verifier instead of producing an empty (reject-everything) trust store.
369        #[test]
370        fn no_ca_falls_back_to_platform_verifier() {
371            #[cfg(feature = "aws-lc-rs")]
372            let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
373
374            rustls_client_config(None, None, false).expect("platform verifier config should build");
375        }
376    }
377}
378
379#[cfg(feature = "openssl-tls")]
380pub mod openssl_tls {
381    use openssl::{
382        pkey::PKey,
383        ssl::{SslConnector, SslConnectorBuilder, SslMethod},
384        x509::{X509, store::X509StoreBuilder},
385    };
386    use thiserror::Error;
387
388    /// Errors from OpenSSL TLS
389    #[derive(Debug, Error)]
390    pub enum Error {
391        /// Failed to create OpenSSL HTTPS connector
392        #[error("failed to create OpenSSL HTTPS connector: {0}")]
393        CreateHttpsConnector(#[source] openssl::error::ErrorStack),
394
395        /// Failed to create OpenSSL SSL connector
396        #[error("failed to create OpenSSL SSL connector: {0}")]
397        CreateSslConnector(#[source] SslConnectorError),
398    }
399
400    /// Errors from creating a `SslConnectorBuilder`
401    #[derive(Debug, Error)]
402    pub enum SslConnectorError {
403        /// Failed to build SslConnectorBuilder
404        #[error("failed to build SslConnectorBuilder: {0}")]
405        CreateBuilder(#[source] openssl::error::ErrorStack),
406
407        /// Failed to deserialize PEM-encoded chain of certificates
408        #[error("failed to deserialize PEM-encoded chain of certificates: {0}")]
409        DeserializeCertificateChain(#[source] openssl::error::ErrorStack),
410
411        /// Failed to deserialize PEM-encoded private key
412        #[error("failed to deserialize PEM-encoded private key: {0}")]
413        DeserializePrivateKey(#[source] openssl::error::ErrorStack),
414
415        /// Failed to set private key
416        #[error("failed to set private key: {0}")]
417        SetPrivateKey(#[source] openssl::error::ErrorStack),
418
419        /// Failed to get a leaf certificate, the certificate chain is empty
420        #[error("failed to get a leaf certificate, the certificate chain is empty")]
421        GetLeafCertificate,
422
423        /// Failed to set the leaf certificate
424        #[error("failed to set the leaf certificate: {0}")]
425        SetLeafCertificate(#[source] openssl::error::ErrorStack),
426
427        /// Failed to append a certificate to the chain
428        #[error("failed to append a certificate to the chain: {0}")]
429        AppendCertificate(#[source] openssl::error::ErrorStack),
430
431        /// Failed to deserialize DER-encoded root certificate
432        #[error("failed to deserialize DER-encoded root certificate: {0}")]
433        DeserializeRootCertificate(#[source] openssl::error::ErrorStack),
434
435        /// Failed to add a root certificate
436        #[error("failed to add a root certificate: {0}")]
437        AddRootCertificate(#[source] openssl::error::ErrorStack),
438    }
439
440    /// Create `openssl::ssl::SslConnectorBuilder` required for `hyper_openssl::HttpsConnector`.
441    pub fn ssl_connector_builder(
442        identity_pem: Option<&Vec<u8>>,
443        root_certs: Option<&Vec<Vec<u8>>>,
444    ) -> Result<SslConnectorBuilder, SslConnectorError> {
445        let mut builder =
446            SslConnector::builder(SslMethod::tls()).map_err(SslConnectorError::CreateBuilder)?;
447        if let Some(pem) = identity_pem {
448            let mut chain = X509::stack_from_pem(pem)
449                .map_err(SslConnectorError::DeserializeCertificateChain)?
450                .into_iter();
451            let leaf_cert = chain.next().ok_or(SslConnectorError::GetLeafCertificate)?;
452            builder
453                .set_certificate(&leaf_cert)
454                .map_err(SslConnectorError::SetLeafCertificate)?;
455            for cert in chain {
456                builder
457                    .add_extra_chain_cert(cert)
458                    .map_err(SslConnectorError::AppendCertificate)?;
459            }
460
461            let pkey = PKey::private_key_from_pem(pem).map_err(SslConnectorError::DeserializePrivateKey)?;
462            builder
463                .set_private_key(&pkey)
464                .map_err(SslConnectorError::SetPrivateKey)?;
465        }
466
467        if let Some(ders) = root_certs {
468            // SslConnector::builder loaded OpenSSL's default verify paths into the context's store.
469            // Replace that store so only the configured roots are trusted, as in client-go and the
470            // rustls path. Without configured roots, the default store stays.
471            let mut store = X509StoreBuilder::new().map_err(SslConnectorError::CreateBuilder)?;
472            for der in ders {
473                let cert = X509::from_der(der).map_err(SslConnectorError::DeserializeRootCertificate)?;
474                store
475                    .add_cert(cert)
476                    .map_err(SslConnectorError::AddRootCertificate)?;
477            }
478            builder.set_cert_store(store.build());
479        }
480
481        Ok(builder)
482    }
483
484    #[cfg(test)]
485    mod tests {
486        use std::{
487            net::{TcpListener, TcpStream},
488            path::Path,
489            process::Command,
490        };
491
492        use openssl::{
493            asn1::Asn1Time,
494            ec::{EcGroup, EcKey},
495            hash::MessageDigest,
496            nid::Nid,
497            pkey::Private,
498            ssl::{HandshakeError, SslAcceptor, SslAcceptorBuilder, SslVerifyMode},
499            x509::{
500                X509Name, X509VerifyResult,
501                extension::{BasicConstraints, SubjectAlternativeName},
502            },
503        };
504
505        use super::*;
506
507        const SERVER_NAME: &str = "kube.test";
508
509        // Set in the child process to the file the "default" CA is written to. The parent points
510        // SSL_CERT_FILE at the same file.
511        const DEFAULT_CA_FILE_ENV: &str = "KUBE_TEST_OPENSSL_DEFAULT_CA_FILE";
512
513        struct Issued {
514            cert: X509,
515            key: PKey<Private>,
516        }
517
518        // A CA cert, or a leaf with a DNS SAN for SERVER_NAME. Self-signed when `issuer` is None.
519        fn issue(cn: &str, ca: bool, issuer: Option<&Issued>) -> Issued {
520            let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap();
521            let key = PKey::from_ec_key(EcKey::generate(&group).unwrap()).unwrap();
522
523            let mut name = X509Name::builder().unwrap();
524            name.append_entry_by_text("CN", cn).unwrap();
525            let name = name.build();
526
527            let mut builder = X509::builder().unwrap();
528            builder.set_version(2).unwrap();
529            builder.set_subject_name(&name).unwrap();
530            match issuer {
531                Some(issuer) => builder.set_issuer_name(issuer.cert.subject_name()).unwrap(),
532                None => builder.set_issuer_name(&name).unwrap(),
533            }
534            builder.set_pubkey(&key).unwrap();
535            builder
536                .set_not_before(&Asn1Time::days_from_now(0).unwrap())
537                .unwrap();
538            builder
539                .set_not_after(&Asn1Time::days_from_now(1).unwrap())
540                .unwrap();
541            if ca {
542                builder
543                    .append_extension(BasicConstraints::new().critical().ca().build().unwrap())
544                    .unwrap();
545            } else {
546                let san = SubjectAlternativeName::new()
547                    .dns(SERVER_NAME)
548                    .build(&builder.x509v3_context(None, None))
549                    .unwrap();
550                builder.append_extension(san).unwrap();
551            }
552            let signing_key = issuer.map_or(&key, |issuer| &issuer.key);
553            builder.sign(signing_key, MessageDigest::sha256()).unwrap();
554
555            Issued {
556                cert: builder.build(),
557                key,
558            }
559        }
560
561        fn connector(roots: Option<&[&X509]>, identity: Option<&Vec<u8>>) -> SslConnector {
562            let roots = roots.map(|roots| roots.iter().map(|c| c.to_der().unwrap()).collect::<Vec<_>>());
563            ssl_connector_builder(identity, roots.as_ref()).unwrap().build()
564        }
565
566        fn acceptor(leaf: &Issued, extra_chain: &[&X509]) -> SslAcceptorBuilder {
567            let mut acceptor = SslAcceptor::mozilla_intermediate_v5(SslMethod::tls()).unwrap();
568            acceptor.set_private_key(&leaf.key).unwrap();
569            acceptor.set_certificate(&leaf.cert).unwrap();
570            for cert in extra_chain {
571                acceptor.add_extra_chain_cert((*cert).clone()).unwrap();
572            }
573            acceptor
574        }
575
576        // One handshake on localhost, verifying the server as `domain`. Returns the client's verify
577        // error if it rejected the server certificate, and the server's handshake result.
578        fn handshake(
579            client: &SslConnector,
580            acceptor: SslAcceptor,
581            domain: &str,
582        ) -> (Result<(), X509VerifyResult>, Result<(), String>) {
583            let listener = TcpListener::bind("127.0.0.1:0").unwrap();
584            let addr = listener.local_addr().unwrap();
585            let server = std::thread::spawn(move || {
586                let (stream, _) = listener.accept().unwrap();
587                acceptor.accept(stream).map(drop).map_err(|e| e.to_string())
588            });
589
590            match client.connect(domain, TcpStream::connect(addr).unwrap()) {
591                Ok(stream) => {
592                    // Keep the connection open until the server has finished its side.
593                    let server = server.join().unwrap();
594                    drop(stream);
595                    (Ok(()), server)
596                }
597                Err(HandshakeError::Failure(mid)) => {
598                    let verify = mid.ssl().verify_result();
599                    assert_ne!(
600                        verify,
601                        X509VerifyResult::OK,
602                        "handshake failed for a reason other than verification: {}",
603                        mid.error()
604                    );
605                    drop(mid);
606                    (Err(verify), server.join().unwrap())
607                }
608                Err(e) => panic!("unexpected handshake error: {e}"),
609            }
610        }
611
612        // A server cert from a CA in OpenSSL's default store must be rejected once root certs are
613        // configured, as client-go and the rustls path do. SSL_CERT_FILE is process-global and
614        // unsafe_code is forbidden (no env::set_var), so the test re-runs itself in a child process
615        // with the variable set.
616        #[test]
617        fn default_verify_paths_are_not_trusted_with_root_certs() {
618            if let Some(file) = std::env::var_os(DEFAULT_CA_FILE_ENV) {
619                return check_default_verify_paths(Path::new(&file));
620            }
621            // LibreSSL ignores SSL_CERT_FILE and SSL_CERT_DIR, so its default store can't be redirected.
622            if openssl::version::version().starts_with("LibreSSL") {
623                return;
624            }
625
626            let dir = tempfile::tempdir().unwrap();
627            let file = dir.path().join("default-ca.pem");
628            let test = concat!(
629                module_path!(),
630                "::default_verify_paths_are_not_trusted_with_root_certs"
631            );
632            // libtest names omit the crate name.
633            let test = test.split_once("::").unwrap().1;
634            let output = Command::new(std::env::current_exe().unwrap())
635                .args([test, "--exact", "--test-threads=1"])
636                .env(DEFAULT_CA_FILE_ENV, &file)
637                .env("SSL_CERT_FILE", &file)
638                .env("SSL_CERT_DIR", dir.path())
639                .output()
640                .unwrap();
641            let stdout = String::from_utf8_lossy(&output.stdout);
642            assert!(
643                output.status.success() && stdout.contains("1 passed"),
644                "child test failed:\n{stdout}\n{}",
645                String::from_utf8_lossy(&output.stderr)
646            );
647        }
648
649        fn check_default_verify_paths(default_ca_file: &Path) {
650            let default_ca = issue("default-ca", true, None);
651            std::fs::write(default_ca_file, default_ca.cert.to_pem().unwrap()).unwrap();
652            let by_default_ca = issue("server", false, Some(&default_ca));
653            let cluster_ca = issue("cluster-ca", true, None);
654            let by_cluster_ca = issue("server", false, Some(&cluster_ca));
655
656            // No root certs: the default store applies. This also shows SSL_CERT_FILE took effect.
657            let (client, _) = handshake(
658                &connector(None, None),
659                acceptor(&by_default_ca, &[]).build(),
660                SERVER_NAME,
661            );
662            assert!(client.is_ok(), "default store should be used without root certs");
663
664            let pinned = connector(Some(&[&cluster_ca.cert]), None);
665            let (client, _) = handshake(&pinned, acceptor(&by_cluster_ca, &[]).build(), SERVER_NAME);
666            assert!(client.is_ok(), "configured root should be trusted");
667            let (client, _) = handshake(&pinned, acceptor(&by_default_ca, &[]).build(), SERVER_NAME);
668            assert!(
669                client.is_err(),
670                "default store must not be trusted when root certs are configured"
671            );
672
673            // An empty root list trusts nothing rather than falling back to the default store.
674            let (client, _) = handshake(
675                &connector(Some(&[]), None),
676                acceptor(&by_default_ca, &[]).build(),
677                SERVER_NAME,
678            );
679            assert!(
680                client.is_err(),
681                "empty root list must not fall back to the default store"
682            );
683        }
684
685        #[test]
686        fn root_certs_with_intermediates() {
687            let root = issue("root-ca", true, None);
688            let intermediate = issue("intermediate-ca", true, Some(&root));
689            let leaf = issue("server", false, Some(&intermediate));
690
691            // Bundle with root and intermediate; the server sends only its leaf.
692            let bundle = connector(Some(&[&root.cert, &intermediate.cert]), None);
693            let (client, _) = handshake(&bundle, acceptor(&leaf, &[]).build(), SERVER_NAME);
694            assert!(
695                client.is_ok(),
696                "intermediate from the bundle should complete the chain"
697            );
698
699            // Bundle with only the root; the server sends the intermediate.
700            let root_only = connector(Some(&[&root.cert]), None);
701            let (client, _) = handshake(
702                &root_only,
703                acceptor(&leaf, &[&intermediate.cert]).build(),
704                SERVER_NAME,
705            );
706            assert!(
707                client.is_ok(),
708                "intermediate from the server should complete the chain"
709            );
710
711            // Hostname verification is still on.
712            let (client, _) = handshake(
713                &root_only,
714                acceptor(&leaf, &[&intermediate.cert]).build(),
715                "other.test",
716            );
717            assert!(client.is_err(), "hostname mismatch must be rejected");
718        }
719
720        #[test]
721        fn identity_chain_is_sent_with_root_certs() {
722            let server_ca = issue("server-ca", true, None);
723            let server = issue("server", false, Some(&server_ca));
724            let client_root = issue("client-root-ca", true, None);
725            let client_intermediate = issue("client-intermediate-ca", true, Some(&client_root));
726            let client = issue("client", false, Some(&client_intermediate));
727
728            let mut identity = client.cert.to_pem().unwrap();
729            identity.extend(client_intermediate.cert.to_pem().unwrap());
730            identity.extend(client.key.private_key_to_pem_pkcs8().unwrap());
731
732            // The server only knows the client root, so it needs the intermediate from the client.
733            let mut acceptor = acceptor(&server, &[]);
734            acceptor.set_verify(SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT);
735            acceptor
736                .cert_store_mut()
737                .add_cert(client_root.cert.clone())
738                .unwrap();
739
740            let (client, server) = handshake(
741                &connector(Some(&[&server_ca.cert]), Some(&identity)),
742                acceptor.build(),
743                SERVER_NAME,
744            );
745            assert!(client.is_ok(), "client should trust the server");
746            server.expect("server should verify the client chain through the intermediate");
747        }
748    }
749}