Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions quest/a1/rind/noq.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,7 @@ 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.

## Waiting

- moq-dev/rind: publish a stable `rind-rustls` version implementing rustls `PacketKey::encrypt_in_place_for_path` and `decrypt_in_place_for_path`, including path 0. Noq 1.4 calls these for every packet; `rind-rustls` 0.23.0 and rind main `6dbdebd578aa2c36b7109261009084148a183aad` inherit rustls's error-returning defaults, so the migration compiles but Noq panics before handshake completion. Update the dependency to that stable release and verify `rind_packet_keys_support_noq_path_api` and `ring_peer_handshake_and_retry` pass, then run the full local checks and cross-vendor review. Keep the migration draft until this clears; do not duplicate packet cryptography locally.
12 changes: 7 additions & 5 deletions rs/web-transport-noq/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,6 @@ categories = ["network-programming", "web-programming"]
all-features = true

[features]
default = ["aws-lc-rs"]
aws-lc-rs = ["noq/aws-lc-rs", "rustls/aws-lc-rs"]
ring = ["noq/ring", "rustls/ring"]
# Unlocks `noq::TransportConfig::qlog_*`, which this crate re-exports but cannot
# enable on a caller's behalf.
qlog = ["noq/qlog"]
Expand All @@ -27,18 +24,20 @@ bytes = "1"
futures = "0.3"
http = "1"
kio = "0.6.2"
noq = { version = "1", default-features = false, features = [
noq = { version = "1.4", default-features = false, features = [
"tracing-log",
"platform-verifier",
"runtime-tokio",
"rustls",
"bloom",
] }
rind = "0.2.1"
rind-rustls = "0.23"
rustls = { version = "0.23", default-features = false, features = [
"logging",
"std",
] }
rustls-native-certs = "0.8"
socket2 = "0.6"
thiserror = "2"
tokio = { version = "1", default-features = false, features = [
"io-util",
Expand All @@ -53,7 +52,10 @@ web-transport-trait = { workspace = true }
[dev-dependencies]
anyhow = "1"
clap = { version = "4", features = ["derive"] }
noq = { version = "1.4", default-features = false, features = ["ring"] }
rcgen = "0.14"
ring = "0.17"
rustls = { version = "0.23", default-features = false, features = ["ring"] }
rustls-pemfile = "2"
tokio = { version = "1", features = ["full", "test-util"] }
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
74 changes: 59 additions & 15 deletions rs/web-transport-noq/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,29 +28,73 @@ Both endpoints can send datagrams below the MTU size (~1.2kb minimum) and they m
They are basically UDP packets, except they are encrypted and congestion controlled.

# Usage
To use web-transport-noq, first you need to create a [noq::Endpoint](https://docs.rs/noq/latest/noq/struct.Endpoint.html); see the documentation and examples for more information.
The only requirement is that the ALPN is set to `web_transport_noq::ALPN` (aka `h3`).
Use `ClientBuilder` and `ServerBuilder` for WebTransport endpoints. Set the server's
certificate with `ServerBuilder::with_certificate`, and choose system roots or
certificate fingerprints when finishing the client builder.

Afterwards, you use [web_transport_noq::accept](https://docs.rs/web-transport-noq/latest/web_transport_noq/fn.accept.html) (as a server) or [web_transport_noq::connect](https://docs.rs/web-transport-noq/latest/web_transport_noq/fn.connect.html) (as a client) to establish a WebTransport session.
This will take over the QUIC connection and perform the boring HTTP/3 handshake for you.
```rust
# async fn example() -> Result<(), Box<dyn std::error::Error>> {
let client = web_transport_noq::ClientBuilder::new().with_system_roots()?;
let session = client.connect(url::Url::parse("https://localhost:4433/")?).await?;
let (mut send, mut recv) = session.open_bi().await?;
send.write_all(b"hello").await?;
# Ok(())
# }
```

See the [examples](examples) or [moq-native](https://github.com/moq-dev/moq-rs/blob/main/moq-native/src/quic.rs) for a full setup.
See the [examples](examples) for full client and server setup.

```rust
// Create a QUIC client.
let mut endpoint = noq::Endpoint::client("[::]:0".parse()?)?;
endpoint.set_default_client_config(/* ... */);
## Crypto and CPU support

// Connect to the given URL.
let session = web_transport_noq::connect(&client, Url::parse("https://localhost")?).await?;
TLS uses `rind-rustls` unless the process has already installed a rustls
`CryptoProvider`, which takes precedence. QUIC initial packets and endpoint reset
and handshake-token keys always use rind. The `aws-lc-rs` and `ring` features are
removed; `qlog` remains available. Normal and build dependencies need no C crypto.

// Create a bidirectional stream.
let (mut send, mut recv) = session.open_bi().await?;
Rind supports the release architectures x86_64, aarch64 and armv7. It requires a
minimum CPU instruction set described in [rind's platforms](https://github.com/moq-dev/rind/blob/main/PLATFORMS.md).
Builders remain infallible to create and return `ClientError::UnsupportedCpu` or
`ServerError::UnsupportedCpu` from their finishing methods when that CPU check
fails, including with an installed provider. `Client::default()` unwraps setup and
can panic; use `ClientBuilder` to handle errors.

// Send a message.
send.write(b"hello").await?;
Advanced callers still use Noq's `crypto::rustls` types and `HandshakeData`.
Pass `crypto::initial_suite()?` to `QuicClientConfig::with_initial` or
`QuicServerConfig::with_initial`, rather than `try_from`, which depends on Noq's
built-in providers. Set ALPN to `web_transport_noq::ALPN` (`h3`) for WebTransport.
Use `crypto::endpoint_config()` for fresh reset keys and `crypto::server_config()`
for fresh Retry/validation-token keys. These helpers are fallible, as are
`crypto::default_provider()` and `crypto::sha256()`.

```rust
# fn example(tls: rustls::ClientConfig) -> Result<noq::Endpoint, Box<dyn std::error::Error>> {
use std::sync::Arc;
use web_transport_noq::{crypto, noq};

let tls = noq::crypto::rustls::QuicClientConfig::with_initial(
Arc::new(tls), crypto::initial_suite()?,
)?;
let client_config = noq::ClientConfig::new(Arc::new(tls));
let endpoint = noq::Endpoint::new(
crypto::endpoint_config()?,
None,
std::net::UdpSocket::bind("0.0.0.0:0")?,
Arc::new(noq::TokioRuntime),
)?;
endpoint.set_default_client_config(client_config);
# Ok(endpoint)
# }
```

For servers, wrap `QuicServerConfig::with_initial` in `crypto::server_config`,
then pass `Some(server_config)` to `Endpoint::new`. Bind sockets to match the
address families your application supports. Noq's `Endpoint::client`,
`Endpoint::server`, `EndpointConfig::default` and `ServerConfig::with_crypto`
require Noq's ring/aws-lc-rs features and are unavailable in this crate's normal
provider configuration. For persistent reset or token secrets, supply
`crypto::ResetKey` to `EndpointConfig::new` and `crypto::TokenKey` to
`ServerConfig::new`; each secret needs at least 32 bytes of entropy.

## API
The `web-transport-noq` API is almost identical to the Noq API, except that [Connection](https://docs.rs/noq/latest/noq/struct.Connection.html) is called [Session](https://docs.rs/web-transport-noq/latest/web_transport_noq/struct.Session.html).

Expand Down
14 changes: 11 additions & 3 deletions rs/web-transport-noq/examples/echo-client-advanced.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,16 +44,24 @@ async fn main() -> anyhow::Result<()> {
// Standard noq setup, accepting only the given certificate.
// You should use system roots in production.
let mut config =
rustls::ClientConfig::builder_with_provider(web_transport_noq::crypto::default_provider())
rustls::ClientConfig::builder_with_provider(web_transport_noq::crypto::default_provider()?)
.with_protocol_versions(&[&rustls::version::TLS13])?
.with_root_certificates(roots)
.with_no_client_auth();
config.alpn_protocols = vec![web_transport_noq::ALPN.as_bytes().to_vec()]; // this one is important

let config: noq::crypto::rustls::QuicClientConfig = config.try_into()?;
let config = noq::crypto::rustls::QuicClientConfig::with_initial(
Arc::new(config),
web_transport_noq::crypto::initial_suite()?,
)?;
let config = noq::ClientConfig::new(Arc::new(config));

let client = noq::Endpoint::client("[::]:0".parse()?)?;
let client = noq::Endpoint::new(
web_transport_noq::crypto::endpoint_config()?,
None,
std::net::UdpSocket::bind("[::]:0")?,
Arc::new(noq::TokioRuntime),
)?;
let client = web_transport_noq::Client::new(client, config);

// Connect to the given URL.
Expand Down
16 changes: 12 additions & 4 deletions rs/web-transport-noq/examples/echo-server-advanced.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,20 +63,28 @@ async fn main() -> anyhow::Result<()> {

// Standard Noq setup
let mut config =
rustls::ServerConfig::builder_with_provider(web_transport_noq::crypto::default_provider())
rustls::ServerConfig::builder_with_provider(web_transport_noq::crypto::default_provider()?)
.with_protocol_versions(&[&rustls::version::TLS13])?
.with_no_client_auth()
.with_single_cert(chain, key)?;

config.max_early_data_size = u32::MAX;
config.alpn_protocols = vec![web_transport_noq::ALPN.as_bytes().to_vec()]; // this one is important

let config: noq::crypto::rustls::QuicServerConfig = config.try_into()?;
let config = noq::ServerConfig::with_crypto(Arc::new(config));
let config = noq::crypto::rustls::QuicServerConfig::with_initial(
Arc::new(config),
web_transport_noq::crypto::initial_suite()?,
)?;
let config = web_transport_noq::crypto::server_config(Arc::new(config))?;

tracing::info!(addr = %args.addr, "listening");

let server = noq::Endpoint::server(config, args.addr)?;
let server = noq::Endpoint::new(
web_transport_noq::crypto::endpoint_config()?,
Some(config),
std::net::UdpSocket::bind(args.addr)?,
Arc::new(noq::TokioRuntime),
)?;

// Accept new connections.
while let Some(conn) = server.accept().await {
Expand Down
53 changes: 26 additions & 27 deletions rs/web-transport-noq/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@ use std::net::{IpAddr, SocketAddr};
use std::sync::Arc;

use crate::proto::ConnectRequest;
#[cfg(any(feature = "aws-lc-rs", feature = "ring"))]
use noq::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};

Expand All @@ -25,18 +23,16 @@ pub enum CongestionControl {
LowLatency,
}

#[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.
#[derive(Clone)]
pub struct ClientBuilder {
provider: crypto::Provider,
provider: Result<crypto::Provider, crypto::UnsupportedCpu>,
congestion_controller:
Option<Arc<dyn noq::congestion::ControllerFactory + Send + Sync + 'static>>,
}

#[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 {
Expand Down Expand Up @@ -79,7 +75,7 @@ impl ClientBuilder {
}

let crypto = self
.builder()
.builder()?
.with_root_certificates(roots)
.with_no_client_auth();

Expand All @@ -91,12 +87,12 @@ impl ClientBuilder {
self,
certs: Vec<CertificateDer>,
) -> Result<Client, ClientError> {
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(|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::<Result<_, _>>()?)
}

/// Supply sha256 hashes for accepted certificates instead of using root CAs.
Expand All @@ -106,13 +102,13 @@ impl ClientBuilder {
) -> Result<Client, ClientError> {
// 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();
Expand All @@ -129,16 +125,22 @@ impl ClientBuilder {
DangerousClientBuilder { inner: self }
}

fn builder(&self) -> rustls::ConfigBuilder<rustls::ClientConfig, rustls::WantsVerifier> {
rustls::ClientConfig::builder_with_provider(self.provider.clone())
.with_protocol_versions(&[&rustls::version::TLS13])
.unwrap()
fn builder(
&self,
) -> Result<rustls::ConfigBuilder<rustls::ClientConfig, rustls::WantsVerifier>, ClientError>
{
Ok(
rustls::ClientConfig::builder_with_provider(self.provider.clone()?)
.with_protocol_versions(&[&rustls::version::TLS13])?,
)
}

fn build(self, mut crypto: rustls::ClientConfig) -> Result<Client, ClientError> {
crypto.alpn_protocols = vec![ALPN.as_bytes().to_vec()];

let client_config = QuicClientConfig::try_from(crypto).unwrap();
let client_config =
QuicClientConfig::with_initial(Arc::new(crypto), crypto::initial_suite()?)
.expect("rind initial suite is AES-128-GCM-SHA256");
let mut client_config = noq::ClientConfig::new(Arc::new(client_config));

let mut transport = noq::TransportConfig::default();
Expand All @@ -148,22 +150,21 @@ impl ClientBuilder {

client_config.transport_config(transport.into());

let client = noq::Endpoint::client("[::]:0".parse().unwrap()).unwrap();
let client = crate::endpoint(crypto::endpoint_config()?, None, "[::]:0".parse().unwrap())
.map_err(|e| ClientError::IoError(Arc::new(e)))?;
Ok(Client {
endpoint: client,
config: client_config,
})
}
}

#[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.
Expand All @@ -173,7 +174,6 @@ pub struct DangerousClientBuilder {
inner: ClientBuilder,
}

#[cfg(any(feature = "aws-lc-rs", feature = "ring"))]
impl DangerousClientBuilder {
/// Disable certificate verification entirely.
///
Expand All @@ -183,11 +183,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<Client, ClientError> {
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();
Expand Down Expand Up @@ -257,14 +257,13 @@ impl Client {
}
}

#[cfg(any(feature = "aws-lc-rs", feature = "ring"))]
/// Panics if endpoint 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,
Expand All @@ -280,7 +279,7 @@ impl ServerCertVerifier for ServerFingerprints {
_ocsp_response: &[u8],
_now: rustls::pki_types::UnixTime,
) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
let cert_hash = crypto::sha256(&self.provider, end_entity);
let cert_hash = crypto::sha256(&self.provider, end_entity)?;
if self
.fingerprints
.iter()
Expand Down
Loading
Loading