diff --git a/.github/workflows/release-py.yml b/.github/workflows/release-py.yml index eb1160bd..f1b7fa8d 100644 --- a/.github/workflows/release-py.yml +++ b/.github/workflows/release-py.yml @@ -90,8 +90,7 @@ jobs: os: ubuntu-latest - target: aarch64-unknown-linux-gnu os: ubuntu-latest - # Use manylinux_2_28 for aarch64-linux to get a newer GCC. - # manylinux2014 ships GCC 4.8.5 which can't compile aws-lc-sys. + # Keep the aarch64 Linux wheel's existing glibc 2.28 baseline. manylinux: 2_28 # The cross image sets TARGET_CC/CXX which leaks into host builds. before-script-linux: "unset TARGET_CC TARGET_CXX" diff --git a/js/web-transport/README.md b/js/web-transport/README.md index a0e82caf..69099950 100644 --- a/js/web-transport/README.md +++ b/js/web-transport/README.md @@ -192,3 +192,11 @@ unchanged. ## License MIT OR Apache-2.0 + +## Native crypto + +The native Quinn backend uses rind through rind-rustls, with an installed process-wide +rustls provider taking precedence. Endpoint keys and Retry integrity always use rind. +Native builds support x86_64, aarch64 and 32-bit ARM; constructing a client or server +returns an error if the CPU lacks a required feature. This also applies with another +TLS provider installed. The native dependency graph no longer builds ring or aws-lc-rs. diff --git a/justfile b/justfile index 36cffcd0..cbad4480 100644 --- a/justfile +++ b/justfile @@ -36,16 +36,10 @@ check: cargo fmt --all --check # requires: cargo install cargo-hack - # web-transport-ffi excluded from the feature powerset because aws-lc-rs and - # ring are mutually exclusive at link time (one rustls provider must win). - cargo hack check --feature-powerset --workspace --keep-going --exclude web-transport-node --exclude web-transport-ffi + cargo hack check --feature-powerset --workspace --keep-going --exclude web-transport-node cargo hack check --feature-powerset --target wasm32-unknown-unknown -p web-transport --keep-going cargo hack check --feature-powerset --target wasm32-unknown-unknown -p web-transport-wasm --keep-going - # web-transport-ffi: explicit check under each TLS provider. - cargo check -p web-transport-ffi - cargo check -p web-transport-ffi --no-default-features --features ring - # requires: cargo install cargo-shear cargo shear diff --git a/kt/README.md b/kt/README.md index 5748d2c2..e10c37e4 100644 --- a/kt/README.md +++ b/kt/README.md @@ -81,3 +81,11 @@ kt/ ## Publishing Publishing to Maven Central is CI-only via `.github/workflows/release-kt.yml`, which runs on every `web-transport-ffi-v*` tag. See the moq-dev org docs for Sonatype credentials. + +## Native crypto + +The native Quinn backend uses rind through rind-rustls, with an installed process-wide +rustls provider taking precedence. Endpoint keys and Retry integrity always use rind. +Native builds support x86_64, aarch64 and 32-bit ARM; constructing a client or server +returns an error if the CPU lacks a required feature. This also applies with another +TLS provider installed. The native dependency graph no longer builds ring or aws-lc-rs. diff --git a/py/web-transport/README.md b/py/web-transport/README.md index 30e1f1d8..c646b26f 100644 --- a/py/web-transport/README.md +++ b/py/web-transport/README.md @@ -146,3 +146,11 @@ uv run pytest ## License MIT OR Apache-2.0 + +## Native crypto + +The native Quinn backend uses rind through rind-rustls, with an installed process-wide +rustls provider taking precedence. Endpoint keys and Retry integrity always use rind. +Native builds support x86_64, aarch64 and 32-bit ARM; constructing a client or server +returns an error if the CPU lacks a required feature. This also applies with another +TLS provider installed. The native dependency graph no longer builds ring or aws-lc-rs. diff --git a/quest/a1/native-client-config.md b/quest/a1/native-client-config.md index 1e6e4f42..16dc994d 100644 --- a/quest/a1/native-client-config.md +++ b/quest/a1/native-client-config.md @@ -13,7 +13,3 @@ Do not add a pretend browser certificate-verification bypass, a browser panic or ## Closes - [#135](https://github.com/moq-dev/web-transport/issues/135) - the implementation completes this report - -## Related - -- [Quinn on rind](/quest/a1/rind/quinn.md) - replaces the crypto these builders configure diff --git a/quest/a1/rind/README.md b/quest/a1/rind/README.md index 3cc914d9..347766df 100644 --- a/quest/a1/rind/README.md +++ b/quest/a1/rind/README.md @@ -33,6 +33,5 @@ Decision prompts (✅ chosen): ## Required -- [Quinn on rind](/quest/a1/rind/quinn.md) - provider-neutral QUIC crypto adapter; Quinn, FFI, Node and router on rind - [Noq on rind](/quest/a1/rind/noq.md) - Noq's rustls without ring, with rind keys - [iroh on rind](/quest/a1/rind/iroh.md) - iroh endpoint built with rind's provider diff --git a/quest/a1/rind/noq.md b/quest/a1/rind/noq.md index 045f9d07..e562d87f 100644 --- a/quest/a1/rind/noq.md +++ b/quest/a1/rind/noq.md @@ -8,4 +8,4 @@ web-transport-noq compiles no ring or aws-lc-rs: its builders run TLS on rind-ru Per rind's MIGRATING.md, noq 1.4's `rustls` feature works without `ring`. The client and server use `QuicClientConfig::with_initial` and `QuicServerConfig::with_initial`, which are public, with rind-rustls's TLS13_AES_128_GCM_SHA256 QUIC suite as the initial. `EndpointConfig::new` takes a reset `HmacKey` on rind's HMAC, and `ServerConfig::new` a `HandshakeTokenKey` on rind's HKDF and AES-256-GCM. noq-proto's Retry tag already uses pure-Rust aes-gcm. -Replace `crypto::default_provider()` with the installed process provider, else rind. A CPU rind refuses returns an `UnsupportedCpu` error from the finishing methods, as [the Quinn child](/quest/a1/rind/quinn.md) does: `rind::cpu::check()` runs before the HMAC and token keys are built, even with an installed provider, and `Client::default()` documents its panic. Keep test-only ring in dev-dependencies only if a test needs it. Test a handshake and Retry against a ring-backed noq peer. +Replace `crypto::default_provider()` with the installed process provider, else rind. A CPU rind refuses returns an `UnsupportedCpu` error from the finishing methods, as web-transport-quinn does: `rind::cpu::check()` runs before the HMAC and token keys are built, even with an installed provider, and `Client::default()` documents its panic. Keep test-only ring in dev-dependencies only if a test needs it. Test a handshake and Retry against a ring-backed noq peer. diff --git a/quest/a1/rind/quinn.md b/quest/a1/rind/quinn.md deleted file mode 100644 index 94baca10..00000000 --- a/quest/a1/rind/quinn.md +++ /dev/null @@ -1,21 +0,0 @@ -# [L] Run Quinn, FFI, Node and the router on rind - -## Goal - -web-transport-quinn and everything built on it (web-transport-ffi, web-transport-node, and the `web-transport` router's native path) compile no ring or aws-lc-rs. Clients and servers run TLS on rind-rustls through a QUIC crypto adapter this crate exposes. Their `aws-lc-rs`/`ring` features are removed, including the router's interim ones. - -## Plan - -Decided with the maintainer on 2026-11-06 (planning interview): - -- quinn-proto 0.11's `crypto::rustls` module compiles only with ring or aws-lc-rs ([quinn-rs/quinn#2341](https://github.com/quinn-rs/quinn/issues/2341)), and rind ships no quinn adapter (rind's decision, 2026-10-31). So this crate carries its own adapter. It was verified that `quinn` with `default-features = false` plus `runtime-tokio`, `bloom` and `platform-verifier`, next to rind-rustls, builds with no ring, aws-lc-sys or `cc`. -- A public `web_transport_quinn::crypto` module implements quinn-proto's public crypto traits over `rustls::quic`: the session, `QuicClientConfig`/`QuicServerConfig` equivalents, packet and header keys, the Retry integrity tag (AES-128-GCM), the reset `HmacKey`, and the `HandshakeTokenKey` (HKDF). Retry, HMAC and HKDF come from rind. The session accepts any rustls provider with QUIC suites. Endpoints are built with `Endpoint::new` and an `EndpointConfig` from this module, since `Endpoint::client`/`server` need ring. -- FFI and callers of `Client::new(endpoint, quinn::ClientConfig)` build their configs from this module. Document the migration from `quinn::crypto::rustls`. -- Builders default to the installed process provider, else rind. A CPU rind refuses returns a new `UnsupportedCpu` error from the finishing methods. `rind::cpu::check()` runs before any rind primitive is built (the Retry, reset and token keys), even when an installed provider is used. FFI's client constructor, which builds configs from this module, runs the same check first and returns the refusal as a `WebTransportError`. `Client::default()` keeps its `with_system_roots().unwrap()` and documents that it panics on such a CPU. -- Remove `aws-lc-rs`/`ring` from web-transport-quinn and web-transport-ffi, so the router no longer pulls aws-lc-rs in through its default dependency. Check that py/kt/swift and Node still build and pass their binding CI. -- Test interop against an unmodified quinn peer on aws-lc-rs: handshake, Retry, stateless reset, key update, 0-RTT rejection, and a CPU-refusal path. Use controlled time where the protocol allows. -- The adapter is deleted once upstream allows any provider; see [Quinn adapter removal](/quest/a2/quinn-adapter-removal.md). - -## Related - -- [Native client composition](/quest/a1/native-client-config.md) - converts a configured Quinn client into the router diff --git a/quest/a2/quinn-adapter-removal.md b/quest/a2/quinn-adapter-removal.md index c353f5b3..a4244518 100644 --- a/quest/a2/quinn-adapter-removal.md +++ b/quest/a2/quinn-adapter-removal.md @@ -2,7 +2,7 @@ ## Goal -web-transport-quinn uses quinn's own provider-neutral `rustls` support and deletes the adapter from [Quinn on rind](/quest/a1/rind/quinn.md). +web-transport-quinn uses quinn's own provider-neutral `rustls` support and deletes the local `web_transport_quinn::crypto` adapter. ## Plan @@ -10,5 +10,4 @@ Bump the quinn pin in web-transport-quinn and web-transport-ffi together (FFI ha ## Required -- [Quinn on rind](/quest/a1/rind/quinn.md) - the adapter this replaces - [Quinn provider-neutral rustls release](/quest/a2/quinn-provider-release.md) - the upstream release this switches to diff --git a/rs/web-transport-ffi/Cargo.toml b/rs/web-transport-ffi/Cargo.toml index d7e7bec6..0c54f870 100644 --- a/rs/web-transport-ffi/Cargo.toml +++ b/rs/web-transport-ffi/Cargo.toml @@ -18,11 +18,6 @@ crate-type = ["staticlib", "cdylib"] name = "uniffi-bindgen" path = "./uniffi-bindgen.rs" -[features] -default = ["aws-lc-rs"] -aws-lc-rs = ["quinn/rustls-aws-lc-rs", "rustls/aws-lc-rs", "web-transport-quinn/aws-lc-rs"] -ring = ["quinn/rustls-ring", "rustls/ring", "web-transport-quinn/ring"] - [dependencies] bytes = "1" http = "1" diff --git a/rs/web-transport-ffi/README.md b/rs/web-transport-ffi/README.md index 0059360c..5b323483 100644 --- a/rs/web-transport-ffi/README.md +++ b/rs/web-transport-ffi/README.md @@ -21,3 +21,14 @@ close both sockets, including pending connections. Call `close` before awaiting ``` Artifacts land in `dist/`. + +## Crypto + +The native Quinn backend uses rind through rind-rustls, with an installed process-wide +rustls provider taking precedence. Endpoint keys and Retry integrity always use rind. +Native builds support x86_64, aarch64 and 32-bit ARM; constructing a client or server +returns an error if the CPU lacks a required feature. This also applies with another +TLS provider installed. The native dependency graph no longer builds ring or aws-lc-rs. + +The `ring` and `aws-lc-rs` Cargo features have been removed. Language API signatures +and generated bindings remain unchanged; CPU refusal is a `WebTransportError`. diff --git a/rs/web-transport-ffi/src/client.rs b/rs/web-transport-ffi/src/client.rs index 408e8859..3e046d48 100644 --- a/rs/web-transport-ffi/src/client.rs +++ b/rs/web-transport-ffi/src/client.rs @@ -1,8 +1,4 @@ //! WebTransport client wrapped for UniFFI. -//! -//! Mirrors `rs/web-transport-python/src/client.rs` with PyO3 replaced by -//! `#[uniffi::export]` and the `ring` crypto provider replaced by either -//! `aws-lc-rs` (default) or `ring` (feature-gated). use std::sync::Arc; use std::time::Duration; @@ -68,7 +64,7 @@ impl Client { )); } - let provider = Arc::new(default_crypto_provider()); + let provider = default_crypto_provider()?; let tls_builder = rustls::ClientConfig::builder_with_provider(provider.clone()) .with_protocol_versions(&[&rustls::version::TLS13]) @@ -136,7 +132,7 @@ impl Client { } } - let quic_config = quinn::crypto::rustls::QuicClientConfig::try_from(tls_config) + let quic_config = web_transport_quinn::crypto::QuicClientConfig::try_from(tls_config) .map_err(|e| WebTransportError::invalid(format!("QUIC config: {e}")))?; let mut client_config = quinn::ClientConfig::new(Arc::new(quic_config)); client_config.transport_config(transport.into()); @@ -192,22 +188,12 @@ impl Drop for Client { } // --------------------------------------------------------------------------- -// Crypto provider selection (matches feature gates in Cargo.toml). +// Crypto provider selection and CPU support. // --------------------------------------------------------------------------- -fn default_crypto_provider() -> rustls::crypto::CryptoProvider { - #[cfg(feature = "aws-lc-rs")] - { - rustls::crypto::aws_lc_rs::default_provider() - } - #[cfg(all(feature = "ring", not(feature = "aws-lc-rs")))] - { - rustls::crypto::ring::default_provider() - } - #[cfg(not(any(feature = "aws-lc-rs", feature = "ring")))] - { - compile_error!("web-transport-ffi requires one of: aws-lc-rs, ring"); - } +fn default_crypto_provider() -> Result, WebTransportError> { + web_transport_quinn::crypto::default_provider() + .map_err(|e| WebTransportError::invalid(e.to_string())) } // --------------------------------------------------------------------------- @@ -229,7 +215,7 @@ impl ServerCertVerifier for ServerFingerprints { _ocsp_response: &[u8], _now: rustls::pki_types::UnixTime, ) -> Result { - let cert_hash = sha256(&self.provider, end_entity)?; + let cert_hash = web_transport_quinn::crypto::sha256(&self.provider, end_entity)?; if self.fingerprints.iter().any(|fp| fp == cert_hash.as_ref()) { return Ok(rustls::client::danger::ServerCertVerified::assertion()); } @@ -321,25 +307,6 @@ impl ServerCertVerifier for NoCertificateVerification { } } -fn sha256( - provider: &Arc, - cert: &CertificateDer<'_>, -) -> Result { - let hash_provider = provider - .cipher_suites - .iter() - .find_map(|suite| { - let hp = suite.tls13()?.common.hash_provider; - if hp.algorithm() == rustls::crypto::hash::HashAlgorithm::SHA256 { - Some(hp) - } else { - None - } - }) - .ok_or_else(|| rustls::Error::General("crypto provider missing SHA-256".into()))?; - Ok(hash_provider.hash(cert)) -} - // --------------------------------------------------------------------------- // Helper used by server.rs for TLS configuration. // --------------------------------------------------------------------------- @@ -355,8 +322,8 @@ pub(crate) fn build_server_tls( let key = rustls::pki_types::PrivateKeyDer::try_from(private_key) .map_err(|e| WebTransportError::invalid(format!("invalid private key: {e}")))?; - let provider = default_crypto_provider(); - let mut tls = rustls::ServerConfig::builder_with_provider(Arc::new(provider)) + let provider = default_crypto_provider()?; + let mut tls = rustls::ServerConfig::builder_with_provider(provider) .with_protocol_versions(&[&rustls::version::TLS13]) .map_err(|e| WebTransportError::invalid(format!("TLS config: {e}")))? .with_no_client_auth() diff --git a/rs/web-transport-ffi/src/error.rs b/rs/web-transport-ffi/src/error.rs index 8bd577a1..2eeb1fc6 100644 --- a/rs/web-transport-ffi/src/error.rs +++ b/rs/web-transport-ffi/src/error.rs @@ -240,7 +240,9 @@ pub fn map_server_error(err: web_transport_quinn::ServerError) -> WebTransportEr | web_transport_quinn::ServerError::SettingsError(_) | web_transport_quinn::ServerError::ConnectError(_) | web_transport_quinn::ServerError::IoError(_) - | web_transport_quinn::ServerError::Rustls(_) => { + | web_transport_quinn::ServerError::Rustls(_) + | web_transport_quinn::ServerError::Crypto(_) + | web_transport_quinn::ServerError::UnsupportedCpu(_) => { WebTransportError::protocol(err.to_string()) } } diff --git a/rs/web-transport-ffi/src/server.rs b/rs/web-transport-ffi/src/server.rs index 8c1ed137..3124b9b2 100644 --- a/rs/web-transport-ffi/src/server.rs +++ b/rs/web-transport-ffi/src/server.rs @@ -83,14 +83,24 @@ impl Server { } let transport_config = Arc::new(transport); - let quic = quinn::crypto::rustls::QuicServerConfig::try_from(tls) + let quic = web_transport_quinn::crypto::QuicServerConfig::try_from(tls) .map_err(|e| WebTransportError::invalid(format!("QUIC config: {e}")))?; - let mut server_config = quinn::ServerConfig::with_crypto(Arc::new(quic)); + let mut server_config = web_transport_quinn::crypto::server_config(Arc::new(quic)) + .map_err(|e| WebTransportError::invalid(e.to_string()))?; server_config.transport_config(transport_config.clone()); let _guard = RUNTIME.enter(); - let endpoint = quinn::Endpoint::server(server_config, addr) + let endpoint_config = web_transport_quinn::crypto::endpoint_config() + .map_err(|e| WebTransportError::invalid(e.to_string()))?; + let socket = std::net::UdpSocket::bind(addr) .map_err(|e| WebTransportError::Io(format!("failed to bind: {e}")))?; + let endpoint = quinn::Endpoint::new( + endpoint_config, + Some(server_config), + socket, + Arc::new(quinn::TokioRuntime), + ) + .map_err(|e| WebTransportError::Io(format!("failed to bind: {e}")))?; let local_addr = endpoint .local_addr() @@ -153,9 +163,10 @@ impl Server { private_key: Vec, ) -> Result<(), WebTransportError> { let tls = build_server_tls(certificate_chain, private_key)?; - let quic = quinn::crypto::rustls::QuicServerConfig::try_from(tls) + let quic = web_transport_quinn::crypto::QuicServerConfig::try_from(tls) .map_err(|e| WebTransportError::invalid(format!("QUIC config: {e}")))?; - let mut server_config = quinn::ServerConfig::with_crypto(Arc::new(quic)); + let mut server_config = web_transport_quinn::crypto::server_config(Arc::new(quic)) + .map_err(|e| WebTransportError::invalid(e.to_string()))?; server_config.transport_config(self.transport_config.clone()); self.endpoint.set_server_config(Some(server_config)); Ok(()) diff --git a/rs/web-transport-ffi/src/test.rs b/rs/web-transport-ffi/src/test.rs index 4bae179f..94223d43 100644 --- a/rs/web-transport-ffi/src/test.rs +++ b/rs/web-transport-ffi/src/test.rs @@ -33,8 +33,6 @@ fn client_config_for(cert_hash: Vec) -> ClientConfig { #[tokio::test] async fn echo_datagram() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); - let (chain, key) = self_signed_cert(); let cert_hash = sha256(&chain[0]); diff --git a/rs/web-transport-node/src/lib.rs b/rs/web-transport-node/src/lib.rs index 6f837662..3cae0fa5 100644 --- a/rs/web-transport-node/src/lib.rs +++ b/rs/web-transport-node/src/lib.rs @@ -272,23 +272,13 @@ mod server_tests { } fn bind() -> NapiServer { - // Workspace all-features tests enable both TLS backends; choose one for this process. - static PROVIDER: std::sync::Once = std::sync::Once::new(); - PROVIDER.call_once(|| { - web_transport_quinn::quinn::rustls::crypto::aws_lc_rs::default_provider() - .install_default() - .expect("install test TLS provider"); - }); let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap(); + let key = rustls_pemfile::private_key(&mut cert.signing_key.serialize_pem().as_bytes()) + .unwrap() + .unwrap(); let server = web_transport_quinn::ServerBuilder::new() .with_addr("127.0.0.1:0".parse().unwrap()) - .with_certificate( - vec![cert.cert.der().clone()], - web_transport_quinn::quinn::rustls::pki_types::PrivatePkcs8KeyDer::from( - cert.signing_key.serialize_der(), - ) - .into(), - ) + .with_certificate(vec![cert.cert.der().clone()], key) .unwrap(); NapiServer { inner: Arc::new(ServerState { diff --git a/rs/web-transport-quinn/Cargo.toml b/rs/web-transport-quinn/Cargo.toml index 4bcbb07b..6892a139 100644 --- a/rs/web-transport-quinn/Cargo.toml +++ b/rs/web-transport-quinn/Cargo.toml @@ -15,9 +15,6 @@ categories = ["network-programming", "web-programming"] all-features = true [features] -default = ["aws-lc-rs"] -aws-lc-rs = ["quinn/rustls-aws-lc-rs", "rustls/aws-lc-rs"] -ring = ["quinn/rustls-ring", "rustls/ring"] # Unlocks `quinn::TransportConfig::qlog_stream` and `quinn::QlogConfig`, which this # crate re-exports but cannot enable on a caller's behalf. qlog = ["quinn/qlog"] @@ -34,6 +31,10 @@ quinn = { version = "0.11", default-features = false, features = [ "bloom", ] } +quinn-proto = { version = "0.11.19", default-features = false } +rind = "0.2.1" +rind-rustls = "0.23" + rustls = { version = "0.23", default-features = false, features = [ "logging", "std", @@ -54,6 +55,7 @@ web-transport-trait = { workspace = true } [dev-dependencies] anyhow = "1" clap = { version = "4", features = ["derive"] } +quinn = { version = "0.11", default-features = false, features = ["rustls-aws-lc-rs"] } rcgen = "0.14" rustls-pemfile = "2" tokio = { version = "1", features = ["full"] } diff --git a/rs/web-transport-quinn/README.md b/rs/web-transport-quinn/README.md index 5c43071f..3e30de22 100644 --- a/rs/web-transport-quinn/README.md +++ b/rs/web-transport-quinn/README.md @@ -39,14 +39,64 @@ runtime present at construction, or at the first connection if constructed outside a runtime. Keep that runtime alive while using the client. For an existing `quinn::ClientConfig`, `Client::from(config)` uses the same -lazy sockets. Set its ALPN to `h3`. `Client::new(endpoint, config)` instead keeps -the caller's endpoint and address handling. +lazy sockets. Set its ALPN to `web_transport_quinn::ALPN` (`h3`). +`Client::new(endpoint, config)` instead keeps the caller's endpoint and address +handling, and `Server::new(endpoint)` accepts a caller's server endpoint. `client.close(code, reason)` closes all bound endpoints and prevents new connections through any clone. Await `client.wait_idle()` after closing to wait for every bound endpoint to drain. -See the [examples](examples) for certificate setup and server construction. +## Crypto and migration + +TLS uses the process-wide rustls provider if one is installed, otherwise +[rind-rustls](https://github.com/moq-dev/rind/tree/main/rind-rustls). Retry integrity, +stateless resets and handshake tokens always use rind. The normal and build +dependency graph contains no ring or aws-lc-rs; aws-lc-rs is a development dependency +for interop tests. The `ring` and `aws-lc-rs` crate features have been removed. + +rind supports x86_64, aarch64 and 32-bit ARM. A CPU missing a required feature is +rejected by the builders' finishing methods with `ClientError::UnsupportedCpu` or +`ServerError::UnsupportedCpu`. `new()` stays infallible. This check also applies +when the process installed another TLS provider, because endpoint keys use rind. +`Client::default()` unwraps system-root setup and panics on an unsupported CPU; +use `ClientBuilder::new().with_system_roots()` to handle the error. + +For manually configured endpoints, replace `quinn::crypto::rustls::QuicClientConfig`, +`QuicServerConfig` and `HandshakeData` with the same names under +`web_transport_quinn::crypto`. `crypto::default_provider()` and `crypto::sha256()` now return a `Result`. +Import rustls directly instead of through the feature-gated `quinn::rustls` re-export. +Use `crypto::server_config(Arc::new(crypto))?` instead of +`quinn::ServerConfig::with_crypto`, and `quinn::Endpoint::new` with +`crypto::endpoint_config()?` instead of `Endpoint::client` or `Endpoint::server`. +Those Quinn convenience methods require its ring or aws-lc-rs feature. + +```rust,no_run +# fn main() -> Result<(), Box> { +use std::sync::Arc; +use web_transport_quinn::{crypto, quinn}; + +let mut roots = rustls::RootCertStore::empty(); +roots.add_parsable_certificates(rustls_native_certs::load_native_certs().certs); + +let mut tls = rustls::ClientConfig::builder_with_provider(crypto::default_provider()?) + .with_protocol_versions(&[&rustls::version::TLS13])? + .with_root_certificates(roots) + .with_no_client_auth(); +tls.alpn_protocols = vec![web_transport_quinn::ALPN.as_bytes().to_vec()]; +let config = quinn::ClientConfig::new(Arc::new(crypto::QuicClientConfig::try_from(tls)?)); +let client = web_transport_quinn::Client::from(config); +# Ok(()) +# } +``` + +The adapter accepts any rustls provider exposing the QUIC AES-128-GCM-SHA256 +initial suite. Configure TLS 1.3, and set server `max_early_data_size` to zero or +`u32::MAX`. `crypto::ResetKey` and `crypto::TokenKey` accept persistent secrets +when endpoints need keys that survive restarts. `HandshakeData` is a distinct +Rust type from Quinn's, so raw-session ALPN discovery requires this adapter. + +See the [advanced examples](examples) for custom TLS and WebTransport setup. ## Async runtimes Each WebTransport session runs a background task that reads capsules from the CONNECT stream, and `Session::close` runs the graceful close in another. diff --git a/rs/web-transport-quinn/examples/echo-client-advanced.rs b/rs/web-transport-quinn/examples/echo-client-advanced.rs index d8f57d6b..7c6bd0f8 100644 --- a/rs/web-transport-quinn/examples/echo-client-advanced.rs +++ b/rs/web-transport-quinn/examples/echo-client-advanced.rs @@ -44,18 +44,17 @@ async fn main() -> anyhow::Result<()> { // Standard quinn setup, accepting only the given certificate. // You should use system roots in production. let mut config = rustls::ClientConfig::builder_with_provider( - web_transport_quinn::crypto::default_provider(), + web_transport_quinn::crypto::default_provider()?, ) .with_protocol_versions(&[&rustls::version::TLS13])? .with_root_certificates(roots) .with_no_client_auth(); config.alpn_protocols = vec![web_transport_quinn::ALPN.as_bytes().to_vec()]; // this one is important - let config: quinn::crypto::rustls::QuicClientConfig = config.try_into()?; + let config: web_transport_quinn::crypto::QuicClientConfig = config.try_into()?; let config = quinn::ClientConfig::new(Arc::new(config)); - let client = quinn::Endpoint::client("[::]:0".parse()?)?; - let client = web_transport_quinn::Client::new(client, config); + let client = web_transport_quinn::Client::from(config); // Connect to the given URL. tracing::info!(host = ?args.url.host_str(), path = args.url.path(), "connecting"); diff --git a/rs/web-transport-quinn/examples/echo-server-advanced.rs b/rs/web-transport-quinn/examples/echo-server-advanced.rs index 60e77bf6..7c3758c0 100644 --- a/rs/web-transport-quinn/examples/echo-server-advanced.rs +++ b/rs/web-transport-quinn/examples/echo-server-advanced.rs @@ -63,7 +63,7 @@ async fn main() -> anyhow::Result<()> { // Standard Quinn setup let mut config = rustls::ServerConfig::builder_with_provider( - web_transport_quinn::crypto::default_provider(), + web_transport_quinn::crypto::default_provider()?, ) .with_protocol_versions(&[&rustls::version::TLS13])? .with_no_client_auth() @@ -72,12 +72,17 @@ async fn main() -> anyhow::Result<()> { config.max_early_data_size = u32::MAX; config.alpn_protocols = vec![web_transport_quinn::ALPN.as_bytes().to_vec()]; // this one is important - let config: quinn::crypto::rustls::QuicServerConfig = config.try_into()?; - let config = quinn::ServerConfig::with_crypto(Arc::new(config)); + let config: web_transport_quinn::crypto::QuicServerConfig = config.try_into()?; + let config = web_transport_quinn::crypto::server_config(Arc::new(config))?; tracing::info!(addr = %args.addr, "listening"); - let server = quinn::Endpoint::server(config, args.addr)?; + let server = quinn::Endpoint::new( + web_transport_quinn::crypto::endpoint_config()?, + Some(config), + std::net::UdpSocket::bind(args.addr)?, + quinn::default_runtime().context("no async runtime")?, + )?; // Accept new connections. while let Some(conn) = server.accept().await { diff --git a/rs/web-transport-quinn/src/client.rs b/rs/web-transport-quinn/src/client.rs index fb793690..ab9213a7 100644 --- a/rs/web-transport-quinn/src/client.rs +++ b/rs/web-transport-quinn/src/client.rs @@ -1,15 +1,13 @@ use std::net::{IpAddr, SocketAddr}; use std::sync::{Arc, Mutex}; +use crate::crypto::QuicClientConfig; use crate::proto::ConnectRequest; -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] -use quinn::crypto::rustls::QuicClientConfig; use rustls::{client::danger::ServerCertVerifier, pki_types::CertificateDer}; use tokio::net::lookup_host; use url::Host; use crate::crypto; -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] use crate::ALPN; use crate::{ClientError, Session}; @@ -25,12 +23,10 @@ pub enum CongestionControl { LowLatency, } -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] pub(crate) type ControllerFactory = Arc; /// Turn a [CongestionControl] choice into the factory quinn wants. -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] pub(crate) fn controller_factory(algorithm: CongestionControl) -> Option { match algorithm { CongestionControl::LowLatency => Some(Arc::new(quinn::congestion::BbrConfig::default())), @@ -42,7 +38,6 @@ pub(crate) fn controller_factory(algorithm: CongestionControl) -> Option, @@ -54,18 +49,16 @@ pub(crate) fn transport_config( Arc::new(transport) } -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] /// Construct a WebTransport [Client] using sane defaults. /// /// This is optional; advanced users may use [Client::new] directly. /// Build a client before cloning it to share its endpoints and configuration. pub struct ClientBuilder { - provider: crypto::Provider, + provider: Result, transport: quinn::TransportConfig, congestion_controller: Option, } -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] impl ClientBuilder { /// Create a Client builder, which can be used to establish multiple [Session]s. pub fn new() -> Self { @@ -113,7 +106,7 @@ impl ClientBuilder { } let crypto = self - .builder() + .builder()? .with_root_certificates(roots) .with_no_client_auth(); @@ -125,12 +118,12 @@ impl ClientBuilder { self, certs: Vec, ) -> Result { - let hashes = certs.iter().map({ - let provider = self.provider.clone(); - move |cert| crypto::sha256(&provider, cert).as_ref().to_vec() - }); + let provider = self.provider.clone()?; + let hashes = certs + .iter() + .map(move |cert| crypto::sha256(&provider, cert).map(|hash| hash.as_ref().to_vec())); - self.with_server_certificate_hashes(hashes.collect()) + self.with_server_certificate_hashes(hashes.collect::>()?) } /// Supply sha256 hashes for accepted certificates instead of using root CAs. @@ -140,13 +133,13 @@ impl ClientBuilder { ) -> Result { // Use a custom fingerprint verifier. let fingerprints = Arc::new(ServerFingerprints { - provider: self.provider.clone(), + provider: self.provider.clone()?, fingerprints: hashes, }); // Configure the crypto client. let crypto = self - .builder() + .builder()? .dangerous() .with_custom_certificate_verifier(fingerprints.clone()) .with_no_client_auth(); @@ -163,16 +156,20 @@ impl ClientBuilder { DangerousClientBuilder { inner: self } } - fn builder(&self) -> rustls::ConfigBuilder { - rustls::ClientConfig::builder_with_provider(self.provider.clone()) - .with_protocol_versions(&[&rustls::version::TLS13]) - .unwrap() + fn builder( + &self, + ) -> Result, ClientError> + { + Ok( + rustls::ClientConfig::builder_with_provider(self.provider.clone()?) + .with_protocol_versions(&[&rustls::version::TLS13])?, + ) } fn build(self, mut crypto: rustls::ClientConfig) -> Result { crypto.alpn_protocols = vec![ALPN.as_bytes().to_vec()]; - let client_config = QuicClientConfig::try_from(crypto).unwrap(); + let client_config = QuicClientConfig::try_from(crypto)?; let mut client_config = quinn::ClientConfig::new(Arc::new(client_config)); client_config.transport_config(transport_config( self.transport, @@ -183,14 +180,12 @@ impl ClientBuilder { } } -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] impl Default for ClientBuilder { fn default() -> Self { Self::new() } } -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] /// Builder for dangerous TLS configuration options. /// /// This builder provides access to potentially insecure TLS configurations. @@ -200,7 +195,6 @@ pub struct DangerousClientBuilder { inner: ClientBuilder, } -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] impl DangerousClientBuilder { /// Disable certificate verification entirely. /// @@ -210,11 +204,11 @@ impl DangerousClientBuilder { /// This method is safe in the Rust sense (no memory unsafety), but dangerous in the /// security sense, hence the explicit `dangerous()` builder requirement. pub fn with_no_certificate_verification(self) -> Result { - let noop = NoCertificateVerification(self.inner.provider.clone()); + let noop = NoCertificateVerification(self.inner.provider.clone()?); let crypto = self .inner - .builder() + .builder()? .dangerous() .with_custom_certificate_verifier(Arc::new(noop)) .with_no_client_auth(); @@ -324,7 +318,6 @@ impl Client { } } -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] impl From for Client { /// Create a client that lazily binds one socket for each server address family. /// @@ -353,7 +346,6 @@ struct ClientEndpoints { #[derive(Debug)] enum Binding { Custom(quinn::Endpoint), - #[cfg(any(feature = "aws-lc-rs", feature = "ring"))] Default { ipv4: Option, ipv6: Option, @@ -365,7 +357,6 @@ impl Binding { fn endpoints(&self) -> impl Iterator { match self { Self::Custom(endpoint) => [Some(endpoint), None], - #[cfg(any(feature = "aws-lc-rs", feature = "ring"))] Self::Default { ipv4, ipv6, .. } => [ipv4.as_ref(), ipv6.as_ref()], } .into_iter() @@ -387,7 +378,6 @@ impl ClientEndpoints { // cannot miss a newly created endpoint or an in-progress connection. let (endpoint, remote) = match &mut self.binding { Binding::Custom(endpoint) => (endpoint, remote), - #[cfg(any(feature = "aws-lc-rs", feature = "ring"))] Binding::Default { ipv4, ipv6, @@ -411,11 +401,7 @@ impl ClientEndpoints { "no async runtime found", ))) })?; - *slot = Some( - runtime - .bind(remote) - .map_err(|err| ClientError::IoError(Arc::new(err)))?, - ); + *slot = Some(runtime.bind(remote)?); } (slot.as_mut().unwrap(), remote) } @@ -424,14 +410,12 @@ impl ClientEndpoints { } } -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] #[derive(Debug)] struct ClientRuntime { inner: Arc, tokio: Option, } -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] impl ClientRuntime { fn current() -> Option { Some(Self { @@ -440,28 +424,27 @@ impl ClientRuntime { }) } - fn bind(&self, remote: SocketAddr) -> std::io::Result { + fn bind(&self, remote: SocketAddr) -> Result { // TokioRuntime registers sockets and spawns drivers in the current context. let _guard = self.tokio.as_ref().map(tokio::runtime::Handle::enter); bind_endpoint(remote, self.inner.clone()) } } -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] fn bind_endpoint( remote: SocketAddr, runtime: Arc, -) -> std::io::Result { +) -> Result { let bind: SocketAddr = if remote.is_ipv4() { (std::net::Ipv4Addr::UNSPECIFIED, 0).into() } else { (std::net::Ipv6Addr::UNSPECIFIED, 0).into() }; - let socket = bind_socket(bind)?; - quinn::Endpoint::new(quinn::EndpointConfig::default(), None, socket, runtime) + let io = |err| ClientError::IoError(Arc::new(err)); + let socket = bind_socket(bind).map_err(io)?; + quinn::Endpoint::new(crypto::endpoint_config()?, None, socket, runtime).map_err(io) } -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] fn bind_socket(bind: SocketAddr) -> std::io::Result { let socket = socket2::Socket::new( socket2::Domain::for_address(bind), @@ -475,14 +458,13 @@ fn bind_socket(bind: SocketAddr) -> std::io::Result { Ok(socket.into()) } -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] +/// Panics if system-root setup fails, including on a CPU rind does not support. impl Default for Client { fn default() -> Self { ClientBuilder::new().with_system_roots().unwrap() } } -#[cfg_attr(not(any(feature = "aws-lc-rs", feature = "ring")), allow(dead_code))] #[derive(Debug)] struct ServerFingerprints { provider: crypto::Provider, @@ -498,7 +480,7 @@ impl ServerCertVerifier for ServerFingerprints { _ocsp_response: &[u8], _now: rustls::pki_types::UnixTime, ) -> Result { - let cert_hash = crypto::sha256(&self.provider, end_entity); + let cert_hash = crypto::sha256(&self.provider, end_entity)?; if self .fingerprints .iter() @@ -595,5 +577,5 @@ impl rustls::client::danger::ServerCertVerifier for NoCertificateVerification { } } -#[cfg(all(test, any(feature = "aws-lc-rs", feature = "ring")))] +#[cfg(test)] pub(crate) mod tests; diff --git a/rs/web-transport-quinn/src/client/tests.rs b/rs/web-transport-quinn/src/client/tests.rs index 169c9e6c..e05d3135 100644 --- a/rs/web-transport-quinn/src/client/tests.rs +++ b/rs/web-transport-quinn/src/client/tests.rs @@ -4,17 +4,7 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::Duration; pub(crate) fn builder() -> ClientBuilder { - // Avoid a process-wide provider when both features are enabled. - #[cfg(feature = "aws-lc-rs")] - let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider()); - #[cfg(all(feature = "ring", not(feature = "aws-lc-rs")))] - let provider = Arc::new(rustls::crypto::ring::default_provider()); - - ClientBuilder { - provider, - transport: quinn::TransportConfig::default(), - congestion_controller: None, - } + ClientBuilder::new() } fn client() -> Client { @@ -236,7 +226,13 @@ fn missing_runtime_is_a_connect_error_and_allows_later_connections() { #[tokio::test] async fn caller_endpoint_keeps_its_address_and_remote_handling() { - let endpoint = backend::Endpoint::client("127.0.0.1:0".parse().unwrap()).unwrap(); + let endpoint = backend::Endpoint::new( + crypto::endpoint_config().unwrap(), + None, + std::net::UdpSocket::bind("127.0.0.1:0").unwrap(), + backend::default_runtime().unwrap(), + ) + .unwrap(); let addr = endpoint.local_addr().unwrap(); let client = Client::new(endpoint, client().config); let error = client diff --git a/rs/web-transport-quinn/src/crypto.rs b/rs/web-transport-quinn/src/crypto.rs index 224abc43..5e8b9336 100644 --- a/rs/web-transport-quinn/src/crypto.rs +++ b/rs/web-transport-quinn/src/crypto.rs @@ -1,65 +1,195 @@ -//! Simple crypto provider utilities for rustls. +//! Provider-neutral Quinn TLS over rustls, with rind for Retry and endpoint keys. //! -//! This module provides helper functions for working with rustls crypto providers, -//! supporting both ring and aws-lc-rs backends. +//! Use [`QuicClientConfig`] and [`QuicServerConfig`] in place of Quinn's +//! `crypto::rustls` types, [`endpoint_config`] with `quinn::Endpoint::new`, and +//! [`server_config`] in place of `quinn::ServerConfig::with_crypto`. use std::sync::Arc; use rustls::crypto::hash::{self, HashAlgorithm}; use rustls::crypto::CryptoProvider; use rustls::pki_types::CertificateDer; +use thiserror::Error; + +mod session; +pub use session::{HandshakeData, QuicClientConfig, QuicServerConfig}; +mod keys; +pub use keys::{ResetKey, TokenKey}; /// A shared reference to a crypto provider. pub type Provider = Arc; -/// Returns the default crypto provider. -/// -/// This function checks for a process-wide default provider first, -/// then falls back to feature-enabled providers (aws-lc-rs or ring). -/// -/// # Panics -/// -/// Panics if no provider is available. Either call `CryptoProvider::set_default()` -/// or enable exactly one of the `ring` or `aws-lc-rs` features. -pub fn default_provider() -> Provider { - // See - if let Some(provider) = CryptoProvider::get_default().cloned() { - return provider; - } +/// A CPU feature required by rind is unavailable. +#[derive(Clone, Debug, Error)] +#[error("unsupported CPU: {0}")] +pub struct UnsupportedCpu(pub(crate) String); - #[cfg(all(feature = "aws-lc-rs", not(feature = "ring")))] - { - return Arc::new(rustls::crypto::aws_lc_rs::default_provider()); - } - #[cfg(all(feature = "ring", not(feature = "aws-lc-rs")))] - { - return Arc::new(rustls::crypto::ring::default_provider()); +/// An error constructing QUIC cryptography. +#[derive(Clone, Debug, Error)] +#[non_exhaustive] +pub enum ConfigError { + /// A CPU feature required by rind is unavailable. + #[error(transparent)] + UnsupportedCpu(#[from] UnsupportedCpu), + /// The system random source failed. + #[error("system random source failed")] + Random, + /// The provider lacks the QUIC AES-128-GCM-SHA256 initial suite. + #[error("provider has no QUIC AES-128-GCM-SHA256 initial cipher suite")] + NoInitialCipherSuite, + /// The TLS configuration is invalid for QUIC. + #[error("invalid QUIC TLS configuration: {0}")] + Tls(#[from] rustls::Error), +} + +/// Checks CPU support before using rind, including with an installed TLS provider. +fn check_cpu() -> Result<(), UnsupportedCpu> { + #[cfg(test)] + if REFUSE_CPU.get() { + return Err(UnsupportedCpu("simulated missing CPU feature".into())); } - #[allow(unreachable_code)] - { - panic!( - "CryptoProvider::set_default() must be called; or only enable one ring/aws-lc-rs feature." - ); + rind::cpu::check().map_err(|e| UnsupportedCpu(e.to_string())) +} + +/// Returns the installed process provider, otherwise rind, after checking CPU support. +pub fn default_provider() -> Result { + check_cpu()?; + if let Some(provider) = CryptoProvider::get_default().cloned() { + return Ok(provider); } + rind_rustls::default_provider() + .map(Arc::new) + .map_err(|e| UnsupportedCpu(e.to_string())) +} + +/// Creates endpoint configuration with a fresh rind stateless-reset key. +pub fn endpoint_config() -> Result { + check_cpu()?; + let mut secret = [0; 64]; + rind::rand::fill(&mut secret).map_err(|_| ConfigError::Random)?; + Ok(quinn::EndpointConfig::new(Arc::new(ResetKey::new( + &secret, + )?))) +} + +/// Creates server configuration with a fresh rind handshake-token key. +pub fn server_config( + crypto: Arc, +) -> Result { + check_cpu()?; + let mut secret = [0; 64]; + rind::rand::fill(&mut secret).map_err(|_| ConfigError::Random)?; + Ok(quinn::ServerConfig::new( + crypto, + Arc::new(TokenKey::new(&secret)?), + )) } /// Computes the SHA-256 hash of a certificate using the provided crypto provider. -/// -/// # Panics -/// -/// Panics if the provider doesn't expose a SHA-256 hash algorithm. -pub fn sha256(provider: &Provider, cert: &CertificateDer<'_>) -> hash::Output { +pub fn sha256( + provider: &Provider, + cert: &CertificateDer<'_>, +) -> Result { let hash_provider = provider.cipher_suites.iter().find_map(|suite| { let hash_provider = suite.tls13()?.common.hash_provider; - if hash_provider.algorithm() == HashAlgorithm::SHA256 { - Some(hash_provider) - } else { - None - } + (hash_provider.algorithm() == HashAlgorithm::SHA256).then_some(hash_provider) }); - if let Some(hash_provider) = hash_provider { - return hash_provider.hash(cert); - } + Ok(hash_provider + .ok_or_else(|| rustls::Error::General("provider has no SHA-256 hash".into()))? + .hash(cert)) +} - panic!("No SHA-256 backend available. Ensure your provider exposes SHA-256 or enable the 'ring'/'aws-lc-rs' feature."); +#[cfg(test)] +thread_local! { + static REFUSE_CPU: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn installed_provider_and_cpu_refusal() { + // Isolate the process-wide provider from every other test in this binary. + const CHILD: &str = "WEB_TRANSPORT_QUINN_PROVIDER_TEST_CHILD"; + if std::env::var_os(CHILD).is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "crypto::tests::installed_provider_and_cpu_refusal", + ]) + .env(CHILD, "1") + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); + return; + } + rustls::crypto::aws_lc_rs::default_provider() + .install_default() + .expect("only this test installs a provider"); + let provider = CryptoProvider::get_default().unwrap().clone(); + assert!(Arc::ptr_eq(&default_provider().unwrap(), &provider)); + let mut roots = rustls::RootCertStore::empty(); + let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap(); + roots.add(cert.cert.der().clone()).unwrap(); + let client_tls = rustls::ClientConfig::builder_with_provider(provider.clone()) + .with_protocol_versions(&[&rustls::version::TLS13]) + .unwrap() + .with_root_certificates(roots) + .with_no_client_auth(); + let key = rustls::pki_types::PrivatePkcs8KeyDer::from(cert.signing_key.serialize_der()); + let server_tls = rustls::ServerConfig::builder_with_provider(provider) + .with_protocol_versions(&[&rustls::version::TLS13]) + .unwrap() + .with_no_client_auth() + .with_single_cert(vec![cert.cert.der().clone()], key.clone_key().into()) + .unwrap(); + let server = Arc::new(QuicServerConfig::try_from(server_tls.clone()).unwrap()); + struct Reset; + impl Drop for Reset { + fn drop(&mut self) { + REFUSE_CPU.set(false); + } + } + let _reset = Reset; + REFUSE_CPU.set(true); + assert!( + default_provider().is_err(), + "installed provider must not bypass rind's CPU check" + ); + assert!(endpoint_config().is_err()); + assert!(server_config(server).is_err()); + assert!(ResetKey::new(&[0; 64]).is_err()); + assert!(TokenKey::new(&[0; 64]).is_err()); + assert!(matches!( + QuicClientConfig::try_from(client_tls), + Err(ConfigError::UnsupportedCpu(_)) + )); + assert!(matches!( + QuicServerConfig::try_from(server_tls), + Err(ConfigError::UnsupportedCpu(_)) + )); + assert!(matches!( + crate::ClientBuilder::new().with_system_roots(), + Err(crate::ClientError::UnsupportedCpu(_)) + )); + assert!(matches!( + crate::ClientBuilder::new().with_server_certificates(vec![]), + Err(crate::ClientError::UnsupportedCpu(_)) + )); + assert!(matches!( + crate::ClientBuilder::new().with_server_certificate_hashes(vec![]), + Err(crate::ClientError::UnsupportedCpu(_)) + )); + assert!(matches!( + crate::ClientBuilder::new() + .dangerous() + .with_no_certificate_verification(), + Err(crate::ClientError::UnsupportedCpu(_)) + )); + assert!(matches!( + crate::ServerBuilder::new().with_certificate(vec![], key.into()), + Err(crate::ServerError::UnsupportedCpu(_)) + )); + } } diff --git a/rs/web-transport-quinn/src/crypto/LICENSE-MIT b/rs/web-transport-quinn/src/crypto/LICENSE-MIT new file mode 100644 index 00000000..f6561040 --- /dev/null +++ b/rs/web-transport-quinn/src/crypto/LICENSE-MIT @@ -0,0 +1,7 @@ +Copyright (c) 2018 The quinn Developers + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/rs/web-transport-quinn/src/crypto/keys.rs b/rs/web-transport-quinn/src/crypto/keys.rs new file mode 100644 index 00000000..fa32fe1f --- /dev/null +++ b/rs/web-transport-quinn/src/crypto/keys.rs @@ -0,0 +1,79 @@ +use quinn::crypto::{AeadKey, CryptoError, HandshakeTokenKey, HmacKey}; +use rind::{aead, hkdf, hmac}; + +use super::{check_cpu, UnsupportedCpu}; + +/// A rind HMAC-SHA256 key for Quinn stateless resets. +pub struct ResetKey(hmac::Key); + +impl ResetKey { + /// Uses a persistent secret to reproduce reset tokens across endpoint restarts. + pub fn new(secret: &[u8]) -> Result { + check_cpu()?; + Ok(Self(hmac::Key::new(&hmac::HMAC_SHA256, secret))) + } +} + +impl HmacKey for ResetKey { + fn sign(&self, data: &[u8], out: &mut [u8]) { + out.copy_from_slice(hmac::sign(&self.0, data).as_ref()); + } + + fn signature_len(&self) -> usize { + 32 + } + + fn verify(&self, data: &[u8], signature: &[u8]) -> Result<(), CryptoError> { + hmac::verify(&self.0, data, signature).map_err(|_| CryptoError) + } +} + +/// A rind HKDF-SHA256 key for Quinn Retry and validation tokens. +pub struct TokenKey(hkdf::Prk); + +impl TokenKey { + /// Derives a token key from a secret with at least 32 bytes of entropy. + pub fn new(secret: &[u8]) -> Result { + check_cpu()?; + Ok(Self( + hkdf::Salt::new(&hkdf::HKDF_SHA256, &[]).extract(secret), + )) + } +} + +impl HandshakeTokenKey for TokenKey { + fn aead_from_hkdf(&self, random_bytes: &[u8]) -> Box { + // Quinn supplies fresh random bytes per token, so each key seals only once. + Box::new(TokenAead(aead::Key::from( + self.0.expand(&[random_bytes], &aead::AES_256_GCM), + ))) + } +} + +struct TokenAead(aead::Key); + +impl AeadKey for TokenAead { + fn seal(&self, data: &mut Vec, additional_data: &[u8]) -> Result<(), CryptoError> { + self.0 + .seal_in_place_append_tag( + aead::Nonce::assume_unique_for_key([0; 12]), + additional_data, + data, + ) + .map_err(|_| CryptoError) + } + + fn open<'a>( + &self, + data: &'a mut [u8], + additional_data: &[u8], + ) -> Result<&'a mut [u8], CryptoError> { + self.0 + .open_in_place( + aead::Nonce::assume_unique_for_key([0; 12]), + additional_data, + data, + ) + .map_err(|_| CryptoError) + } +} diff --git a/rs/web-transport-quinn/src/crypto/session.rs b/rs/web-transport-quinn/src/crypto/session.rs new file mode 100644 index 00000000..89fc5436 --- /dev/null +++ b/rs/web-transport-quinn/src/crypto/session.rs @@ -0,0 +1,493 @@ +// Adapted from quinn-proto 0.11.19's crypto/rustls.rs. +// Copyright (c) 2018 The quinn Developers, licensed under MIT OR Apache-2.0. +// The upstream MIT license is included in LICENSE-MIT beside this file. + +use super::{check_cpu, ConfigError}; +use bytes::BytesMut; +use quinn_proto::{ + crypto::{ + self, CryptoError, ExportKeyingMaterialError, HeaderKey, KeyPair, Keys, UnsupportedVersion, + }, + transport_parameters::TransportParameters, + ConnectError, ConnectionId, Side, TransportError, TransportErrorCode, +}; +use rind::aead; +use rustls::{ + pki_types::{CertificateDer, ServerName}, + quic::{Connection, HeaderProtectionKey, KeyChange, PacketKey, Secrets, Suite, Version}, +}; +use std::{any::Any, io, sync::Arc}; + +fn rustls_side(side: Side) -> rustls::Side { + match side { + Side::Client => rustls::Side::Client, + Side::Server => rustls::Side::Server, + } +} + +/// A rustls TLS session +struct TlsSession { + version: Version, + got_handshake_data: bool, + next_secrets: Option, + inner: Connection, + suite: Suite, +} + +impl TlsSession { + fn side(&self) -> Side { + match self.inner { + Connection::Client(_) => Side::Client, + Connection::Server(_) => Side::Server, + } + } +} + +impl crypto::Session for TlsSession { + fn initial_keys(&self, dst_cid: &ConnectionId, side: Side) -> Keys { + initial_keys(self.version, *dst_cid, side, &self.suite) + } + + fn handshake_data(&self) -> Option> { + if !self.got_handshake_data { + return None; + } + Some(Box::new(HandshakeData { + protocol: self.inner.alpn_protocol().map(|x| x.into()), + server_name: match self.inner { + Connection::Client(_) => None, + Connection::Server(ref session) => session.server_name().map(|x| x.into()), + }, + })) + } + + /// For the rustls `TlsSession`, the `Any` type is `Vec` + fn peer_identity(&self) -> Option> { + self.inner.peer_certificates().map(|v| -> Box { + Box::new( + v.iter() + .map(|v| v.clone().into_owned()) + .collect::>>(), + ) + }) + } + + fn early_crypto(&self) -> Option<(Box, Box)> { + let keys = self.inner.zero_rtt_keys()?; + Some((Box::new(Header(keys.header)), Box::new(Packet(keys.packet)))) + } + + fn early_data_accepted(&self) -> Option { + match self.inner { + Connection::Client(ref session) => Some(session.is_early_data_accepted()), + _ => None, + } + } + + fn is_handshaking(&self) -> bool { + self.inner.is_handshaking() + } + + fn read_handshake(&mut self, buf: &[u8]) -> Result { + self.inner.read_hs(buf).map_err(|e| { + if let Some(alert) = self.inner.alert() { + TransportError { + code: TransportErrorCode::crypto(alert.into()), + frame: None, + reason: e.to_string(), + } + } else { + TransportError { + code: TransportErrorCode::PROTOCOL_VIOLATION, + frame: None, + reason: format!("TLS error: {e}"), + } + } + })?; + if !self.got_handshake_data { + // Hack around the lack of an explicit signal from rustls to reflect ClientHello being + // ready on incoming connections, or ALPN negotiation completing on outgoing + // connections. + let have_server_name = match self.inner { + Connection::Client(_) => false, + Connection::Server(ref session) => session.server_name().is_some(), + }; + if self.inner.alpn_protocol().is_some() || have_server_name || !self.is_handshaking() { + self.got_handshake_data = true; + return Ok(true); + } + } + Ok(false) + } + + fn transport_parameters(&self) -> Result, TransportError> { + match self.inner.quic_transport_parameters() { + None => Ok(None), + Some(buf) => match TransportParameters::read(self.side(), &mut io::Cursor::new(buf)) { + Ok(params) => Ok(Some(params)), + Err(e) => Err(e.into()), + }, + } + } + + fn write_handshake(&mut self, buf: &mut Vec) -> Option { + let keys = match self.inner.write_hs(buf)? { + KeyChange::Handshake { keys } => keys, + KeyChange::OneRtt { keys, next } => { + self.next_secrets = Some(next); + keys + } + }; + + Some(Keys { + header: KeyPair { + local: Box::new(Header(keys.local.header)), + remote: Box::new(Header(keys.remote.header)), + }, + packet: KeyPair { + local: Box::new(Packet(keys.local.packet)), + remote: Box::new(Packet(keys.remote.packet)), + }, + }) + } + + fn next_1rtt_keys(&mut self) -> Option>> { + let secrets = self.next_secrets.as_mut()?; + let keys = secrets.next_packet_keys(); + Some(KeyPair { + local: Box::new(Packet(keys.local)), + remote: Box::new(Packet(keys.remote)), + }) + } + + fn is_valid_retry(&self, orig_dst_cid: &ConnectionId, header: &[u8], payload: &[u8]) -> bool { + let tag_start = match payload.len().checked_sub(16) { + Some(x) => x, + None => return false, + }; + + let mut pseudo_packet = + Vec::with_capacity(header.len() + payload.len() + orig_dst_cid.len() + 1); + pseudo_packet.push(orig_dst_cid.len() as u8); + pseudo_packet.extend_from_slice(orig_dst_cid); + pseudo_packet.extend_from_slice(header); + let tag_start = tag_start + pseudo_packet.len(); + pseudo_packet.extend_from_slice(payload); + + let (nonce, key) = match self.version { + Version::V1 => (RETRY_INTEGRITY_NONCE_V1, RETRY_INTEGRITY_KEY_V1), + Version::V1Draft => (RETRY_INTEGRITY_NONCE_DRAFT, RETRY_INTEGRITY_KEY_DRAFT), + _ => unreachable!(), + }; + + let nonce = aead::Nonce::assume_unique_for_key(nonce); + let key = aead::Key::new(&aead::AES_128_GCM, &key).unwrap(); + + let (aad, tag) = pseudo_packet.split_at_mut(tag_start); + key.open_in_place(nonce, aad, tag).is_ok() + } + + fn export_keying_material( + &self, + output: &mut [u8], + label: &[u8], + context: &[u8], + ) -> Result<(), ExportKeyingMaterialError> { + self.inner + .export_keying_material(output, label, Some(context)) + .map_err(|_| ExportKeyingMaterialError)?; + Ok(()) + } +} + +const RETRY_INTEGRITY_KEY_DRAFT: [u8; 16] = [ + 0xcc, 0xce, 0x18, 0x7e, 0xd0, 0x9a, 0x09, 0xd0, 0x57, 0x28, 0x15, 0x5a, 0x6c, 0xb9, 0x6b, 0xe1, +]; +const RETRY_INTEGRITY_NONCE_DRAFT: [u8; 12] = [ + 0xe5, 0x49, 0x30, 0xf9, 0x7f, 0x21, 0x36, 0xf0, 0x53, 0x0a, 0x8c, 0x1c, +]; + +const RETRY_INTEGRITY_KEY_V1: [u8; 16] = [ + 0xbe, 0x0c, 0x69, 0x0b, 0x9f, 0x66, 0x57, 0x5a, 0x1d, 0x76, 0x6b, 0x54, 0xe3, 0x68, 0xc8, 0x4e, +]; +const RETRY_INTEGRITY_NONCE_V1: [u8; 12] = [ + 0x46, 0x15, 0x99, 0xd3, 0x5d, 0x63, 0x2b, 0xf2, 0x23, 0x98, 0x25, 0xbb, +]; + +struct Header(Box); + +impl crypto::HeaderKey for Header { + fn decrypt(&self, pn_offset: usize, packet: &mut [u8]) { + let (header, sample) = packet.split_at_mut(pn_offset + 4); + let (first, rest) = header.split_at_mut(1); + let pn_end = Ord::min(pn_offset + 3, rest.len()); + self.0 + .decrypt_in_place( + &sample[..self.sample_size()], + &mut first[0], + &mut rest[pn_offset - 1..pn_end], + ) + .unwrap(); + } + + fn encrypt(&self, pn_offset: usize, packet: &mut [u8]) { + let (header, sample) = packet.split_at_mut(pn_offset + 4); + let (first, rest) = header.split_at_mut(1); + let pn_end = Ord::min(pn_offset + 3, rest.len()); + self.0 + .encrypt_in_place( + &sample[..self.sample_size()], + &mut first[0], + &mut rest[pn_offset - 1..pn_end], + ) + .unwrap(); + } + + fn sample_size(&self) -> usize { + self.0.sample_len() + } +} + +/// Authentication data for (rustls) TLS session +pub struct HandshakeData { + /// The negotiated application protocol, if ALPN is in use + /// + /// Guaranteed to be set if a nonempty list of protocols was specified for this connection. + pub protocol: Option>, + /// The server name specified by the client, if any + /// + /// Always `None` for outgoing connections + pub server_name: Option, +} + +/// A provider-neutral rustls client configuration for Quinn. +/// +/// TLS 1.3 and the QUIC AES-128-GCM-SHA256 initial suite are required. +/// Set `enable_early_data` on the rustls config to allow 0-RTT. +pub struct QuicClientConfig { + inner: Arc, + initial: Suite, +} + +impl crypto::ClientConfig for QuicClientConfig { + fn start_session( + self: Arc, + version: u32, + server_name: &str, + params: &TransportParameters, + ) -> Result, ConnectError> { + let version = interpret_version(version)?; + Ok(Box::new(TlsSession { + version, + got_handshake_data: false, + next_secrets: None, + inner: rustls::quic::Connection::Client( + rustls::quic::ClientConnection::new( + self.inner.clone(), + version, + ServerName::try_from(server_name) + .map_err(|_| ConnectError::InvalidServerName(server_name.into()))? + .to_owned(), + to_vec(params), + ) + .expect("validated QUIC client configuration and working random source"), + ), + suite: self.initial, + })) + } +} + +impl TryFrom for QuicClientConfig { + type Error = ConfigError; + + fn try_from(inner: rustls::ClientConfig) -> Result { + Arc::new(inner).try_into() + } +} + +impl TryFrom> for QuicClientConfig { + type Error = ConfigError; + + fn try_from(inner: Arc) -> Result { + check_cpu()?; + // Validation must not take a single-use ticket from the caller's session cache. + let mut validation = (*inner).clone(); + validation.resumption = rustls::client::Resumption::disabled(); + rustls::quic::ClientConnection::new( + Arc::new(validation), + Version::V1, + ServerName::try_from("localhost").unwrap(), + Vec::new(), + )?; + Ok(Self { + initial: initial_suite_from_provider(inner.crypto_provider()) + .ok_or(ConfigError::NoInitialCipherSuite)?, + inner, + }) + } +} + +/// A provider-neutral rustls server configuration for Quinn. +/// +/// TLS 1.3 and the QUIC AES-128-GCM-SHA256 initial suite are required. +/// `max_early_data_size` must be zero (reject 0-RTT) or `u32::MAX` (accept it). +pub struct QuicServerConfig { + inner: Arc, + initial: Suite, +} + +impl TryFrom for QuicServerConfig { + type Error = ConfigError; + + fn try_from(inner: rustls::ServerConfig) -> Result { + Arc::new(inner).try_into() + } +} + +impl TryFrom> for QuicServerConfig { + type Error = ConfigError; + + fn try_from(inner: Arc) -> Result { + check_cpu()?; + rustls::quic::ServerConnection::new(inner.clone(), Version::V1, Vec::new())?; + Ok(Self { + initial: initial_suite_from_provider(inner.crypto_provider()) + .ok_or(ConfigError::NoInitialCipherSuite)?, + inner, + }) + } +} + +impl crypto::ServerConfig for QuicServerConfig { + fn start_session( + self: Arc, + version: u32, + params: &TransportParameters, + ) -> Box { + // Safe: `start_session()` is never called if `initial_keys()` rejected `version` + let version = interpret_version(version).unwrap(); + Box::new(TlsSession { + version, + got_handshake_data: false, + next_secrets: None, + inner: rustls::quic::Connection::Server( + rustls::quic::ServerConnection::new(self.inner.clone(), version, to_vec(params)) + .unwrap(), + ), + suite: self.initial, + }) + } + + fn initial_keys( + &self, + version: u32, + dst_cid: &ConnectionId, + ) -> Result { + let version = interpret_version(version)?; + Ok(initial_keys(version, *dst_cid, Side::Server, &self.initial)) + } + + fn retry_tag(&self, version: u32, orig_dst_cid: &ConnectionId, packet: &[u8]) -> [u8; 16] { + // Safe: `start_session()` is never called if `initial_keys()` rejected `version` + let version = interpret_version(version).unwrap(); + let (nonce, key) = match version { + Version::V1 => (RETRY_INTEGRITY_NONCE_V1, RETRY_INTEGRITY_KEY_V1), + Version::V1Draft => (RETRY_INTEGRITY_NONCE_DRAFT, RETRY_INTEGRITY_KEY_DRAFT), + _ => unreachable!(), + }; + + let mut pseudo_packet = Vec::with_capacity(packet.len() + orig_dst_cid.len() + 1); + pseudo_packet.push(orig_dst_cid.len() as u8); + pseudo_packet.extend_from_slice(orig_dst_cid); + pseudo_packet.extend_from_slice(packet); + + let nonce = aead::Nonce::assume_unique_for_key(nonce); + let key = aead::Key::new(&aead::AES_128_GCM, &key).unwrap(); + + let tag = key + .seal_in_place_separate_tag(nonce, &pseudo_packet, &mut []) + .unwrap(); + let mut result = [0; 16]; + result.copy_from_slice(tag.as_ref()); + result + } +} + +fn initial_suite_from_provider(provider: &Arc) -> Option { + provider + .cipher_suites + .iter() + .find_map(|cs| match (cs.suite(), cs.tls13()) { + (rustls::CipherSuite::TLS13_AES_128_GCM_SHA256, Some(suite)) => { + Some(suite.quic_suite()) + } + _ => None, + }) + .flatten() +} + +fn to_vec(params: &TransportParameters) -> Vec { + let mut bytes = Vec::new(); + params.write(&mut bytes); + bytes +} + +fn initial_keys(version: Version, dst_cid: ConnectionId, side: Side, suite: &Suite) -> Keys { + let keys = suite.keys(&dst_cid, rustls_side(side), version); + Keys { + header: KeyPair { + local: Box::new(Header(keys.local.header)), + remote: Box::new(Header(keys.remote.header)), + }, + packet: KeyPair { + local: Box::new(Packet(keys.local.packet)), + remote: Box::new(Packet(keys.remote.packet)), + }, + } +} + +struct Packet(Box); + +impl crypto::PacketKey for Packet { + fn encrypt(&self, packet: u64, buf: &mut [u8], header_len: usize) { + let (header, payload_tag) = buf.split_at_mut(header_len); + let (payload, tag_storage) = payload_tag.split_at_mut(payload_tag.len() - self.tag_len()); + let tag = self.0.encrypt_in_place(packet, &*header, payload).unwrap(); + tag_storage.copy_from_slice(tag.as_ref()); + } + + fn decrypt( + &self, + packet: u64, + header: &[u8], + payload: &mut BytesMut, + ) -> Result<(), CryptoError> { + let plain = self + .0 + .decrypt_in_place(packet, header, payload.as_mut()) + .map_err(|_| CryptoError)?; + let plain_len = plain.len(); + payload.truncate(plain_len); + Ok(()) + } + + fn tag_len(&self) -> usize { + self.0.tag_len() + } + + fn confidentiality_limit(&self) -> u64 { + self.0.confidentiality_limit() + } + + fn integrity_limit(&self) -> u64 { + self.0.integrity_limit() + } +} + +fn interpret_version(version: u32) -> Result { + match version { + 0xff00_001d..=0xff00_0020 => Ok(Version::V1Draft), + 0x0000_0001 | 0xff00_0021..=0xff00_0022 => Ok(Version::V1), + _ => Err(UnsupportedVersion), + } +} diff --git a/rs/web-transport-quinn/src/error.rs b/rs/web-transport-quinn/src/error.rs index a1175948..39698582 100644 --- a/rs/web-transport-quinn/src/error.rs +++ b/rs/web-transport-quinn/src/error.rs @@ -7,9 +7,18 @@ use crate::{ConnectError, SettingsError}; /// An error returned when connecting to a WebTransport endpoint. #[derive(Error, Debug, Clone)] pub enum ClientError { + /// Creating or binding a client endpoint failed. #[error("failed to bind client endpoint: {0}")] IoError(Arc), + /// A CPU feature required by rind is unavailable. + #[error(transparent)] + UnsupportedCpu(#[from] crate::crypto::UnsupportedCpu), + + /// Constructing QUIC cryptography failed. + #[error(transparent)] + Crypto(#[from] crate::crypto::ConfigError), + #[error("unexpected end of stream")] UnexpectedEnd, @@ -34,7 +43,6 @@ pub enum ClientError { #[error("invalid DNS name: {0}")] InvalidDnsName(String), - #[cfg(any(feature = "aws-lc-rs", feature = "ring"))] #[error("rustls error: {0}")] Rustls(#[from] rustls::Error), } @@ -293,6 +301,14 @@ impl From for ClosedStream { /// An error returned when receiving a new WebTransport session. #[derive(Error, Debug, Clone)] pub enum ServerError { + /// A CPU feature required by rind is unavailable. + #[error(transparent)] + UnsupportedCpu(#[from] crate::crypto::UnsupportedCpu), + + /// Constructing QUIC cryptography failed. + #[error(transparent)] + Crypto(#[from] crate::crypto::ConfigError), + #[error("unexpected end of stream")] UnexpectedEnd, @@ -314,7 +330,6 @@ pub enum ServerError { #[error("io error: {0}")] IoError(Arc), - #[cfg(any(feature = "aws-lc-rs", feature = "ring"))] #[error("rustls error: {0}")] Rustls(#[from] rustls::Error), } diff --git a/rs/web-transport-quinn/src/server.rs b/rs/web-transport-quinn/src/server.rs index d766aa4c..b5953745 100644 --- a/rs/web-transport-quinn/src/server.rs +++ b/rs/web-transport-quinn/src/server.rs @@ -1,4 +1,3 @@ -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] use std::sync::Arc; use std::task::Poll; @@ -7,37 +6,31 @@ use futures::{ stream::FuturesUnordered, StreamExt, }; -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] use rustls::pki_types::{CertificateDer, PrivateKeyDer}; -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] use crate::client::{controller_factory, transport_config, ControllerFactory}; -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] use crate::{crypto, CongestionControl}; use crate::{ proto::{ConnectRequest, ConnectResponse}, Connecting, ServerError, Session, Settings, }; -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] /// Construct a WebTransport [Server] using sane defaults. /// /// This is optional; advanced users may use [Server::new] directly. pub struct ServerBuilder { - provider: crypto::Provider, + provider: Result, addr: std::net::SocketAddr, transport: quinn::TransportConfig, congestion_controller: Option, } -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] impl Default for ServerBuilder { fn default() -> Self { Self::new() } } -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] impl ServerBuilder { /// Create a server builder with sane defaults. pub fn new() -> Self { @@ -82,8 +75,15 @@ impl ServerBuilder { let addr = self.addr; let config = self.config(chain, key)?; - let server = - quinn::Endpoint::server(config, addr).map_err(|e| ServerError::IoError(e.into()))?; + let server = quinn::Endpoint::new( + crypto::endpoint_config()?, + Some(config), + std::net::UdpSocket::bind(addr).map_err(|e| ServerError::IoError(e.into()))?, + quinn::default_runtime().ok_or_else(|| { + ServerError::IoError(std::io::Error::other("no async runtime found").into()) + })?, + ) + .map_err(|e| ServerError::IoError(e.into()))?; Ok(Server::new(server)) } @@ -94,15 +94,15 @@ impl ServerBuilder { key: PrivateKeyDer<'static>, ) -> Result { // Standard Quinn setup - let mut config = rustls::ServerConfig::builder_with_provider(self.provider.clone()) + let mut config = rustls::ServerConfig::builder_with_provider(self.provider.clone()?) .with_protocol_versions(&[&rustls::version::TLS13])? .with_no_client_auth() .with_single_cert(chain, key)?; config.alpn_protocols = vec![crate::ALPN.as_bytes().to_vec()]; // this one is important - let config: quinn::crypto::rustls::QuicServerConfig = config.try_into().unwrap(); - let mut config = quinn::ServerConfig::with_crypto(Arc::new(config)); + let config: crate::crypto::QuicServerConfig = config.try_into()?; + let mut config = crypto::server_config(Arc::new(config))?; config.transport_config(transport_config( self.transport, self.congestion_controller.as_ref(), @@ -252,7 +252,7 @@ impl core::ops::Deref for Request { } } -#[cfg(all(test, any(feature = "aws-lc-rs", feature = "ring")))] +#[cfg(test)] pub(crate) mod tests { use super::*; use crate::client::tests::{assert_transport, custom_transport}; @@ -266,21 +266,8 @@ pub(crate) mod tests { (chain, PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(der))) } - /// `ServerBuilder::new` goes through [crypto::default_provider], which panics when - /// both backends are compiled in and no process-wide default is installed. Pick one - /// here rather than mutating global state from a test. pub(crate) fn builder() -> ServerBuilder { - #[cfg(feature = "aws-lc-rs")] - let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider()); - #[cfg(all(feature = "ring", not(feature = "aws-lc-rs")))] - let provider = Arc::new(rustls::crypto::ring::default_provider()); - - ServerBuilder { - provider, - addr: "[::]:0".parse().unwrap(), - transport: quinn::TransportConfig::default(), - congestion_controller: None, - } + ServerBuilder::new().with_addr("[::]:0".parse().unwrap()) } /// quinn installs its own default transport config, so the builder's has to be diff --git a/rs/web-transport-quinn/src/session.rs b/rs/web-transport-quinn/src/session.rs index c8cdb4aa..5075056b 100644 --- a/rs/web-transport-quinn/src/session.rs +++ b/rs/web-transport-quinn/src/session.rs @@ -25,29 +25,13 @@ use crate::{ /// /// Quinn only exposes the ALPN via a downcast of the boxed handshake data, so the result /// is owned rather than borrowed from the connection. -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] fn negotiated_alpn(conn: &quinn::Connection) -> Option { let data = conn.handshake_data()?; - let data = data - .downcast::() - .ok()?; + let data = data.downcast::().ok()?; String::from_utf8(data.protocol?).ok() } -/// `quinn::crypto::rustls` only exists once a TLS backend is enabled, so there is no -/// handshake data type to name here. -/// -/// This crate's own builders are gated the same way, so normally there is no connection -/// to read an ALPN from either. A caller that enables a provider on `quinn` directly and -/// brings its own endpoint can still establish one, and [`Session::protocol`] reports -/// `None` for those raw sessions. Enable this crate's `aws-lc-rs` or `ring` feature to -/// get the ALPN. -#[cfg(not(any(feature = "aws-lc-rs", feature = "ring")))] -fn negotiated_alpn(_conn: &quinn::Connection) -> Option { - None -} - /// An established WebTransport session, acting like a full QUIC connection. See [`quinn::Connection`]. /// /// It is important to remember that WebTransport is layered on top of QUIC: @@ -1326,7 +1310,7 @@ impl web_transport_trait::poll::Session for Session { } } -#[cfg(all(test, any(feature = "aws-lc-rs", feature = "ring")))] +#[cfg(test)] mod tests { use std::{net::Ipv4Addr, sync::Arc}; @@ -1346,26 +1330,49 @@ mod tests { async fn pair_with( transport: quinn::TransportConfig, ) -> (quinn::Connection, quinn::Connection, [quinn::Endpoint; 2]) { - #[cfg(all(feature = "aws-lc-rs", feature = "ring"))] - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); - let CertifiedKey { cert, signing_key } = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap(); let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(KeyPair::serialize_der( &signing_key, ))); - let server_config = - quinn::ServerConfig::with_single_cert(vec![cert.der().clone()], key).unwrap(); - let server = - quinn::Endpoint::server(server_config, (Ipv4Addr::LOCALHOST, 0).into()).unwrap(); + let provider = crate::crypto::default_provider().unwrap(); + let server_tls = rustls::ServerConfig::builder_with_provider(provider.clone()) + .with_protocol_versions(&[&rustls::version::TLS13]) + .unwrap() + .with_no_client_auth() + .with_single_cert(vec![cert.der().clone()], key) + .unwrap(); + let server_config = crate::crypto::server_config(Arc::new( + crate::crypto::QuicServerConfig::try_from(server_tls).unwrap(), + )) + .unwrap(); + let server = quinn::Endpoint::new( + crate::crypto::endpoint_config().unwrap(), + Some(server_config), + std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).unwrap(), + quinn::default_runtime().unwrap(), + ) + .unwrap(); let mut roots = rustls::RootCertStore::empty(); roots.add(cert.der().clone()).unwrap(); - let mut client_config = - quinn::ClientConfig::with_root_certificates(Arc::new(roots)).unwrap(); + let client_tls = rustls::ClientConfig::builder_with_provider(provider) + .with_protocol_versions(&[&rustls::version::TLS13]) + .unwrap() + .with_root_certificates(roots) + .with_no_client_auth(); + let mut client_config = quinn::ClientConfig::new(Arc::new( + crate::crypto::QuicClientConfig::try_from(client_tls).unwrap(), + )); client_config.transport_config(Arc::new(transport)); - let client = quinn::Endpoint::client((Ipv4Addr::LOCALHOST, 0).into()).unwrap(); + let client = quinn::Endpoint::new( + crate::crypto::endpoint_config().unwrap(), + None, + std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).unwrap(), + quinn::default_runtime().unwrap(), + ) + .unwrap(); let connecting = client .connect_with(client_config, server.local_addr().unwrap(), "localhost") diff --git a/rs/web-transport-quinn/tests/accept_wakers.rs b/rs/web-transport-quinn/tests/accept_wakers.rs index f4f65604..37bf5fa3 100644 --- a/rs/web-transport-quinn/tests/accept_wakers.rs +++ b/rs/web-transport-quinn/tests/accept_wakers.rs @@ -25,9 +25,9 @@ use std::{ use anyhow::{Context as _, Result}; use rcgen::{CertifiedKey, KeyPair}; +use rustls::pki_types::{PrivateKeyDer, PrivatePkcs8KeyDer}; use tokio::time::timeout; use web_transport_proto::ConnectRequest; -use web_transport_quinn::quinn::rustls::pki_types::{PrivateKeyDer, PrivatePkcs8KeyDer}; use web_transport_quinn::{ClientBuilder, ServerBuilder}; /// How many accepters give up, one after another. Well past any plausible bound on @@ -57,20 +57,8 @@ impl Wake for FlagWaker { } } -/// With both crypto features enabled — as `--all-features` does — the crate cannot -/// pick a provider for us, so the test installs one. -fn install_crypto_provider() { - #[cfg(all(feature = "aws-lc-rs", feature = "ring"))] - { - let _ = web_transport_quinn::quinn::rustls::crypto::aws_lc_rs::default_provider() - .install_default(); - } -} - /// A client and server session, already connected. async fn pair() -> Result<(web_transport_quinn::Session, web_transport_quinn::Session)> { - install_crypto_provider(); - let CertifiedKey { cert, signing_key } = rcgen::generate_simple_self_signed(vec!["localhost".into(), "127.0.0.1".into()])?; let chain = vec![cert.der().clone()]; diff --git a/rs/web-transport-quinn/tests/crypto.rs b/rs/web-transport-quinn/tests/crypto.rs new file mode 100644 index 00000000..4c93db81 --- /dev/null +++ b/rs/web-transport-quinn/tests/crypto.rs @@ -0,0 +1,407 @@ +//! Exercise the adapter against Quinn's unmodified aws-lc-rs adapter without sockets or sleeps. + +use bytes::{Bytes, BytesMut}; +use quinn_proto::{ + Connection, ConnectionHandle, DatagramEvent, Endpoint, EndpointConfig, Event, Side, +}; +use rustls::pki_types::PrivatePkcs8KeyDer; +use std::{ + collections::HashMap, + net::SocketAddr, + sync::Arc, + time::{Duration, Instant}, +}; +use web_transport_quinn::crypto; + +struct Peer { + endpoint: Endpoint, + config: Arc, + connections: HashMap, + addr: SocketAddr, + retry: bool, + retries: usize, +} + +impl Peer { + fn new(server: Option>, port: u16, ours: bool) -> Self { + let mut config = if ours { + crypto::endpoint_config().unwrap() + } else { + EndpointConfig::default() + }; + config.cid_generator(|| Box::new(quinn_proto::HashedConnectionIdGenerator::from_key(0))); + let config = Arc::new(config); + Self { + endpoint: Endpoint::new(config.clone(), server, true, None), + config, + connections: HashMap::new(), + addr: ([127, 0, 0, 1], port).into(), + retry: true, + retries: 0, + } + } + + fn receive(&mut self, now: Instant, from: SocketAddr, packet: BytesMut) -> Vec { + let mut out = Vec::new(); + let mut buf = Vec::new(); + match self + .endpoint + .handle(now, from, None, None, packet, &mut buf) + { + Some(DatagramEvent::NewConnection(incoming)) => { + if self.retry && !incoming.remote_address_validated() { + self.retries += 1; + let tx = self.endpoint.retry(incoming, &mut buf).unwrap(); + out.push(BytesMut::from(&buf[..tx.size])); + } else { + let (handle, connection) = + self.endpoint.accept(incoming, now, &mut buf, None).unwrap(); + self.connections.insert(handle, connection); + } + } + Some(DatagramEvent::ConnectionEvent(handle, event)) => self + .connections + .get_mut(&handle) + .unwrap() + .handle_event(event), + Some(DatagramEvent::Response(tx)) => out.push(BytesMut::from(&buf[..tx.size])), + None => {} + } + out + } + + fn transmit(&mut self, now: Instant) -> Vec { + let mut out = Vec::new(); + let mut events = Vec::new(); + for (&handle, conn) in &mut self.connections { + if conn.poll_timeout().is_some_and(|t| t <= now) { + conn.handle_timeout(now); + } + let mut buf = Vec::new(); + while let Some(tx) = conn.poll_transmit(now, 1, &mut buf) { + assert!(tx.segment_size.is_none()); + out.push(BytesMut::from(&buf[..tx.size])); + buf.clear(); + } + while let Some(event) = conn.poll_endpoint_events() { + events.push((handle, event)); + } + } + for (handle, event) in events { + if let Some(event) = self.endpoint.handle_event(handle, event) { + self.connections + .get_mut(&handle) + .unwrap() + .handle_event(event); + } + } + out + } + + fn conn(&mut self) -> &mut Connection { + self.connections.values_mut().next().unwrap() + } +} + +struct Pair { + client: Peer, + server: Peer, + now: Instant, +} + +impl Pair { + fn drive(&mut self) { + let end = self.now + Duration::from_secs(1); + let mut pending_server = Vec::new(); + for _ in 0..10_000 { + let mut to_server = std::mem::take(&mut pending_server); + to_server.extend(self.client.transmit(self.now)); + let mut to_client = self.server.transmit(self.now); + let traffic = !to_server.is_empty() || !to_client.is_empty(); + for packet in to_server.drain(..) { + to_client.extend(self.server.receive(self.now, self.client.addr, packet)); + } + for packet in to_client { + pending_server.extend(self.client.receive(self.now, self.server.addr, packet)); + } + if traffic || !pending_server.is_empty() { + continue; + } + let deadline = self + .client + .connections + .values_mut() + .chain(self.server.connections.values_mut()) + .filter_map(Connection::poll_timeout) + .min(); + let Some(deadline) = deadline.filter(|t| *t <= end) else { + self.now = end; + return; + }; + self.now = deadline; + } + panic!("protocol failed to quiesce"); + } + + fn connect(&mut self, config: quinn::ClientConfig) { + let (handle, conn) = self + .client + .endpoint + .connect(self.now, config, self.server.addr, "localhost") + .unwrap(); + self.client.connections.insert(handle, conn); + } + + fn connected(&mut self) { + for peer in [&mut self.client, &mut self.server] { + assert!(matches!( + peer.conn().poll(), + Some(Event::HandshakeDataReady) + )); + assert!(matches!(peer.conn().poll(), Some(Event::Connected))); + } + } + + fn traffic(&mut self, side: Side, message: &'static [u8]) { + let sender = match side { + Side::Client => &mut self.client, + Side::Server => &mut self.server, + }; + sender + .conn() + .datagrams() + .send(Bytes::from_static(message), false) + .unwrap(); + self.drive(); + let receiver = match side { + Side::Client => &mut self.server, + Side::Server => &mut self.client, + }; + assert_eq!(receiver.conn().datagrams().recv().unwrap(), message); + } +} + +fn configs( + ours_server: bool, + suite: rustls::CipherSuite, +) -> (rustls::ClientConfig, quinn::ServerConfig) { + let certified = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap(); + let key = PrivatePkcs8KeyDer::from(certified.signing_key.serialize_der()).into(); + let mut ours = rind_rustls::default_provider().unwrap(); + let mut upstream = rustls::crypto::aws_lc_rs::default_provider(); + for provider in [&mut ours, &mut upstream] { + provider.cipher_suites.sort_by_key(|s| s.suite() != suite); + } + let ours = Arc::new(ours); + let upstream = Arc::new(upstream); + let (client_provider, server_provider) = if ours_server { + (upstream, ours) + } else { + (ours, upstream) + }; + let mut tls = rustls::ServerConfig::builder_with_provider(server_provider) + .with_protocol_versions(&[&rustls::version::TLS13]) + .unwrap() + .with_no_client_auth() + .with_single_cert(vec![certified.cert.der().clone()], key) + .unwrap(); + tls.alpn_protocols = vec![b"a".to_vec(), b"b".to_vec()]; + tls.max_early_data_size = u32::MAX; + tls.send_tls13_tickets = 1; + let server = if ours_server { + crypto::server_config(Arc::new(crypto::QuicServerConfig::try_from(tls).unwrap())).unwrap() + } else { + quinn::ServerConfig::with_crypto(Arc::new( + quinn::crypto::rustls::QuicServerConfig::try_from(tls).unwrap(), + )) + }; + let mut roots = rustls::RootCertStore::empty(); + roots.add(certified.cert.der().clone()).unwrap(); + let mut client = rustls::ClientConfig::builder_with_provider(client_provider) + .with_protocol_versions(&[&rustls::version::TLS13]) + .unwrap() + .with_root_certificates(roots) + .with_no_client_auth(); + client.alpn_protocols = vec![b"a".to_vec()]; + client.enable_early_data = true; + (client, server) +} + +fn client_crypto(tls: rustls::ClientConfig, ours: bool) -> Arc { + if ours { + Arc::new(crypto::QuicClientConfig::try_from(tls).unwrap()) + } else { + Arc::new(quinn::crypto::rustls::QuicClientConfig::try_from(tls).unwrap()) + } +} + +fn client_config(tls: rustls::ClientConfig, ours: bool) -> quinn::ClientConfig { + quinn::ClientConfig::new(client_crypto(tls, ours)) +} + +#[test] +fn upstream_handshake_retry_key_update_and_reset() { + for suite in [ + rustls::CipherSuite::TLS13_AES_128_GCM_SHA256, + rustls::CipherSuite::TLS13_AES_256_GCM_SHA384, + rustls::CipherSuite::TLS13_CHACHA20_POLY1305_SHA256, + ] { + for ours_server in [false, true] { + let (tls, server) = configs(ours_server, suite); + let mut pair = Pair { + client: Peer::new(None, 4434, !ours_server), + server: Peer::new(Some(Arc::new(server)), 4433, ours_server), + now: Instant::now(), + }; + pair.connect(client_config(tls, !ours_server)); + pair.drive(); + pair.connected(); + assert!(pair.server.retries > 0); + assert!(!pair.client.conn().is_handshaking()); + assert!(!pair.server.conn().is_handshaking()); + let mut client_export = [0; 32]; + let mut server_export = [0; 32]; + pair.client + .conn() + .crypto_session() + .export_keying_material(&mut client_export, b"test", b"context") + .unwrap(); + pair.server + .conn() + .crypto_session() + .export_keying_material(&mut server_export, b"test", b"context") + .unwrap(); + assert_eq!(client_export, server_export); + for side in [Side::Client, Side::Server] { + pair.traffic(side, b"before key update"); + match side { + Side::Client => pair.client.conn(), + Side::Server => pair.server.conn(), + } + .force_key_update(); + pair.traffic(side, b"after key update"); + } + // Restart the rind endpoint and require the unmodified peer to recognize its reset. + let (restarted, remote) = if ours_server { + (&mut pair.server, &mut pair.client) + } else { + (&mut pair.client, &mut pair.server) + }; + restarted.endpoint = Endpoint::new(restarted.config.clone(), None, true, None); + restarted.connections.clear(); + while remote.conn().poll().is_some() {} + remote.conn().ping(); + pair.drive(); + let remote = if ours_server { + &mut pair.client + } else { + &mut pair.server + }; + assert!(matches!( + remote.conn().poll(), + Some(Event::ConnectionLost { + reason: quinn::ConnectionError::Reset + }) + )); + } + } +} + +#[test] +fn upstream_zero_rtt_rejection() { + for ours_server in [false, true] { + let (mut tls, server) = configs(ours_server, rustls::CipherSuite::TLS13_AES_128_GCM_SHA256); + let mut pair = Pair { + client: Peer::new(None, 4434, !ours_server), + server: Peer::new(Some(Arc::new(server)), 4433, ours_server), + now: Instant::now(), + }; + pair.server.retry = false; + pair.connect(client_config(tls.clone(), !ours_server)); + pair.drive(); + pair.connected(); + assert!(!pair.client.conn().has_0rtt()); + let now = pair.now; + pair.client.conn().close(now, 0u32.into(), Bytes::new()); + pair.drive(); + pair.client.connections.clear(); + pair.server.connections.clear(); + tls.alpn_protocols = vec![b"b".to_vec()]; + pair.connect(client_config(tls, !ours_server)); + assert!(pair.client.conn().has_0rtt()); + pair.client + .conn() + .datagrams() + .send(Bytes::from_static(b"early"), false) + .unwrap(); + pair.drive(); + pair.connected(); + assert!(!pair.client.conn().accepted_0rtt()); + assert!(pair.server.conn().datagrams().recv().is_none()); + pair.traffic(Side::Client, b"after rejection"); + } +} + +#[test] +fn invalid_quic_config_is_rejected() { + let (tls, _) = configs(true, rustls::CipherSuite::TLS13_AES_128_GCM_SHA256); + let mut provider = rustls::crypto::aws_lc_rs::default_provider(); + provider + .cipher_suites + .retain(|s| s.suite() == rustls::CipherSuite::TLS13_CHACHA20_POLY1305_SHA256); + let client = rustls::ClientConfig::builder_with_provider(Arc::new(provider)) + .with_protocol_versions(&[&rustls::version::TLS13]) + .unwrap() + .with_root_certificates(rustls::RootCertStore::empty()) + .with_no_client_auth(); + assert!(matches!( + crypto::QuicClientConfig::try_from(client), + Err(crypto::ConfigError::NoInitialCipherSuite) + )); + let client = rustls::ClientConfig::builder_with_provider(tls.crypto_provider().clone()) + .with_protocol_versions(&[&rustls::version::TLS12]) + .unwrap() + .with_root_certificates(rustls::RootCertStore::empty()) + .with_no_client_auth(); + assert!(matches!( + crypto::QuicClientConfig::try_from(client), + Err(crypto::ConfigError::Tls(_)) + )); +} + +#[test] +fn upstream_retry_authentication_rejects_tampering() { + for ours_server in [false, true] { + let (tls, server) = configs(ours_server, rustls::CipherSuite::TLS13_AES_128_GCM_SHA256); + let cfg = client_crypto(tls, !ours_server); + for version in [1, 0xff00_001d] { + let session = cfg + .clone() + .start_session( + version, + "localhost", + &quinn_proto::transport_parameters::TransportParameters::read( + Side::Client, + &mut std::io::Cursor::new([]), + ) + .unwrap(), + ) + .unwrap(); + let cid = quinn::ConnectionId::new(b"original"); + let header = b"header"; + let token = b"token"; + let packet = [header.as_slice(), token.as_slice()].concat(); + let tag = server.crypto.retry_tag(version, &cid, &packet); + let mut payload = [token.as_slice(), tag.as_slice()].concat(); + assert!(session.is_valid_retry(&cid, header, &payload)); + assert!(!session.is_valid_retry(&quinn::ConnectionId::new(b"other"), header, &payload)); + assert!(!session.is_valid_retry(&cid, b"changed", &payload)); + payload[0] ^= 1; + assert!(!session.is_valid_retry(&cid, header, &payload)); + payload[0] ^= 1; + *payload.last_mut().unwrap() ^= 1; + assert!(!session.is_valid_retry(&cid, header, &payload)); + assert!(!session.is_valid_retry(&cid, header, &payload[..15])); + } + } +} diff --git a/rs/web-transport-quinn/tests/poll.rs b/rs/web-transport-quinn/tests/poll.rs index a8b557e1..6309b106 100644 --- a/rs/web-transport-quinn/tests/poll.rs +++ b/rs/web-transport-quinn/tests/poll.rs @@ -13,29 +13,16 @@ use std::{ use anyhow::{Context as _, Result}; use rcgen::{CertifiedKey, KeyPair}; +use rustls::pki_types::{PrivateKeyDer, PrivatePkcs8KeyDer}; use web_transport_proto::ConnectRequest; -use web_transport_quinn::quinn::rustls::pki_types::{PrivateKeyDer, PrivatePkcs8KeyDer}; use web_transport_quinn::{ClientBuilder, ServerBuilder}; use web_transport_trait::{ poll::{RecvStream, SendStream, Session}, Error as _, }; -/// With both crypto features enabled — as `--all-features` does — the crate cannot -/// pick a provider for us, so the test installs one. Harmless when only one feature -/// is on, since a default is already set by then. -fn install_crypto_provider() { - #[cfg(all(feature = "aws-lc-rs", feature = "ring"))] - { - let _ = web_transport_quinn::quinn::rustls::crypto::aws_lc_rs::default_provider() - .install_default(); - } -} - /// A client and server session, already connected. async fn pair() -> Result<(web_transport_quinn::Session, web_transport_quinn::Session)> { - install_crypto_provider(); - let CertifiedKey { cert, signing_key } = rcgen::generate_simple_self_signed(vec!["localhost".into(), "127.0.0.1".into()])?; let chain = vec![cert.der().clone()]; diff --git a/rs/web-transport-quinn/tests/raw.rs b/rs/web-transport-quinn/tests/raw.rs index bdc66023..056cef35 100644 --- a/rs/web-transport-quinn/tests/raw.rs +++ b/rs/web-transport-quinn/tests/raw.rs @@ -4,10 +4,6 @@ //! There is no HTTP/3 exchange on this path, so there is neither a request URL nor //! a response. The session reports the negotiated ALPN as its protocol instead. -// A crypto provider is needed to establish the connection, matching the gate on -// the crate's own builders. -#![cfg(any(feature = "aws-lc-rs", feature = "ring"))] - use std::{ net::{Ipv4Addr, SocketAddr}, sync::Arc, @@ -35,24 +31,10 @@ fn self_signed() -> Result<(CertificateDer<'static>, PrivateKeyDer<'static>)> { Ok((cert_der, key_der)) } -/// The provider is passed explicitly rather than relying on the process-level -/// default, which rustls cannot determine when both backend features are enabled -/// (as `--all-features` does). -fn crypto_provider() -> Arc { - #[cfg(feature = "aws-lc-rs")] - { - Arc::new(rustls::crypto::aws_lc_rs::default_provider()) - } - #[cfg(all(feature = "ring", not(feature = "aws-lc-rs")))] - { - Arc::new(rustls::crypto::ring::default_provider()) - } -} - /// Bind a server endpoint and a client endpoint, both offering only `RAW_ALPN`. fn endpoints() -> Result<(quinn::Endpoint, quinn::Endpoint, SocketAddr)> { let (cert, key) = self_signed()?; - let provider = crypto_provider(); + let provider = web_transport_quinn::crypto::default_provider()?; let mut server_crypto = rustls::ServerConfig::builder_with_provider(provider.clone()) .with_protocol_versions(&[&rustls::version::TLS13])? @@ -61,12 +43,17 @@ fn endpoints() -> Result<(quinn::Endpoint, quinn::Endpoint, SocketAddr)> { server_crypto.alpn_protocols = vec![RAW_ALPN.as_bytes().to_vec()]; server_crypto.max_early_data_size = u32::MAX; - let server_config = quinn::ServerConfig::with_crypto(Arc::new( - quinn::crypto::rustls::QuicServerConfig::try_from(server_crypto)?, - )); + let server_config = web_transport_quinn::crypto::server_config(Arc::new( + web_transport_quinn::crypto::QuicServerConfig::try_from(server_crypto)?, + ))?; let bind: SocketAddr = (Ipv4Addr::LOCALHOST, 0).into(); - let server = quinn::Endpoint::server(server_config, bind)?; + let server = quinn::Endpoint::new( + web_transport_quinn::crypto::endpoint_config()?, + Some(server_config), + std::net::UdpSocket::bind(bind)?, + quinn::default_runtime().context("no async runtime")?, + )?; let server_addr = server.local_addr()?; let mut roots = rustls::RootCertStore::empty(); @@ -82,10 +69,15 @@ fn endpoints() -> Result<(quinn::Endpoint, quinn::Endpoint, SocketAddr)> { client_crypto.enable_early_data = true; let client_config = quinn::ClientConfig::new(Arc::new( - quinn::crypto::rustls::QuicClientConfig::try_from(client_crypto)?, + web_transport_quinn::crypto::QuicClientConfig::try_from(client_crypto)?, )); - let mut client = quinn::Endpoint::client((Ipv4Addr::LOCALHOST, 0).into())?; + let mut client = quinn::Endpoint::new( + web_transport_quinn::crypto::endpoint_config()?, + None, + std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?, + quinn::default_runtime().context("no async runtime")?, + )?; client.set_default_client_config(client_config); Ok((server, client, server_addr)) @@ -111,7 +103,7 @@ fn negotiated_alpn(conn: &quinn::Connection) -> Result { let data = conn .handshake_data() .context("no handshake data")? - .downcast::() + .downcast::() .ok() .context("unexpected handshake data")?; diff --git a/rs/web-transport/README.md b/rs/web-transport/README.md index 6a9ab0f8..e29240da 100644 --- a/rs/web-transport/README.md +++ b/rs/web-transport/README.md @@ -31,3 +31,14 @@ WASM is `!Send` and as far as I can tell, it's not possible to implement a trait This crate skirts the issue by switching the underlying implementation based on the platform. The compiler can then automatically apply `Send` bounds instead of explicitly requiring them. Unfortunate, I know. + +## Native crypto + +The native Quinn backend uses rind through rind-rustls, with an installed process-wide +rustls provider taking precedence. Endpoint keys and Retry integrity always use rind. +Native builds support x86_64, aarch64 and 32-bit ARM; constructing a client or server +returns an error if the CPU lacks a required feature. This also applies with another +TLS provider installed. The native dependency graph no longer builds ring or aws-lc-rs. + +WASM uses the browser's TLS and does not depend on rind. Advanced native callers use +[`web_transport_quinn::crypto`](../web-transport-quinn/README.md#crypto-and-migration). diff --git a/swift/README.md b/swift/README.md index 3c958cdc..cdaac854 100644 --- a/swift/README.md +++ b/swift/README.md @@ -64,3 +64,11 @@ swift/ Tests/HostTests/ macOS host runtime tests (check.sh only) scripts/ check.sh, package.sh ``` + +## Native crypto + +The native Quinn backend uses rind through rind-rustls, with an installed process-wide +rustls provider taking precedence. Endpoint keys and Retry integrity always use rind. +Native builds support x86_64, aarch64 and 32-bit ARM; constructing a client or server +returns an error if the CPU lacks a required feature. This also applies with another +TLS provider installed. The native dependency graph no longer builds ring or aws-lc-rs.