rustls 0.24.0-dev.1

Rustls is a modern TLS library written in Rust.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
//! # Rustls - a modern TLS library
//!
//! Rustls is a TLS library that aims to provide a good level of cryptographic security,
//! requires no configuration to achieve that security, and provides no unsafe features or
//! obsolete cryptography by default.
//!
//! Rustls implements TLS1.2 and TLS1.3 for both clients and servers. See [the full
//! list of protocol features](manual::_04_features).
//!
//! ### Platform support
//!
//! While Rustls itself is platform independent, it requires the use of cryptography primitives
//! for implementing the cryptography algorithms used in TLS. In Rustls, a
//! [`crypto::CryptoProvider`] represents a collection of crypto primitive implementations.
//!
//! By providing a custom instance of the [`crypto::CryptoProvider`] struct, you
//! can replace all cryptography dependencies of rustls.  This is a route to being portable
//! to a wider set of architectures and environments, or compliance requirements.  See the
//! [`crypto::CryptoProvider`] documentation for more details.
//!
//! [`crypto::CryptoProvider`]: crate::crypto::CryptoProvider
//!
//! ### Cryptography providers
//!
//! Since Rustls 0.22 it has been possible to choose the provider of the cryptographic primitives
//! that Rustls uses. This may be appealing if you have specific platform, compliance or feature
//! requirements.
//!
//! From 0.24, users must explicitly provide a crypto provider when constructing `ClientConfig` or
//! `ServerConfig` instances. See the [`crypto::CryptoProvider`] documentation for more details.
//!
//! #### First-party providers
//!
//! The Rustls project currently maintains two cryptography providers:
//!
//! * [`rustls-aws-lc-rs`] - a provider that uses the [`aws-lc-rs`] crate for cryptography.
//!   While this provider can be harder to build on [some platforms][aws-lc-rs-platforms-faq], it provides excellent
//!   performance and a complete feature set (including post-quantum algorithms).
//! * [`rustls-ring`] - a provider that uses the [`ring`] crate for cryptography. This
//!   provider is easier to build on a variety of platforms, but has a more limited feature set
//!   (for example, it does not support post-quantum algorithms).
//!
//! The Rustls team recommends using the [`rustls-aws-lc-rs`] crate for its complete feature set
//! and performance. See [the aws-lc-rs FAQ][aws-lc-rs-platforms-faq] for more details of the
//! platform/architecture support constraints in aws-lc-rs.
//!
//! See the documentation for [`crypto::CryptoProvider`] for details on how providers are
//! selected.
//!
//! (For rustls versions prior to 0.24, both of these providers were shipped as part of the rustls
//! crate, and Cargo features were used to select the preferred provider. The `aws-lc-rs` feature
//! was enabled by default.)
//!
//! [`rustls-aws-lc-rs`]: https://crates.io/crates/rustls-aws-lc-rs
//! [`aws-lc-rs`]: https://crates.io/crates/aws-lc-rs
//! [aws-lc-rs-platforms-faq]: https://aws.github.io/aws-lc-rs/faq.html#can-i-run-aws-lc-rs-on-x-platform-or-architecture
//! [`rustls-ring`]: https://crates.io/crates/rustls-ring
//! [`ring`]: https://crates.io/crates/ring
//!
//! #### Third-party providers
//!
//! The community has also started developing third-party providers for Rustls:
//!
//!   * [`boring-rustls-provider`] - a work-in-progress provider that uses [`boringssl`] for
//!     cryptography.
//!   * [`rustls-ccm`] - adds AES-CCM cipher suites (TLS 1.2 and 1.3) using [`RustCrypto`], for IoT/constrained-device protocols (IEEE 2030.5, Matter, RFC 7925).
//!   * [`rustls-graviola`] - a provider that uses [`graviola`] for cryptography.
//!   * [`rustls-mbedtls-provider`] - a provider that uses [`mbedtls`] for cryptography.
//!   * [`rustls-openssl`] - a provider that uses [OpenSSL] for cryptography.
//!   * [`rustls-rustcrypto`] - an experimental provider that uses the crypto primitives
//!     from [`RustCrypto`] for cryptography.
//!   * [`rustls-symcrypt`] - a provider that uses Microsoft's [SymCrypt] library.
//!   * [`rustls-wolfcrypt-provider`] - a work-in-progress provider that uses [`wolfCrypt`] for cryptography.
//!
//! [`rustls-ccm`]: https://github.com/jsulmont/rustls-ccm
//! [`rustls-graviola`]: https://crates.io/crates/rustls-graviola
//! [`graviola`]: https://github.com/ctz/graviola
//! [`rustls-mbedtls-provider`]: https://github.com/fortanix/rustls-mbedtls-provider
//! [`mbedtls`]: https://github.com/Mbed-TLS/mbedtls
//! [`rustls-openssl`]: https://github.com/tofay/rustls-openssl
//! [OpenSSL]: https://openssl-library.org/
//! [`rustls-symcrypt`]: https://github.com/microsoft/rustls-symcrypt
//! [SymCrypt]: https://github.com/microsoft/SymCrypt
//! [`boring-rustls-provider`]: https://github.com/janrueth/boring-rustls-provider
//! [`boringssl`]: https://github.com/google/boringssl
//! [`rustls-rustcrypto`]: https://github.com/RustCrypto/rustls-rustcrypto
//! [`RustCrypto`]: https://github.com/RustCrypto
//! [`rustls-wolfcrypt-provider`]: https://github.com/wolfSSL/rustls-wolfcrypt-provider
//! [`wolfCrypt`]: https://www.wolfssl.com/products/wolfcrypt
//!
//! See the [Making a custom CryptoProvider] section of the documentation for more information
//! on this topic.
//!
//! [Making a custom CryptoProvider]: https://docs.rs/rustls/latest/rustls/crypto/struct.CryptoProvider.html#making-a-custom-cryptoprovider
//!
//! ## Design overview
//!
//! Rustls is a low-level library. If your goal is to make HTTPS connections you may prefer
//! to use a library built on top of Rustls like [hyper] or [ureq].
//!
//! [hyper]: https://crates.io/crates/hyper
//! [ureq]: https://crates.io/crates/ureq
//!
//! ### Rustls does not take care of network IO
//! It doesn't make or accept TCP connections, or do DNS, or read or write files.
//!
//! Our [examples] directory contains demos that show how to handle I/O using the
//! `rustls_util::Stream` helper, as well as more complex asynchronous I/O using [`mio`].
//! If you're already using Tokio for an async runtime you may prefer to use [`tokio-rustls`] instead
//! of interacting with rustls directly.
//!
//! [examples]: https://github.com/rustls/rustls/tree/main/examples
//! [`tokio-rustls`]: https://github.com/rustls/tokio-rustls
//!
//! ### Rustls provides encrypted pipes
//! These are the [`ServerConnection`] and [`ClientConnection`] types.  You supply raw TLS traffic
//! on the left (via the [`TlsInputBuffer`] supplied to [`process_new_packets()`], and [`write_tls()`] methods)
//! and then read/write the plaintext on the right:
//!
//! [`write_tls()`]: Connection::write_tls
//! [`process_new_packets()`]: Connection::process_new_packets
//!
//! ```text
//!          TLS                                   Plaintext
//!          ===                                   =========
//!  process_new_packets()  +-----------------------+      reader() as io::Read
//!                         |                       |
//!               +--------->   ClientConnection    +--------->
//!                         |          or           |
//!               <---------+   ServerConnection    <---------+
//!                         |                       |
//!         write_tls()     +-----------------------+      writer() as io::Write
//! ```
//!
//! ### Rustls takes care of server certificate verification
//! You do not need to provide anything other than a set of root certificates to trust.
//! Certificate verification cannot be turned off or disabled in the main API.
//!
//! ## Getting started
//! This is the minimum you need to do to make a TLS client connection.
//!
//! First we load some root certificates.  These are used to authenticate the server.
//! The simplest way is to depend on the [`webpki_roots`] crate which contains
//! the Mozilla set of root certificates.
//!
//! ```rust,no_run
//! let root_store = rustls::RootCertStore::from_iter(
//!     webpki_roots::TLS_SERVER_ROOTS
//!         .iter()
//!         .cloned(),
//! );
//! ```
//!
//! [`webpki_roots`]: https://crates.io/crates/webpki-roots
//!
//! Next, we make a `ClientConfig`.  You're likely to make one of these per process,
//! and use it for all connections made by that process.
//!
//! ```rust,no_run
//! # let DEFAULT_PROVIDER = rustls::crypto::CryptoProvider::get_default().unwrap().clone();
//! # let root_store: rustls::RootCertStore = panic!();
//! let config = rustls::ClientConfig::builder(DEFAULT_PROVIDER)
//!     .with_root_certificates(root_store)
//!     .with_no_client_auth()
//!     .unwrap();
//! ```
//!
//! Now we can make a connection.  You need to provide the server's hostname so we
//! know what to expect to find in the server's certificate.
//!
//! ```rust,no_run
//! # use rustls;
//! # use webpki;
//! # use std::sync::Arc;
//! # let DEFAULT_PROVIDER = rustls::crypto::CryptoProvider::get_default().unwrap().clone();
//! # let root_store = rustls::RootCertStore::from_iter(
//! #  webpki_roots::TLS_SERVER_ROOTS
//! #      .iter()
//! #      .cloned(),
//! # );
//! # let client_config = Arc::new(rustls::ClientConfig::builder(DEFAULT_PROVIDER)
//! #     .with_root_certificates(root_store)
//! #     .with_no_client_auth()
//! #     .unwrap());
//!
//! let example_com = "example.com".try_into().unwrap();
//! let mut client = client_config.connect(example_com)
//!     .build()
//!     .unwrap();
//! ```
//!
//! Now you should do appropriate IO for the `client` object.  If `client.wants_read()` yields
//! true, you should call `client.process_new_packets()` with the data from the underlying connection.
//! Likewise, if `client.wants_write()` yields true, you should call `client.write_tls()`
//! when the underlying connection is able to send data.  You should continue doing this
//! as long as the connection is valid.
//!
//! Any error returned from `process_new_packets()` is fatal to the connection, and will tell you
//! why.  For example, if the server's certificate is expired `process_new_packets()` will
//! return `Err(InvalidCertificate(Expired))`.  From this point on,
//! `process_new_packets()` will not do any new work and will return that error continually.
//!
//! You can extract newly received data by calling `client.reader()` (which implements the
//! `io::Read` trait).  You can send data to the peer by calling `client.writer()` (which
//! implements `io::Write` trait).  Note that `client.writer().write()` buffers data you
//! send if the TLS connection is not yet established: this is useful for writing (say) a
//! HTTP request, but this is buffered so avoid large amounts of data.
//!
//! The following code uses a fictional socket IO API for illustration, and does not handle
//! errors.
//!
//! ```rust,no_run
//! # let mut client: rustls::ClientConnection = panic!();
//! # struct Socket { }
//! # impl Socket {
//! #   fn ready_for_write(&self) -> bool { false }
//! #   fn ready_for_read(&self) -> bool { false }
//! #   fn wait_for_something_to_happen(&self) { }
//! # }
//! #
//! # use std::io::{Read, Write, Result};
//! # impl Read for Socket {
//! #   fn read(&mut self, buf: &mut [u8]) -> Result<usize> { panic!() }
//! # }
//! # impl Write for Socket {
//! #   fn write(&mut self, buf: &[u8]) -> Result<usize> { panic!() }
//! #   fn flush(&mut self) -> Result<()> { panic!() }
//! # }
//! #
//! # fn connect(_address: &str, _port: u16) -> Socket {
//! #   panic!();
//! # }
//! use std::io;
//! use rustls::{Connection, VecInput};
//!
//! client.writer().write(b"GET / HTTP/1.0\r\n\r\n").unwrap();
//! let mut socket = connect("example.com", 443);
//! let mut input = VecInput::default();
//! loop {
//!   if client.wants_read() && socket.ready_for_read() {
//!     input.read(&mut socket).unwrap();
//!     client.process_new_packets(&mut input).unwrap();
//!
//!     let mut plaintext = Vec::new();
//!     client.reader().read_to_end(&mut plaintext).unwrap();
//!     io::stdout().write(&plaintext).unwrap();
//!   }
//!
//!   if client.wants_write() && socket.ready_for_write() {
//!     client.write_tls(&mut socket).unwrap();
//!   }
//!
//!   socket.wait_for_something_to_happen();
//! }
//! ```
//!
//! # Examples
//!
//! You can find several client and server examples of varying complexity in the [examples]
//! directory, including [`tlsserver-mio`](https://github.com/rustls/rustls/blob/main/examples/src/bin/tlsserver-mio.rs)
//! and [`tlsclient-mio`](https://github.com/rustls/rustls/blob/main/examples/src/bin/tlsclient-mio.rs)
//! \- full worked examples using [`mio`].
//!
//! [`mio`]: https://docs.rs/mio/latest/mio/
//!
//! # Manual
//!
//! The [rustls manual](crate::manual) explains design decisions and includes how-to guidance.
//!
//! # Crate features
//! Here's a list of what features are exposed by the rustls crate and what
//! they mean.
//!
//! - `std` (enabled by default): enable the high-level (buffered) Connection API and other functionality
//!   which relies on the `std` library.
//!
//! - `log` (enabled by default): make the rustls crate depend on the `log` crate.
//!   rustls outputs interesting protocol-level messages at `trace!` and `debug!` level,
//!   and protocol-level errors at `warn!` and `error!` level.  The log messages do not
//!   contain secret key data, and so are safe to archive without affecting session security.
//!
//! - `webpki` (enabled by default): make the rustls crate depend on the `rustls-webpki` crate, which
//!   is used by default to provide built-in certificate verification.  Without this feature, users must
//!   provide certificate verification themselves.
//!
//! - `brotli`: uses the `brotli` crate for RFC8879 certificate compression support.
//!
//! - `zlib`: uses the `zlib-rs` crate for RFC8879 certificate compression support.
//!
//! [x25519mlkem768-manual]: manual::_05_defaults#about-the-post-quantum-secure-key-exchange-x25519mlkem768

