A modern TLS library in Rust

Overview

Rustls is a modern TLS library written in Rust. It uses ring for cryptography and libwebpki for certificate verification.

Status

Rustls is ready for use. There are no major breaking interface changes envisioned after the set included in the 0.20 release.

If you'd like to help out, please see CONTRIBUTING.md.

Build Status Coverage Status (codecov.io) Documentation

Release history:

  • Next release:
    • Planned: removal of unused signature verification schemes at link-time.
  • 0.20.6 (2022-05-18)
    • 0.20.5 included a change to track more context for the Error::CorruptMessage which made API-incompatible changes to the Error type. We yanked 0.20.5 and have reverted that change as part of 0.20.6.
  • 0.20.5 (2022-05-14)
    • Correct compatbility with servers which return no TLS extensions and take advantage of a special case encoding.
    • Remove spurious warn-level logging introduced in 0.20.3.
    • Expose cipher suites in ClientHello type.
    • Allow verification of IP addresses with dangerous_config enabled.
    • Retry I/O operations in ConnectionCommon::complete_io() when interrupted.
    • Fix server::ResolvesServerCertUsingSni case sensitivity.
  • 0.20.4 (2022-02-19)
    • Correct regression in QUIC 0-RTT support.
  • 0.20.3 (2022-02-13)
    • Support loading ECDSA keys in SEC1 format.
    • Support receipt of 0-RTT "early data" in TLS1.3 servers. It is not enabled by default; opt in by setting ServerConfig::max_early_data_size to a non-zero value.
    • Support sending of data with the first server flight. This is also not enabled by default either: opt in by setting ServerConfig::send_half_rtt_data.
    • Support read_buf interface when compiled with nightly. This means data can be safely read out of a rustls connection into a buffer without the buffer requiring initialisation first. Set the read_buf feature to use this.
    • Improve efficiency when writing vectors of TLS types.
    • Reduce copying and improve efficiency in TLS1.2 handshake.
  • 0.20.2 (2021-11-21)
    • Fix CipherSuite::as_str() value (as introduced in 0.20.1).
  • 0.20.1 (2021-11-14)
    • Allow cipher suite enum items to be stringified.
    • Improve documentation of configuration builder types.
    • Ensure unused cipher suites can be removed at link-time.
    • Ensure single-use error types implement std::error::Error, and are public.

See RELEASE_NOTES.md for further change history.

Documentation

Lives here: https://docs.rs/rustls/

Approach

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.

Current features

  • TLS1.2 and TLS1.3.
  • ECDSA, Ed25519 or RSA server authentication by clients.
  • ECDSA, Ed25519 or RSA server authentication by servers.
  • Forward secrecy using ECDHE; with curve25519, nistp256 or nistp384 curves.
  • AES128-GCM and AES256-GCM bulk encryption, with safe nonces.
  • ChaCha20-Poly1305 bulk encryption (RFC7905).
  • ALPN support.
  • SNI support.
  • Tunable fragment size to make TLS messages match size of underlying transport.
  • Optional use of vectored IO to minimise system calls.
  • TLS1.2 session resumption.
  • TLS1.2 resumption via tickets (RFC5077).
  • TLS1.3 resumption via tickets or session storage.
  • TLS1.3 0-RTT data for clients.
  • TLS1.3 0-RTT data for servers.
  • Client authentication by clients.
  • Client authentication by servers.
  • Extended master secret support (RFC7627).
  • Exporters (RFC5705).
  • OCSP stapling by servers.
  • SCT stapling by servers.
  • SCT verification by clients.

Possible future features

  • PSK support.
  • OCSP verification by clients.
  • Certificate pinning.

Non-features

For reasons explained in the manual, rustls does not and will not support:

  • SSL1, SSL2, SSL3, TLS1 or TLS1.1.
  • RC4.
  • DES or triple DES.
  • EXPORT ciphersuites.
  • MAC-then-encrypt ciphersuites.
  • Ciphersuites without forward secrecy.
  • Renegotiation.
  • Kerberos.
  • Compression.
  • Discrete-log Diffie-Hellman.
  • Automatic protocol version downgrade.

There are plenty of other libraries that provide these features should you need them.

Platform support

Rustls uses ring for implementing the cryptography in TLS. As a result, rustls only runs on platforms supported by ring. At the time of writing this means x86, x86-64, armv7, and aarch64.

Example code

There are two example programs which use mio to do asynchronous IO.

Client example program

The client example program is named tlsclient. The interface looks like:

