Skip to content

Commit

Permalink
Update to rustls 0.22 alpha
Browse files Browse the repository at this point in the history
  • Loading branch information
djc committed Sep 8, 2023
1 parent a70ea6c commit 63b8d6f
Show file tree
Hide file tree
Showing 8 changed files with 72 additions and 117 deletions.
8 changes: 4 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ exclude = ["/.github", "/examples", "/scripts"]

[dependencies]
tokio = "1.0"
rustls = { version = "0.21.6", default-features = false }
rustls = { version = "=0.22.0-alpha.2", default-features = false }

[features]
default = ["logging", "tls12"]
Expand All @@ -29,6 +29,6 @@ argh = "0.1"
tokio = { version = "1.0", features = ["full"] }
futures-util = "0.3.1"
lazy_static = "1"
webpki-roots = "0.25"
rustls-pemfile = "1"
webpki = { package = "rustls-webpki", version = "0.101.2", features = ["alloc", "std"] }
webpki-roots = "=0.26.0-alpha.1"
rustls-pemfile = "=2.0.0-alpha.1"
webpki = { package = "rustls-webpki", version = "=0.102.0-alpha.2", features = ["alloc", "std"] }
22 changes: 4 additions & 18 deletions examples/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ use std::sync::Arc;
use argh::FromArgs;
use tokio::io::{copy, split, stdin as tokio_stdin, stdout as tokio_stdout, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio_rustls::rustls::{self, OwnedTrustAnchor};
use tokio_rustls::TlsConnector;

/// Tokio Rustls client example
Expand Down Expand Up @@ -45,24 +44,11 @@ async fn main() -> io::Result<()> {
let mut root_cert_store = rustls::RootCertStore::empty();
if let Some(cafile) = &options.cafile {
let mut pem = BufReader::new(File::open(cafile)?);
let certs = rustls_pemfile::certs(&mut pem)?;
let trust_anchors = certs.iter().map(|cert| {
let ta = webpki::TrustAnchor::try_from_cert_der(&cert[..]).unwrap();
OwnedTrustAnchor::from_subject_spki_name_constraints(
ta.subject,
ta.spki,
ta.name_constraints,
)
});
root_cert_store.add_trust_anchors(trust_anchors);
for cert in rustls_pemfile::certs(&mut pem) {
root_cert_store.add(cert?).unwrap();
}
} else {
root_cert_store.add_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.iter().map(|ta| {
OwnedTrustAnchor::from_subject_spki_name_constraints(
ta.subject,
ta.spki,
ta.name_constraints,
)
}));
root_cert_store.add_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
}

let config = rustls::ClientConfig::builder()
Expand Down
19 changes: 9 additions & 10 deletions examples/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ use argh::FromArgs;
use rustls_pemfile::{certs, rsa_private_keys};
use tokio::io::{copy, sink, split, AsyncWriteExt};
use tokio::net::TcpListener;
use tokio_rustls::rustls::{self, Certificate, PrivateKey};
use tokio_rustls::TlsAcceptor;
use webpki::types::{CertificateDer, PrivateKeyDer};

/// Tokio Rustls server example
#[derive(FromArgs)]
Expand All @@ -31,16 +31,15 @@ struct Options {
echo_mode: bool,
}

fn load_certs(path: &Path) -> io::Result<Vec<Certificate>> {
certs(&mut BufReader::new(File::open(path)?))
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "invalid cert"))
.map(|mut certs| certs.drain(..).map(Certificate).collect())
fn load_certs(path: &Path) -> io::Result<Vec<CertificateDer<'static>>> {
certs(&mut BufReader::new(File::open(path)?)).collect()
}

fn load_keys(path: &Path) -> io::Result<Vec<PrivateKey>> {
fn load_keys(path: &Path) -> io::Result<PrivateKeyDer<'static>> {
rsa_private_keys(&mut BufReader::new(File::open(path)?))
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "invalid key"))
.map(|mut keys| keys.drain(..).map(PrivateKey).collect())
.next()
.unwrap()
.map(Into::into)
}

#[tokio::main]
Expand All @@ -53,13 +52,13 @@ async fn main() -> io::Result<()> {
.next()
.ok_or_else(|| io::Error::from(io::ErrorKind::AddrNotAvailable))?;
let certs = load_certs(&options.cert)?;
let mut keys = load_keys(&options.key)?;
let key = load_keys(&options.key)?;
let flag_echo = options.echo_mode;

let config = rustls::ServerConfig::builder()
.with_safe_defaults()
.with_no_client_auth()
.with_single_cert(certs, keys.remove(0))
.with_single_cert(certs, key)
.map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?;
let acceptor = TlsAcceptor::from(Arc::new(config));

Expand Down
20 changes: 11 additions & 9 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ use std::sync::Arc;
use std::task::{Context, Poll};

pub use rustls;
use rustls::crypto::ring::Ring;
use rustls::{ClientConfig, ClientConnection, CommonState, ServerConfig, ServerConnection};
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};