// Require docs for public APIs, deny unsafe code, etc.
#![warn(missing_docs, clippy::exhaustive_enums, clippy::exhaustive_structs)]
#![forbid(unsafe_code, unused_must_use)]
#![cfg_attr(not(any(bench, coverage_nightly)), forbid(unstable_features))]
// Enable documentation for all features on docs.rs
#![cfg_attr(rustls_docsrs, feature(doc_cfg))]
// Enable coverage() attr for nightly coverage builds, see
// <https://github.com/rust-lang/rust/issues/84605>
// (`coverage_nightly` is a cfg set by `cargo-llvm-cov`)
#![cfg_attr(coverage_nightly, feature(coverage_attribute))]
#![cfg_attr(bench, feature(test))]
#![no_std]

extern crate alloc;
// This `extern crate` plus the `#![no_std]` attribute changes the default prelude from
// `std::prelude` to `core::prelude`. That forces one to _explicitly_ import (`use`) everything that
// is in `std::prelude` but not in `core::prelude`. This helps maintain no-std support as even
// developers that are not interested in, or aware of, no-std support and / or that never run
// `cargo build --no-default-features` locally will get errors when they rely on `std::prelude` API.
extern crate std;

#[cfg(doc)]
use crate::crypto::CryptoProvider;

// Import `test` sysroot crate for `Bencher` definitions.
#[cfg(bench)]
#[allow(unused_extern_crates)]
extern crate test;