Connects to the TLS server at hostname:PORT.  The default PORT
is 443.  By default, this reads a request from stdin (to EOF)
before making the connection.  --http replaces this with a
basic HTTP GET request for /.

If --cafile is not supplied, a built-in set of CA certificates
are used from the webpki-roots crate.

Usage:
  tlsclient [options] [--suite SUITE ...] [--proto PROTO ...] <hostname>
  tlsclient (--version | -v)
  tlsclient (--help | -h)

Options:
    -p, --port PORT     Connect to PORT [default: 443].
    --http              Send a basic HTTP GET request for /.
    --cafile CAFILE     Read root certificates from CAFILE.
    --auth-key KEY      Read client authentication key from KEY.
    --auth-certs CERTS  Read client authentication certificates from CERTS.
                        CERTS must match up with KEY.
    --protover VERSION  Disable default TLS version list, and use
                        VERSION instead.  May be used multiple times.
    --suite SUITE       Disable default cipher suite list, and use
                        SUITE instead.  May be used multiple times.
    --proto PROTOCOL    Send ALPN extension containing PROTOCOL.
                        May be used multiple times to offer several protocols.
    --cache CACHE       Save session cache to file CACHE.
    --no-tickets        Disable session ticket support.
    --no-sni            Disable server name indication support.
    --insecure          Disable certificate verification.
    --verbose           Emit log output.
    --max-frag-size M   Limit outgoing messages to M bytes.
    --version, -v       Show tool version.
    --help, -h          Show this screen.

Some sample runs:

$ cargo run --example tlsclient -- --http mozilla-modern.badssl.com
HTTP/1.1 200 OK
Server: nginx/1.6.2 (Ubuntu)
Date: Wed, 01 Jun 2016 18:44:00 GMT
Content-Type: text/html
Content-Length: 644
(...)

or

$ cargo run --example tlsclient -- --http expired.badssl.com
TLS error: WebPkiError(CertExpired, ValidateServerCert)
Connection closed

Server example program

The server example program is named tlsserver. The interface looks like:

Runs a TLS server on :PORT.  The default PORT is 443.

`echo' mode means the server echoes received data on each connection.

`http' mode means the server blindly sends a HTTP response on each
connection.

`forward' means the server forwards plaintext to a connection made to
localhost:fport.

`--certs' names the full certificate chain, `--key' provides the
RSA private key.

Usage:
  tlsserver --certs CERTFILE --key KEYFILE [--suite SUITE ...] [--proto PROTO ...] [options] echo
  tlsserver --certs CERTFILE --key KEYFILE [--suite SUITE ...] [--proto PROTO ...] [options] http
  tlsserver --certs CERTFILE --key KEYFILE [--suite SUITE ...] [--proto PROTO ...] [options] forward <fport>
  tlsserver (--version | -v)
  tlsserver (--help | -h)

Options:
    -p, --port PORT     Listen on PORT [default: 443].
    --certs CERTFILE    Read server certificates from CERTFILE.
                        This should contain PEM-format certificates
                        in the right order (the first certificate should
                        certify KEYFILE, the last should be a root CA).
    --key KEYFILE       Read private key from KEYFILE.  This should be a RSA
                        private key or PKCS8-encoded private key, in PEM format.
    --ocsp OCSPFILE     Read DER-encoded OCSP response from OCSPFILE and staple
                        to certificate.  Optional.
    --auth CERTFILE     Enable client authentication, and accept certificates
                        signed by those roots provided in CERTFILE.
    --require-auth      Send a fatal alert if the client does not complete client
                        authentication.
    --resumption        Support session resumption.
    --tickets           Support tickets.
    --protover VERSION  Disable default TLS version list, and use
                        VERSION instead.  May be used multiple times.
    --suite SUITE       Disable default cipher suite list, and use
                        SUITE instead.  May be used multiple times.
    --proto PROTOCOL    Negotiate PROTOCOL using ALPN.
                        May be used multiple times.
    --verbose           Emit log output.
    --version, -v       Show tool version.
    --help, -h          Show this screen.

Here's a sample run; we start a TLS echo server, then connect to it with openssl and tlsclient:

$ cargo run --example tlsserver -- --certs test-ca/rsa/end.fullchain --key test-ca/rsa/end.rsa -p 8443 echo &
$ echo hello world | openssl s_client -ign_eof -quiet -connect localhost:8443
depth=2 CN = ponytown RSA CA
verify error:num=19:self signed certificate in certificate chain
hello world
^C
$ echo hello world | cargo run --example tlsclient -- --cafile test-ca/rsa/ca.cert -p 8443 localhost
hello world
^C

