rustls/crypto/
mod.rs

1use alloc::boxed::Box;
2use alloc::vec::Vec;
3use core::fmt::Debug;
4
5use pki_types::PrivateKeyDer;
6use zeroize::Zeroize;
7
8#[cfg(doc)]
9use crate::Tls12CipherSuite;
10use crate::msgs::ffdhe_groups::FfdheGroup;
11use crate::msgs::handshake::ALL_KEY_EXCHANGE_ALGORITHMS;
12use crate::sign::SigningKey;
13use crate::sync::Arc;
14pub use crate::webpki::{
15    WebPkiSupportedAlgorithms, verify_tls12_signature, verify_tls13_signature,
16    verify_tls13_signature_with_raw_key,
17};
18#[cfg(doc)]
19use crate::{
20    ClientConfig, ConfigBuilder, ServerConfig, SupportedCipherSuite, Tls13CipherSuite, client,
21    crypto, server, sign,
22};
23use crate::{Error, NamedGroup, ProtocolVersion, SupportedProtocolVersion, suites};
24
25/// *ring* based CryptoProvider.
26#[cfg(feature = "ring")]
27pub mod ring;
28
29/// aws-lc-rs-based CryptoProvider.
30#[cfg(feature = "aws-lc-rs")]
31pub mod aws_lc_rs;
32
33/// TLS message encryption/decryption interfaces.
34pub mod cipher;
35
36/// Hashing interfaces.
37pub mod hash;
38
39/// HMAC interfaces.
40pub mod hmac;
41
42/// Cryptography specific to TLS1.2.
43pub mod tls12;
44
45/// Cryptography specific to TLS1.3.
46pub mod tls13;
47
48/// Hybrid public key encryption (RFC 9180).
49pub mod hpke;
50
51// Message signing interfaces. Re-exported under rustls::sign. Kept crate-internal here to
52// avoid having two import paths to the same types.
53pub(crate) mod signer;
54
55pub use crate::msgs::handshake::KeyExchangeAlgorithm;
56pub use crate::rand::GetRandomFailed;
57pub use crate::suites::CipherSuiteCommon;
58
59/// Controls core cryptography used by rustls.
60///
61/// This crate comes with two built-in options, provided as
62/// `CryptoProvider` structures:
63///
64/// - [`crypto::aws_lc_rs::default_provider`]: (behind the `aws_lc_rs` crate feature).
65///   This provider uses the [aws-lc-rs](https://github.com/aws/aws-lc-rs)
66///   crate.  The `fips` crate feature makes this option use FIPS140-3-approved cryptography.
67/// - [`crypto::ring::default_provider`]: (behind the `ring` crate feature).
68///   This provider uses the [*ring*](https://github.com/briansmith/ring) crate.
69///
70/// This structure provides defaults. Everything in it can be overridden at
71/// runtime by replacing field values as needed.
72///
73/// # Using the per-process default `CryptoProvider`
74///
75/// There is the concept of an implicit default provider, configured at run-time once in
76/// a given process.
77///
78/// It is used for functions like [`ClientConfig::builder()`] and [`ServerConfig::builder()`].
79///
80/// The intention is that an application can specify the [`CryptoProvider`] they wish to use
81/// once, and have that apply to the variety of places where their application does TLS
82/// (which may be wrapped inside other libraries).
83/// They should do this by calling [`CryptoProvider::install_default()`] early on.
84///
85/// To achieve this goal:
86///
87/// - _libraries_ should use [`ClientConfig::builder()`]/[`ServerConfig::builder()`]
88///   or otherwise rely on the [`CryptoProvider::get_default()`] provider.
89/// - _applications_ should call [`CryptoProvider::install_default()`] early
90///   in their `fn main()`. If _applications_ uses a custom provider based on the one built-in,
91///   they can activate the `custom-provider` feature to ensure its usage.
92///
93/// # Using a specific `CryptoProvider`
94///
95/// Supply the provider when constructing your [`ClientConfig`] or [`ServerConfig`]:
96///
97/// - [`ClientConfig::builder_with_provider()`]
98/// - [`ServerConfig::builder_with_provider()`]
99///
100/// When creating and configuring a webpki-backed client or server certificate verifier, a choice of
101/// provider is also needed to start the configuration process:
102///
103/// - [`client::WebPkiServerVerifier::builder_with_provider()`]
104/// - [`server::WebPkiClientVerifier::builder_with_provider()`]
105///
106/// If you install a custom provider and want to avoid any accidental use of a built-in provider, the feature
107/// `custom-provider` can be activated to ensure your custom provider is used everywhere
108/// and not a built-in one. This will disable any implicit use of a built-in provider.
109///
110/// # Making a custom `CryptoProvider`
111///
112/// Your goal will be to populate an instance of this `CryptoProvider` struct.
113///
114/// ## Which elements are required?
115///
116/// There is no requirement that the individual elements ([`SupportedCipherSuite`], [`SupportedKxGroup`],
117/// [`SigningKey`], etc.) come from the same crate.  It is allowed and expected that uninteresting
118/// elements would be delegated back to one of the default providers (statically) or a parent
119/// provider (dynamically).
120///
121/// For example, if we want to make a provider that just overrides key loading in the config builder
122/// API (with [`ConfigBuilder::with_single_cert`], etc.), it might look like this:
123///
124/// ```
125/// # #[cfg(feature = "aws-lc-rs")] {
126/// # use std::sync::Arc;
127/// # mod fictious_hsm_api { pub fn load_private_key(key_der: pki_types::PrivateKeyDer<'static>) -> ! { unreachable!(); } }
128/// use rustls::crypto::aws_lc_rs;
129///
130/// pub fn provider() -> rustls::crypto::CryptoProvider {
131///   rustls::crypto::CryptoProvider{
132///     key_provider: &HsmKeyLoader,
133///     ..aws_lc_rs::default_provider()
134///   }
135/// }
136///
137/// #[derive(Debug)]
138/// struct HsmKeyLoader;
139///
140/// impl rustls::crypto::KeyProvider for HsmKeyLoader {
141///     fn load_private_key(&self, key_der: pki_types::PrivateKeyDer<'static>) -> Result<Arc<dyn rustls::sign::SigningKey>, rustls::Error> {
142///          fictious_hsm_api::load_private_key(key_der)
143///     }
144/// }
145/// # }
146/// ```
147///
148/// ## References to the individual elements
149///
150/// The elements are documented separately:
151///
152/// - **Random** - see [`crypto::SecureRandom::fill()`].
153/// - **Cipher suites** - see [`SupportedCipherSuite`], [`Tls12CipherSuite`], and
154///   [`Tls13CipherSuite`].
155/// - **Key exchange groups** - see [`crypto::SupportedKxGroup`].
156/// - **Signature verification algorithms** - see [`crypto::WebPkiSupportedAlgorithms`].
157/// - **Authentication key loading** - see [`crypto::KeyProvider::load_private_key()`] and
158///   [`sign::SigningKey`].
159///
160/// # Example code
161///
162/// See custom [`provider-example/`] for a full client and server example that uses
163/// cryptography from the [`RustCrypto`] and [`dalek-cryptography`] projects.
164///
165/// ```shell
166/// $ cargo run --example client | head -3
167/// Current ciphersuite: TLS13_CHACHA20_POLY1305_SHA256
168/// HTTP/1.1 200 OK
169/// Content-Type: text/html; charset=utf-8
170/// Content-Length: 19899
171/// ```
172///
173/// [`provider-example/`]: https://github.com/rustls/rustls/tree/main/provider-example/
174/// [`RustCrypto`]: https://github.com/RustCrypto
175/// [`dalek-cryptography`]: https://github.com/dalek-cryptography
176///
177/// # FIPS-approved cryptography
178/// The `fips` crate feature enables use of the `aws-lc-rs` crate in FIPS mode.
179///
180/// You can verify the configuration at runtime by checking
181/// [`ServerConfig::fips()`]/[`ClientConfig::fips()`] return `true`.
182#[allow(clippy::exhaustive_structs)]
183#[derive(Debug, Clone)]
184pub struct CryptoProvider {
185    /// List of supported ciphersuites, in preference order -- the first element
186    /// is the highest priority.
187    ///
188    /// The `SupportedCipherSuite` type carries both configuration and implementation.
189    ///
190    /// A valid `CryptoProvider` must ensure that all cipher suites are accompanied by at least
191    /// one matching key exchange group in [`CryptoProvider::kx_groups`].
192    pub cipher_suites: Vec<suites::SupportedCipherSuite>,
193
194    /// List of supported key exchange groups, in preference order -- the
195    /// first element is the highest priority.
196    ///
197    /// The first element in this list is the _default key share algorithm_,
198    /// and in TLS1.3 a key share for it is sent in the client hello.
199    ///
200    /// The `SupportedKxGroup` type carries both configuration and implementation.
201    pub kx_groups: Vec<&'static dyn SupportedKxGroup>,
202
203    /// List of signature verification algorithms for use with webpki.
204    ///
205    /// These are used for both certificate chain verification and handshake signature verification.
206    ///
207    /// This is called by [`ConfigBuilder::with_root_certificates()`],
208    /// [`server::WebPkiClientVerifier::builder_with_provider()`] and
209    /// [`client::WebPkiServerVerifier::builder_with_provider()`].
210    pub signature_verification_algorithms: WebPkiSupportedAlgorithms,
211
212    /// Source of cryptographically secure random numbers.
213    pub secure_random: &'static dyn SecureRandom,
214
215    /// Provider for loading private [`SigningKey`]s from [`PrivateKeyDer`].
216    pub key_provider: &'static dyn KeyProvider,
217}
218
219impl CryptoProvider {
220    /// Sets this `CryptoProvider` as the default for this process.
221    ///
222    /// This can be called successfully at most once in any process execution.
223    ///
224    /// Call this early in your process to configure which provider is used for
225    /// the provider.  The configuration should happen before any use of
226    /// [`ClientConfig::builder()`] or [`ServerConfig::builder()`].
227    pub fn install_default(self) -> Result<(), Arc<Self>> {
228        static_default::install_default(self)
229    }
230
231    /// Returns the default `CryptoProvider` for this process.
232    ///
233    /// This will be `None` if no default has been set yet.
234    pub fn get_default() -> Option<&'static Arc<Self>> {
235        static_default::get_default()
236    }
237
238    /// An internal function that:
239    ///
240    /// - gets the pre-installed default, or
241    /// - installs one `from_crate_features()`, or else
242    /// - panics about the need to call [`CryptoProvider::install_default()`]
243    pub(crate) fn get_default_or_install_from_crate_features() -> &'static Arc<Self> {
244        if let Some(provider) = Self::get_default() {
245            return provider;
246        }
247
248        let provider = Self::from_crate_features()
249            .expect(r###"
250Could not automatically determine the process-level CryptoProvider from Rustls crate features.
251Call CryptoProvider::install_default() before this point to select a provider manually, or make sure exactly one of the 'aws-lc-rs' and 'ring' features is enabled.
252See the documentation of the CryptoProvider type for more information.
253            "###);
254        // Ignore the error resulting from us losing a race, and accept the outcome.
255        let _ = provider.install_default();
256        Self::get_default().unwrap()
257    }
258
259    /// Returns a provider named unambiguously by rustls crate features.
260    ///
261    /// This function returns `None` if the crate features are ambiguous (ie, specify two
262    /// providers), or specify no providers, or the feature `custom-provider` is activated.
263    /// In all cases the application should explicitly specify the provider to use
264    /// with [`CryptoProvider::install_default`].
265    ///
266    /// This can be used to check if a default provider is available before
267    /// invoking functions that require an installed `CryptoProvider`, like
268    /// [`ClientConfig::builder()`] or [`ServerConfig::builder()`].
269    ///
270    /// ```rust,no_run
271    /// # use rustls::crypto::CryptoProvider;
272    /// if CryptoProvider::get_default().is_some() || CryptoProvider::from_crate_features().is_some() {
273    ///     // A default provider is available, either from the
274    ///     // process-level default or from the crate features.
275    /// }
276    /// ```
277    ///
278    /// [`ClientConfig::builder()`]: crate::ClientConfig::builder
279    /// [`ServerConfig::builder()`]: crate::ServerConfig::builder
280    pub fn from_crate_features() -> Option<Self> {
281        #[cfg(all(
282            feature = "ring",
283            not(feature = "aws-lc-rs"),
284            not(feature = "custom-provider")
285        ))]
286        {
287            return Some(ring::default_provider());
288        }
289
290        #[cfg(all(
291            feature = "aws-lc-rs",
292            not(feature = "ring"),
293            not(feature = "custom-provider")
294        ))]
295        {
296            return Some(aws_lc_rs::default_provider());
297        }
298
299        #[allow(unreachable_code)]
300        None
301    }
302
303    /// Returns `true` if this `CryptoProvider` is operating in FIPS mode.
304    ///
305    /// This covers only the cryptographic parts of FIPS approval.  There are
306    /// also TLS protocol-level recommendations made by NIST.  You should
307    /// prefer to call [`ClientConfig::fips()`] or [`ServerConfig::fips()`]
308    /// which take these into account.
309    pub fn fips(&self) -> bool {
310        let Self {
311            cipher_suites,
312            kx_groups,
313            signature_verification_algorithms,
314            secure_random,
315            key_provider,
316        } = self;
317        cipher_suites.iter().all(|cs| cs.fips())
318            && kx_groups.iter().all(|kx| kx.fips())
319            && signature_verification_algorithms.fips()
320            && secure_random.fips()
321            && key_provider.fips()
322    }
323
324    /// Return a new `CryptoProvider` that only supports TLS1.3.
325    pub fn with_only_tls13(self) -> Self {
326        let cipher_suites = self
327            .cipher_suites
328            .into_iter()
329            .filter(|cs| cs.version() == crate::version::TLS13)
330            .collect();
331        Self {
332            cipher_suites,
333            ..self
334        }
335    }
336
337    /// Return a new `CryptoProvider` that only supports TLS1.2.
338    pub fn with_only_tls12(self) -> Self {
339        let cipher_suites = self
340            .cipher_suites
341            .into_iter()
342            .filter(|cs| cs.version() == crate::version::TLS12)
343            .collect();
344        Self {
345            cipher_suites,
346            ..self
347        }
348    }
349
350    pub(crate) fn consistency_check(&self) -> Result<(), Error> {
351        if self.cipher_suites.is_empty() {
352            return Err(Error::General("no cipher suites configured".into()));
353        }
354
355        if self.kx_groups.is_empty() {
356            return Err(Error::General("no kx groups configured".into()));
357        }
358
359        // verifying cipher suites have matching kx groups
360        let mut supported_kx_algos = Vec::with_capacity(ALL_KEY_EXCHANGE_ALGORITHMS.len());
361        for group in self.kx_groups.iter() {
362            let kx = group.name().key_exchange_algorithm();
363            if !supported_kx_algos.contains(&kx) {
364                supported_kx_algos.push(kx);
365            }
366            // Small optimization. We don't need to go over other key exchange groups
367            // if we already cover all supported key exchange algorithms
368            if supported_kx_algos.len() == ALL_KEY_EXCHANGE_ALGORITHMS.len() {
369                break;
370            }
371        }
372
373        for cs in self.cipher_suites.iter() {
374            let cs_kx = cs.key_exchange_algorithms();
375            if cs_kx
376                .iter()
377                .any(|kx| supported_kx_algos.contains(kx))
378            {
379                continue;
380            }
381            let suite_name = cs.common().suite;
382            return Err(Error::General(alloc::format!(
383                "Ciphersuite {suite_name:?} requires {cs_kx:?} key exchange, but no {cs_kx:?}-compatible \
384                key exchange groups were present in `CryptoProvider`'s `kx_groups` field",
385            )));
386        }
387
388        Ok(())
389    }
390}
391
392/// A source of cryptographically secure randomness.
393pub trait SecureRandom: Send + Sync + Debug {
394    /// Fill the given buffer with random bytes.
395    ///
396    /// The bytes must be sourced from a cryptographically secure random number
397    /// generator seeded with good quality, secret entropy.
398    ///
399    /// This is used for all randomness required by rustls, but not necessarily
400    /// randomness required by the underlying cryptography library.  For example:
401    /// [`SupportedKxGroup::start()`] requires random material to generate
402    /// an ephemeral key exchange key, but this is not included in the interface with
403    /// rustls: it is assumed that the cryptography library provides for this itself.
404    fn fill(&self, buf: &mut [u8]) -> Result<(), GetRandomFailed>;
405
406    /// Return `true` if this is backed by a FIPS-approved implementation.
407    fn fips(&self) -> bool {
408        false
409    }
410}
411
412/// A mechanism for loading private [`SigningKey`]s from [`PrivateKeyDer`].
413///
414/// This trait is intended to be used with private key material that is sourced from DER,
415/// such as a private-key that may be present on-disk. It is not intended to be used with
416/// keys held in hardware security modules (HSMs) or physical tokens. For these use-cases
417/// see the Rustls manual section on [customizing private key usage].
418///
419/// [customizing private key usage]: <https://docs.rs/rustls/latest/rustls/manual/_03_howto/index.html#customising-private-key-usage>
420pub trait KeyProvider: Send + Sync + Debug {
421    /// Decode and validate a private signing key from `key_der`.
422    ///
423    /// This is used by [`ConfigBuilder::with_client_auth_cert()`], [`ConfigBuilder::with_single_cert()`],
424    /// and [`ConfigBuilder::with_single_cert_with_ocsp()`].  The key types and formats supported by this
425    /// function directly defines the key types and formats supported in those APIs.
426    ///
427    /// Return an error if the key type encoding is not supported, or if the key fails validation.
428    fn load_private_key(
429        &self,
430        key_der: PrivateKeyDer<'static>,
431    ) -> Result<Arc<dyn SigningKey>, Error>;
432
433    /// Return `true` if this is backed by a FIPS-approved implementation.
434    ///
435    /// If this returns `true`, that must be the case for all possible key types
436    /// supported by [`KeyProvider::load_private_key()`].
437    fn fips(&self) -> bool {
438        false
439    }
440}
441
442/// A supported key exchange group.
443///
444/// This type carries both configuration and implementation. Specifically,
445/// it has a TLS-level name expressed using the [`NamedGroup`] enum, and
446/// a function which produces a [`ActiveKeyExchange`].
447///
448/// Compare with [`NamedGroup`], which carries solely a protocol identifier.
449pub trait SupportedKxGroup: Send + Sync + Debug {
450    /// Start a key exchange.
451    ///
452    /// This will prepare an ephemeral secret key in the supported group, and a corresponding
453    /// public key. The key exchange can be completed by calling [ActiveKeyExchange#complete]
454    /// or discarded.
455    ///
456    /// # Errors
457    ///
458    /// This can fail if the random source fails during ephemeral key generation.
459    fn start(&self) -> Result<Box<dyn ActiveKeyExchange>, Error>;
460
461    /// Start and complete a key exchange, in one operation.
462    ///
463    /// The default implementation for this calls `start()` and then calls
464    /// `complete()` on the result.  This is suitable for Diffie-Hellman-like
465    /// key exchange algorithms, where there is not a data dependency between
466    /// our key share (named "pub_key" in this API) and the peer's (`peer_pub_key`).
467    ///
468    /// If there is such a data dependency (like key encapsulation mechanisms), this
469    /// function should be implemented.
470    fn start_and_complete(&self, peer_pub_key: &[u8]) -> Result<CompletedKeyExchange, Error> {
471        let kx = self.start()?;
472
473        Ok(CompletedKeyExchange {
474            group: kx.group(),
475            pub_key: kx.pub_key().to_vec(),
476            secret: kx.complete(peer_pub_key)?,
477        })
478    }
479
480    /// FFDHE group the `SupportedKxGroup` operates in, if any.
481    ///
482    /// The default implementation returns `None`, so non-FFDHE groups (the
483    /// most common) do not need to do anything.
484    ///
485    /// FFDHE groups must implement this. `rustls::ffdhe_groups` contains
486    /// suitable values to return, for example
487    /// [`rustls::ffdhe_groups::FFDHE2048`][crate::ffdhe_groups::FFDHE2048].
488    fn ffdhe_group(&self) -> Option<FfdheGroup<'static>> {
489        None
490    }
491
492    /// Named group the SupportedKxGroup operates in.
493    ///
494    /// If the `NamedGroup` enum does not have a name for the algorithm you are implementing,
495    /// you can use [`NamedGroup::Unknown`].
496    fn name(&self) -> NamedGroup;
497
498    /// Return `true` if this is backed by a FIPS-approved implementation.
499    fn fips(&self) -> bool {
500        false
501    }
502}
503
504/// An in-progress key exchange originating from a [`SupportedKxGroup`].
505pub trait ActiveKeyExchange: Send + Sync {
506    /// Completes the key exchange, given the peer's public key.
507    ///
508    /// This method must return an error if `peer_pub_key` is invalid: either
509    /// mis-encoded, or an invalid public key (such as, but not limited to, being
510    /// in a small order subgroup).
511    ///
512    /// If the key exchange algorithm is FFDHE, the result must be left-padded with zeros,
513    /// as required by [RFC 8446](https://www.rfc-editor.org/rfc/rfc8446#section-7.4.1)
514    /// (see [`complete_for_tls_version()`](Self::complete_for_tls_version) for more details).
515    ///
516    /// The shared secret is returned as a [`SharedSecret`] which can be constructed
517    /// from a `&[u8]`.
518    ///
519    /// This consumes and so terminates the [`ActiveKeyExchange`].
520    fn complete(self: Box<Self>, peer_pub_key: &[u8]) -> Result<SharedSecret, Error>;
521
522    /// Completes the key exchange for the given TLS version, given the peer's public key.
523    ///
524    /// Note that finite-field Diffie–Hellman key exchange has different requirements for the derived
525    /// shared secret in TLS 1.2 and TLS 1.3 (ECDHE key exchange is the same in TLS 1.2 and TLS 1.3):
526    ///
527    /// In TLS 1.2, the calculated secret is required to be stripped of leading zeros
528    /// [(RFC 5246)](https://www.rfc-editor.org/rfc/rfc5246#section-8.1.2).
529    ///
530    /// In TLS 1.3, the calculated secret is required to be padded with leading zeros to be the same
531    /// byte-length as the group modulus [(RFC 8446)](https://www.rfc-editor.org/rfc/rfc8446#section-7.4.1).
532    ///
533    /// The default implementation of this method delegates to [`complete()`](Self::complete) assuming it is
534    /// implemented for TLS 1.3 (i.e., for FFDHE KX, removes padding as needed). Implementers of this trait
535    /// are encouraged to just implement [`complete()`](Self::complete) assuming TLS 1.3, and let the default
536    /// implementation of this method handle TLS 1.2-specific requirements.
537    ///
538    /// This method must return an error if `peer_pub_key` is invalid: either
539    /// mis-encoded, or an invalid public key (such as, but not limited to, being
540    /// in a small order subgroup).
541    ///
542    /// The shared secret is returned as a [`SharedSecret`] which can be constructed
543    /// from a `&[u8]`.
544    ///
545    /// This consumes and so terminates the [`ActiveKeyExchange`].
546    fn complete_for_tls_version(
547        self: Box<Self>,
548        peer_pub_key: &[u8],
549        tls_version: &SupportedProtocolVersion,
550    ) -> Result<SharedSecret, Error> {
551        if tls_version.version() != ProtocolVersion::TLSv1_2 {
552            return self.complete(peer_pub_key);
553        }
554
555        let group = self.group();
556        let mut complete_res = self.complete(peer_pub_key)?;
557        if group.key_exchange_algorithm() == KeyExchangeAlgorithm::DHE {
558            complete_res.strip_leading_zeros();
559        }
560        Ok(complete_res)
561    }
562
563    /// For hybrid key exchanges, returns the [`NamedGroup`] and key share
564    /// for the classical half of this key exchange.
565    ///
566    /// There is no requirement for a hybrid scheme (or any other!) to implement
567    /// `hybrid_component()`. It only enables an optimization; described below.
568    ///
569    /// "Hybrid" means a key exchange algorithm which is constructed from two
570    /// (or more) independent component algorithms. Usually one is post-quantum-secure,
571    /// and the other is "classical".  See
572    /// <https://datatracker.ietf.org/doc/draft-ietf-tls-hybrid-design/11/>
573    ///
574    /// # Background
575    /// Rustls always sends a presumptive key share in its `ClientHello`, using
576    /// (absent any other information) the first item in [`CryptoProvider::kx_groups`].
577    /// If the server accepts the client's selection, it can complete the handshake
578    /// using that key share.  If not, the server sends a `HelloRetryRequest` instructing
579    /// the client to send a different key share instead.
580    ///
581    /// This request costs an extra round trip, and wastes the key exchange computation
582    /// (in [`SupportedKxGroup::start()`]) the client already did.  We would
583    /// like to avoid those wastes if possible.
584    ///
585    /// It is early days for post-quantum-secure hybrid key exchange deployment.
586    /// This means (commonly) continuing to offer both the hybrid and classical
587    /// key exchanges, so the handshake can be completed without a `HelloRetryRequest`
588    /// for servers that support the offered hybrid or classical schemes.
589    ///
590    /// Implementing `hybrid_component()` enables two optimizations:
591    ///
592    /// 1. Sending both the hybrid and classical key shares in the `ClientHello`.
593    ///
594    /// 2. Performing the classical key exchange setup only once.  This is important
595    ///    because the classical key exchange setup is relatively expensive.
596    ///    This optimization is permitted and described in
597    ///    <https://www.ietf.org/archive/id/draft-ietf-tls-hybrid-design-11.html#section-3.2>
598    ///
599    /// Both of these only happen if the classical algorithm appears separately in
600    /// the client's [`CryptoProvider::kx_groups`], and if the hybrid algorithm appears
601    /// first in that list.
602    ///
603    /// # How it works
604    /// This function is only called by rustls for clients.  It is called when
605    /// constructing the initial `ClientHello`.  rustls follows these steps:
606    ///
607    /// 1. If the return value is `None`, nothing further happens.
608    /// 2. If the given [`NamedGroup`] does not appear in
609    ///    [`CryptoProvider::kx_groups`], nothing further happens.
610    /// 3. The given key share is added to the `ClientHello`, after the hybrid entry.
611    ///
612    /// Then, one of three things may happen when the server replies to the `ClientHello`:
613    ///
614    /// 1. The server sends a `HelloRetryRequest`.  Everything is thrown away and
615    ///    we start again.
616    /// 2. The server agrees to our hybrid key exchange: rustls calls
617    ///    [`ActiveKeyExchange::complete()`] consuming `self`.
618    /// 3. The server agrees to our classical key exchange: rustls calls
619    ///    [`ActiveKeyExchange::complete_hybrid_component()`] which
620    ///    discards the hybrid key data, and completes just the classical key exchange.
621    fn hybrid_component(&self) -> Option<(NamedGroup, &[u8])> {
622        None
623    }
624
625    /// Completes the classical component of the key exchange, given the peer's public key.
626    ///
627    /// This is only called if `hybrid_component` returns `Some(_)`.
628    ///
629    /// This method must return an error if `peer_pub_key` is invalid: either
630    /// mis-encoded, or an invalid public key (such as, but not limited to, being
631    /// in a small order subgroup).
632    ///
633    /// The shared secret is returned as a [`SharedSecret`] which can be constructed
634    /// from a `&[u8]`.
635    ///
636    /// See the documentation on [`Self::hybrid_component()`] for explanation.
637    fn complete_hybrid_component(
638        self: Box<Self>,
639        _peer_pub_key: &[u8],
640    ) -> Result<SharedSecret, Error> {
641        unreachable!("only called if `hybrid_component()` implemented")
642    }
643
644    /// Return the public key being used.
645    ///
646    /// For ECDHE, the encoding required is defined in
647    /// [RFC8446 section 4.2.8.2](https://www.rfc-editor.org/rfc/rfc8446#section-4.2.8.2).
648    ///
649    /// For FFDHE, the encoding required is defined in
650    /// [RFC8446 section 4.2.8.1](https://www.rfc-editor.org/rfc/rfc8446#section-4.2.8.1).
651    fn pub_key(&self) -> &[u8];
652
653    /// FFDHE group the `ActiveKeyExchange` is operating in.
654    ///
655    /// The default implementation returns `None`, so non-FFDHE groups (the
656    /// most common) do not need to do anything.
657    ///
658    /// FFDHE groups must implement this. `rustls::ffdhe_groups` contains
659    /// suitable values to return, for example
660    /// [`rustls::ffdhe_groups::FFDHE2048`][crate::ffdhe_groups::FFDHE2048].
661    fn ffdhe_group(&self) -> Option<FfdheGroup<'static>> {
662        None
663    }
664
665    /// Return the group being used.
666    fn group(&self) -> NamedGroup;
667}
668
669/// The result from [`SupportedKxGroup::start_and_complete()`].
670#[allow(clippy::exhaustive_structs)]
671pub struct CompletedKeyExchange {
672    /// Which group was used.
673    pub group: NamedGroup,
674
675    /// Our key share (sometimes a public key).
676    pub pub_key: Vec<u8>,
677
678    /// The computed shared secret.
679    pub secret: SharedSecret,
680}
681
682/// The result from [`ActiveKeyExchange::complete`] or [`ActiveKeyExchange::complete_hybrid_component`].
683pub struct SharedSecret {
684    buf: Vec<u8>,
685    offset: usize,
686}
687
688impl SharedSecret {
689    /// Returns the shared secret as a slice of bytes.
690    pub fn secret_bytes(&self) -> &[u8] {
691        &self.buf[self.offset..]
692    }
693
694    /// Removes leading zeros from `secret_bytes()` by adjusting the `offset`.
695    ///
696    /// This function does not re-allocate.
697    fn strip_leading_zeros(&mut self) {
698        let start = self
699            .secret_bytes()
700            .iter()
701            .enumerate()
702            .find(|(_i, x)| **x != 0)
703            .map(|(i, _x)| i)
704            .unwrap_or(self.secret_bytes().len());
705        self.offset += start;
706    }
707}
708
709impl Drop for SharedSecret {
710    fn drop(&mut self) {
711        self.buf.zeroize();
712    }
713}
714
715impl From<&[u8]> for SharedSecret {
716    fn from(source: &[u8]) -> Self {
717        Self {
718            buf: source.to_vec(),
719            offset: 0,
720        }
721    }
722}
723
724impl From<Vec<u8>> for SharedSecret {
725    fn from(buf: Vec<u8>) -> Self {
726        Self { buf, offset: 0 }
727    }
728}
729
730/// This function returns a [`CryptoProvider`] that uses
731/// FIPS140-3-approved cryptography.
732///
733/// Using this function expresses in your code that you require
734/// FIPS-approved cryptography, and will not compile if you make
735/// a mistake with cargo features.
736///
737/// See our [FIPS documentation](crate::manual::_06_fips) for
738/// more detail.
739///
740/// Install this as the process-default provider, like:
741///
742/// ```rust
743/// # #[cfg(feature = "fips")] {
744/// rustls::crypto::default_fips_provider().install_default()
745///     .expect("default provider already set elsewhere");
746/// # }
747/// ```
748///
749/// You can also use this explicitly, like:
750///
751/// ```rust
752/// # #[cfg(feature = "fips")] {
753/// # let root_store = rustls::RootCertStore::empty();
754/// let config = rustls::ClientConfig::builder_with_provider(
755///         rustls::crypto::default_fips_provider().into()
756///     )
757///     .with_root_certificates(root_store)
758///     .with_no_client_auth()
759///     .unwrap();
760/// # }
761/// ```
762#[cfg(all(feature = "aws-lc-rs", any(feature = "fips", docsrs)))]
763#[cfg_attr(docsrs, doc(cfg(feature = "fips")))]
764pub fn default_fips_provider() -> CryptoProvider {
765    aws_lc_rs::default_provider()
766}
767
768mod static_default {
769    #[cfg(not(feature = "std"))]
770    use alloc::boxed::Box;
771    #[cfg(feature = "std")]
772    use std::sync::OnceLock;
773
774    #[cfg(not(feature = "std"))]
775    use once_cell::race::OnceBox;
776
777    use super::CryptoProvider;
778    use crate::sync::Arc;
779
780    #[cfg(feature = "std")]
781    pub(crate) fn install_default(
782        default_provider: CryptoProvider,
783    ) -> Result<(), Arc<CryptoProvider>> {
784        PROCESS_DEFAULT_PROVIDER.set(Arc::new(default_provider))
785    }
786
787    #[cfg(not(feature = "std"))]
788    pub(crate) fn install_default(
789        default_provider: CryptoProvider,
790    ) -> Result<(), Arc<CryptoProvider>> {
791        PROCESS_DEFAULT_PROVIDER
792            .set(Box::new(Arc::new(default_provider)))
793            .map_err(|e| *e)
794    }
795
796    pub(crate) fn get_default() -> Option<&'static Arc<CryptoProvider>> {
797        PROCESS_DEFAULT_PROVIDER.get()
798    }
799
800    #[cfg(feature = "std")]
801    static PROCESS_DEFAULT_PROVIDER: OnceLock<Arc<CryptoProvider>> = OnceLock::new();
802    #[cfg(not(feature = "std"))]
803    static PROCESS_DEFAULT_PROVIDER: OnceBox<Arc<CryptoProvider>> = OnceBox::new();
804}
805
806#[cfg(test)]
807mod tests {
808    use std::vec;
809
810    use super::SharedSecret;
811
812    #[test]
813    fn test_shared_secret_strip_leading_zeros() {
814        let test_cases = [
815            (vec![0, 1], vec![1]),
816            (vec![1], vec![1]),
817            (vec![1, 0, 2], vec![1, 0, 2]),
818            (vec![0, 0, 1, 2], vec![1, 2]),
819            (vec![0, 0, 0], vec![]),
820            (vec![], vec![]),
821        ];
822        for (buf, expected) in test_cases {
823            let mut secret = SharedSecret::from(&buf[..]);
824            assert_eq!(secret.secret_bytes(), buf);
825            secret.strip_leading_zeros();
826            assert_eq!(secret.secret_bytes(), expected);
827        }
828    }
829}