// log for logging (optional).
#[cfg(feature = "log")]
#[expect(clippy::single_component_path_imports)]
use log;

#[cfg(not(feature = "log"))]
mod log {
    macro_rules! trace    ( ($($tt:tt)*) => { crate::log::_used!($($tt)*) } );
    macro_rules! debug    ( ($($tt:tt)*) => { crate::log::_used!($($tt)*) } );
    macro_rules! error    ( ($($tt:tt)*) => { crate::log::_used!($($tt)*) } );
    macro_rules! _warn    ( ($($tt:tt)*) => { crate::log::_used!($($tt)*) } );
    macro_rules! _used    ( ($($tt:tt)*) => { { let _ = format_args!($($tt)*); } } );
    pub(crate) use _used;
    pub(crate) use _warn as warn;
    pub(crate) use debug;
    pub(crate) use error;
    pub(crate) use trace;
}

/// This internal `sync` module aliases the `Arc` implementation to allow downstream forks
/// of rustls targeting architectures without atomic pointers to replace the implementation
/// with another implementation such as `portable_atomic_util::Arc` in one central location.
mod sync {
    #[expect(clippy::disallowed_types)]
    pub(crate) type Arc<T> = alloc::sync::Arc<T>;
}

#[expect(unnameable_types)]
#[macro_use]
mod msgs;
mod common_state;
pub mod compress;
mod conn;
/// Crypto provider interface.
pub mod crypto;
pub mod error;
mod hash_hs;
mod limited_cache;
mod tls12;
mod tls13;
mod vecbuf;
mod verify;
mod x509;
#[macro_use]
mod check;
mod bs_debug;
mod builder;
pub mod enums;
mod key_log;
mod suites;
mod versions;
#[cfg(feature = "webpki")]
mod webpki;

