Skip to content

Commit

Permalink
Update quinn to 0.11
Browse files Browse the repository at this point in the history
  • Loading branch information
Ralith committed May 7, 2024
1 parent 7cf0cd6 commit 9bae084
Show file tree
Hide file tree
Showing 8 changed files with 66 additions and 30 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ members = ["client", "server", "common", "save", "save/gen-protos"]
[workspace.dependencies]
hecs = "0.10.0"
nalgebra = { version = "0.32.1", features = ["libm-force"] }
quinn = "0.10.2"
quinn = { version = "0.11", default-features = false, features = ["rustls", "ring", "runtime-tokio"] }
toml = { version = "0.8.0", default-features = false, features = ["parse"] }

[profile.dev]
Expand Down
1 change: 0 additions & 1 deletion client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ fxhash = "0.2.1"
downcast-rs = "1.1.1"
quinn = { workspace = true }
futures-util = "0.3.1"
rustls = { version = "0.21.7", features = ["dangerous_configuration"] }
webpki = "0.22.0"
hecs = { workspace = true }
rcgen = { version = "0.13.1", default-features = false, features = ["ring"] }
Expand Down
5 changes: 3 additions & 2 deletions client/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::{
};

use client::{graphics, metrics, net, Config};
use quinn::rustls::pki_types::{CertificateDer, PrivatePkcs8KeyDer};
use save::Save;

