Skip to content

Commit 10dca0a

Browse files
eric-seppanenMaxFangX
authored andcommitted
cargo: rustls->0.22.1, tokio-rustls->0.25.0
This patch is from this axum-server draft PR, credit to @eric-seppanen: - programatik29#106 It looks like axum-server will skip directly to 0.23, so this patch can be removed then. programatik29#112
1 parent 61fdf52 commit 10dca0a

File tree

2 files changed

+66
-65
lines changed

2 files changed

+66
-65
lines changed

Cargo.toml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,17 +37,17 @@ tracing = "0.1"
3737
# optional dependencies
3838
## rustls
3939
arc-swap = { version = "1", optional = true }
40-
rustls = { version = "0.21", features = ["dangerous_configuration"], optional = true }
40+
rustls = { version = "0.22.1", optional = true }
4141
rustls-pemfile = { version = "2.0.0", optional = true }
42-
tokio-rustls = { version = "0.24", optional = true }
42+
tokio-rustls = { version = "0.25.0", optional = true }
4343

4444
## openssl
4545
openssl = { version = "0.10", optional = true }
4646
tokio-openssl = { version = "0.6", optional = true }
4747

4848
[dev-dependencies]
4949
serial_test = "2.0"
50-
axum = "0.7"
50+
axum = "0.7.1"
5151
hyper = { version = "1.0.1", features = ["full"] }
5252
tokio = { version = "1", features = ["full"] }
5353
tower = { version = "0.4", features = ["util"] }

src/tls_rustls/mod.rs