/// Internal classes that are used in integration tests.
/// The contents of this section DO NOT form part of the stable interface.
#[doc(hidden)]
pub mod internal {
    pub use crate::msgs::fuzzing;
}

// The public interface is:
pub use crate::builder::{ConfigBuilder, ConfigSide, WantsVerifier};
pub use crate::common_state::{CommonState, ConnectionOutputs, HandshakeKind};
pub use crate::conn::{
    Connection, IoState, KeyingMaterialExporter, Reader, SideData, SliceInput, TlsInputBuffer,
    VecInput, Writer, kernel,
};
/// Types related to "split" mode.
///
/// See [`split::SplitConnection`] for more information.
pub mod split {
    pub use crate::conn::WrittenInto;
    pub use crate::conn::split::{
        FlushSender, ReceiveTraffic, ReceiveTrafficState, ReceivedApplicationData, SendTraffic,
        SplitConnection,
    };
}
pub use crate::error::Error;
pub use crate::key_log::{KeyLog, NoKeyLog};
pub use crate::suites::{
    CipherSuiteCommon, ConnectionTrafficSecrets, ExtractedSecrets, SupportedCipherSuite,
};
pub use crate::ticketer::TicketRotator;
pub use crate::tls12::Tls12CipherSuite;
pub use crate::tls13::Tls13CipherSuite;
pub use crate::verify::{DigitallySignedStruct, DistinguishedName, SignerPublicKey};
pub use crate::versions::{ALL_VERSIONS, DEFAULT_VERSIONS, SupportedProtocolVersion};
#[cfg(feature = "webpki")]
pub use crate::webpki::RootCertStore;

