rustls/server/
builder.rs

1use alloc::vec::Vec;
2use core::marker::PhantomData;
3
4use pki_types::{CertificateDer, PrivateKeyDer};
5
6use super::{ResolvesServerCert, ServerConfig, handy};
7use crate::builder::{ConfigBuilder, WantsVerifier};
8use crate::error::Error;
9use crate::sign::{CertifiedKey, SingleCertAndKey};
10use crate::sync::Arc;
11use crate::verify::{ClientCertVerifier, NoClientAuth};
12use crate::{NoKeyLog, compress};
13
14impl ConfigBuilder<ServerConfig, WantsVerifier> {
15    /// Choose how to verify client certificates.
16    pub fn with_client_cert_verifier(
17        self,
18        client_cert_verifier: Arc<dyn ClientCertVerifier>,
19    ) -> ConfigBuilder<ServerConfig, WantsServerCert> {
20        ConfigBuilder {
21            state: WantsServerCert {
22                verifier: client_cert_verifier,
23            },
24            provider: self.provider,
25            time_provider: self.time_provider,
26            side: PhantomData,
27        }
28    }
29
30    /// Disable client authentication.
31    pub fn with_no_client_auth(self) -> ConfigBuilder<ServerConfig, WantsServerCert> {
32        self.with_client_cert_verifier(Arc::new(NoClientAuth))
33    }
34}
35
36/// A config builder state where the caller must supply how to provide a server certificate to
37/// the connecting peer.
38///
39/// For more information, see the [`ConfigBuilder`] documentation.
40#[derive(Clone, Debug)]
41pub struct WantsServerCert {
42    verifier: Arc<dyn ClientCertVerifier>,
43}
44
45impl ConfigBuilder<ServerConfig, WantsServerCert> {
46    /// Sets a single certificate chain and matching private key.  This
47    /// certificate and key is used for all subsequent connections,
48    /// irrespective of things like SNI hostname.
49    ///
50    /// Note that the end-entity certificate must have the
51    /// [Subject Alternative Name](https://tools.ietf.org/html/rfc6125#section-4.1)
52    /// extension to describe, e.g., the valid DNS name. The `commonName` field is
53    /// disregarded.
54    ///
55    /// `cert_chain` is a vector of DER-encoded certificates.
56    /// `key_der` is a DER-encoded private key as PKCS#1, PKCS#8, or SEC1. The
57    /// `aws-lc-rs` and `ring` [`CryptoProvider`][crate::CryptoProvider]s support
58    /// all three encodings, but other `CryptoProviders` may not.
59    ///
60    /// This function fails if `key_der` is invalid, or if the
61    /// `SubjectPublicKeyInfo` from the private key does not match the public
62    /// key for the end-entity certificate from the `cert_chain`.
63    pub fn with_single_cert(
64        self,
65        cert_chain: Vec<CertificateDer<'static>>,
66        key_der: PrivateKeyDer<'static>,
67    ) -> Result<ServerConfig, Error> {
68        let certified_key = CertifiedKey::from_der(cert_chain, key_der, self.crypto_provider())?;
69        self.with_cert_resolver(Arc::new(SingleCertAndKey::from(certified_key)))
70    }
71
72    /// Sets a single certificate chain, matching private key and optional OCSP
73    /// response.  This certificate and key is used for all
74    /// subsequent connections, irrespective of things like SNI hostname.
75    ///
76    /// `cert_chain` is a vector of DER-encoded certificates.
77    /// `key_der` is a DER-encoded private key as PKCS#1, PKCS#8, or SEC1. The
78    /// `aws-lc-rs` and `ring` [`CryptoProvider`][crate::CryptoProvider]s support
79    /// all three encodings, but other `CryptoProviders` may not.
80    /// `ocsp` is a DER-encoded OCSP response.  Ignored if zero length.
81    ///
82    /// This function fails if `key_der` is invalid, or if the
83    /// `SubjectPublicKeyInfo` from the private key does not match the public
84    /// key for the end-entity certificate from the `cert_chain`.
85    pub fn with_single_cert_with_ocsp(
86        self,
87        cert_chain: Vec<CertificateDer<'static>>,
88        key_der: PrivateKeyDer<'static>,
89        ocsp: Vec<u8>,
90    ) -> Result<ServerConfig, Error> {
91        let mut certified_key =
92            CertifiedKey::from_der(cert_chain, key_der, self.crypto_provider())?;
93        certified_key.ocsp = Some(ocsp);
94        self.with_cert_resolver(Arc::new(SingleCertAndKey::from(certified_key)))
95    }
96
97    /// Sets a custom [`ResolvesServerCert`].
98    pub fn with_cert_resolver(
99        self,
100        cert_resolver: Arc<dyn ResolvesServerCert>,
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        })
126    }
127}