Lines changed: 63 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,10 @@ use crate::{
3333
server::{io_other, Server},
3434
};
3535
use arc_swap::ArcSwap;
36-
use rustls::{Certificate, PrivateKey, ServerConfig};
37-
use rustls_pemfile::Item;
36+
use rustls::{
37+
pki_types::{CertificateDer, PrivateKeyDer},
38+
ServerConfig,
39+
};
3840
use std::time::Duration;
3941
use std::{fmt, io, net::SocketAddr, path::Path, sync::Arc};
4042
use tokio::{
@@ -172,10 +174,8 @@ impl RustlsConfig {
172174
/// The certificate must be DER-encoded X.509.
173175
///
174176
/// The private key must be DER-encoded ASN.1 in either PKCS#8 or PKCS#1 format.
175-
pub async fn from_der(cert: Vec<Vec<u8>>, key: Vec<u8>) -> io::Result<Self> {
176-
let server_config = spawn_blocking(|| config_from_der(cert, key))
177-
.await
178-
.unwrap()?;
177+
pub async fn from_der(cert: Vec<Vec<u8>>, key: PrivateKeyDer<'static>) -> io::Result<Self> {
178+
let server_config = config_from_der(cert, key)?;
179179
let inner = Arc::new(ArcSwap::from_pointee(server_config));
180180

181181
Ok(Self { inner })
@@ -218,10 +218,12 @@ impl RustlsConfig {
218218
/// The certificate must be DER-encoded X.509.
219219
///
220220
/// The private key must be DER-encoded ASN.1 in either PKCS#8 or PKCS#1 format.
221-
pub async fn reload_from_der(&self, cert: Vec<Vec<u8>>, key: Vec<u8>) -> io::Result<()> {
222-
let server_config = spawn_blocking(|| config_from_der(cert, key))
223-
.await
224-
.unwrap()?;
221+
pub async fn reload_from_der(
222+
&self,
223+
cert: Vec<Vec<u8>>,
224+
key: PrivateKeyDer<'static>,
225+
) -> io::Result<()> {
226+
let server_config = config_from_der(cert, key)?;
225227
let inner = Arc::new(server_config);
226228

227229
self.inner.store(inner);
@@ -278,12 +280,10 @@ impl fmt::Debug for RustlsConfig {
278280
}
279281
}
280282

281-
fn config_from_der(cert: Vec<Vec<u8>>, key: Vec<u8>) -> io::Result<ServerConfig> {
282-
let cert = cert.into_iter().map(Certificate).collect();
283-
let key = PrivateKey(key);
283+
fn config_from_der(cert: Vec<Vec<u8>>, key: PrivateKeyDer<'static>) -> io::Result<ServerConfig> {
284+
let cert = cert.into_iter().map(CertificateDer::from).collect();
284285

285286
let mut config = ServerConfig::builder()
286-
.with_safe_defaults()
287287
.with_no_client_auth()
288288
.with_single_cert(cert, key)
289289
.map_err(io_other)?;
@@ -295,24 +295,13 @@ fn config_from_der(cert: Vec<Vec<u8>>, key: Vec<u8>) -> io::Result<ServerConfig>
295295

296296
fn config_from_pem(cert: Vec<u8>, key: Vec<u8>) -> io::Result<ServerConfig> {
297297
let cert = rustls_pemfile::certs(&mut cert.as_ref())
298-
.map(|it| it.map(|it| it.to_vec()))
298+
.map(|cert| cert.map(|cert| cert.as_ref().to_vec()))
299299
.collect::<Result<Vec<_>, _>>()?;
300-
// Check the entire PEM file for the key in case it is not first section
301-
let mut key_vec: Vec<Vec<u8>> = rustls_pemfile::read_all(&mut key.as_ref())
302-
.filter_map(|i| match i.ok()? {
303-
Item::Sec1Key(key) => Some(key.secret_sec1_der().to_vec()),
304-
Item::Pkcs1Key(key) => Some(key.secret_pkcs1_der().to_vec().into()),
305-
Item::Pkcs8Key(key) => Some(key.secret_pkcs8_der().to_vec().into()),
306-
_ => None,
307-
})
308-
.collect();
309-
310-
// Make sure file contains only one key
311-
if key_vec.len() != 1 {
312-
return Err(io_other("private key format not supported"));
313-
}
300+
// Use the first private key found.
301+
let key = rustls_pemfile::private_key(&mut key.as_ref())?
302+
.ok_or(io_other("private key format not found"))?;
314303

315-
config_from_der(cert, key_vec.pop().unwrap())
304+
config_from_der(cert, key)
316305
}
317306

318307
async fn config_from_pem_file(
@@ -330,21 +319,12 @@ async fn config_from_pem_chain_file(
330319
chain: impl AsRef<Path>,
331320
) -> io::Result<ServerConfig> {
332321
let cert = tokio::fs::read(cert.as_ref()).await?;
333-
let cert = rustls_pemfile::certs(&mut cert.as_ref())
334-
.map(|it| it.map(|it| rustls::Certificate(it.to_vec())))
335-
.collect::<Result<Vec<_>, _>>()?;
322+
let cert = rustls_pemfile::certs(&mut cert.as_ref()).collect::<Result<Vec<_>, _>>()?;
336323
let key = tokio::fs::read(chain.as_ref()).await?;
337-
let key_cert: rustls::PrivateKey = match rustls_pemfile::read_one(&mut key.as_ref())?
338-
.ok_or_else(|| io_other("could not parse pem file"))?
339-
{
340-
Item::Pkcs8Key(key) => Ok(rustls::PrivateKey(key.secret_pkcs8_der().to_vec().into())),
341-
x => Err(io_other(format!(
342-
"invalid certificate format, received: {x:?}"
343-
))),
344-
}?;
324+
let key_cert = rustls_pemfile::private_key(&mut key.as_ref())?
325+
.ok_or_else(|| io_other("could not parse pem file"))?;
345326

346327
ServerConfig::builder()
347-
.with_safe_defaults()
348328
.with_no_client_auth()
349329
.with_single_cert(cert, key_cert)
350330
.map_err(|_| io_other("invalid certificate"))
@@ -362,17 +342,10 @@ mod tests {
362342
use http_body_util::BodyExt;
363343
use hyper::client::conn::http1::{handshake, SendRequest};
364344
use hyper_util::rt::TokioIo;
365-
use rustls::{
366-
client::{ServerCertVerified, ServerCertVerifier},
367-
Certificate, ClientConfig, ServerName,
368-
};
369-
use std::{
370-
convert::TryFrom,
371-
io,
372-
net::SocketAddr,
373-
sync::Arc,
374-
time::{Duration, SystemTime},
375-
};
345+
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
346+
use rustls::pki_types::{CertificateDer, ServerName};
347+
use rustls::{ClientConfig, SignatureScheme};
348+
use std::{io, net::SocketAddr, sync::Arc, time::Duration};
376349
use tokio::time::sleep;
377350
use tokio::{net::TcpStream, task::JoinHandle, time::timeout};
378351
use tokio_rustls::TlsConnector;
@@ -552,13 +525,15 @@ mod tests {
552525
(handle, server_task, addr)
553526
}
554527

555-
async fn get_first_cert(addr: SocketAddr) -> Certificate {
528+
async fn get_first_cert(addr: SocketAddr) -> CertificateDer<'static> {
556529
let stream = TcpStream::connect(addr).await.unwrap();
557530
let tls_stream = tls_connector().connect(dns_name(), stream).await.unwrap();
558531

559532
let (_io, client_connection) = tls_stream.into_inner();
560533

561-
client_connection.peer_certificates().unwrap()[0].clone()
534+
client_connection.peer_certificates().unwrap()[0]
535+
.clone()
536+
.into_owned()
562537
}
563538

564539
async fn connect(addr: SocketAddr) -> (SendRequest<Body>, JoinHandle<()>) {
@@ -586,24 +561,50 @@ mod tests {
586561
}
587562

588563
fn tls_connector() -> TlsConnector {
564+
#[derive(Debug)]
589565
struct NoVerify;
590566

591567
impl ServerCertVerifier for NoVerify {
592568
fn verify_server_cert(
593569
&self,
594-
_end_entity: &Certificate,
595-
_intermediates: &[Certificate],
596-
_server_name: &ServerName,
597-
_scts: &mut dyn Iterator<Item = &[u8]>,
570+
_end_entity: &CertificateDer<'_>,
571+
_intermediates: &[CertificateDer<'_>],
572+
_server_name: &ServerName<'_>,
598573
_ocsp_response: &[u8],
599-
_now: SystemTime,
574+
_now: rustls::pki_types::UnixTime,
600575
) -> Result<ServerCertVerified, rustls::Error> {
601576
Ok(ServerCertVerified::assertion())
602577
}
578+
579+
fn verify_tls12_signature(
580+
&self,
581+
_message: &[u8],
582+
_cert: &CertificateDer<'_>,
583+
_dss: &rustls::DigitallySignedStruct,
584+
) -> Result<HandshakeSignatureValid, rustls::Error> {
585+
Ok(HandshakeSignatureValid::assertion())
586+
}
587+
588+
fn verify_tls13_signature(
589+
&self,
590+
_message: &[u8],
591+
_cert: &CertificateDer<'_>,
592+
_dss: &rustls::DigitallySignedStruct,
593+
) -> Result<HandshakeSignatureValid, rustls::Error> {
594+
Ok(HandshakeSignatureValid::assertion())
595+
}
596+
597+
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
598+
vec![
599+
SignatureScheme::RSA_PKCS1_SHA256,
600+
SignatureScheme::RSA_PSS_SHA256,
601+
SignatureScheme::ECDSA_NISTP256_SHA256,
602+
]
603+
}
603604
}
604605

605606
let mut client_config = ClientConfig::builder()
606-
.with_safe_defaults()
607+
.dangerous()
607608
.with_custom_certificate_verifier(Arc::new(NoVerify))
608609
.with_no_client_auth();
609610

@@ -612,7 +613,7 @@ mod tests {
612613
TlsConnector::from(Arc::new(client_config))
613614
}
614615

615-
fn dns_name() -> ServerName {
616+
fn dns_name() -> ServerName<'static> {
616617
ServerName::try_from("localhost").unwrap()
617618
}
618619
}

0 commit comments

Comments
 (0)