License

Rustls is distributed under the following three licenses:

  • Apache License version 2.0.
  • MIT license.
  • ISC license.

These are included as LICENSE-APACHE, LICENSE-MIT and LICENSE-ISC respectively. You may use this software under the terms of any of these licenses, at your option.

Code of conduct

This project adopts the Rust Code of Conduct. Please email [email protected] to report any instance of misconduct, or if you have any comments or questions on the Code of Conduct.

Comments
  • Asynchronous/tokio ResolvesServerCert?

    Asynchronous/tokio ResolvesServerCert?

    I don't have a use case for this yet, but as more and more of the rust community moves towards async libraries like tokio, I wonder if there's a way ResolvesServerCert could support callback functions which do not return immediately/play nicely with the tokio Core.

    Specific use case that might require this are servers which process many different domains and store certs/keys in a database, or servers which attempt to lazily obtain certificates from CAs like let's encrypt.

    opened by alex 41
  • ClientConfig and ServerConfig vs Builders

    ClientConfig and ServerConfig vs Builders

    In the latest master, ClientConfig and ServerConfig no longer have a new(). There are new Builder types to construct them, but someone attempting to port old code without many changes might be tempted to try and instantiated a ClientConfig or ServerConfig by setting all of their fields. That's currently impossible, because verifier on both types is private.

    Is that an intentional choice, to prevent construction of ClientConfig and ServerConfig without going through the Builders? If so, we should document it on the respective structs. Also if that's the case: should all the other fields be made private, if the intent is only to support construction via Builder?

    opened by jsha 37
  • KTLS Support

    KTLS Support

    KTLS is tls support in linux kernel, but it only handles symmetric encryption and decryption, so using Rustls as a handshake is great.

    We can simply public SessionSecrets, but this does not apply to TLS 1.3.

    opened by quininer 31
  • Send session ID when resuming TLS 1.3 sessions.

    Send session ID when resuming TLS 1.3 sessions.

    Rustls implements client- and server-side requirements for RFC8446 Appendix D.4, except it forgets to send a session ID in the ClientHello when also resuming TLS 1.3 sessions. This PR addresses that issue.

    opened by dhobsd 30
  • Allow passing extra extensions to the Client, to be added to the handshake

    Allow passing extra extensions to the Client, to be added to the handshake

    This is what I've been using with my QUIC implementation; seems to work.

    As a next step, we could pull out the TransportParameters code again, and I could just pass in an UnknownExtension, but I wanted to run this by you first.

    The clone is a bit ugly, but I'm not sure there is a better way right now. I suppose there could be a second ext_refs that copies a ref from the locally-created extensions, which we could then add the externally-added extensions to. There is also the risk of code size bulking from the extra impls, not sure how concerning that is to you.

    opened by djc 29
  • Handshake fails with BadDER

    Handshake fails with BadDER

    Hi!

    My Tokio-based PostgreSQL crate https://nest.pijul.com/pmeunier/pleingres was originally based on Rustls, but I couldn't connect to a Google Cloud PostgreSQL database.

    I replaced tokio-rustls with tokio-openssl, and it started working.

    The error originated from webpki, and was BadDER. The CA certificate was from Google, and there was no other DER-encoded file involved (besides what's in webpki-roots maybe?).

    Now that I got a working version, I can reproduce that bug if needed. With OpenSSL, I needed a function that doesn't check the hostname (the host I want to connect to has no hostname and is supposed to be accessed by its IP address).

    opened by P-E-Meunier 25
  • SessionID as Option

    SessionID as Option

    As discussed in #584, this patch makes SessionID an Option in most places. I had to touch parts of the codebase I'm not very familiar with, so I'm not that confident in this patch, but it does pass all of the tests.

    I wasn't sure what to do when reading a zero-length SessionID off the wire. I left it as-is, but perhaps it should result in None.

    opened by sayrer 24
  • Upgrade to *ring* 0.16

    Upgrade to *ring* 0.16

    Here I will leave some tips for upgrading to ring 0.15, which implements a new AEAD API, a new HKDF API, and an extended ring::rand API. I'll describe how Rustls can use the new features in this issue.

    opened by briansmith 22
  • Get a security audit done

    Get a security audit done

    There is a discussion about TLS implementations in the newly spun up networking WG:

    https://github.com/rust-lang-nursery/wg-net/issues/40

    Given the comments there, I've been thinking that it would be great if the rustls stack (which probably means ring + webpki + rustls) went through a security audit somehow (maybe with a MOSS grant?).

    opened by djc 22
  • Respect the SSLKEYLOGFILE variable by default

    Respect the SSLKEYLOGFILE variable by default

    Currently, to look at traffic in wireshark, you have to opt-in not just by setting the env variable, but also opting-in in the application itself. This makes it possible to debug the traffic with just the env variable, which is the same default behavior as curl and openssl.

    opened by jyn514 20
  • Support for fully user-defined certificate verification

    Support for fully user-defined certificate verification

    libp2p needs to be able to verify certificates that would normally be considered invalid (they contain a critical extension that webpki does not, and should not, know about). It also needs to return data from this process to the application. The easiest way to do this is for rustls to not even try to parse the certificate itself. Instead, it should just treat it as bytes.

    opened by Demi-Marie 19
  • Include IP address of sender in ClientHello struct

    Include IP address of sender in ClientHello struct

    Hey there,

    In the API documentation (https://docs.rs/rustls/0.20.7/rustls/server/struct.ClientHello.html), I don't see any option to query the IP address of the sender of the ClientHello message. This would be a welcome addition to see who is sending these messages (for ratelimiting, etcetera)!

    opened by edwardwc 1
  • Rework client persistence interface for RFC8446 C.4 client tracking prevention

    Rework client persistence interface for RFC8446 C.4 client tracking prevention

    This is for #466

    Todo:

    • [ ] review coverage
    • [ ] reinstate unit tests in client/handy.rs
    • [ ] add tests for overall TLS1.3 repeated resumption behaviour
    next-major-release 
    opened by ctz 0
  • Tweaking TLS

    Tweaking TLS

    Any recommendation how to tweak TLS for latency purposes? I have a lot of small constantly incoming packets and sometimes i see a lot of batches made by Rustls.

    opened by serzhiio 14
  • Removing SCTs from certificate before verification

    Removing SCTs from certificate before verification

    Hi!

    I was looking at the code to verify SCTs in a certificate, and it looks like yall use this sct.rs library from rustls. Looking at the source code from the library, it doesn't remove embedded SCTs from a certificate if it has them before validating the signature. I believe this implies that the caller has to do this instead, but I wasn't able to find where/whether Rustls does this verification.

    Would you be able to confirm whether Rustls has this functionality and if so, point me to it? I'm trying to get the sct verification library to work for my own certificate verification and not able to find a straightforward way of doing this.

    opened by akshitdewan 1
  • Passing certificate for client authentication in rustls::ClientConfig

    Passing certificate for client authentication in rustls::ClientConfig

    I have implemented these method and enabled "dangerous_configuration". `struct SkipServerVerification;

    impl SkipServerVerification { fn new() -> Arc { Arc::new(Self) } }

    impl rustls::client::ServerCertVerifier for SkipServerVerification { fn verify_server_cert( &self, _end_entity: &rustls::Certificate, _intermediates: &[rustls::Certificate], _server_name: &rustls::ServerName, _scts: &mut dyn Iterator<Item = &[u8]>, _ocsp_response: &[u8], _now: std::time::SystemTime, ) -> Result<rustls::client::ServerCertVerified, rustls::Error> { Ok(rustls::client::ServerCertVerified::assertion()) } } ` Now, i want to use ClientConfig for creating a custom configuration :

    fn configure_client() -> ClientConfig { let crypto = rustls::ClientConfig::builder().with_safe_defaults().with_custom_certificate_verifier(SkipServerVerification::new()).with_single_cert(client_cert.to_vec(), Key::RSA(client_key.to_vec())); rustls::ClientConfig::new(Arc::new(crypto)) } I want to pass these certificate to ClientConfig:

    let root_certs = include_bytes!("../certs/ca.crt"); let client_cert = include_bytes!("../certs/client.crt"); let client_key = include_bytes!("../certs/client.key"); How can i achieve this? Thanks.

    opened by ciclonite 1
Owner
Modern TLS for Rust
null
A modern TLS library in Rust

Rustls is a modern TLS library written in Rust. It uses ring for cryptography and libwebpki for certificate verification. Status Rustls is ready for u

null 4k Jan 9, 2023
[INACTIVE] TLS 1.2 implementation in Rust

suruga is Rust implementation of TLS 1.2. It currently implements some core parts of TLS 1.2, NIST P-256 ECDHE and chacha20-poly1305. Usage extern cra

klutzy/defunct 123 Dec 27, 2022
A Rust implementation of Trojan with QUIC tunnel, Lite-TLS and more.

Trojan-Oxide A Rust implementation of Trojan with QUIC tunnel, Lite-TLS and more. Overview Full support for the original Trojan Protocol, including TC

null 13 Oct 17, 2022
OpenSSL compatibility layer for the Rust SSL/TLS stack

An OpenSSL compatibility layer for the Rust SSL/TLS stack. MesaLink is an OpenSSL compatibility layer for the Rust SSL/TLS stack, namely rustls, webpk

MesaLock Linux 1.5k Dec 23, 2022
A no-std / no-alloc TLS 1.3 client

puny-tls - no-std/no-alloc TLS 1.3 client This is an improvement over tiny-tls-rs to make it more useable. However the only reason this exists is to r

Björn Quentin 2 Aug 22, 2022
A modern, portable, easy to use crypto library.

Sodium is a new, easy-to-use software library for encryption, decryption, signatures, password hashing and more. It is a portable, cross-compilable, i

Frank Denis 10.7k Jan 3, 2023
Cryptography-oriented big integer library with constant-time, stack-allocated (no_std-friendly) implementations of modern formulas

RustCrypto: Cryptographic Big Integers Pure Rust implementation of a big integer library which has been designed from the ground-up for use in cryptog

Rust Crypto 88 Dec 31, 2022
QuickDash A modern alternative to QuickSFV using Rust.

QuickDash A modern alternative to QuickSFV using Rust. It's supports BLAKE3 and BLAKE2 hashes, CRC32, MD5, SHA1, SHA2, SHA3, xxHash The docs for user

null 11 Nov 9, 2022
Modern, lightweight & standard-compliant bitcoin wallet runtime & cli without rust-bitcoin dependencies

Bitcoin protocol command-line wallet & tools Modern, minimalistic & standard-compliant cold wallet from LNP/BP Standards Association. Contributing Con

BP: Bitcoin protocol 3 Jul 31, 2023
Modern Cryptographic Firmware

Trussed® Modern Cryptographic Firmware Status Very much WIP. Actively developed. Unstable APIs.

Trussed® 300 Dec 16, 2022
A modern runtime for javascript.

Just NOTICE: README LINKS AND SITE ARE WIP. LINKS MAY NOT WORK Just is a simple, and modern runtime for JavaScript that uses V8 and is built in Rust.

Exact Labs 6 Dec 15, 2022
High-level networking library that extends the bevy_replicon library to allow snapshot interpolation and client-side prediction

bevy_replicon_snap A Snapshot Interpolation plugin for the networking solution bevy_replicon in the Bevy game engine. This library is a very rough pro

Ben 3 Oct 15, 2023
A Rust library for working with Bitcoin SV

Rust-SV A library to build Bitcoin SV applications in Rust. Documentation Features P2P protocol messages (construction and serialization) Address enco

Brenton Gunning 51 Oct 13, 2022
A Rust library for generating cryptocurrency wallets

Table of Contents 1. Overview 2. Build Guide 2.1 Install Rust 2.2a Build from Homebrew 2.2b Build from Crates.io 2.2c Build from Source Code 3. Usage

Aleo 552 Dec 29, 2022
Sodium Oxide: Fast cryptographic library for Rust (bindings to libsodium)

sodiumoxide |Crate|Documentation|Gitter| |:---:|:-----------:|:--------:|:-----:|:------:|:----:| |||| NaCl (pronounced "salt") is a new easy-to-use h

sodiumoxide 642 Dec 17, 2022
rabe is an Attribute Based Encryption library, written in Rust

Rabe rabe is a rust library implementing several Attribute Based Encryption (ABE) schemes using a modified version of the bn library of zcash (type-3

Fraunhofer AISEC 52 Dec 15, 2022
A Rust library for lattice-based additive homomorphic encryption.

Cupcake Cupcake is an efficient Rust library for the (additive version of) Fan-Vercauteren homomorphic encryption scheme, offering capabilities to enc

Facebook Research 365 Dec 11, 2022
Mundane is a Rust cryptography library backed by BoringSSL that is difficult to misuse, ergonomic, and performant (in that order).

Mundane Mundane is a Rust cryptography library backed by BoringSSL that is difficult to misuse, ergonomic, and performant (in that order). Issues and

Google 1.1k Jan 3, 2023
The most advanced Merkle tree library for Rust

rs-merkle rs-merkle is the most advanced Merkle tree library for Rust. Basic features include building a Merkle tree, creation, and verification of Me

Anton Suprunchuk 85 Dec 31, 2022