rustls_fork_shadow_tls/
lib.rs

1//! # Rustls - a modern TLS library
2//! Rustls is a TLS library that aims to provide a good level of cryptographic security,
3//! requires no configuration to achieve that security, and provides no unsafe features or
4//! obsolete cryptography.
5//!
6//! ## Current features
7//!
8//! * TLS1.2 and TLS1.3.
9//! * ECDSA, Ed25519 or RSA server authentication by clients.
10//! * ECDSA, Ed25519 or RSA server authentication by servers.
11//! * Forward secrecy using ECDHE; with curve25519, nistp256 or nistp384 curves.
12//! * AES128-GCM and AES256-GCM bulk encryption, with safe nonces.
13//! * ChaCha20-Poly1305 bulk encryption ([RFC7905](https://tools.ietf.org/html/rfc7905)).
14//! * ALPN support.
15//! * SNI support.
16//! * Tunable fragment size to make TLS messages match size of underlying transport.
17//! * Optional use of vectored IO to minimise system calls.
18//! * TLS1.2 session resumption.
19//! * TLS1.2 resumption via tickets ([RFC5077](https://tools.ietf.org/html/rfc5077)).
20//! * TLS1.3 resumption via tickets or session storage.
21//! * TLS1.3 0-RTT data for clients.
22//! * TLS1.3 0-RTT data for servers.
23//! * Client authentication by clients.
24//! * Client authentication by servers.
25//! * Extended master secret support ([RFC7627](https://tools.ietf.org/html/rfc7627)).
26//! * Exporters ([RFC5705](https://tools.ietf.org/html/rfc5705)).
27//! * OCSP stapling by servers.
28//! * SCT stapling by servers.
29//! * SCT verification by clients.
30//!
31//! ## Possible future features
32//!
33//! * PSK support.
34//! * OCSP verification by clients.
35//! * Certificate pinning.
36//!
37//! ## Non-features
38//!
39//! For reasons [explained in the manual](manual),
40//! rustls does not and will not support:
41//!
42//! * SSL1, SSL2, SSL3, TLS1 or TLS1.1.
43//! * RC4.
44//! * DES or triple DES.
45//! * EXPORT ciphersuites.
46//! * MAC-then-encrypt ciphersuites.
47//! * Ciphersuites without forward secrecy.
48//! * Renegotiation.
49//! * Kerberos.
50//! * Compression.
51//! * Discrete-log Diffie-Hellman.
52//! * Automatic protocol version downgrade.
53//!
54//! There are plenty of other libraries that provide these features should you
55//! need them.
56//!
57//! ### Platform support
58//!
59//! Rustls uses [`ring`](https://crates.io/crates/ring) for implementing the
60//! cryptography in TLS. As a result, rustls only runs on platforms
61//! [supported by `ring`](https://github.com/briansmith/ring#online-automated-testing).
62//! At the time of writing this means x86, x86-64, armv7, and aarch64.
63//!
64//! ## Design Overview
65//! ### Rustls does not take care of network IO
66//! It doesn't make or accept TCP connections, or do DNS, or read or write files.
67//!
68//! There's example client and server code which uses mio to do all needed network
69//! IO.
70//!
71//! ### Rustls provides encrypted pipes
72//! These are the [`ServerConnection`] and [`ClientConnection`] types.  You supply raw TLS traffic
73//! on the left (via the [`read_tls()`] and [`write_tls()`] methods) and then read/write the
74//! plaintext on the right:
75//!
76//! [`read_tls()`]: Connection::read_tls
77//! [`write_tls()`]: Connection::read_tls
78//!
79//! ```text
80//!          TLS                                   Plaintext
81//!          ===                                   =========
82//!     read_tls()      +-----------------------+      reader() as io::Read
83//!                     |                       |
84//!           +--------->   ClientConnection    +--------->
85//!                     |          or           |
86//!           <---------+   ServerConnection    <---------+
87//!                     |                       |
88//!     write_tls()     +-----------------------+      writer() as io::Write
89//! ```
90//!
91//! ### Rustls takes care of server certificate verification
92//! You do not need to provide anything other than a set of root certificates to trust.
93//! Certificate verification cannot be turned off or disabled in the main API.
94//!
95//! ## Getting started
96//! This is the minimum you need to do to make a TLS client connection.
97//!
98//! First we load some root certificates.  These are used to authenticate the server.
99//! The recommended way is to depend on the `webpki_roots` crate which contains
100//! the Mozilla set of root certificates.
101//!
102//! ```rust,no_run
103//! let mut root_store = rustls::RootCertStore::empty();
104//! root_store.add_server_trust_anchors(
105//!     webpki_roots::TLS_SERVER_ROOTS
106//!         .0
107//!         .iter()
108//!         .map(|ta| {
109//!             rustls::OwnedTrustAnchor::from_subject_spki_name_constraints(
110//!                 ta.subject,
111//!                 ta.spki,
112//!                 ta.name_constraints,
113//!             )
114//!         })
115//! );
116//! ```
117//!
118//! Next, we make a `ClientConfig`.  You're likely to make one of these per process,
119//! and use it for all connections made by that process.
120//!
121//! ```rust,no_run
122//! # let root_store: rustls::RootCertStore = panic!();
123//! let config = rustls::ClientConfig::builder()
124//!     .with_safe_defaults()
125//!     .with_root_certificates(root_store)
126//!     .with_no_client_auth();
127//! ```
128//!
129//! Now we can make a connection.  You need to provide the server's hostname so we
130//! know what to expect to find in the server's certificate.
131//!
132//! ```rust
133//! # use rustls;
134//! # use webpki;
135//! # use std::sync::Arc;
136//! # use std::convert::TryInto;
137//! # let mut root_store = rustls::RootCertStore::empty();
138//! # root_store.add_server_trust_anchors(
139//! #  webpki_roots::TLS_SERVER_ROOTS
140//! #      .0
141//! #      .iter()
142//! #      .map(|ta| {
143//! #          rustls::OwnedTrustAnchor::from_subject_spki_name_constraints(
144//! #              ta.subject,
145//! #              ta.spki,
146//! #              ta.name_constraints,
147//! #          )
148//! #      })
149//! # );
150//! # let config = rustls::ClientConfig::builder()
151//! #     .with_safe_defaults()
152//! #     .with_root_certificates(root_store)
153//! #     .with_no_client_auth();
154//! let rc_config = Arc::new(config);
155//! let example_com = "example.com".try_into().unwrap();
156//! let mut client = rustls::ClientConnection::new(rc_config, example_com);
157//! ```
158//!
159//! Now you should do appropriate IO for the `client` object.  If `client.wants_read()` yields
160//! true, you should call `client.read_tls()` when the underlying connection has data.
161//! Likewise, if `client.wants_write()` yields true, you should call `client.write_tls()`
162//! when the underlying connection is able to send data.  You should continue doing this
163//! as long as the connection is valid.
164//!
165//! The return types of `read_tls()` and `write_tls()` only tell you if the IO worked.  No
166//! parsing or processing of the TLS messages is done.  After each `read_tls()` you should
167//! therefore call `client.process_new_packets()` which parses and processes the messages.
168//! Any error returned from `process_new_packets` is fatal to the connection, and will tell you
169//! why.  For example, if the server's certificate is expired `process_new_packets` will
170//! return `Err(WebPkiError(CertExpired, ValidateServerCert))`.  From this point on,
171//! `process_new_packets` will not do any new work and will return that error continually.
172//!
173//! You can extract newly received data by calling `client.reader()` (which implements the
174//! `io::Read` trait).  You can send data to the peer by calling `client.writer()` (which
175//! implements `io::Write` trait).  Note that `client.writer().write()` buffers data you
176//! send if the TLS connection is not yet established: this is useful for writing (say) a
177//! HTTP request, but this is buffered so avoid large amounts of data.
178//!
179//! The following code uses a fictional socket IO API for illustration, and does not handle
180//! errors.
181//!
182//! ```rust,no_run
183//! # let mut client = rustls::ClientConnection::new(panic!(), panic!()).unwrap();
184//! # struct Socket { }
185//! # impl Socket {
186//! #   fn ready_for_write(&self) -> bool { false }
187//! #   fn ready_for_read(&self) -> bool { false }
188//! #   fn wait_for_something_to_happen(&self) { }
189//! # }
190//! #
191//! # use std::io::{Read, Write, Result};
192//! # impl Read for Socket {
193//! #   fn read(&mut self, buf: &mut [u8]) -> Result<usize> { panic!() }
194//! # }
195//! # impl Write for Socket {
196//! #   fn write(&mut self, buf: &[u8]) -> Result<usize> { panic!() }
197//! #   fn flush(&mut self) -> Result<()> { panic!() }
198//! # }
199//! #
200//! # fn connect(_address: &str, _port: u16) -> Socket {
201//! #   panic!();
202//! # }
203//! use std::io;
204//! use rustls::Connection;
205//!
206//! client.writer().write(b"GET / HTTP/1.0\r\n\r\n").unwrap();
207//! let mut socket = connect("example.com", 443);
208//! loop {
209//!   if client.wants_read() && socket.ready_for_read() {
210//!     client.read_tls(&mut socket).unwrap();
211//!     client.process_new_packets().unwrap();
212//!
213//!     let mut plaintext = Vec::new();
214//!     client.reader().read_to_end(&mut plaintext).unwrap();
215//!     io::stdout().write(&plaintext).unwrap();
216//!   }
217//!
218//!   if client.wants_write() && socket.ready_for_write() {
219//!     client.write_tls(&mut socket).unwrap();
220//!   }
221//!
222//!   socket.wait_for_something_to_happen();
223//! }
224//! ```
225//!
226//! # Examples
227//! [`tlsserver`](https://github.com/rustls/rustls/blob/main/examples/src/bin/tlsserver-mio.rs)
228//! and [`tlsclient`](https://github.com/rustls/rustls/blob/main/examples/src/bin/tlsclient-mio.rs)
229//! are full worked examples.  These both use mio.
230//!
231//! # Crate features
232//! Here's a list of what features are exposed by the rustls crate and what
233//! they mean.
234//!
235//! - `logging`: this makes the rustls crate depend on the `log` crate.
236//!   rustls outputs interesting protocol-level messages at `trace!` and `debug!`
237//!   level, and protocol-level errors at `warn!` and `error!` level.  The log
238//!   messages do not contain secret key data, and so are safe to archive without
239//!   affecting session security.  This feature is in the default set.
240//!
241//! - `dangerous_configuration`: this feature enables a `dangerous()` method on
242//!   `ClientConfig` and `ServerConfig` that allows setting inadvisable options,
243//!   such as replacing the certificate verification process.  Applications
244//!   requesting this feature should be reviewed carefully.
245//!
246//! - `quic`: this feature exposes additional constructors and functions
247//!   for using rustls as a TLS library for QUIC.  See the `quic` module for
248//!   details of these.  You will only need this if you're writing a QUIC
249//!   implementation.
250//!
251//! - `tls12`: enables support for TLS version 1.2. This feature is in the default
252//!   set. Note that, due to the additive nature of Cargo features and because it
253//!   is enabled by default, other crates in your dependency graph could re-enable
254//!   it for your application. If you want to disable TLS 1.2 for security reasons,
255//!   consider explicitly enabling TLS 1.3 only in the config builder API.
256//!
257//! - `read_buf`: When building with Rust Nightly, adds support for the unstable
258//!   `std::io::ReadBuf` and related APIs. This reduces costs from initializing
259//!   buffers. Will do nothing on non-Nightly releases.
260
261// Require docs for public APIs, deny unsafe code, etc.
262#![forbid(unsafe_code, unused_must_use)]
263#![cfg_attr(not(read_buf), forbid(unstable_features))]
264#![deny(
265    clippy::clone_on_ref_ptr,
266    clippy::use_self,
267    trivial_casts,
268    trivial_numeric_casts,
269    missing_docs,
270    unreachable_pub,
271    unused_import_braces,
272    unused_extern_crates,
273    unused_qualifications
274)]
275// Relax these clippy lints:
276// - ptr_arg: this triggers on references to type aliases that are Vec
277//   underneath.
278// - too_many_arguments: some things just need a lot of state, wrapping it
279//   doesn't necessarily make it easier to follow what's going on
280// - new_ret_no_self: we sometimes return `Arc<Self>`, which seems fine
281// - single_component_path_imports: our top-level `use log` import causes
282//   a false positive, https://github.com/rust-lang/rust-clippy/issues/5210
283// - new_without_default: for internal constructors, the indirection is not
284//   helpful
285#![allow(
286    clippy::too_many_arguments,
287    clippy::new_ret_no_self,
288    clippy::ptr_arg,
289    clippy::single_component_path_imports,
290    clippy::new_without_default
291)]
292// Enable documentation for all features on docs.rs
293#![cfg_attr(docsrs, feature(doc_cfg))]
294// XXX: Because of https://github.com/rust-lang/rust/issues/54726, we cannot
295// write `#![rustversion::attr(nightly, feature(read_buf))]` here. Instead,
296// build.rs set `read_buf` for (only) Rust Nightly to get the same effect.
297//
298// All the other conditional logic in the crate could use
299// `#[rustversion::nightly]` instead of `#[cfg(read_buf)]`; `#[cfg(read_buf)]`
300// is used to avoid needing `rustversion` to be compiled twice during
301// cross-compiling.
302#![cfg_attr(read_buf, feature(read_buf))]
303
304// log for logging (optional).
305#[cfg(feature = "logging")]
306use log;
307
308#[cfg(not(feature = "logging"))]
309#[macro_use]
310mod log {
311    macro_rules! trace    ( ($($tt:tt)*) => {{}} );
312    macro_rules! debug    ( ($($tt:tt)*) => {{}} );
313    macro_rules! warn     ( ($($tt:tt)*) => {{}} );
314    macro_rules! error    ( ($($tt:tt)*) => {{}} );
315}
316
317#[macro_use]
318mod msgs;
319mod anchors;
320mod cipher;
321mod conn;
322mod error;
323mod hash_hs;
324mod limited_cache;
325mod rand;
326mod record_layer;
327mod stream;
328#[cfg(feature = "tls12")]
329mod tls12;
330mod tls13;
331mod vecbuf;
332mod verify;
333#[cfg(test)]
334mod verifybench;
335mod x509;
336#[macro_use]
337mod check;
338mod bs_debug;
339mod builder;
340mod enums;
341mod key;
342mod key_log;
343mod key_log_file;
344mod kx;
345mod suites;
346mod ticketer;
347mod versions;
348
349/// Internal classes which may be useful outside the library.
350/// The contents of this section DO NOT form part of the stable interface.
351pub mod internal {
352    /// Low-level TLS message parsing and encoding functions.
353    pub mod msgs {
354        pub use crate::msgs::*;
355    }
356    /// Low-level TLS message decryption functions.
357    pub mod cipher {
358        pub use crate::cipher::MessageDecrypter;
359    }
360}
361
362// The public interface is:
363pub use crate::anchors::{OwnedTrustAnchor, RootCertStore};
364pub use crate::builder::{
365    ConfigBuilder, ConfigSide, WantsCipherSuites, WantsKxGroups, WantsVerifier, WantsVersions,
366};
367pub use crate::conn::{
368    CommonState, Connection, ConnectionCommon, IoState, Reader, SideData, Writer,
369};
370pub use crate::enums::{CipherSuite, ProtocolVersion, SignatureScheme};
371pub use crate::error::Error;
372pub use crate::key::{Certificate, PrivateKey};
373pub use crate::key_log::{KeyLog, NoKeyLog};
374pub use crate::key_log_file::KeyLogFile;
375pub use crate::kx::{SupportedKxGroup, ALL_KX_GROUPS};
376pub use crate::msgs::enums::{
377    AlertDescription, ContentType, HandshakeType, NamedGroup, SignatureAlgorithm,
378};
379pub use crate::msgs::handshake::{DigitallySignedStruct, DistinguishedNames};
380pub use crate::stream::{Stream, StreamOwned};
381pub use crate::suites::{
382    BulkAlgorithm, SupportedCipherSuite, ALL_CIPHER_SUITES, DEFAULT_CIPHER_SUITES,
383};
384#[cfg(feature = "secret_extraction")]
385pub use crate::suites::{ConnectionTrafficSecrets, ExtractedSecrets};
386pub use crate::ticketer::Ticketer;
387#[cfg(feature = "tls12")]
388pub use crate::tls12::Tls12CipherSuite;
389pub use crate::tls13::Tls13CipherSuite;
390pub use crate::versions::{SupportedProtocolVersion, ALL_VERSIONS, DEFAULT_VERSIONS};
391
392/// Items for use in a client.
393pub mod client {
394    pub(super) mod builder;
395    mod client_conn;
396    mod common;
397    pub(super) mod handy;
398    mod hs;
399    #[cfg(feature = "tls12")]
400    mod tls12;
401    mod tls13;
402
403    pub use builder::{WantsClientCert, WantsTransparencyPolicyOrClientCert};
404    #[cfg(feature = "quic")]
405    pub use client_conn::ClientQuicExt;
406    pub use client_conn::InvalidDnsNameError;
407    pub use client_conn::ResolvesClientCert;
408    pub use client_conn::ServerName;
409    pub use client_conn::StoresClientSessions;
410    pub use client_conn::{ClientConfig, ClientConnection, ClientConnectionData, WriteEarlyData};
411    pub use handy::{ClientSessionMemoryCache, NoClientSessionStorage};
412
413    #[cfg(feature = "dangerous_configuration")]
414    pub use crate::verify::{
415        CertificateTransparencyPolicy, HandshakeSignatureValid, ServerCertVerified,
416        ServerCertVerifier, WebPkiVerifier,
417    };
418    #[cfg(feature = "dangerous_configuration")]
419    pub use client_conn::danger::DangerousClientConfig;
420}
421
422pub use client::{ClientConfig, ClientConnection, ServerName};
423
424/// Items for use in a server.
425pub mod server {
426    pub(crate) mod builder;
427    mod common;
428    pub(crate) mod handy;
429    mod hs;
430    mod server_conn;
431    #[cfg(feature = "tls12")]
432    mod tls12;
433    mod tls13;
434
435    pub use crate::verify::{
436        AllowAnyAnonymousOrAuthenticatedClient, AllowAnyAuthenticatedClient, NoClientAuth,
437    };
438    pub use builder::WantsServerCert;
439    pub use handy::ResolvesServerCertUsingSni;
440    pub use handy::{NoServerSessionStorage, ServerSessionMemoryCache};
441    #[cfg(feature = "quic")]
442    pub use server_conn::ServerQuicExt;
443    pub use server_conn::StoresServerSessions;
444    pub use server_conn::{
445        Accepted, Acceptor, ReadEarlyData, ServerConfig, ServerConnection, ServerConnectionData,
446    };
447    pub use server_conn::{ClientHello, ProducesTickets, ResolvesServerCert};
448
449    #[cfg(feature = "dangerous_configuration")]
450    pub use crate::verify::{ClientCertVerified, ClientCertVerifier, DnsName};
451}
452
453pub use server::{ServerConfig, ServerConnection};
454
455/// All defined ciphersuites appear in this module.
456///
457/// [`ALL_CIPHER_SUITES`] is provided as an array of all of these values.
458pub mod cipher_suite {
459    pub use crate::suites::CipherSuiteCommon;
460    #[cfg(feature = "tls12")]
461    pub use crate::tls12::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256;
462    #[cfg(feature = "tls12")]
463    pub use crate::tls12::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384;
464    #[cfg(feature = "tls12")]
465    pub use crate::tls12::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256;
466    #[cfg(feature = "tls12")]
467    pub use crate::tls12::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256;
468    #[cfg(feature = "tls12")]
469    pub use crate::tls12::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384;
470    #[cfg(feature = "tls12")]
471    pub use crate::tls12::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256;
472    pub use crate::tls13::TLS13_AES_128_GCM_SHA256;
473    pub use crate::tls13::TLS13_AES_256_GCM_SHA384;
474    pub use crate::tls13::TLS13_CHACHA20_POLY1305_SHA256;
475}
476
477/// All defined protocol versions appear in this module.
478///
479/// ALL_VERSIONS is a provided as an array of all of these values.
480pub mod version {
481    #[cfg(feature = "tls12")]
482    pub use crate::versions::TLS12;
483    pub use crate::versions::TLS13;
484}
485
486/// All defined key exchange groups appear in this module.
487///
488/// ALL_KX_GROUPS is provided as an array of all of these values.
489pub mod kx_group {
490    pub use crate::kx::SECP256R1;
491    pub use crate::kx::SECP384R1;
492    pub use crate::kx::X25519;
493}
494
495/// Message signing interfaces and implementations.
496pub mod sign;
497
498#[cfg(feature = "quic")]
499#[cfg_attr(docsrs, doc(cfg(feature = "quic")))]
500/// APIs for implementing QUIC TLS
501pub mod quic;
502
503/// This is the rustls manual.
504pub mod manual;
505
506/** Type renames. */
507#[allow(clippy::upper_case_acronyms)]
508#[doc(hidden)]
509#[deprecated(since = "0.20.0", note = "Use ResolvesServerCertUsingSni")]
510pub type ResolvesServerCertUsingSNI = server::ResolvesServerCertUsingSni;
511#[allow(clippy::upper_case_acronyms)]
512#[cfg(feature = "dangerous_configuration")]
513#[doc(hidden)]
514#[deprecated(since = "0.20.0", note = "Use client::WebPkiVerifier")]
515pub type WebPKIVerifier = client::WebPkiVerifier;
516#[allow(clippy::upper_case_acronyms)]
517#[doc(hidden)]
518#[deprecated(since = "0.20.0", note = "Use Error")]
519pub type TLSError = Error;
520#[doc(hidden)]
521#[deprecated(since = "0.20.0", note = "Use ClientConnection")]
522pub type ClientSession = ClientConnection;
523#[doc(hidden)]
524#[deprecated(since = "0.20.0", note = "Use ServerConnection")]
525pub type ServerSession = ServerConnection;
526
527/* Apologies: would make a trait alias here, but those remain unstable.
528pub trait Session = Connection;
529*/