rustls/server/
builder.rs

1use alloc::sync::Arc;
2use alloc::vec::Vec;
3use core::marker::PhantomData;
4
5use pki_types::{CertificateDer, PrivateKeyDer};
6
7use crate::builder::{ConfigBuilder, WantsVerifier};
8use crate::error::Error;
9use crate::server::{handy, ResolvesServerCert, ServerConfig};
10use crate::sign::CertifiedKey;
11use crate::verify::{ClientCertVerifier, NoClientAuth};
12use crate::{compress, versions, InconsistentKeys, NoKeyLog};
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                versions: self.state.versions,
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    versions: versions::EnabledVersions,
44    verifier: Arc<dyn ClientCertVerifier>,
45}
46
47impl ConfigBuilder<ServerConfig, WantsServerCert> {
48    /// Sets a single certificate chain and matching private key.  This
49    /// certificate and key is used for all subsequent connections,
50    /// irrespective of things like SNI hostname.
51    ///
52    /// Note that the end-entity certificate must have the
53    /// [Subject Alternative Name](https://tools.ietf.org/html/rfc6125#section-4.1)
54    /// extension to describe, e.g., the valid DNS name. The `commonName` field is
55    /// disregarded.
56    ///
57    /// `cert_chain` is a vector of DER-encoded certificates.
58    /// `key_der` is a DER-encoded private key as PKCS#1, PKCS#8, or SEC1. The
59    /// `aws-lc-rs` and `ring` [`CryptoProvider`][crate::CryptoProvider]s support
60    /// all three encodings, but other `CryptoProviders` may not.
61    ///
62    /// This function fails if `key_der` is invalid, or if the
63    /// `SubjectPublicKeyInfo` from the private key does not match the public
64    /// key for the end-entity certificate from the `cert_chain`.
65    pub fn with_single_cert(
66        self,
67        cert_chain: Vec<CertificateDer<'static>>,
68        key_der: PrivateKeyDer<'static>,
69    ) -> Result<ServerConfig, Error> {
70        let private_key = self
71            .provider
72            .key_provider
73            .load_private_key(key_der)?;
74
75        let certified_key = CertifiedKey::new(cert_chain, private_key);
76        match certified_key.keys_match() {
77            // Don't treat unknown consistency as an error
78            Ok(()) | Err(Error::InconsistentKeys(InconsistentKeys::Unknown)) => (),
79            Err(err) => return Err(err),
80        }
81
82        let resolver = handy::AlwaysResolvesChain::new(certified_key);
83        Ok(self.with_cert_resolver(Arc::new(resolver)))
84    }
85
86    /// Sets a single certificate chain, matching private key and optional OCSP
87    /// response.  This certificate and key is used for all
88    /// subsequent connections, irrespective of things like SNI hostname.
89    ///
90    /// `cert_chain` is a vector of DER-encoded certificates.
91    /// `key_der` is a DER-encoded private key as PKCS#1, PKCS#8, or SEC1. The
92    /// `aws-lc-rs` and `ring` [`CryptoProvider`][crate::CryptoProvider]s support
93    /// all three encodings, but other `CryptoProviders` may not.
94    /// `ocsp` is a DER-encoded OCSP response.  Ignored if zero length.
95    ///
96    /// This function fails if `key_der` is invalid, or if the
97    /// `SubjectPublicKeyInfo` from the private key does not match the public
98    /// key for the end-entity certificate from the `cert_chain`.
99    pub fn with_single_cert_with_ocsp(
100        self,
101        cert_chain: Vec<CertificateDer<'static>>,
102        key_der: PrivateKeyDer<'static>,
103        ocsp: Vec<u8>,
104    ) -> Result<ServerConfig, Error> {
105        let private_key = self
106            .provider
107            .key_provider
108            .load_private_key(key_der)?;
109
110        let certified_key = CertifiedKey::new(cert_chain, private_key);
111        match certified_key.keys_match() {
112            // Don't treat unknown consistency as an error
113            Ok(()) | Err(Error::InconsistentKeys(InconsistentKeys::Unknown)) => (),
114            Err(err) => return Err(err),
115        }
116
117        let resolver = handy::AlwaysResolvesChain::new_with_extras(certified_key, ocsp);
118        Ok(self.with_cert_resolver(Arc::new(resolver)))
119    }
120
121    /// Sets a custom [`ResolvesServerCert`].
122    pub fn with_cert_resolver(self, cert_resolver: Arc<dyn ResolvesServerCert>) -> ServerConfig {
123        ServerConfig {
124            provider: self.provider,
125            verifier: self.state.verifier,
126            cert_resolver,
127            ignore_client_order: false,
128            max_fragment_size: None,
129            #[cfg(feature = "std")]
130            session_storage: handy::ServerSessionMemoryCache::new(256),
131            #[cfg(not(feature = "std"))]
132            session_storage: Arc::new(handy::NoServerSessionStorage {}),
133            ticketer: Arc::new(handy::NeverProducesTickets {}),
134            alpn_protocols: Vec::new(),
135            versions: self.state.versions,
136            key_log: Arc::new(NoKeyLog {}),
137            enable_secret_extraction: false,
138            max_early_data_size: 0,
139            send_half_rtt_data: false,
140            send_tls13_tickets: 2,
141            #[cfg(feature = "tls12")]
142            require_ems: cfg!(feature = "fips"),
143            time_provider: self.time_provider,
144            cert_compressors: compress::default_cert_compressors().to_vec(),
145            cert_compression_cache: Arc::new(compress::CompressionCache::default()),
146            cert_decompressors: compress::default_cert_decompressors().to_vec(),
147        }
148    }
149}