rustls/server/
builder.rs

1use alloc::vec::Vec;
2use core::marker::PhantomData;
3
4use pki_types::PrivateKeyDer;
5
6use super::server_conn::InvalidSniPolicy;
7use super::{ServerConfig, ServerCredentialResolver, handy};
8use crate::builder::{ConfigBuilder, WantsVerifier};
9use crate::crypto::{Credentials, Identity, SingleCredential};
10use crate::error::Error;
11use crate::sync::Arc;
12use crate::verify::{ClientVerifier, NoClientAuth};
13use crate::{NoKeyLog, compress};
14
15impl ConfigBuilder<ServerConfig, WantsVerifier> {
16    /// Choose how to verify client certificates.
17    pub fn with_client_cert_verifier(
18        self,
19        client_cert_verifier: Arc<dyn ClientVerifier>,
20    ) -> ConfigBuilder<ServerConfig, WantsServerCert> {
21        ConfigBuilder {
22            state: WantsServerCert {
23                verifier: client_cert_verifier,
24            },
25            provider: self.provider,
26            time_provider: self.time_provider,
27            side: PhantomData,
28        }
29    }
30
31    /// Disable client authentication.
32    pub fn with_no_client_auth(self) -> ConfigBuilder<ServerConfig, WantsServerCert> {
33        self.with_client_cert_verifier(Arc::new(NoClientAuth))
34    }
35}
36
37/// A config builder state where the caller must supply how to provide a server certificate to
38/// the connecting peer.
39///
40/// For more information, see the [`ConfigBuilder`] documentation.
41#[derive(Clone, Debug)]
42pub struct WantsServerCert {
43    verifier: Arc<dyn ClientVerifier>,
44}
45
46impl ConfigBuilder<ServerConfig, WantsServerCert> {
47    /// Sets a single certificate chain and matching private key.  This
48    /// certificate and key is used for all subsequent connections,
49    /// irrespective of things like SNI hostname.
50    ///
51    /// Note that the end-entity certificate must have the
52    /// [Subject Alternative Name](https://tools.ietf.org/html/rfc6125#section-4.1)
53    /// extension to describe, e.g., the valid DNS name. The `commonName` field is
54    /// disregarded.
55    ///
56    /// `cert_chain` is a vector of DER-encoded certificates.
57    /// `key_der` is a DER-encoded private key as PKCS#1, PKCS#8, or SEC1. The
58    /// `aws-lc-rs` and `ring` [`CryptoProvider`][crate::CryptoProvider]s support
59    /// all three encodings, but other `CryptoProviders` may not.
60    ///
61    /// This function fails if `key_der` is invalid, or if the
62    /// `SubjectPublicKeyInfo` from the private key does not match the public
63    /// key for the end-entity certificate from the `cert_chain`.
64    pub fn with_single_cert(
65        self,
66        identity: Arc<Identity<'static>>,
67        key_der: PrivateKeyDer<'static>,
68    ) -> Result<ServerConfig, Error> {
69        let credentials = Credentials::from_der(identity, key_der, self.crypto_provider())?;
70        self.with_server_credential_resolver(Arc::new(SingleCredential::from(credentials)))
71    }
72
73    /// Sets a single certificate chain, matching private key and optional OCSP
74    /// response.  This certificate and key is used for all
75    /// subsequent connections, irrespective of things like SNI hostname.
76    ///
77    /// `cert_chain` is a vector of DER-encoded certificates.
78    /// `key_der` is a DER-encoded private key as PKCS#1, PKCS#8, or SEC1. The
79    /// `aws-lc-rs` and `ring` [`CryptoProvider`][crate::CryptoProvider]s support
80    /// all three encodings, but other `CryptoProviders` may not.
81    /// `ocsp` is a DER-encoded OCSP response.  Ignored if zero length.
82    ///
83    /// This function fails if `key_der` is invalid, or if the
84    /// `SubjectPublicKeyInfo` from the private key does not match the public
85    /// key for the end-entity certificate from the `cert_chain`.
86    pub fn with_single_cert_with_ocsp(
87        self,
88        identity: Arc<Identity<'static>>,
89        key_der: PrivateKeyDer<'static>,
90        ocsp: Arc<[u8]>,
91    ) -> Result<ServerConfig, Error> {
92        let mut credentials = Credentials::from_der(identity, key_der, self.crypto_provider())?;
93        credentials.ocsp = Some(ocsp);
94        self.with_server_credential_resolver(Arc::new(SingleCredential::from(credentials)))
95    }
96
97    /// Sets a custom [`ServerCredentialResolver`].
98    pub fn with_server_credential_resolver(
99        self,
100        cert_resolver: Arc<dyn ServerCredentialResolver>,
101    ) -> Result<ServerConfig, Error> {
102        self.provider.consistency_check()?;
103        Ok(ServerConfig {
104            provider: self.provider,
105            verifier: self.state.verifier,
106            cert_resolver,
107            ignore_client_order: false,
108            max_fragment_size: None,
109            #[cfg(feature = "std")]
110            session_storage: handy::ServerSessionMemoryCache::new(256),
111            #[cfg(not(feature = "std"))]
112            session_storage: Arc::new(handy::NoServerSessionStorage {}),
113            ticketer: Arc::new(handy::NeverProducesTickets {}),
114            alpn_protocols: Vec::new(),
115            key_log: Arc::new(NoKeyLog {}),
116            enable_secret_extraction: false,
117            max_early_data_size: 0,
118            send_half_rtt_data: false,
119            send_tls13_tickets: 2,
120            require_ems: cfg!(feature = "fips"),
121            time_provider: self.time_provider,
122            cert_compressors: compress::default_cert_compressors().to_vec(),
123            cert_compression_cache: Arc::new(compress::CompressionCache::default()),
124            cert_decompressors: compress::default_cert_decompressors().to_vec(),
125            invalid_sni_policy: InvalidSniPolicy::default(),
126        })
127    }
128}