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