Expand All @@ -67,19 +68,19 @@ pub mod server;
/// A wrapper around a `rustls::ClientConfig`, providing an async `connect` method.
#[derive(Clone)]
pub struct TlsConnector {
inner: Arc<ClientConfig>,
inner: Arc<ClientConfig<Ring>>,
#[cfg(feature = "early-data")]
early_data: bool,
}

/// A wrapper around a `rustls::ServerConfig`, providing an async `accept` method.
#[derive(Clone)]
pub struct TlsAcceptor {
inner: Arc<ServerConfig>,
inner: Arc<ServerConfig<Ring>>,
}

impl From<Arc<ClientConfig>> for TlsConnector {
fn from(inner: Arc<ClientConfig>) -> TlsConnector {
impl From<Arc<ClientConfig<Ring>>> for TlsConnector {
fn from(inner: Arc<ClientConfig<Ring>>) -> TlsConnector {
TlsConnector {
inner,
#[cfg(feature = "early-data")]
Expand All @@ -88,8 +89,8 @@ impl From<Arc<ClientConfig>> for TlsConnector {
}
}

impl From<Arc<ServerConfig>> for TlsAcceptor {
fn from(inner: Arc<ServerConfig>) -> TlsAcceptor {
impl From<Arc<ServerConfig<Ring>>> for TlsAcceptor {
fn from(inner: Arc<ServerConfig<Ring>>) -> TlsAcceptor {
TlsAcceptor { inner }
}
}
Expand Down Expand Up @@ -210,9 +211,10 @@ where
/// # Example
///
/// ```no_run
/// # use rustls::crypto::ring::Ring;
/// # fn choose_server_config(
/// # _: rustls::server::ClientHello,
/// # ) -> std::sync::Arc<rustls::ServerConfig> {
/// # ) -> std::sync::Arc<rustls::ServerConfig<Ring>> {
/// # unimplemented!();
/// # }
/// # #[allow(unused_variables)]
Expand Down Expand Up @@ -304,11 +306,11 @@ where
self.accepted.client_hello()
}

pub fn into_stream(self, config: Arc<ServerConfig>) -> Accept<IO> {
pub fn into_stream(self, config: Arc<ServerConfig<Ring>>) -> Accept<IO> {
self.into_stream_with(config, |_| ())
}

pub fn into_stream_with<F>(self, config: Arc<ServerConfig>, f: F) -> Accept<IO>
pub fn into_stream_with<F>(self, config: Arc<ServerConfig<Ring>>, f: F) -> Accept<IO>
where
F: FnOnce(&mut ServerConnection),
{
Expand Down
21 changes: 5 additions & 16 deletions tests/badssl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,17 @@ use std::io;
use std::net::ToSocketAddrs;
use std::sync::Arc;

use rustls::crypto::ring::Ring;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio_rustls::{
client::TlsStream,
rustls::{self, ClientConfig, OwnedTrustAnchor},
rustls::{self, ClientConfig},
TlsConnector,
};

async fn get(
config: Arc<ClientConfig>,
config: Arc<ClientConfig<Ring>>,
domain: &str,
port: u16,
) -> io::Result<(TlsStream<TcpStream>, String)> {
Expand All @@ -34,13 +35,7 @@ async fn get(
#[tokio::test]
async fn test_tls12() -> io::Result<()> {
let mut root_store = rustls::RootCertStore::empty();
root_store.add_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.iter().map(|ta| {
OwnedTrustAnchor::from_subject_spki_name_constraints(
ta.subject,
ta.spki,
ta.name_constraints,
)
}));
root_store.add_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
let config = rustls::ClientConfig::builder()
.with_safe_default_cipher_suites()
.with_safe_default_kx_groups()
Expand Down Expand Up @@ -72,13 +67,7 @@ fn test_tls13() {
#[tokio::test]
async fn test_modern() -> io::Result<()> {
let mut root_store = rustls::RootCertStore::empty();
root_store.add_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.iter().map(|ta| {
OwnedTrustAnchor::from_subject_spki_name_constraints(
ta.subject,
ta.spki,
ta.name_constraints,
)
}));
root_store.add_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
let config = rustls::ClientConfig::builder()
.with_safe_defaults()
.with_root_certificates(root_store)
Expand Down
25 changes: 8 additions & 17 deletions tests/early-data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,13 @@ use std::thread;
use std::time::Duration;

use futures_util::{future, future::Future, ready};
use rustls::RootCertStore;
use rustls::crypto::ring::Ring;
use rustls::{self, ClientConfig, RootCertStore};
use tokio::io::{split, AsyncRead, AsyncWriteExt, ReadBuf};
use tokio::net::TcpStream;
use tokio::sync::oneshot;
use tokio::time::sleep;
use tokio_rustls::{
client::TlsStream,
rustls::{self, ClientConfig, OwnedTrustAnchor},
TlsConnector,
};
use tokio_rustls::{client::TlsStream, TlsConnector};

struct Read1<T>(T);

Expand All @@ -42,7 +39,7 @@ impl<T: AsyncRead + Unpin> Future for Read1<T> {
}

async fn send(
config: Arc<ClientConfig>,
config: Arc<ClientConfig<Ring>>,
addr: SocketAddr,
data: &[u8],
) -> io::Result<TlsStream<TcpStream>> {
Expand Down Expand Up @@ -132,17 +129,11 @@ async fn test_0rtt() -> io::Result<()> {
wait_for_server(format!("127.0.0.1:{}", server_port).as_str()).await;

let mut chain = BufReader::new(Cursor::new(include_str!("end.chain")));
let certs = rustls_pemfile::certs(&mut chain).unwrap();
let trust_anchors = certs.iter().map(|cert| {
let ta = webpki::TrustAnchor::try_from_cert_der(&cert[..]).unwrap();
OwnedTrustAnchor::from_subject_spki_name_constraints(
ta.subject,
ta.spki,
ta.name_constraints,
)
});
let mut root_store = RootCertStore::empty();
root_store.add_trust_anchors(trust_anchors);
for cert in rustls_pemfile::certs(&mut chain) {
root_store.add(cert.unwrap()).unwrap();
}

let mut config = rustls::ClientConfig::builder()
.with_safe_default_cipher_suites()
.with_safe_default_kx_groups()
Expand Down
45 changes: 19 additions & 26 deletions tests/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ use std::{io, thread};

use futures_util::future::TryFutureExt;
use lazy_static::lazy_static;
use rustls::{ClientConfig, OwnedTrustAnchor};
use rustls::crypto::ring::Ring;
use rustls::ClientConfig;
use rustls_pemfile::{certs, rsa_private_keys};
use tokio::io::{copy, split, AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
Expand All @@ -22,17 +23,17 @@ const RSA: &str = include_str!("end.rsa");
lazy_static! {
static ref TEST_SERVER: (SocketAddr, &'static str, &'static [u8]) = {
let cert = certs(&mut BufReader::new(Cursor::new(CERT)))
.unwrap()
.drain(..)
.map(rustls::Certificate)
.map(|result| result.unwrap())
.collect();
let mut keys = rsa_private_keys(&mut BufReader::new(Cursor::new(RSA))).unwrap();
let mut keys = keys.drain(..).map(rustls::PrivateKey);
let key = rsa_private_keys(&mut BufReader::new(Cursor::new(RSA)))
.next()
.unwrap()
.unwrap();

let config = rustls::ServerConfig::builder()
.with_safe_defaults()
.with_no_client_auth()
.with_single_cert(cert, keys.next().unwrap())
.with_single_cert(cert, key.into())
.unwrap();
let acceptor = TlsAcceptor::from(Arc::new(config));

Expand Down Expand Up @@ -83,7 +84,11 @@ fn start_server() -> &'static (SocketAddr, &'static str, &'static [u8]) {
&TEST_SERVER
}

async fn start_client(addr: SocketAddr, domain: &str, config: Arc<ClientConfig>) -> io::Result<()> {
async fn start_client(
addr: SocketAddr,
domain: &str,
config: Arc<ClientConfig<Ring>>,
) -> io::Result<()> {
const FILE: &[u8] = include_bytes!("../README.md");

let domain = rustls::ServerName::try_from(domain).unwrap();
Expand Down Expand Up @@ -111,16 +116,10 @@ async fn pass() -> io::Result<()> {
use std::time::*;
tokio::time::sleep(Duration::from_secs(1)).await;

let chain = certs(&mut std::io::Cursor::new(*chain)).unwrap();
let mut root_store = rustls::RootCertStore::empty();
root_store.add_trust_anchors(chain.iter().map(|cert| {
let ta = webpki::TrustAnchor::try_from_cert_der(&cert[..]).unwrap();
OwnedTrustAnchor::from_subject_spki_name_constraints(
ta.subject,
ta.spki,
ta.name_constraints,
)
}));
for cert in certs(&mut std::io::Cursor::new(*chain)) {
root_store.add(cert.unwrap()).unwrap();
}

let config = rustls::ClientConfig::builder()
.with_safe_defaults()
Expand All @@ -137,16 +136,10 @@ async fn pass() -> io::Result<()> {
async fn fail() -> io::Result<()> {
let (addr, domain, chain) = start_server();

let chain = certs(&mut std::io::Cursor::new(*chain)).unwrap();
let mut root_store = rustls::RootCertStore::empty();
root_store.add_trust_anchors(chain.iter().map(|cert| {
let ta = webpki::TrustAnchor::try_from_cert_der(&cert[..]).unwrap();
OwnedTrustAnchor::from_subject_spki_name_constraints(
ta.subject,
ta.spki,
ta.name_constraints,
)
}));
for cert in certs(&mut std::io::Cursor::new(*chain)) {
root_store.add(cert.unwrap()).unwrap();
}

let config = rustls::ClientConfig::builder()
.with_safe_defaults()
Expand Down
Loading

0 comments on commit 63b8d6f

Please sign in to comment.