/// Items for use in a client.
pub mod client;
pub use client::{ClientConfig, ClientConnection};

/// Items for use in a server.
pub mod server;
pub use server::{ServerConfig, ServerConnection};

/// All defined protocol versions appear in this module.
///
/// ALL_VERSIONS is provided as an array of all of these values.
pub mod version {
    pub use crate::versions::{
        TLS12, TLS12_VERSION, TLS13, TLS13_VERSION, Tls12Version, Tls13Version,
    };
}

/// Re-exports the contents of the [rustls-pki-types](https://docs.rs/rustls-pki-types) crate for easy access
pub mod pki_types {
    #[doc(no_inline)]
    pub use pki_types::*;
}

/// APIs for implementing QUIC TLS
pub mod quic;

/// APIs for implementing TLS tickets
pub mod ticketer;

/// This is the rustls manual.
pub mod manual;

pub mod time_provider;

/// APIs abstracting over locking primitives.
pub mod lock;

mod hash_map {
    pub(crate) use std::collections::HashMap;
    pub(crate) use std::collections::hash_map::Entry;
}

mod sealed {
    #[expect(unnameable_types)]
    pub trait Sealed {}
}

mod core_hash_polyfill {
    use core::hash::Hasher;

    /// Working around `core::hash::Hasher` not being dyn-compatible
    pub(super) struct DynHasher<'a>(pub(crate) &'a mut dyn Hasher);

    impl Hasher for DynHasher<'_> {
        fn finish(&self) -> u64 {
            self.0.finish()
        }

        fn write(&mut self, bytes: &[u8]) {
            self.0.write(bytes)
        }
    }
}

pub(crate) use core_hash_polyfill::DynHasher;