use ash::khr;
Expand Down Expand Up @@ -44,8 +45,8 @@ fn main() {
let _guard = span.enter();
if let Err(e) = server::run(
server::NetParams {
certificate_chain: vec![rustls::Certificate(cert)],
private_key: rustls::PrivateKey(key),
certificate_chain: vec![CertificateDer::from(cert)],
private_key: PrivatePkcs8KeyDer::from(key).into(),
socket,
},
sim_cfg,
Expand Down
56 changes: 46 additions & 10 deletions client/src/net.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::{sync::Arc, thread};

use anyhow::{anyhow, Error, Result};
use quinn::rustls;
use tokio::sync::mpsc;

use common::{codec, proto};
Expand Down Expand Up @@ -44,10 +45,12 @@ async fn run(
) -> Result<()> {
let mut endpoint = quinn::Endpoint::client("[::]:0".parse().unwrap())?;
let crypto = rustls::ClientConfig::builder()
.with_safe_defaults()
.dangerous()
.with_custom_certificate_verifier(Arc::new(AcceptAnyCert))
.with_no_client_auth();
let client_cfg = quinn::ClientConfig::new(Arc::new(crypto));
let client_cfg = quinn::ClientConfig::new(Arc::new(
quinn::crypto::rustls::QuicClientConfig::try_from(crypto).unwrap(),
));
endpoint.set_default_client_config(client_cfg);

let result = inner(cfg, incoming, outgoing, endpoint.clone()).await;
Expand Down Expand Up @@ -133,18 +136,51 @@ async fn handle_unordered(incoming: mpsc::UnboundedSender<Message>, connection:
}
}

#[derive(Debug)]
struct AcceptAnyCert;

impl rustls::client::ServerCertVerifier for AcceptAnyCert {
impl rustls::client::danger::ServerCertVerifier for AcceptAnyCert {
fn verify_server_cert(
&self,
_end_entity: &rustls::Certificate,
_intermediates: &[rustls::Certificate],
_server_name: &rustls::ServerName,
_scts: &mut dyn Iterator<Item = &[u8]>,
_end_entity: &rustls::pki_types::CertificateDer,
_intermediates: &[rustls::pki_types::CertificateDer],
_server_name: &rustls::pki_types::ServerName,
_ocsp_response: &[u8],
_now: std::time::SystemTime,
) -> Result<rustls::client::ServerCertVerified, rustls::Error> {
Ok(rustls::client::ServerCertVerified::assertion())
_now: rustls::pki_types::UnixTime,
) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
Ok(rustls::client::danger::ServerCertVerified::assertion())
}

fn verify_tls12_signature(
&self,
_message: &[u8],
_cert: &rustls::pki_types::CertificateDer<'_>,
_dss: &rustls::DigitallySignedStruct,
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
// QUIC is TLS 1.3 only
unreachable!();
}

fn verify_tls13_signature(
&self,
message: &[u8],
cert: &rustls::pki_types::CertificateDer<'_>,
dss: &rustls::DigitallySignedStruct,
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
rustls::crypto::verify_tls13_signature(
message,
cert,
dss,
&rustls::crypto::CryptoProvider::get_default()
.unwrap()
.signature_verification_algorithms,
)
}

fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
rustls::crypto::CryptoProvider::get_default()
.unwrap()
.signature_verification_algorithms
.supported_schemes()
}
}
5 changes: 2 additions & 3 deletions common/src/codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,15 @@ pub async fn send<T: Serialize + ?Sized>(stream: &mut quinn::SendStream, msg: &T
pub async fn recv<T: DeserializeOwned>(stream: &mut quinn::RecvStream) -> Result<Option<T>> {
let mut tag = [0; 4];
match stream.read_exact(&mut tag[0..3]).await {
Err(quinn::ReadExactError::FinishedEarly) => return Ok(None),
Err(quinn::ReadExactError::FinishedEarly(_)) => return Ok(None),
Err(quinn::ReadExactError::ReadError(e)) => return Err(e.into()),
Ok(()) => {}
}

let len = u32::from_le_bytes(tag) as usize;
let mut buf = vec![0; len];
match stream.read_exact(&mut buf).await {
Err(quinn::ReadExactError::FinishedEarly) => return Ok(None),
Err(quinn::ReadExactError::FinishedEarly(_)) => return Ok(None),
Err(quinn::ReadExactError::ReadError(e)) => return Err(e.into()),
Ok(()) => {}
}
Expand All @@ -40,7 +40,6 @@ pub async fn send_whole<T: Serialize + ?Sized>(
) -> std::result::Result<(), quinn::WriteError> {
let buf = bincode::serialize(msg).unwrap();
stream.write_all(&buf).await?;
stream.finish().await?;
Ok(())
}

Expand Down
3 changes: 1 addition & 2 deletions server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,5 @@ fxhash = "0.2.1"
nalgebra = { workspace = true }
libm = "0.2.6"
slotmap = "1.0.6"
rustls = "0.21.7"
rustls-pemfile = "1.0.0"
rustls-pemfile = "2.1.2"
save = { path = "../save" }
5 changes: 3 additions & 2 deletions server/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use std::{net::UdpSocket, sync::Arc, time::Instant};
use anyhow::{Context, Error, Result};
use futures::{select, StreamExt};
use hecs::Entity;
use quinn::rustls::pki_types::{CertificateDer, PrivateKeyDer};
use slotmap::DenseSlotMap;
use tokio::sync::mpsc;
use tokio_stream::wrappers::{IntervalStream, ReceiverStream};
Expand All @@ -21,8 +22,8 @@ use save::Save;
use sim::Sim;

pub struct NetParams {
pub certificate_chain: Vec<rustls::Certificate>,
pub private_key: rustls::PrivateKey,
pub certificate_chain: Vec<CertificateDer<'static>>,
pub private_key: PrivateKeyDer<'static>,
pub socket: UdpSocket,
}

Expand Down
19 changes: 10 additions & 9 deletions server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ mod config;
use std::{fs, net::UdpSocket, path::Path};

use anyhow::{anyhow, Context, Result};
use quinn::rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
use tracing::{info, warn};

use common::SimConfig;
Expand Down Expand Up @@ -32,18 +33,15 @@ pub fn run() -> Result<()> {
rustls_pemfile::certs(
&mut &*fs::read(certificate_chain).context("reading certificate chain")?,
)
.context("parsing certificate chain")?
.into_iter()
.map(rustls::Certificate)
.collect(),
.collect::<Result<Vec<_>, _>>()
.context("parsing certificate chain")?,
rustls_pemfile::pkcs8_private_keys(
&mut &*fs::read(private_key).context("reading private key")?,
)
.context("parsing private key")?
.into_iter()
.map(rustls::PrivateKey)
.next()
.ok_or_else(|| anyhow!("no private key found with PKCS #8 format"))?,
.ok_or_else(|| anyhow!("no private key found with PKCS #8 format"))?
.context("parsing private key")?
.into(),
),
_ => {
// TODO: Cache on disk
Expand All @@ -61,7 +59,10 @@ pub fn run() -> Result<()> {
.unwrap();
let key = certified_key.key_pair.serialize_der();
let cert = certified_key.cert.der().to_vec();
(vec![rustls::Certificate(cert)], rustls::PrivateKey(key))
(
vec![CertificateDer::from(cert)],
PrivateKeyDer::from(PrivatePkcs8KeyDer::from(key)),
)
}
};

Expand Down

0 comments on commit 9bae084

Please sign in to comment.