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