diff --git a/Cargo.lock b/Cargo.lock index 310b4c59163..b1f41440492 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -711,7 +711,7 @@ dependencies = [ "bitflags 2.13.2", "cexpr", "clang-sys", - "itertools 0.13.0", + "itertools 0.10.5", "log", "prettyplease", "proc-macro2", @@ -732,7 +732,7 @@ dependencies = [ "bitflags 2.13.2", "cexpr", "clang-sys", - "itertools 0.13.0", + "itertools 0.10.5", "log", "prettyplease", "proc-macro2", @@ -3926,33 +3926,6 @@ dependencies = [ "syn 3.0.6", ] -[[package]] -name = "libcrux-ml-kem" -version = "0.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ceed00367748ec0b545bc4a7b0521f8c9fd476d02484340f0a95b0f45f828cd" -dependencies = [ - "hax-lib 0.4.2", - "libcrux-intrinsics", - "libcrux-platform", - "libcrux-secrets", - "libcrux-sha3", - "libcrux-traits", -] - -[[package]] -name = "libcrux-p256" -version = "0.0.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7489aa205be22524e2f6ddbe006c0c4ff5f1dfc7c17b783e3d02f1cb2a01c605" -dependencies = [ - "libcrux-hacl-rs", - "libcrux-macros", - "libcrux-secrets", - "libcrux-sha2", - "libcrux-traits", -] - [[package]] name = "libcrux-platform" version = "0.0.4" @@ -3982,29 +3955,6 @@ dependencies = [ "hax-lib 0.4.2", ] -[[package]] -name = "libcrux-sha2" -version = "0.0.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86aa35d8fc9576a41df34af4d95d1f11186c1f65cd6c829329748915ea556d71" -dependencies = [ - "libcrux-hacl-rs", - "libcrux-macros", - "libcrux-traits", -] - -[[package]] -name = "libcrux-sha3" -version = "0.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c8117e86e1f03417d8ebe50ed298c6ee0b05557783a75697d0c59a2ef2dcfc6" -dependencies = [ - "hax-lib 0.4.2", - "libcrux-intrinsics", - "libcrux-platform", - "libcrux-traits", -] - [[package]] name = "libcrux-traits" version = "0.0.9" @@ -4601,6 +4551,8 @@ dependencies = [ "kio", "moq-net", "rind", + "rind-rustls", + "rustls", "serde", "serde_json", "tempfile", @@ -4897,7 +4849,6 @@ version = "0.1.0" dependencies = [ "arbitrary", "assert_matches", - "aws-lc-rs", "bench-harness", "bytes", "cpu-time", @@ -4907,13 +4858,16 @@ dependencies = [ "kio", "lru-slab", "moq-congestion", + "moq-crypto", "moq-quic", "proptest", "qlog", "rand 0.10.3", "rand_pcg", "rcgen", - "ring", + "rind", + "rind-rcgen", + "rind-rustls", "rustc-hash 2.1.3", "rustls", "slab", @@ -4937,7 +4891,6 @@ name = "moq-relay" version = "0.17.2" dependencies = [ "anyhow", - "aws-lc-rs", "axum", "axum-server", "bench-harness", @@ -4961,12 +4914,16 @@ dependencies = [ "moq-stats", "moq-tokio", "moq-uring", + "pem 3.0.6", "prometheus-client", "qmux 0.7.0", "rand 0.10.3", "rcgen", "reqwest", "reqwest-middleware", + "rind", + "rind-rcgen", + "rind-rustls", "rustls", "sd-notify", "serde", @@ -5037,14 +4994,14 @@ dependencies = [ "bytes", "futures", "hang", - "hmac 0.13.0", "kio", "moq-mux", "moq-net", "moq-tokio", "rand 0.10.3", + "rind", + "rind-rustls", "rustls", - "sha2 0.11.1", "socket2 0.6.5", "thiserror 2.0.21", "tokio", @@ -5187,7 +5144,6 @@ dependencies = [ "flume", "futures", "hex", - "hmac 0.13.0", "http", "humantime", "humantime-serde", @@ -5197,6 +5153,7 @@ dependencies = [ "libc", "mdns-sd", "moq-congestion", + "moq-crypto", "moq-ice", "moq-net", "moq-quic", @@ -5204,21 +5161,23 @@ dependencies = [ "moq-sock", "moq-tokio", "notify", + "pem 3.0.6", "qmux 0.7.0", "rand 0.10.3", "rcgen", "reqwest", + "rind", + "rind-rcgen", + "rind-rustls", "rustc-hash 2.1.3", "rustls", "rustls-platform-verifier", "rustls-webpki", "serde", "serde_with", - "sha2 0.11.1", "socket2 0.6.5", "str0m", "stun-types", - "subtle", "tempfile", "thiserror 2.0.21", "tikv-jemalloc-ctl", @@ -5275,6 +5234,7 @@ dependencies = [ "kio", "libc", "moq-congestion", + "moq-crypto", "moq-net", "moq-quic", "moq-shaper", @@ -5282,7 +5242,10 @@ dependencies = [ "moq-tokio", "moq-uring", "nix", + "pem 3.0.6", "rcgen", + "rind-rcgen", + "rind-rustls", "rustc-hash 2.1.3", "rustls", "rustls-platform-verifier", @@ -7051,11 +7014,14 @@ dependencies = [ "futures", "kio", "libc", + "moq-crypto", "moq-net", "moq-quic", "qmux 0.6.5", "rcgen", + "rind-rcgen", "rustls", + "rustls-native-certs", "thiserror 2.0.21", "tokio", "tokio-rustls", @@ -7328,7 +7294,6 @@ checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8" dependencies = [ "aws-lc-rs", "pem 4.0.0", - "ring", "rustls-pki-types", "time", "x509-parser", @@ -7537,9 +7502,9 @@ dependencies = [ [[package]] name = "rind" -version = "0.1.2" +version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "460a4041e5ae933ff4e2c11aad0d05a60ddf21a89eaea0806520b8c50f1d5727" +checksum = "422500e50252ad3bd319f359c54431441711a8fd55cb228973dde123ff8c2039" dependencies = [ "cfg-if", "curve25519-dalek", @@ -7549,8 +7514,6 @@ dependencies = [ "libcrux-aes", "libcrux-hacl-rs", "libcrux-macros", - "libcrux-ml-kem", - "libcrux-p256", "libcrux-poly1305", "libcrux-traits", ] @@ -7577,11 +7540,23 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "rind-rcgen" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b0f7d386858c030aff879c224a0c3d59b02e7ff953ca96214825a3e77ecba76" +dependencies = [ + "rcgen", + "rind", + "rustls-pki-types", + "zeroize", +] + [[package]] name = "rind-rustls" -version = "0.1.2" +version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10988f0bacd30c97c41510648647d97d68fdef593f737724dd05d5cdb72d948d" +checksum = "5e67845e30d1c9a194485cdcb585abf7dcc011a4413488d57634ec39d7e832f0" dependencies = [ "rind", "rustls", @@ -7724,9 +7699,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "aws-lc-rs", - "log", "once_cell", - "ring", "rustls-pki-types", "rustls-webpki", "subtle", @@ -9099,7 +9072,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", "rustix 1.1.6", "windows-sys 0.61.2", @@ -11015,6 +10988,7 @@ dependencies = [ "anyhow", "aws-lc-rs", "aws-lc-sys", + "base64 0.22.1", "base64 0.23.1", "bitflags 2.13.2", "block2 0.6.2", @@ -11059,7 +11033,7 @@ dependencies = [ "futures-sink", "futures-task", "futures-util", - "getrandom 0.2.17", + "getrandom 0.3.4", "getrandom 0.4.3", "half", "hashbrown 0.17.1", @@ -11070,7 +11044,6 @@ dependencies = [ "hyper-rustls", "hyper-util", "indexmap 2.14.2", - "itertools 0.13.0", "jsonwebtoken", "lazy_static", "libc", @@ -11252,7 +11225,6 @@ dependencies = [ "lazy_static", "nom 7.1.3", "oid-registry", - "ring", "rusticata-macros", "thiserror 2.0.21", "time", diff --git a/Cargo.toml b/Cargo.toml index f6ffa1c4660..4d2fcff63a6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -106,8 +106,6 @@ hang = { version = "0.21.11", path = "rs/hang" } hashbrown = { version = "0.17.1", default-features = false } hashlink = "0.12.2" hex = "0.4" -# HMAC-SHA256 for the mDNS membership proofs (moq-tokio's `mdns` feature). -hmac = "0.13" humantime = "2.3" humantime-serde = "1.1.1" hyper = "1.11" @@ -188,6 +186,7 @@ objc2-screen-capture-kit = "0.3.2" # Default features off so a consumer that only needs InMemory does not pull the # local-filesystem stack; `fs` (and cloud backends) are opted in by the caller. object_store = { version = "0.14", default-features = false } +pem = "3.0.6" percent-encoding = "2" pkcs1 = { version = "0.7.5", features = ["alloc"] } pkcs8 = "0.11.0" @@ -203,24 +202,24 @@ rcgen = { version = "0.14", default-features = false } # default-features off so each consumer picks its own TLS backend and body # features; nothing here wants the default native-tls stack. reqwest = { version = "0.13", default-features = false } -rind = "0.1.2" +rind = "0.1.12" rind-jsonwebtoken = "0.1.2" rind-object-store = "0.1.2" -rind-rustls = "0.1.2" +rind-rcgen = "0.1.12" +rind-rustls = "0.1.12" rustc-hash = "2.1.3" +rustls-native-certs = "0.8.5" sd-notify = "0.5" send_wrapper = "0.6" serde = { version = "1", features = ["derive"] } serde_json = "1" serde_with = "3" -sha2 = "0.11" slab = "0.4.12" socket2 = "0.6" # Sans-IO WebRTC. The default `examples` feature pulls in a web server, and aws-lc-rs # is the provider rustls already brings. str0m = { version = "0.24.1", default-features = false, features = ["aws-lc-rs"] } stun-types = "2.0.3" -subtle = "2.6" tempfile = "3" thiserror = "2" time = "0.3" diff --git a/doc/bin/cli.md b/doc/bin/cli.md index 3f79d7f5666..75e0dacf98a 100644 --- a/doc/bin/cli.md +++ b/doc/bin/cli.md @@ -14,7 +14,8 @@ Docker; see [Install](/setup/install). Its cryptography comes from [rind](https://github.com/moq-dev/rind), which runs on any x86\_64 CPU and on any aarch64 CPU with NEON, including a Raspberry Pi 4, CM4, or Zero 2 W on a 64-bit OS. On a CPU missing a feature rind needs, -`moq` exits at startup naming it. +`moq` exits at startup naming it. The Rust library also supports armv7; +prebuilt CLI artifacts for 32-bit boards are not yet available. ## What it does diff --git a/doc/bin/relay/index.md b/doc/bin/relay/index.md index bdce59e3039..bd5033433a3 100644 --- a/doc/bin/relay/index.md +++ b/doc/bin/relay/index.md @@ -9,6 +9,11 @@ description: The MoQ relay server groups, merges duplicate subscriptions, and never parses the media, so one relay serves video, audio, and data alike. +Its transport and HTTP cryptography uses [rind](https://github.com/moq-dev/rind): +every x86\_64 CPU, aarch64 with NEON (including Raspberry Pi 4, CM4, and +Zero 2 W without crypto extensions), and armv7 are supported. An unsupported +CPU fails startup with an error naming the missing feature. + ## Features - **QUIC, WebTransport, and WebSocket** listeners, so browsers and native clients connect to one process. diff --git a/doc/lib/rs/index.md b/doc/lib/rs/index.md index 37512dc989f..3a74e86a022 100644 --- a/doc/lib/rs/index.md +++ b/doc/lib/rs/index.md @@ -14,13 +14,20 @@ then add [hang](/lib/rs/hang) for media. To run a tool without embedding it, see [Applications](/bin/). [Examples](/setup/examples) links runnable consumers; [Repository map](/setup/repository) locates internal crates and their tests. +Transport cryptography comes from [rind](https://github.com/moq-dev/rind). +It supports every x86\_64 CPU, aarch64 with NEON (including Raspberry Pi 4, +CM4, and Zero 2 W without crypto extensions), and armv7. Setup reports a +missing required CPU feature before starting transport cryptography. +`aws-lc-rs` and `ring` are no longer `moq-tokio` or `moq-quic` features; +remove them from dependency declarations. + ## Crates | Crate | Does | | --- | --- | | [moq-net](/lib/rs/moq-net) | The pub/sub layer: sessions, origins, broadcasts, tracks, groups, frames. Transport-agnostic. | | [moq-pattern](https://docs.rs/moq-pattern) | Path patterns such as `room/**`. Re-exported by moq-net and moq-auth. | -| [moq-tokio](https://docs.rs/moq-tokio) | Connects and listens over QUIC, WebTransport, WebSocket, TCP, or Unix sockets, from config or CLI flags, and runs WebRTC data channels that the caller signals (`webrtc` feature). With default features off, `driver` plus `aws-lc-rs` or `ring` builds a Tokio QUIC stack without MoQ. | +| [moq-tokio](https://docs.rs/moq-tokio) | Connects and listens over QUIC, WebTransport, WebSocket, TCP, or Unix sockets, from config or CLI flags, and runs WebRTC data channels that the caller signals (`webrtc` feature). With default features off, `driver` builds a Tokio QUIC stack, with rind cryptography, without MoQ. | | [qmux](https://docs.rs/qmux) | QUIC streams, datagrams, and flow control over TCP, TLS, WebSocket, and Unix sockets, on moq-quic's state machine. | | [moq-sock](https://docs.rs/moq-sock) | Socket binding and CPU pinning for thread-per-core listeners. | | [moq-ice](https://github.com/moq-dev/moq/tree/main/rs/moq-ice) | Internal infrastructure with no stability promise; the ICE agent behind native WebRTC: drives a str0m connection over UDP, with a STUN client. | diff --git a/quest/m1/rind/transport.md b/quest/m1/rind/transport.md index 5f9faa72d65..80eb2c2cb7b 100644 --- a/quest/m1/rind/transport.md +++ b/quest/m1/rind/transport.md @@ -1,42 +1,47 @@ -# [L] Transport on rind +# [S] Finish transport on rind ## Goal moq-quic, moq-tokio, moq-uring, moq-rtmp, qmux, and moq-relay's own HTTP and -TLS take all their crypto from -rind and `rind-rustls`, their graphs hold no aws-lc-sys or ring, and moq-tokio's -and moq-quic's `aws-lc-rs` and `ring` features are gone. Every binary built on -moq-tokio checks rind's CPU support at startup. +TLS use rind, without selecting aws-lc or ring. Remove moq-tokio's and +moq-quic's provider features and report unsupported CPU features at setup. +No wire format changes. ## Plan -Decided with the maintainer on 2026-10-26; see the -[epic](/quest/m1/rind/README.md). - -- moq-quic's direct calls move to rind's API: stateless reset HMAC-SHA256 and - its HKDF-SHA256 key derivation, address-validation tokens (HKDF to - AES-256-GCM), and Retry integrity (AES-128-GCM). Packet keys and header - protection come through rustls's QUIC traits from `rind-rustls`. The - provider is no longer picked per feature. -- moq-tokio installs `rind-rustls`, generates self-signed certificates through - `rind-rcgen`, drops rustls's default features and rustls-webpki's `aws-lc-rs`, - and moves mDNS's HMAC-SHA256 from RustCrypto to rind. -- moq-uring builds its configs from `rind-rustls` instead of hardcoding - aws-lc's provider. -- moq-rtmp's handshake HMAC-SHA256 moves to rind, and its rustls stops forcing - aws-lc. qmux's TLS takes `rind-rustls`; tungstenite's own `sha1` stays. -- reqwest and axum-server switch to their no-provider features wherever these - crates enable them. Decided 2026-10-31 (maintainer): this includes - moq-relay's own reqwest, axum-server, and rustls `aws-lc-rs` features, which - no other area owns. Built-in ACME and rustls-acme were removed separately. -- The roughly 100 test call sites that install aws-lc's provider install - rind's. -- The startup check runs where moq-tokio's crypto is first configured, and its - error names the missing CPU feature. Every binary inherits it, including - moq-ffi. -- Docs: the CPU requirement goes into the relay, CLI, and library docs, and - the removed features leave `doc/lib`. - -Public API: moq-tokio's and moq-quic's `aws-lc-rs` and `ring` features are -removed (breaking; migrate by dropping them, since rind is always on). -Unsupported CPUs now fail at startup. Wire: none. +The settled migration is implemented in +[moq-dev/moq#7873](https://github.com/moq-dev/moq/pull/7873), with migration +notes and certificate/provider test sites updated together. rind 0.1.12 +supports older x86_64 CPUs without crypto extensions, aarch64 with NEON +(including Pi 4, CM4, and Zero 2 W without crypto extensions), and armv7. +The epic owns the final workspace crypto graph guard; WebRTC consolidation +and signing remain in their separate areas. + +Public error contract, decided by the maintainer on 2026-11-04: + +- ✅ Introduce a shared typed crypto error, and make `crypto::provider()` and + `crypto::install_default()` fallible, with MIGRATE notes for the broader + API migration. This replaces `moq_quic::ConfigError::Crypto(String)` and + `moq_tokio::tls::Error::Crypto(String)`. +- Not chosen: keeping `Crypto(String)` with the existing infallible + provider-helper signatures. + +Placement of the shared error, decided by the maintainer on 2026-11-04: + +- ✅ In `moq-crypto`, behind a new `provider` feature holding + `UnsupportedCpu`, `check()`, `provider()` and `install_default()`. It + depends only on rind and rustls, never on moq-net, so moq-quic, moq-tokio, + qmux and moq-uring use it without a cycle, and net-only builds gain only + that feature's dependencies. rind stays private: the error wraps rind's + `MissingFeature` instead of re-exporting it. +- Not chosen: re-exporting rind's `MissingFeature`; defining the error in + moq-quic and requiring moq-quic from moq-tokio; a brand-new crate. + +Complete the PR's local validation and cross-vendor review before marking +it ready. Keep every existing test in CI, at least nightly; do not disable a +flaky test to satisfy checks. This follows the user's explicit requirement +over the repository's immediate-disable instruction. + +## Related + +- [MoQ on rind](/quest/m1/rind/README.md) - the settled provider and CPU support decisions diff --git a/rs/hang/Cargo.toml b/rs/hang/Cargo.toml index 73d2d00f5d2..cba18cab5eb 100644 --- a/rs/hang/Cargo.toml +++ b/rs/hang/Cargo.toml @@ -31,7 +31,7 @@ features = ["from", "display", "debug"] [dev-dependencies] anyhow = { workspace = true } moq-mux = { path = "../moq-mux" } -moq-tokio = { path = "../moq-tokio", default-features = false, features = ["quic", "aws-lc-rs", "websocket"] } +moq-tokio = { path = "../moq-tokio", default-features = false, features = ["quic", "websocket"] } tokio = { workspace = true, features = ["macros", "fs"] } tracing = { workspace = true } url = { workspace = true } diff --git a/rs/moq-bench/Cargo.toml b/rs/moq-bench/Cargo.toml index 074ffb59cec..80206310b56 100644 --- a/rs/moq-bench/Cargo.toml +++ b/rs/moq-bench/Cargo.toml @@ -47,7 +47,7 @@ anyhow = { workspace = true, features = ["backtrace"] } humantime = { workspace = true } kio = { workspace = true, features = ["runtime"] } moq-net = { workspace = true } -moq-tokio = { workspace = true, default-features = false, features = ["aws-lc-rs", "net"] } +moq-tokio = { workspace = true, default-features = false, features = ["net"] } rand = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/rs/moq-bench/src/main.rs b/rs/moq-bench/src/main.rs index 28e59fee506..1ce10e85bd1 100644 --- a/rs/moq-bench/src/main.rs +++ b/rs/moq-bench/src/main.rs @@ -15,7 +15,7 @@ use rand::RngExt; #[tokio::main] async fn main() -> anyhow::Result<()> { - moq_tokio::crypto::install_default().expect("failed to install default crypto provider"); + moq_tokio::crypto::install_default()?; let config = Config::load()?; anyhow::ensure!( diff --git a/rs/moq-boy/Cargo.toml b/rs/moq-boy/Cargo.toml index 5ac64f902dc..f714c7e23de 100644 --- a/rs/moq-boy/Cargo.toml +++ b/rs/moq-boy/Cargo.toml @@ -38,7 +38,7 @@ moq-audio = { workspace = true } moq-json = { workspace = true } moq-mux = { workspace = true } moq-net = { workspace = true } -moq-tokio = { workspace = true, default-features = false, features = ["aws-lc-rs", "net"] } +moq-tokio = { workspace = true, default-features = false, features = ["net"] } # Select the Linux NVIDIA and VAAPI codecs explicitly; software H.264 is the # `openh264` feature. moq-video = { workspace = true, features = ["nvidia", "vaapi"] } diff --git a/rs/moq-c/Cargo.toml b/rs/moq-c/Cargo.toml index 20276f96d81..2481bb6cb7a 100644 --- a/rs/moq-c/Cargo.toml +++ b/rs/moq-c/Cargo.toml @@ -31,7 +31,7 @@ moq-audio = { workspace = true, features = ["aac"] } moq-json = { workspace = true } moq-mux = { workspace = true } moq-net = { workspace = true } -moq-tokio = { workspace = true, features = ["quic", "aws-lc-rs", "websocket", "tcp", "uds"] } +moq-tokio = { workspace = true, features = ["quic", "websocket", "tcp", "uds"] } # Select the NVIDIA and VAAPI hardware codecs explicitly because workspace # defaults are off. The hardware backends dlopen their driver; `vaapi` also runs # bindgen, so Linux builds need libclang. The software fallback is `openh264`. diff --git a/rs/moq-cli/Cargo.toml b/rs/moq-cli/Cargo.toml index 4f7de0d675a..5855b6af1dd 100644 --- a/rs/moq-cli/Cargo.toml +++ b/rs/moq-cli/Cargo.toml @@ -123,7 +123,7 @@ moq-rtmp = { workspace = true } moq-rtsp = { workspace = true } moq-srt = { workspace = true } # Raw qmux listeners are part of the CLI surface. `uds` compiles only on Unix. -moq-tokio = { workspace = true, default-features = false, features = ["aws-lc-rs", "tcp", "uds"] } +moq-tokio = { workspace = true, default-features = false, features = ["tcp", "uds"] } moq-transcode = { workspace = true, optional = true } moq-video = { workspace = true, optional = true } object_store = { workspace = true, features = ["fs"] } diff --git a/rs/moq-cli/src/announced.rs b/rs/moq-cli/src/announced.rs index ce87d393d42..f695d386e5a 100644 --- a/rs/moq-cli/src/announced.rs +++ b/rs/moq-cli/src/announced.rs @@ -193,7 +193,7 @@ mod tests { impl Fixture { async fn new() -> Self { - let _ = moq_tokio::crypto::install_default(); + moq_tokio::crypto::install_default().unwrap(); let fixture = moq_relay::test_relay().await.expect("test relay"); let ready = fixture.relay.ready(); let shutdown = fixture.relay.shutdown_trigger().clone(); diff --git a/rs/moq-cli/src/complete.rs b/rs/moq-cli/src/complete.rs index 10e001be985..02891375b99 100644 --- a/rs/moq-cli/src/complete.rs +++ b/rs/moq-cli/src/complete.rs @@ -425,7 +425,7 @@ mod tests { if !test_env::Env::without(&["MOQ_CONNECT"]).isolate() { return; } - let _ = moq_tokio::crypto::install_default(); + moq_tokio::crypto::install_default().unwrap(); let origin = moq_tokio::origin::spawn(); let _alpha = origin.create_broadcast("alpha").expect("alpha"); diff --git a/rs/moq-cli/src/fetch.rs b/rs/moq-cli/src/fetch.rs index 1ef750a79e5..08165b67250 100644 --- a/rs/moq-cli/src/fetch.rs +++ b/rs/moq-cli/src/fetch.rs @@ -250,7 +250,7 @@ mod tests { impl NetworkFixture { /// Publish [`Fixture`]'s `demo` through a relay that also holds `.hidden`. async fn new() -> Self { - let _ = moq_tokio::crypto::install_default(); + moq_tokio::crypto::install_default().unwrap(); let fixture = moq_relay::test_relay().await.expect("test relay"); // A dot-prefixed broadcast on the relay itself, like its `.stats`, which // announce listings hide unless asked for by name. diff --git a/rs/moq-cli/src/main.rs b/rs/moq-cli/src/main.rs index a2efb6f0a20..d748f1566eb 100644 --- a/rs/moq-cli/src/main.rs +++ b/rs/moq-cli/src/main.rs @@ -1270,7 +1270,7 @@ mod tests { impl Listening { async fn new(timeout: &str) -> Self { - let _ = moq_tokio::crypto::install_default(); + moq_tokio::crypto::install_default().unwrap(); let cli = Invocation::try_parse_from([ "moq", "--listen-tcp-bind", @@ -1536,7 +1536,7 @@ mod tests { /// drop without its close. #[tokio::test] async fn a_stream_bind_failure_starts_no_dial() { - let _ = moq_tokio::crypto::install_default(); + moq_tokio::crypto::install_default().unwrap(); let occupied = std::net::TcpListener::bind("127.0.0.1:0").expect("occupy a port"); let addr = occupied.local_addr().expect("occupied address").to_string(); let invocation = Invocation::try_parse_from([ @@ -1648,7 +1648,7 @@ mod tests { /// client TLS the way the relay does rather than refuse after validate. #[tokio::test] async fn cluster_api_url_http_attaches_client_tls() { - let _ = moq_tokio::crypto::install_default(); + moq_tokio::crypto::install_default().unwrap(); let invocation = Invocation::try_parse_from(["moq", "--cluster-api-url", "https://api.example/peers", "import", "ts"]) .expect("parse"); @@ -1673,7 +1673,7 @@ mod tests { /// port with a WAN cluster peer starts instead of colliding with itself. #[tokio::test] async fn a_fixed_connect_bind_with_a_cluster_peer_starts() { - let _ = moq_tokio::crypto::install_default(); + moq_tokio::crypto::install_default().unwrap(); // Borrow a free port from the OS, then hand it to `--connect-bind`. let bind = std::net::UdpSocket::bind("127.0.0.1:0") .expect("probe socket") diff --git a/rs/moq-cli/src/publish.rs b/rs/moq-cli/src/publish.rs index a2e10ff1581..07fb905d414 100644 --- a/rs/moq-cli/src/publish.rs +++ b/rs/moq-cli/src/publish.rs @@ -1655,7 +1655,7 @@ pub(crate) mod tests { let second = shifted(24, true); let input = [&lead[..], &second].concat(); - let _ = moq_tokio::crypto::install_default(); + moq_tokio::crypto::install_default().unwrap(); for version in ["moq-lite-06", "moq-lite-07-wip", "moq-transport-18"] { let fixture = moq_relay::test_relay().await.unwrap(); let ready = fixture.relay.ready(); diff --git a/rs/moq-cli/tests/integration/export.rs b/rs/moq-cli/tests/integration/export.rs index 18fe98c7da7..5d3efab29af 100644 --- a/rs/moq-cli/tests/integration/export.rs +++ b/rs/moq-cli/tests/integration/export.rs @@ -92,7 +92,7 @@ struct Relay { /// carries instances, for a client that opts in with `--connect-version`. Its generated /// certificate is trusted blindly, since nothing but loopback reaches it. async fn relay() -> Relay { - let _ = moq_tokio::crypto::install_default(); + moq_tokio::crypto::install_default().unwrap(); let mut config = moq_relay::Config::default(); config.drain_timeout = Some(Duration::ZERO.into()); config.listen.bind = Some("127.0.0.1:0".parse().unwrap()); diff --git a/rs/moq-cli/tests/integration/import.rs b/rs/moq-cli/tests/integration/import.rs index 11333ef629d..6a00c31c3db 100644 --- a/rs/moq-cli/tests/integration/import.rs +++ b/rs/moq-cli/tests/integration/import.rs @@ -58,7 +58,7 @@ fn import_as(url: &str, fingerprint: &str, global: &[&str], name: &str) -> Child #[tokio::test] async fn import_delivers_the_catalog_finish_at_eof() { - let _ = moq_tokio::crypto::install_default(); + moq_tokio::crypto::install_default().unwrap(); let fixture = moq_relay::test_relay().await.expect("test relay"); let ready = fixture.relay.ready(); tokio::spawn(fixture.relay.run()); @@ -136,7 +136,7 @@ const SHORT: &[u8] = include_bytes!("../../../moq-mux/src/container/ts/test_data /// for the linger after EOF. #[tokio::test] async fn a_short_import_drains_its_media_to_a_waiting_subscriber() { - let _ = moq_tokio::crypto::install_default(); + moq_tokio::crypto::install_default().unwrap(); let fixture = moq_relay::test_relay().await.expect("test relay"); let ready = fixture.relay.ready(); tokio::spawn(fixture.relay.run()); diff --git a/rs/moq-cli/tests/integration/instances.rs b/rs/moq-cli/tests/integration/instances.rs index c7e9fc16410..d1156764d71 100644 --- a/rs/moq-cli/tests/integration/instances.rs +++ b/rs/moq-cli/tests/integration/instances.rs @@ -22,7 +22,7 @@ impl Drop for Relay { } async fn relay() -> Relay { - let _ = moq_tokio::crypto::install_default(); + moq_tokio::crypto::install_default().unwrap(); let mut config = moq_relay::Config::default(); config.drain_timeout = Some(Duration::ZERO.into()); config.listen.bind = Some("127.0.0.1:0".parse().unwrap()); diff --git a/rs/moq-cli/tests/integration/listen.rs b/rs/moq-cli/tests/integration/listen.rs index 7fdcc2145a2..a20343a7a87 100644 --- a/rs/moq-cli/tests/integration/listen.rs +++ b/rs/moq-cli/tests/integration/listen.rs @@ -96,7 +96,7 @@ impl Listening { } async fn connects(listening: &Listening, stage: &str) -> (moq_tokio::Connection, moq_net::origin::Consumer) { - let _ = moq_tokio::crypto::install_default(); + moq_tokio::crypto::install_default().unwrap(); let origin = moq_tokio::origin::spawn(); let consumer = origin.consume().with_hidden(true); let client = moq_tokio::connect::Config::default() @@ -145,7 +145,7 @@ async fn listening_export_drains_publishers_on_sigterm() { async fn an_export_stage_ending_during_drain_waits_for_every_session() { let window = Duration::from_secs(3); let listening = listen("export", &["--drain-timeout", "3s"]).await; - let _ = moq_tokio::crypto::install_default(); + moq_tokio::crypto::install_default().unwrap(); let origin = moq_tokio::origin::spawn(); let source = origin.create_broadcast("demo.hang").unwrap(); let catalog = source.create_track("catalog.json", None).unwrap(); diff --git a/rs/moq-cli/tests/integration/report.rs b/rs/moq-cli/tests/integration/report.rs index 53f5bd782fc..d974ba05164 100644 --- a/rs/moq-cli/tests/integration/report.rs +++ b/rs/moq-cli/tests/integration/report.rs @@ -36,7 +36,7 @@ struct Relay { } async fn relay() -> Relay { - let _ = moq_tokio::crypto::install_default(); + moq_tokio::crypto::install_default().unwrap(); let fixture = moq_relay::test_relay().await.expect("test relay"); let ready = fixture.relay.ready(); tokio::spawn(fixture.relay.run()); diff --git a/rs/moq-cli/tests/integration/rtsp.rs b/rs/moq-cli/tests/integration/rtsp.rs index 5614767d01f..b1a048e3584 100644 --- a/rs/moq-cli/tests/integration/rtsp.rs +++ b/rs/moq-cli/tests/integration/rtsp.rs @@ -118,7 +118,7 @@ async fn finished(child: &mut Child, mut catalogs: hang::catalog::Consumer) { #[tokio::test] async fn every_rtsp_session_is_a_fresh_broadcast() { - let _ = moq_tokio::crypto::install_default(); + moq_tokio::crypto::install_default().unwrap(); let fixture = moq_relay::test_relay().await.expect("test relay"); let ready = fixture.relay.ready(); tokio::spawn(fixture.relay.run()); diff --git a/rs/moq-crypto/Cargo.toml b/rs/moq-crypto/Cargo.toml index 9497fbd21e2..ad079403164 100644 --- a/rs/moq-crypto/Cargo.toml +++ b/rs/moq-crypto/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "moq-crypto" -description = "Content signing and end-to-end encryption for MoQ broadcasts." +description = "Cryptography for MoQ: content signing, end-to-end encryption, and the rind provider the transports share." authors = ["Luke Curley "] repository = "https://github.com/moq-dev/moq" license = "MIT OR Apache-2.0" @@ -23,6 +23,9 @@ default = ["sign", "e2ee"] sign = ["dep:bytes", "dep:kio", "dep:moq-net", "dep:rind", "dep:zeroize"] # End-to-end encryption: the `e2ee` module. e2ee = ["dep:base64", "dep:bytes", "dep:kio", "dep:moq-net", "dep:rind", "dep:uuid", "dep:zeroize"] +# rind's rustls provider and CPU check, with the `UnsupportedCpu` error the transport crates +# share. Needs neither `moq-net` nor the other features, so moq-quic and moq-tokio can use it. +provider = ["dep:rind", "dep:rind-rustls", "dep:rustls"] # `sign::PublicKey` serializes as its canonical z-base-32 text. serde = ["dep:serde"] @@ -33,6 +36,8 @@ data-encoding = { workspace = true } kio = { workspace = true, optional = true } moq-net = { workspace = true, optional = true } rind = { workspace = true, optional = true } +rind-rustls = { workspace = true, optional = true } +rustls = { version = "0.23", default-features = false, features = ["std"], optional = true } serde = { workspace = true, optional = true } thiserror = { workspace = true } uuid = { workspace = true, optional = true } diff --git a/rs/moq-crypto/README.md b/rs/moq-crypto/README.md index 7419983584e..983db7842fb 100644 --- a/rs/moq-crypto/README.md +++ b/rs/moq-crypto/README.md @@ -2,17 +2,37 @@ # moq-crypto -Content signing and end-to-end encryption for [Media over QUIC](https://moq.dev): the `sign` -module signs every frame so relays cannot forge it, and the `e2ee` module encrypts groups, -datagrams, and track names so relays cannot read them. Both wrap `moq-net` and check timestamps -with its `track::Info::rescale`, so a frame either half accepts is one `moq-net` accepts. +Cryptography for [Media over QUIC](https://moq.dev): the `sign` module signs every frame so +relays cannot forge it, and the `e2ee` module encrypts groups, datagrams, and track names so +relays cannot read them. Both wrap `moq-net` and check timestamps with its +`track::Info::rescale`, so a frame either half accepts is one `moq-net` accepts. The `provider` +module is the [rind](https://github.com/moq-dev/rind) rustls provider and CPU check that the +MoQ transport crates share. ## Features `sign` and `e2ee`, both default, enable the two modules. With default features off, the crate is only `sign::PublicKey`, the endpoint ID, with its canonical z-base-32 text: it builds without `moq-net` or rind, for crates such as `moq-auth` that name endpoints but sign nothing. -`serde` adds the key's string serialization. +`serde` adds the key's string serialization. `provider`, off by default, enables the `provider` +module; it depends only on rind and rustls, never on `moq-net`, so the transport crates can +use it without a dependency cycle. + +## Provider + +MoQ runs all of its cryptography on rind. Its primitives panic on a CPU missing a feature rind +requires, so the `provider` module refuses such a CPU up front. Today that is NEON on aarch64; +every `x86_64` CPU and armv7 are supported, and a CPU without AES or other crypto extensions +runs rind's slower paths rather than being refused: + +- `provider::check()` returns `UnsupportedCpu`, naming the missing feature. +- `provider::provider()` returns rind's rustls `CryptoProvider`, or that error. It ignores the + process default, so TLS works whether or not one was installed. +- `provider::install_default()` installs rind as rustls' process default for libraries such as + reqwest that read it, leaving a provider the process already installed in place. + +moq-quic, moq-tokio, qmux, and moq-uring report the same `UnsupportedCpu`, and +`moq_tokio::crypto` re-exports this module's API. ## Signing diff --git a/rs/moq-crypto/src/lib.rs b/rs/moq-crypto/src/lib.rs index 53f52dd8151..0070d40b27d 100644 --- a/rs/moq-crypto/src/lib.rs +++ b/rs/moq-crypto/src/lib.rs @@ -1,16 +1,21 @@ -//! Content signing and end-to-end encryption for MoQ. +//! Cryptography for MoQ: content signing, end-to-end encryption, and the shared provider. //! //! [`sign`] signs every grouped frame so a relay can proxy and cache a broadcast without //! forging it. [`e2ee`] encrypts groups, datagrams, and track names so a relay forwards //! ciphertext it cannot read. Both wrap `moq-net` and check a frame's timestamp with //! `moq_net::track::Info::rescale`, so neither accepts a frame the net track would refuse. +//! [`provider`] is rind's rustls provider and CPU check, with the [`provider::UnsupportedCpu`] +//! error that moq-quic, moq-tokio, and the other transport crates report. //! -//! The `sign` and `e2ee` features, both default, gate those halves. Without them the crate holds -//! only [`sign::PublicKey`], the endpoint ID, and its canonical z-base-32 text, with no `moq-net` +//! The `sign` and `e2ee` features, both default, gate those halves; `provider`, off by default, +//! gates the provider and needs no `moq-net`. Without any of them the crate holds only +//! [`sign::PublicKey`], the endpoint ID, and its canonical z-base-32 text, with no `moq-net` //! or crypto backend; `serde` adds its string serialization. #![warn(missing_docs)] #[cfg(feature = "e2ee")] pub mod e2ee; +#[cfg(feature = "provider")] +pub mod provider; pub mod sign; diff --git a/rs/moq-crypto/src/provider.rs b/rs/moq-crypto/src/provider.rs new file mode 100644 index 00000000000..557432825cf --- /dev/null +++ b/rs/moq-crypto/src/provider.rs @@ -0,0 +1,59 @@ +//! rind, MoQ's one cryptography provider: the CPU check and its rustls provider. +//! +//! rind's primitives panic on a CPU missing a feature they require, so each entry point +//! here refuses such a CPU with [`UnsupportedCpu`] instead. The transport crates report +//! this one type, and rind stays out of their public APIs. + +use std::sync::{Arc, OnceLock}; + +/// A shared rustls crypto provider. +pub type Provider = Arc; + +/// This CPU lacks a feature that rind requires, named in the message. +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +#[error("unsupported CPU: {0}")] +pub struct UnsupportedCpu(rind::cpu::MissingFeature); + +/// Refuse a CPU that rind cannot run on, naming the missing feature. +/// +/// Call this before using rind's primitives directly; [`provider`] and +/// [`install_default`] run it themselves. +pub fn check() -> Result<(), UnsupportedCpu> { + rind::cpu::check().map_err(UnsupportedCpu) +} + +/// Return rind's rustls provider, refusing a CPU missing a required feature. +/// +/// The process default is not consulted, so TLS works whether or not one was installed. +pub fn provider() -> Result { + // CPU features never change while the process runs, so the first answer is the answer. + static PROVIDER: OnceLock> = OnceLock::new(); + PROVIDER + .get_or_init(|| rind_rustls::default_provider().map(Arc::new).map_err(UnsupportedCpu)) + .clone() +} + +/// Install rind as rustls' process default, for consumers such as reqwest that read it. +/// +/// Succeeds without replacing a provider the process already installed, which it is +/// entitled to; only an unsupported CPU fails. +pub fn install_default() -> Result<(), UnsupportedCpu> { + let _ = Arc::unwrap_or_clone(provider()?).install_default(); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn provider_is_shared() { + // The test hosts run rind, so the provider builds and every call returns the same one. + let first = provider().unwrap(); + assert!(Arc::ptr_eq(&first, &provider().unwrap())); + check().unwrap(); + install_default().unwrap(); + // A second install keeps the first provider and still succeeds. + install_default().unwrap(); + } +} diff --git a/rs/moq-hls/Cargo.toml b/rs/moq-hls/Cargo.toml index 3d2c94a8bbf..b729f140184 100644 --- a/rs/moq-hls/Cargo.toml +++ b/rs/moq-hls/Cargo.toml @@ -44,7 +44,7 @@ async-trait = { workspace = true } futures = { workspace = true } moq-archive = { path = "../moq-archive" } moq-json = { path = "../moq-json" } -moq-tokio = { path = "../moq-tokio", default-features = false, features = ["tcp", "quic", "aws-lc-rs"] } +moq-tokio = { path = "../moq-tokio", default-features = false, features = ["tcp", "quic"] } mp4-atom = { workspace = true } tempfile = { workspace = true } tokio = { workspace = true, features = ["test-util"] } diff --git a/rs/moq-quic/Cargo.toml b/rs/moq-quic/Cargo.toml index fa878be1fe4..a4ec4690d53 100644 --- a/rs/moq-quic/Cargo.toml +++ b/rs/moq-quic/Cargo.toml @@ -11,15 +11,8 @@ rust-version.workspace = true keywords = ["quic"] categories = ["network-programming", "asynchronous"] -[package.metadata.docs.rs] -features = ["rustls-aws-lc-rs", "ring"] - [features] -default = ["ring"] -aws-lc-rs = ["dep:aws-lc-rs", "aws-lc-rs?/aws-lc-sys", "aws-lc-rs?/prebuilt-nasm", "rustls/aws-lc-rs"] -# Enable rustls with the aws-lc-rs crypto provider. -rustls-aws-lc-rs = ["aws-lc-rs"] -ring = ["dep:ring", "rustls/ring"] +default = [] # Enable qlog support qlog = ["dep:qlog"] # The sans-IO QMux connection, which runs the stream state machine over a reliable, ordered @@ -31,13 +24,12 @@ mux = [] sim = [] # Exposes the `fuzz/` harness's target bodies, and the plaintext crypto the connection -# target and the benches run on, through the hidden `fuzz` module. ring keys the endpoint's +# target and the benches run on, through the hidden `fuzz` module. rind keys the endpoint's # reset and token secrets. Off by default and hidden from the docs. -fuzz = ["dep:arbitrary", "ring"] +fuzz = ["dep:arbitrary"] [dependencies] arbitrary = { version = "1.5", features = ["derive"], optional = true } -aws-lc-rs = { version = "1.9", default-features = false, optional = true } bytes = { workspace = true } fastbloom = { version = "0.17", default-features = false } indexmap = { workspace = true } @@ -46,9 +38,11 @@ indexmap = { workspace = true } kio = { workspace = true } lru-slab = "0.1.2" moq-congestion = { workspace = true } +# rind's rustls provider and the `UnsupportedCpu` error the transport crates share. +moq-crypto = { workspace = true, features = ["provider"] } qlog = { version = "0.18", optional = true } rand = { workspace = true } -ring = { version = "0.17", optional = true } +rind = { workspace = true } rustc-hash = { workspace = true } rustls = { version = "0.23.5", default-features = false, features = ["std"] } slab = { workspace = true } @@ -70,7 +64,9 @@ moq-congestion = { workspace = true, features = ["testing"] } moq-quic = { path = ".", features = ["mux"] } proptest = { workspace = true } rand_pcg = { workspace = true } -rcgen = { workspace = true, features = ["pem", "ring"] } +rcgen = { workspace = true, features = ["pem"] } +rind-rcgen = { workspace = true } +rind-rustls = { workspace = true } tracing-subscriber = { version = "0.3.0", default-features = false, features = ["env-filter", "fmt", "ansi", "time", "local-time"] } workspace-hack = { path = "../workspace-hack" } diff --git a/rs/moq-quic/MIGRATE.md b/rs/moq-quic/MIGRATE.md index 26f7f78e92f..7acb9c140bb 100644 --- a/rs/moq-quic/MIGRATE.md +++ b/rs/moq-quic/MIGRATE.md @@ -4,6 +4,21 @@ How to update your code for each breaking change, newest first. ## Unreleased +### Transport cryptography uses rind + +Remove the `ring`, `aws-lc-rs`, and `rustls-aws-lc-rs` Cargo features. rind is always enabled. +Build caller-supplied rustls configurations on `moq_crypto::provider::provider()?` (enable moq-crypto's `provider` feature) or `moq_tokio::crypto::provider()?`. + +A CPU missing a feature rind needs is reported as `moq_crypto::provider::UnsupportedCpu`, which names the feature: + +- Endpoint initialization returns `ConfigError::UnsupportedCpu`. +- `client::Config::with_root_certificates` now returns `rustls::Error` instead of `VerifierBuilderError`. Both the CPU refusal and a verifier builder failure arrive in `rustls::Error::Other`; downcast its inner error to `UnsupportedCpu` or `rustls::client::VerifierBuilderError`. +- `server::Config::with_single_cert` keeps its `rustls::Error` and reports the CPU refusal the same way, where it used to panic. + +Call `moq_crypto::provider::check()` before calling rind's primitives directly. + +QUIC packet protection, Retry integrity, reset tokens, and address-validation tokens keep their wire formats and derivation labels. + ### Receive operations wake transmission themselves ([#7707](https://github.com/moq-dev/moq/pull/7707)) `ShouldTransmit` is removed. `recv::Stream::lease` returns `Result` and @@ -48,7 +63,7 @@ Replace `crypto_session().peer_identity()` and its downcast with `conn.peer_iden `Connection::export_keying_material` and `transport_parameters` are no longer public. A rustls config without TLS 1.3 or the AES-128-GCM-SHA256 suite now fails each connection: the client's connect returns `ConnectError::Tls`, and the server closes the connection or drops its Initial. `ConnectError` no longer implements `Eq`. -rustls is a required dependency; the `ring` and `aws-lc-rs` features pick only the provider. +rustls is a required dependency; rind supplies transport cryptography. ### An evicted stream fails `received_reset` ([#7624](https://github.com/moq-dev/moq/pull/7624)) diff --git a/rs/moq-quic/src/cid_generator.rs b/rs/moq-quic/src/cid_generator.rs index 908e6747a31..379177bf8f5 100644 --- a/rs/moq-quic/src/cid_generator.rs +++ b/rs/moq-quic/src/cid_generator.rs @@ -166,13 +166,11 @@ impl ConnectionIdGenerator for RandomConnectionIdGenerator { /// /// This generator uses a non-cryptographic hash and can therefore still be spoofed, but nonetheless /// helps prevent the endpoint from responding to non-QUIC packets at very low cost. -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] pub struct HashedConnectionIdGenerator { key: u64, lifetime: Option, } -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] impl HashedConnectionIdGenerator { /// Create a generator with a random key pub fn new() -> Self { @@ -188,14 +186,12 @@ impl HashedConnectionIdGenerator { } } -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] impl Default for HashedConnectionIdGenerator { fn default() -> Self { Self::new() } } -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] impl ConnectionIdGenerator for HashedConnectionIdGenerator { fn generate_cid(&mut self) -> ConnectionId { use std::hash::Hasher; @@ -232,9 +228,7 @@ impl ConnectionIdGenerator for HashedConnectionIdGenerator { } } -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] const NONCE_LEN: usize = 3; // Good for more than 16 million connections -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] const SIGNATURE_LEN: usize = 8 - NONCE_LEN; // 8-byte total CID length #[cfg(test)] diff --git a/rs/moq-quic/src/config/client.rs b/rs/moq-quic/src/config/client.rs index debed151e96..3cf1001a9fd 100644 --- a/rs/moq-quic/src/config/client.rs +++ b/rs/moq-quic/src/config/client.rs @@ -2,11 +2,9 @@ use std::{fmt, sync::Arc}; -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] use rustls::client::WebPkiServerVerifier; -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] -use crate::crypto::rustls::{QuicClientConfig, configured_provider}; +use crate::crypto::rustls::{QuicClientConfig, provider}; use crate::{ MAX_CID_SIZE, RandomConnectionIdGenerator, TokenMemoryCache, TokenStore, Version, cid_generator::ConnectionIdGenerator, crypto, shared::ConnectionId, transport, @@ -47,7 +45,6 @@ impl Config { } } -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] impl Config { /// Run the handshake with `tls` and the default settings /// @@ -60,11 +57,17 @@ impl Config { } /// Dial trusting the specified trust anchors - pub fn with_root_certificates( - roots: Arc, - ) -> Result { - let verifier = WebPkiServerVerifier::builder_with_provider(roots, configured_provider()).build()?; - Ok(Self::new(Arc::new(QuicClientConfig::inner(verifier)))) + /// + /// A CPU that rind cannot run on, and a root store the verifier refuses, both arrive in + /// [`rustls::Error::Other`]: downcast it to + /// [`UnsupportedCpu`](moq_crypto::provider::UnsupportedCpu) or + /// [`VerifierBuilderError`](rustls::client::VerifierBuilderError). + pub fn with_root_certificates(roots: Arc) -> Result { + let provider = provider()?; + let verifier = WebPkiServerVerifier::builder_with_provider(roots, provider.clone()) + .build() + .map_err(|err| rustls::Error::Other(rustls::OtherError(Arc::new(err))))?; + Ok(Self::new(Arc::new(QuicClientConfig::inner(provider, verifier)))) } } diff --git a/rs/moq-quic/src/config/endpoint.rs b/rs/moq-quic/src/config/endpoint.rs index b94bcf5f155..51233fe7d30 100644 --- a/rs/moq-quic/src/config/endpoint.rs +++ b/rs/moq-quic/src/config/endpoint.rs @@ -112,35 +112,23 @@ impl Config { /// The settings an endpoint runs on, with every default filled in, and its connection ID /// generator - #[cfg(any(feature = "aws-lc-rs", feature = "ring"))] pub(crate) fn resolve(&self) -> Result<(Resolved, Box), ConfigError> { - #[cfg(all(feature = "aws-lc-rs", not(feature = "ring")))] - use aws_lc_rs::{hkdf, hmac}; use rand::Rng; - #[cfg(feature = "ring")] - use ring::{hkdf, hmac}; + use rind::{hkdf, hmac}; use crate::cid_generator::HashedConnectionIdGenerator; - struct Len(usize); - impl hkdf::KeyType for Len { - fn len(&self) -> usize { - self.0 - } - } - self.validate()?; + moq_crypto::provider::check()?; let (reset_key, cid_key, min_reset_interval): (Arc, _, _) = match &self.reset_secret { Some(secret) => { - let prk = hkdf::Salt::new(hkdf::HKDF_SHA256, &[]).extract(secret); - let reset_key = prk - .expand(&[b"moq-quic reset key"], hmac::HMAC_SHA256) - .expect("an HMAC key fits HKDF-SHA256"); + let prk = hkdf::Salt::new(&hkdf::HKDF_SHA256, &[]).extract(secret); + let reset_key = prk.expand(&[b"moq-quic reset key"], &hmac::HMAC_SHA256); let mut cid_key = [0; 8]; - prk.expand(&[b"moq-quic cid key"], Len(cid_key.len())) - .and_then(|okm| okm.fill(&mut cid_key)) + prk.expand(&[b"moq-quic cid key"], cid_key.len()) + .fill(&mut cid_key) .expect("8 bytes fit HKDF-SHA256"); ( Arc::new(hmac::Key::from(reset_key)), @@ -152,7 +140,7 @@ impl Config { let mut reset_key = [0; 64]; crate::entropy::rng().fill_bytes(&mut reset_key); ( - Arc::new(hmac::Key::new(hmac::HMAC_SHA256, &reset_key)), + Arc::new(hmac::Key::new(&hmac::HMAC_SHA256, &reset_key)), None, Duration::from_millis(20), ) diff --git a/rs/moq-quic/src/config/mod.rs b/rs/moq-quic/src/config/mod.rs index 04eefc6f92d..174dbb92677 100644 --- a/rs/moq-quic/src/config/mod.rs +++ b/rs/moq-quic/src/config/mod.rs @@ -23,4 +23,7 @@ pub enum ConfigError { /// The maximum UDP payload size is outside 1200 to 65527 bytes #[error("max UDP payload size out of range")] MaxUdpPayloadSize, + /// This CPU lacks a feature that rind, the transport's cryptography, requires + #[error(transparent)] + UnsupportedCpu(#[from] moq_crypto::provider::UnsupportedCpu), } diff --git a/rs/moq-quic/src/config/server/mod.rs b/rs/moq-quic/src/config/server/mod.rs index 428d138d985..61afb2643f9 100644 --- a/rs/moq-quic/src/config/server/mod.rs +++ b/rs/moq-quic/src/config/server/mod.rs @@ -6,10 +6,8 @@ use std::{ sync::Arc, }; -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] use rustls::pki_types::{CertificateDer, PrivateKeyDer}; -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] use crate::crypto::rustls::QuicServerConfig; use crate::{ Duration, @@ -90,7 +88,6 @@ pub struct Config { pub(crate) token_key: Arc, } -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] impl Config { /// Run the handshake with `tls`, with the default settings and a random handshake token key /// @@ -102,16 +99,13 @@ impl Config { /// Serve any crypto, such as the fuzz target's plaintext pub(crate) fn from_crypto(crypto: Arc) -> Self { - #[cfg(all(feature = "aws-lc-rs", not(feature = "ring")))] - use aws_lc_rs::hkdf; use rand::Rng; - #[cfg(feature = "ring")] - use ring::hkdf; + use rind::hkdf; let rng = &mut crate::entropy::rng(); let mut master_key = [0u8; 64]; rng.fill_bytes(&mut master_key); - let token_key = hkdf::Salt::new(hkdf::HKDF_SHA256, &[]).extract(&master_key); + let token_key = hkdf::Salt::new(&hkdf::HKDF_SHA256, &[]).extract(&master_key); Self { transport: transport::Config::default(), @@ -129,6 +123,9 @@ impl Config { } /// Present `cert_chain`, signed for by `key`, with the default settings + /// + /// A CPU that rind cannot run on arrives in [`rustls::Error::Other`]: downcast it to + /// [`UnsupportedCpu`](moq_crypto::provider::UnsupportedCpu). pub fn with_single_cert( cert_chain: Vec>, key: PrivateKeyDer<'static>, diff --git a/rs/moq-quic/src/connection/mod.rs b/rs/moq-quic/src/connection/mod.rs index 0d420a238d4..a0d9551cefc 100644 --- a/rs/moq-quic/src/connection/mod.rs +++ b/rs/moq-quic/src/connection/mod.rs @@ -4526,10 +4526,16 @@ mod tests { endpoint::{self, Dial, Endpoint}, }; - #[cfg(feature = "ring")] #[test] fn large_initial_token_leaves_room_for_close() { - let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap(); + let cert = (|| -> std::result::Result<_, rcgen::Error> { + let signing_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?; + let mut params = rcgen::CertificateParams::new(vec!["localhost".into()])?; + params.serial_number = Some(1u64.into()); + let cert = params.self_signed(&signing_key)?; + Ok(rcgen::CertifiedKey { cert, signing_key }) + })() + .unwrap(); let mut roots = rustls::RootCertStore::empty(); roots.add(cert.cert.der().clone()).unwrap(); let config = client::Config::with_root_certificates(Arc::new(roots)).unwrap(); diff --git a/rs/moq-quic/src/crypto.rs b/rs/moq-quic/src/crypto.rs index 8452aa20982..7a49936e139 100644 --- a/rs/moq-quic/src/crypto.rs +++ b/rs/moq-quic/src/crypto.rs @@ -1,6 +1,6 @@ //! What a connection's TLS handshake negotiated. //! -//! The handshake runs on rustls with ring or aws-lc-rs. The traits here are crate-private: +//! The handshake runs on rustls with rind. The traits here are crate-private: //! rustls is their one real implementation, and the plaintext one behind the `fuzz` feature //! serves the fuzz target and the benchmarks. @@ -14,11 +14,9 @@ use crate::{ transport_parameters::TransportParameters, }; -/// Cryptography interface based on *ring* -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] -mod ring_like; +/// Reset and token cryptography from rind. +mod rind; /// TLS interface based on rustls -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] pub(crate) mod rustls; /// What the handshake negotiated, available once the connection's `poll_handshake_data` is ready. diff --git a/rs/moq-quic/src/crypto/rind.rs b/rs/moq-quic/src/crypto/rind.rs new file mode 100644 index 00000000000..6b073944c77 --- /dev/null +++ b/rs/moq-quic/src/crypto/rind.rs @@ -0,0 +1,34 @@ +use rind::{aead, hkdf, hmac}; + +use crate::crypto::{self, CryptoError}; + +impl crypto::HmacKey for hmac::Key { + fn sign(&self, data: &[u8], out: &mut [u8]) { + out.copy_from_slice(hmac::sign(self, data).as_ref()); + } + + fn signature_len(&self) -> usize { + 32 + } +} + +impl crypto::HandshakeTokenKey for hkdf::Prk { + fn aead_from_hkdf(&self, random_bytes: &[u8]) -> Box { + Box::new(aead::Key::from(self.expand(&[random_bytes], &aead::AES_256_GCM))) + } +} + +impl crypto::AeadKey for aead::Key { + fn seal(&self, data: &mut Vec, additional_data: &[u8]) -> Result<(), CryptoError> { + // Each token derives its own key from a fresh random salt, so its nonce is zero. + let nonce = aead::Nonce::assume_unique_for_key([0; 12]); + self.seal_in_place_append_tag(nonce, additional_data, data) + .map_err(|_| CryptoError) + } + + fn open<'a>(&self, data: &'a mut [u8], additional_data: &[u8]) -> Result<&'a mut [u8], CryptoError> { + let nonce = aead::Nonce::assume_unique_for_key([0; 12]); + self.open_in_place(nonce, additional_data, data) + .map_err(|_| CryptoError) + } +} diff --git a/rs/moq-quic/src/crypto/ring_like.rs b/rs/moq-quic/src/crypto/ring_like.rs deleted file mode 100644 index e669f1d8dcf..00000000000 --- a/rs/moq-quic/src/crypto/ring_like.rs +++ /dev/null @@ -1,49 +0,0 @@ -#[cfg(all(feature = "aws-lc-rs", not(feature = "ring")))] -use aws_lc_rs::{aead, error, hkdf, hmac}; -#[cfg(feature = "ring")] -use ring::{aead, error, hkdf, hmac}; - -use crate::crypto::{self, CryptoError}; - -impl crypto::HmacKey for hmac::Key { - fn sign(&self, data: &[u8], out: &mut [u8]) { - out.copy_from_slice(hmac::sign(self, data).as_ref()); - } - - fn signature_len(&self) -> usize { - 32 - } -} - -impl crypto::HandshakeTokenKey for hkdf::Prk { - fn aead_from_hkdf(&self, random_bytes: &[u8]) -> Box { - let mut key_buffer = [0u8; 32]; - let info = [random_bytes]; - let okm = self.expand(&info, hkdf::HKDF_SHA256).unwrap(); - - okm.fill(&mut key_buffer).unwrap(); - - let key = aead::UnboundKey::new(&aead::AES_256_GCM, &key_buffer).unwrap(); - Box::new(aead::LessSafeKey::new(key)) - } -} - -impl crypto::AeadKey for aead::LessSafeKey { - fn seal(&self, data: &mut Vec, additional_data: &[u8]) -> Result<(), CryptoError> { - let aad = aead::Aad::from(additional_data); - let zero_nonce = aead::Nonce::assume_unique_for_key([0u8; 12]); - Ok(self.seal_in_place_append_tag(zero_nonce, aad, data)?) - } - - fn open<'a>(&self, data: &'a mut [u8], additional_data: &[u8]) -> Result<&'a mut [u8], CryptoError> { - let aad = aead::Aad::from(additional_data); - let zero_nonce = aead::Nonce::assume_unique_for_key([0u8; 12]); - Ok(self.open_in_place(zero_nonce, aad, data)?) - } -} - -impl From for CryptoError { - fn from(_: error::Unspecified) -> Self { - Self - } -} diff --git a/rs/moq-quic/src/crypto/rustls.rs b/rs/moq-quic/src/crypto/rustls.rs index b69c875df1f..0ec294af475 100644 --- a/rs/moq-quic/src/crypto/rustls.rs +++ b/rs/moq-quic/src/crypto/rustls.rs @@ -1,10 +1,7 @@ use std::{io, str, sync::Arc}; -#[cfg(all(feature = "aws-lc-rs", not(feature = "ring")))] -use aws_lc_rs::aead; use bytes::BytesMut; -#[cfg(feature = "ring")] -use ring::aead; +use rind::aead; use rustls::{ self, client::danger::ServerCertVerifier, @@ -160,10 +157,10 @@ impl crypto::Session for TlsSession { }; let nonce = aead::Nonce::assume_unique_for_key(nonce); - let key = aead::LessSafeKey::new(aead::UnboundKey::new(&aead::AES_128_GCM, &key).unwrap()); + 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, aead::Aad::from(aad), tag).is_ok() + key.open_in_place(nonce, aad, tag).is_ok() } fn export_keying_material( @@ -231,9 +228,12 @@ impl QuicClientConfig { Self { inner, initial } } - /// A TLS 1.3 config on this crate's provider that verifies the server with `verifier`. - pub(crate) fn inner(verifier: Arc) -> rustls::ClientConfig { - rustls::ClientConfig::builder_with_provider(configured_provider()) + /// A TLS 1.3 config on `provider` that verifies the server with `verifier`. + pub(crate) fn inner( + provider: Arc, + verifier: Arc, + ) -> rustls::ClientConfig { + rustls::ClientConfig::builder_with_provider(provider) .with_protocol_versions(&[&rustls::version::TLS13]) .unwrap() // The default providers support TLS 1.3 .dangerous() @@ -288,7 +288,7 @@ impl QuicServerConfig { cert_chain: Vec>, key: PrivateKeyDer<'static>, ) -> Result { - rustls::ServerConfig::builder_with_provider(configured_provider()) + rustls::ServerConfig::builder_with_provider(provider()?) .with_protocol_versions(&[&rustls::version::TLS13]) .unwrap() // The default providers support TLS 1.3 .with_no_client_auth() @@ -344,11 +344,9 @@ impl crypto::ServerConfig for QuicServerConfig { pseudo_packet.extend_from_slice(packet); let nonce = aead::Nonce::assume_unique_for_key(nonce); - let key = aead::LessSafeKey::new(aead::UnboundKey::new(&aead::AES_128_GCM, &key).unwrap()); + let key = aead::Key::new(&aead::AES_128_GCM, &key).unwrap(); - let tag = key - .seal_in_place_separate_tag(nonce, aead::Aad::from(pseudo_packet), &mut []) - .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 @@ -373,12 +371,13 @@ fn no_initial_suite() -> rustls::Error { rustls::Error::General("the provider lacks TLS13_AES_128_GCM_SHA256, which QUIC Initial packets need".into()) } -pub(crate) fn configured_provider() -> Arc { - #[cfg(all(feature = "aws-lc-rs", not(feature = "ring")))] - let provider = rustls::crypto::aws_lc_rs::default_provider(); - #[cfg(feature = "ring")] - let provider = rustls::crypto::ring::default_provider(); - Arc::new(provider) +/// rind's provider, with a CPU it cannot run on reported as a rustls error. +/// +/// The convenience constructors return rustls errors already; the refusal stays typed inside +/// [`rustls::Error::Other`], so a caller can downcast it to +/// [`UnsupportedCpu`](moq_crypto::provider::UnsupportedCpu). +pub(crate) fn provider() -> Result, rustls::Error> { + moq_crypto::provider::provider().map_err(|err| rustls::Error::Other(rustls::OtherError(Arc::new(err)))) } fn to_vec(params: &TransportParameters) -> Vec { @@ -482,11 +481,18 @@ mod tests { /// caller's shared configs retain their original policy. #[test] fn supplied_configs_reject_early_data_and_keep_resumption() { - let identity = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap(); + let identity = (|| -> std::result::Result<_, rcgen::Error> { + let signing_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?; + let mut params = rcgen::CertificateParams::new(vec!["localhost".to_string()])?; + params.serial_number = Some(1u64.into()); + let cert = params.self_signed(&signing_key)?; + Ok(rcgen::CertifiedKey { cert, signing_key }) + })() + .unwrap(); let cert = identity.cert.der().clone(); let mut roots = rustls::RootCertStore::empty(); roots.add(cert.clone()).unwrap(); - let mut client = rustls::ClientConfig::builder_with_provider(configured_provider()) + let mut client = rustls::ClientConfig::builder_with_provider(provider().unwrap()) .with_protocol_versions(&[&rustls::version::TLS13]) .unwrap() .with_root_certificates(roots) @@ -494,7 +500,7 @@ mod tests { client.enable_early_data = true; let mut server = QuicServerConfig::inner( vec![cert], - PrivateKeyDer::Pkcs8(identity.signing_key.serialize_der().into()), + PrivateKeyDer::Pkcs8(identity.signing_key.to_pkcs8().secret_pkcs8_der().to_vec().into()), ) .unwrap(); server.max_early_data_size = u32::MAX; @@ -523,12 +529,19 @@ mod tests { /// another provider's suite. #[test] fn provider_without_initial_suite_fails_connections() { - let mut provider = (*configured_provider()).clone(); + let mut provider = (*super::provider().unwrap()).clone(); provider .cipher_suites .retain(|suite| suite.suite() != rustls::CipherSuite::TLS13_AES_128_GCM_SHA256); let provider = Arc::new(provider); - let identity = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap(); + let identity = (|| -> std::result::Result<_, rcgen::Error> { + let signing_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?; + let mut params = rcgen::CertificateParams::new(vec!["localhost".to_string()])?; + params.serial_number = Some(1u64.into()); + let cert = params.self_signed(&signing_key)?; + Ok(rcgen::CertifiedKey { cert, signing_key }) + })() + .unwrap(); let client = rustls::ClientConfig::builder_with_provider(provider.clone()) .with_protocol_versions(&[&rustls::version::TLS13]) @@ -546,7 +559,7 @@ mod tests { .with_no_client_auth() .with_single_cert( vec![identity.cert.der().clone()], - PrivateKeyDer::Pkcs8(identity.signing_key.serialize_der().into()), + PrivateKeyDer::Pkcs8(identity.signing_key.to_pkcs8().secret_pkcs8_der().to_vec().into()), ) .unwrap(); let server = QuicServerConfig::new(Arc::new(server)); diff --git a/rs/moq-quic/src/endpoint.rs b/rs/moq-quic/src/endpoint.rs index bb77d8a1f1c..7b5739f67b0 100644 --- a/rs/moq-quic/src/endpoint.rs +++ b/rs/moq-quic/src/endpoint.rs @@ -70,7 +70,6 @@ impl Endpoint { /// /// Errors on a configuration [`Config::validate`] refuses. Panics if the endpoint cannot be /// seeded from the operating system random source. - #[cfg(any(feature = "aws-lc-rs", feature = "ring"))] pub fn new(config: Config, allow_mtud: bool) -> Result { use rand::SeedableRng; diff --git a/rs/moq-quic/src/entropy.rs b/rs/moq-quic/src/entropy.rs index 55b52eb04dc..fd5203181de 100644 --- a/rs/moq-quic/src/entropy.rs +++ b/rs/moq-quic/src/entropy.rs @@ -10,7 +10,7 @@ pub(crate) fn rng() -> rand::rngs::ThreadRng { /// A generator seeded straight from the OS, not the thread rng, so forked processes diverge /// /// Panics if the OS random source fails. -#[cfg(all(not(test), any(feature = "aws-lc-rs", feature = "ring")))] +#[cfg(not(test))] pub(crate) fn std_rng() -> rand::rngs::StdRng { use rand::SeedableRng; rand::rngs::StdRng::try_from_rng(&mut rand::rngs::SysRng) @@ -21,7 +21,7 @@ pub(crate) fn std_rng() -> rand::rngs::StdRng { pub(crate) use seeded::{rng, std_rng}; // Only the crate's `tests` module reseeds, and it needs a rustls provider. -#[cfg(all(test, any(feature = "aws-lc-rs", feature = "ring")))] +#[cfg(test)] pub(crate) use seeded::reseed; #[cfg(test)] diff --git a/rs/moq-quic/src/lib.rs b/rs/moq-quic/src/lib.rs index 95b7f7db9c0..a62ddf3ea40 100644 --- a/rs/moq-quic/src/lib.rs +++ b/rs/moq-quic/src/lib.rs @@ -13,14 +13,6 @@ #![warn(missing_docs)] #![cfg_attr(test, allow(dead_code, reason = "test builds compile helpers only some tests call"))] -#![cfg_attr( - not(any(feature = "aws-lc-rs", feature = "ring")), - allow( - dead_code, - unused_imports, - reason = "without a crypto provider only the mux connection is reachable" - ) -)] use std::{ net::{IpAddr, SocketAddr}, @@ -32,8 +24,8 @@ mod coding; mod constant_time; mod entropy; // Not part of the public API: compiled only for the crate's own tests, the benches, and -// the `fuzz/` harness. The connection target needs ring or aws-lc-rs for the endpoint's keys. -#[cfg(all(any(test, feature = "fuzz"), any(feature = "aws-lc-rs", feature = "ring")))] +// the `fuzz/` harness. The connection target uses rind for the endpoint's keys. +#[cfg(any(test, feature = "fuzz"))] #[doc(hidden)] pub mod fuzz; mod range_set; @@ -41,7 +33,7 @@ mod range_set; #[cfg(any(test, feature = "sim"))] #[doc(hidden)] pub mod sim; -#[cfg(all(test, any(feature = "aws-lc-rs", feature = "ring")))] +#[cfg(test)] mod tests; mod transport_parameters; mod varint; diff --git a/rs/moq-quic/src/packet.rs b/rs/moq-quic/src/packet.rs index 97e7b83d07a..ba1ce19535e 100644 --- a/rs/moq-quic/src/packet.rs +++ b/rs/moq-quic/src/packet.rs @@ -965,15 +965,14 @@ mod tests { } } - #[cfg(any(feature = "aws-lc-rs", feature = "ring"))] #[test] fn header_encoding() { use crate::Side; - use crate::crypto::rustls::{configured_provider, initial_keys, initial_suite}; + use crate::crypto::rustls::{initial_keys, initial_suite, provider}; use rustls::quic::Version; let dcid = ConnectionId::new(&hex!("06b858ec6f80452b")); - let suite = initial_suite(&configured_provider()).unwrap(); + let suite = initial_suite(&provider().unwrap()).unwrap(); let client = initial_keys(Version::V1, dcid, Side::Client, &suite); let mut buf = Vec::new(); let header = Header::Initial(InitialHeader { diff --git a/rs/moq-quic/src/tests/mod.rs b/rs/moq-quic/src/tests/mod.rs index 24bcd2fccfa..05d4f708ab7 100644 --- a/rs/moq-quic/src/tests/mod.rs +++ b/rs/moq-quic/src/tests/mod.rs @@ -16,10 +16,7 @@ use assert_matches::assert_matches; use bytes::{Buf, Bytes, BytesMut}; use hex_literal::hex; use rand::Rng; -#[cfg(all(feature = "aws-lc-rs", not(feature = "ring")))] -use rustls::crypto::aws_lc_rs::default_provider; -#[cfg(feature = "ring")] -use rustls::crypto::ring::default_provider; +use rind_rustls::default_provider; use rustls::{ AlertDescription, RootCertStore, pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer}, @@ -332,7 +329,10 @@ fn connect_before_the_finished_leaves(pair: &mut Pair, config: client::Config) - #[test] fn close_before_a_client_certificate_leaves_ends() { let _guard = subscribe(); - let provider = Arc::new(default_provider()); + // Keep the server flight in the packet layout this close-packet sweep measures. + let mut provider = default_provider().unwrap(); + provider.kx_groups = vec![rind_rustls::kx_group::X25519]; + let provider = Arc::new(provider); let mut roots = RootCertStore::empty(); roots.add(CERTIFIED_KEY.cert.der().clone()).unwrap(); @@ -342,7 +342,14 @@ fn close_before_a_client_certificate_leaves_ends() { let mut names = vec!["localhost".to_string()]; names.extend((0..len / 50).map(|i| format!("{i:03}{}.test", "a".repeat(42)))); names.push(format!("{}.test", "b".repeat(len % 50 + 1))); - let identity = rcgen::generate_simple_self_signed(names).unwrap(); + let identity = (|| -> std::result::Result<_, rcgen::Error> { + let signing_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?; + let mut params = rcgen::CertificateParams::new(names)?; + params.serial_number = Some(1u64.into()); + let cert = params.self_signed(&signing_key)?; + Ok(rcgen::CertifiedKey { cert, signing_key }) + })() + .unwrap(); let mut store = RootCertStore::empty(); store.add(identity.cert.der().clone()).unwrap(); @@ -356,7 +363,7 @@ fn close_before_a_client_certificate_leaves_ends() { ) .with_single_cert( vec![CERTIFIED_KEY.cert.der().clone()], - PrivatePkcs8KeyDer::from(CERTIFIED_KEY.signing_key.serialize_der()).into(), + PrivatePkcs8KeyDer::from(CERTIFIED_KEY.signing_key.to_pkcs8().secret_pkcs8_der().to_vec()).into(), ) .unwrap(); let client = rustls::ClientConfig::builder_with_provider(provider.clone()) @@ -365,7 +372,7 @@ fn close_before_a_client_certificate_leaves_ends() { .with_root_certificates(roots.clone()) .with_client_auth_cert( vec![identity.cert.der().clone()], - PrivatePkcs8KeyDer::from(identity.signing_key.serialize_der()).into(), + PrivatePkcs8KeyDer::from(identity.signing_key.to_pkcs8().secret_pkcs8_der().to_vec()).into(), ) .unwrap(); let mut client = client::Config::new(Arc::new(client)); @@ -1024,11 +1031,18 @@ fn reject_self_signed_server_cert() { // Create a self-signed certificate with a different distinguished name than the default one, // such that path building cannot confuse the default root the server is using and the one // the client is trusting (in which case we'd get a different error). - let mut cert = rcgen::CertificateParams::new(["localhost".into()]).unwrap(); + let mut cert = rcgen::CertificateParams::new(["localhost".into()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .unwrap(); let mut issuer = rcgen::DistinguishedName::new(); issuer.push(rcgen::DnType::OrganizationName, "Crazy Quinn's House of Certificates"); cert.distinguished_name = issuer; - let cert = cert.self_signed(&rcgen::KeyPair::generate().unwrap()).unwrap(); + let cert = cert + .self_signed(&rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap()) + .unwrap(); let client_ch = pair.begin_connect(client_config_with_certs(vec![cert.into()])); pair.drive(); @@ -1047,10 +1061,10 @@ fn reject_missing_client_cert() { // because it's convenient. store.add(CERTIFIED_KEY.cert.der().clone()).unwrap(); - let key = PrivatePkcs8KeyDer::from(CERTIFIED_KEY.signing_key.serialize_der()); + let key = PrivatePkcs8KeyDer::from(CERTIFIED_KEY.signing_key.to_pkcs8().secret_pkcs8_der().to_vec()); let cert = CERTIFIED_KEY.cert.der().clone(); - let provider = Arc::new(default_provider()); + let provider = Arc::new(default_provider().unwrap()); let config = rustls::ServerConfig::builder_with_provider(provider.clone()) .with_protocol_versions(&[&rustls::version::TLS13]) .unwrap() @@ -4170,17 +4184,23 @@ fn server_can_send_3_inital_packets() { /// Generate a big fat certificate that can't fit inside the initial anti-amplification limit fn big_cert_and_key() -> (CertificateDer<'static>, PrivateKeyDer<'static>) { - let cert = rcgen::generate_simple_self_signed( - Some("localhost".into()) - .into_iter() - .chain((0..1000).map(|x| format!("foo_{x}"))) - .collect::>(), - ) + let cert = (|| -> std::result::Result<_, rcgen::Error> { + let signing_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?; + let mut params = rcgen::CertificateParams::new( + Some("localhost".into()) + .into_iter() + .chain((0..1000).map(|x| format!("foo_{x}"))) + .collect::>(), + )?; + params.serial_number = Some(1u64.into()); + let cert = params.self_signed(&signing_key)?; + Ok(rcgen::CertifiedKey { cert, signing_key }) + })() .unwrap(); ( cert.cert.into(), - PrivateKeyDer::Pkcs8(cert.signing_key.serialize_der().into()), + PrivateKeyDer::Pkcs8(cert.signing_key.to_pkcs8().secret_pkcs8_der().to_vec().into()), ) } diff --git a/rs/moq-quic/src/tests/util.rs b/rs/moq-quic/src/tests/util.rs index bc832f7411f..0b0b9c4bee5 100644 --- a/rs/moq-quic/src/tests/util.rs +++ b/rs/moq-quic/src/tests/util.rs @@ -15,12 +15,11 @@ use bytes::BytesMut; use rand::{SeedableRng, rngs::StdRng}; use rustls::{ KeyLogFile, - client::WebPkiServerVerifier, pki_types::{CertificateDer, PrivateKeyDer}, }; use tracing::{debug_span, trace}; -use super::crypto::rustls::{QuicClientConfig, QuicServerConfig, configured_provider}; +use super::crypto::rustls::QuicServerConfig; use super::*; pub(super) use crate::sim::{Bottleneck, Link, QueueStats}; use crate::{Duration, Instant, entropy}; @@ -754,7 +753,7 @@ fn server_crypto_inner( let (cert, key) = identity.unwrap_or_else(|| { ( CERTIFIED_KEY.cert.der().clone(), - PrivateKeyDer::Pkcs8(CERTIFIED_KEY.signing_key.serialize_der().into()), + PrivateKeyDer::Pkcs8(CERTIFIED_KEY.signing_key.to_pkcs8().secret_pkcs8_der().to_vec().into()), ) }); @@ -814,11 +813,15 @@ fn client_crypto_inner( roots.add(cert).unwrap(); } - let mut inner = QuicClientConfig::inner( - WebPkiServerVerifier::builder_with_provider(Arc::new(roots), configured_provider()) - .build() - .unwrap(), - ); + // Packet-layout tests depend on a ClientHello that fits in one Initial. + // Integration tests exercise rind's default hybrid key share. + let mut provider = rind_rustls::default_provider().unwrap(); + provider.kx_groups = vec![rind_rustls::kx_group::X25519]; + let mut inner = rustls::ClientConfig::builder_with_provider(Arc::new(provider)) + .with_protocol_versions(&[&rustls::version::TLS13]) + .unwrap() + .with_root_certificates(roots) + .with_no_client_auth(); inner.key_log = Arc::new(KeyLogFile::new()); if let Some(alpn) = alpn { inner.alpn_protocols = alpn; @@ -880,8 +883,16 @@ fn set_congestion_experienced(x: Option, congestion_experienced: b }) } -pub(crate) static CERTIFIED_KEY: LazyLock> = - LazyLock::new(|| rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap()); +pub(crate) static CERTIFIED_KEY: LazyLock> = LazyLock::new(|| { + (|| -> std::result::Result<_, rcgen::Error> { + let signing_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?; + let mut params = rcgen::CertificateParams::new(vec!["localhost".into()])?; + params.serial_number = Some(1u64.into()); + let cert = params.self_signed(&signing_key)?; + Ok(rcgen::CertifiedKey { cert, signing_key }) + })() + .unwrap() +}); #[derive(Default)] struct SimpleTokenLog(Mutex>); diff --git a/rs/moq-quic/src/token.rs b/rs/moq-quic/src/token.rs index d88fb7e8167..e49a7932972 100644 --- a/rs/moq-quic/src/token.rs +++ b/rs/moq-quic/src/token.rs @@ -397,20 +397,17 @@ impl fmt::Display for ResetToken { } } -#[cfg(all(test, any(feature = "aws-lc-rs", feature = "ring")))] +#[cfg(test)] mod test { use super::*; - #[cfg(all(feature = "aws-lc-rs", not(feature = "ring")))] - use aws_lc_rs::hkdf; - #[cfg(feature = "ring")] - use ring::hkdf; + use rind::hkdf; fn token_round_trip(payload: TokenPayload) -> TokenPayload { let rng = &mut rand::rng(); let token = Token::new(payload, rng); let mut master_key = [0; 64]; rng.fill_bytes(&mut master_key); - let prk = hkdf::Salt::new(hkdf::HKDF_SHA256, &[]).extract(&master_key); + let prk = hkdf::Salt::new(&hkdf::HKDF_SHA256, &[]).extract(&master_key); let encoded = token.encode(&prk); let decoded = Token::decode(&prk, &encoded).expect("token didn't decrypt / decode"); assert_eq!(token.nonce, decoded.nonce); @@ -494,7 +491,7 @@ mod test { let mut master_key = [0; 64]; rng.fill_bytes(&mut master_key); - let prk = hkdf::Salt::new(hkdf::HKDF_SHA256, &[]).extract(&master_key); + let prk = hkdf::Salt::new(&hkdf::HKDF_SHA256, &[]).extract(&master_key); let mut invalid_token = Vec::new(); diff --git a/rs/moq-relay/Cargo.toml b/rs/moq-relay/Cargo.toml index d81179214eb..2eb1bb4c3bd 100644 --- a/rs/moq-relay/Cargo.toml +++ b/rs/moq-relay/Cargo.toml @@ -53,9 +53,8 @@ _uring = ["dep:moq-sock", "dep:moq-uring"] [dependencies] anyhow = { workspace = true, features = ["backtrace"] } -aws-lc-rs = { workspace = true } axum = { workspace = true } -axum-server = { workspace = true, features = ["tls-rustls"] } +axum-server = { workspace = true, features = ["tls-rustls-no-provider"] } bytes = { workspace = true } bytesize = "2.4.2" futures = { workspace = true } @@ -74,14 +73,15 @@ moq-net = { workspace = true } # The flow-control limits both QUIC runtimes take, for widening a peer's connection. moq-quic = { workspace = true } moq-stats = { workspace = true } -moq-tokio = { workspace = true, default-features = false, features = ["aws-lc-rs", "watch", "tcp"] } +moq-tokio = { workspace = true, default-features = false, features = ["watch", "tcp"] } # The /metrics text encoder; the protobuf features stay off. prometheus-client = "0.25.1" qmux = { workspace = true, features = ["ws"], optional = true } rand = { workspace = true } -reqwest = { workspace = true, features = ["rustls"] } +reqwest = { workspace = true, features = ["rustls-no-provider"] } reqwest-middleware = "0.5" -rustls = { version = "0.23", features = ["aws-lc-rs"], default-features = false } +rind = { workspace = true } +rustls = { version = "0.23", features = ["std"], default-features = false } serde = { workspace = true } serde_json = { workspace = true } serde_with = { workspace = true, features = ["json", "base64"] } @@ -114,8 +114,11 @@ moq-congestion = { path = "../moq-congestion" } # The shared session bench fills FETCH runs through the hidden `fuzz` module. moq-net = { path = "../moq-net", features = ["fuzz"] } moq-shaper = { path = "../moq-shaper", features = ["test"] } +pem = { workspace = true } qmux = { workspace = true, features = ["tcp"] } -rcgen = { workspace = true, features = ["pem", "ring"] } +rcgen = { workspace = true, features = ["pem"] } +rind-rcgen = { workspace = true } +rind-rustls = { workspace = true } stun-types = { workspace = true } tempfile = { workspace = true } # Runs the tests that need a variable set or unset in a child process given it. diff --git a/rs/moq-relay/MIGRATE.md b/rs/moq-relay/MIGRATE.md index 9708c6063e3..33b11c7f8c5 100644 --- a/rs/moq-relay/MIGRATE.md +++ b/rs/moq-relay/MIGRATE.md @@ -5,6 +5,13 @@ Rolling a cluster across a release also follows the [upgrade guide](https://moq. ## Unreleased +### Transport and HTTP cryptography use rind + +The relay checks rind CPU support at startup, including `Relay::load` for embedders. +Its HTTP clients and HTTPS listener use rustls without enabling another crypto provider. +x86\_64 CPUs without crypto extensions and aarch64 Raspberry Pi 4, CM4, and Zero 2 W remain supported through rind's software paths; aarch64 requires NEON and armv7 remains supported. +No configuration or wire format changes. + ### Built-in ACME is removed ([#7803](https://github.com/moq-dev/moq/pull/7803)) Remove the `acme` Cargo feature, `[acme]` table, `--acme-*` flags, and `MOQ_ACME_*` variables. diff --git a/rs/moq-relay/benches/auth.rs b/rs/moq-relay/benches/auth.rs index 820540fc0be..2925cb48d69 100644 --- a/rs/moq-relay/benches/auth.rs +++ b/rs/moq-relay/benches/auth.rs @@ -34,7 +34,7 @@ impl Drop for Fixture { impl Fixture { async fn new(sessions: usize, tokens: usize) -> Self { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let (auth, mut admissions) = auth::Auth::embedded("bench"); let (send, mut receive) = tokio::sync::mpsc::unbounded_channel(); let decider = tokio::spawn(async move { @@ -165,7 +165,7 @@ impl Drop for Queue { impl Queue { async fn new() -> Self { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let (auth, mut admissions) = auth::Auth::embedded("bench"); let mut config = moq_tokio::listen::Config::default(); config.tcp.bind = Some("127.0.0.1:0".parse().unwrap()); diff --git a/rs/moq-relay/benches/http_auth.rs b/rs/moq-relay/benches/http_auth.rs index 910b7b1182f..b67b5f70d94 100644 --- a/rs/moq-relay/benches/http_auth.rs +++ b/rs/moq-relay/benches/http_auth.rs @@ -28,7 +28,7 @@ impl Drop for Fixture { impl Fixture { async fn new(connections: usize, streams: usize, server: bool) -> Self { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let waiting = kio::Shared::new(0usize); let (auth, decider) = if server { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); @@ -57,10 +57,16 @@ impl Fixture { (auth, decider) }; - let pem = rcgen::generate_simple_self_signed(vec!["localhost".into()]) - .unwrap() - .cert - .pem(); + let pem = (|| -> std::result::Result<_, rcgen::Error> { + let signing_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?; + let mut params = rcgen::CertificateParams::new(vec!["localhost".into()])?; + params.serial_number = Some(1u64.into()); + let cert = params.self_signed(&signing_key)?; + Ok(rcgen::CertifiedKey { cert, signing_key }) + })() + .unwrap() + .cert + .pem(); let certificates = moq_tokio::tls::Certificates::from_pem(pem.as_bytes()).unwrap(); let mut config = web::Config::default(); config.http.listen = Some("127.0.0.1:0".parse().unwrap()); diff --git a/rs/moq-relay/examples/embed.rs b/rs/moq-relay/examples/embed.rs index d1723206c92..06629de8e54 100644 --- a/rs/moq-relay/examples/embed.rs +++ b/rs/moq-relay/examples/embed.rs @@ -20,7 +20,8 @@ use moq_relay::{Config, Relay}; #[tokio::main] async fn main() -> anyhow::Result<()> { - rustls::crypto::aws_lc_rs::default_provider() + rind_rustls::default_provider() + .unwrap() .install_default() .expect("failed to install default crypto provider"); diff --git a/rs/moq-relay/src/cluster.rs b/rs/moq-relay/src/cluster.rs index c220f1e24f7..5686ddc3818 100644 --- a/rs/moq-relay/src/cluster.rs +++ b/rs/moq-relay/src/cluster.rs @@ -3759,7 +3759,7 @@ mod tests { #[tokio::test] async fn remote_plaintext_api_refuses_startup() { - let _ = moq_tokio::crypto::install_default(); + moq_tokio::crypto::install_default().unwrap(); for url in ["http://api.example.com/", "http://192.0.2.1/", "http://[2001:db8::1]/"] { let mut config = Config::default(); config.api.url = Some(url.into()); @@ -3792,7 +3792,7 @@ mod tests { #[tokio::test] async fn cluster_api_rejects_redirect_bodies() { use tokio::io::{AsyncReadExt, AsyncWriteExt}; - let _ = moq_tokio::crypto::install_default(); + moq_tokio::crypto::install_default().unwrap(); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let url = format!("http://{}/", listener.local_addr().unwrap()).parse().unwrap(); let server = async move { @@ -3821,7 +3821,7 @@ mod tests { #[tokio::test] async fn lan_cluster_path_carries_broadcasts_both_ways() { const TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); - let _ = moq_tokio::crypto::install_default(); + moq_tokio::crypto::install_default().unwrap(); let node = new_cluster(Config::default()).expect("node cluster"); let fingerprint = new_cluster(Config::default()).expect("fingerprint cluster"); @@ -3912,7 +3912,7 @@ mod tests { /// dropping it releases its client rather than leaving it to `close`. #[tokio::test] async fn a_failed_start_leaves_the_dial_bind_free() { - let _ = moq_tokio::crypto::install_default(); + moq_tokio::crypto::install_default().unwrap(); let dir = tempfile::tempdir().expect("tempdir"); let token = dir.path().join("token"); let config = Config { @@ -3948,8 +3948,12 @@ mod tests { idle: std::time::Duration, ) -> moq_tokio::quic::driver::endpoint::Endpoint { use moq_tokio::quic::driver; - let key = rcgen::KeyPair::generate().expect("keypair"); + let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).expect("keypair"); let cert = rcgen::CertificateParams::new(vec!["localhost".to_string()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) .expect("cert params") .self_signed(&key) .expect("self-signed cert"); @@ -3957,7 +3961,7 @@ mod tests { .with_no_client_auth() .with_single_cert( vec![cert.der().clone()], - rustls::pki_types::PrivateKeyDer::Pkcs8(key.serialize_der().into()), + rustls::pki_types::PrivateKeyDer::Pkcs8(key.to_pkcs8().secret_pkcs8_der().to_vec().into()), ) .expect("server tls"); tls.alpn_protocols = connect @@ -3984,7 +3988,7 @@ mod tests { async fn cancelling_run_stops_its_dynamic_dials() { const TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); const IDLE: std::time::Duration = std::time::Duration::from_secs(300); - let _ = moq_tokio::crypto::install_default(); + moq_tokio::crypto::install_default().unwrap(); let mut connect = moq_tokio::connect::Config::default(); connect.tls.insecure = Some(true); @@ -4033,7 +4037,7 @@ mod tests { use moq_tokio::quic::driver; const TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); const IDLE: std::time::Duration = std::time::Duration::from_secs(300); - let _ = moq_tokio::crypto::install_default(); + moq_tokio::crypto::install_default().unwrap(); let mut connect = moq_tokio::connect::Config::default(); connect.tls.insecure = Some(true); @@ -4132,7 +4136,7 @@ mod tests { async fn closing_a_cluster_closes_its_lan_dials() { const TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); const IDLE: std::time::Duration = std::time::Duration::from_secs(300); - let _ = moq_tokio::crypto::install_default(); + moq_tokio::crypto::install_default().unwrap(); let mut quic = moq_tokio::quic::Config::default(); quic.idle_timeout = Some((IDLE).into()); diff --git a/rs/moq-relay/src/http_client.rs b/rs/moq-relay/src/http_client.rs index cdf2c5b67a0..26eeca91c16 100644 --- a/rs/moq-relay/src/http_client.rs +++ b/rs/moq-relay/src/http_client.rs @@ -57,14 +57,15 @@ pub(crate) fn server_tls( #[cfg(test)] mod tests { use super::*; - use rcgen::{CertificateParams, KeyPair}; + use rcgen::CertificateParams; + use rind_rcgen::KeyPair; use rustls::pki_types::PrivateKeyDer; use std::{path::PathBuf, sync::Arc}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; #[tokio::test] async fn cluster_api_refuses_redirects() { - let _ = moq_tokio::crypto::install_default(); + moq_tokio::crypto::install_default().unwrap(); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); let server = async move { @@ -88,7 +89,7 @@ mod tests { #[tokio::test] async fn auth_trust_is_independent_from_mesh_verification() { - let _ = moq_tokio::crypto::install_default(); + moq_tokio::crypto::install_default().unwrap(); let dir = tempfile::tempdir().unwrap(); let ca = Authority::new("mesh"); let (cert, key) = ca.leaf("127.0.0.1"); @@ -98,7 +99,7 @@ mod tests { .with_no_client_auth() .with_single_cert( vec![cert.der().clone()], - PrivateKeyDer::Pkcs8(key.serialize_der().into()), + PrivateKeyDer::Pkcs8(key.to_pkcs8().secret_pkcs8_der().to_vec().into()), ) .unwrap(); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); @@ -109,7 +110,7 @@ mod tests { "root" => mesh.root = vec![root.clone()], "fingerprint" => { mesh.fingerprint = vec![hex::encode( - aws_lc_rs::digest::digest(&aws_lc_rs::digest::SHA256, cert.der()).as_ref(), + rind::digest::digest(&rind::digest::SHA256, cert.der()).as_ref(), )] } _ => unreachable!(), @@ -194,8 +195,13 @@ mod tests { impl Authority { fn new(name: &str) -> Self { - let key = KeyPair::generate().unwrap(); - let mut params = CertificateParams::new(Vec::::new()).unwrap(); + let key = KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap(); + let mut params = CertificateParams::new(Vec::::new()) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .unwrap(); params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained); params.distinguished_name.push(rcgen::DnType::CommonName, name); let cert = params.self_signed(&key).unwrap(); @@ -203,8 +209,13 @@ mod tests { } fn leaf(&self, name: &str) -> (rcgen::Certificate, KeyPair) { - let key = KeyPair::generate().unwrap(); - let params = CertificateParams::new(vec![name.to_string()]).unwrap(); + let key = KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap(); + let params = CertificateParams::new(vec![name.to_string()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .unwrap(); let cert = params .signed_by(&key, &rcgen::Issuer::from_params(&self.params, &self.key)) .unwrap(); @@ -253,7 +264,7 @@ mod tests { #[tokio::test] async fn peer_api_trust_is_independent_and_keeps_cluster_identity() { - let _ = moq_tokio::crypto::install_default(); + moq_tokio::crypto::install_default().unwrap(); let dir = tempfile::tempdir().unwrap(); let mesh = Authority::new("mesh"); let api = Authority::new("API"); @@ -267,7 +278,13 @@ mod tests { let mut config = moq_tokio::tls::Connect::default(); config.root = vec![write("mesh.pem", mesh.cert.pem())]; config.cert = Some(write("client.pem", identity.pem())); - config.key = Some(write("client-key.pem", identity_key.serialize_pem())); + config.key = Some(write( + "client-key.pem", + pem::encode(&pem::Pem::new( + "PRIVATE KEY", + identity_key.to_pkcs8().secret_pkcs8_der(), + )), + )); let mesh_tls = config.build().unwrap(); let api_root = write("api.pem", api.cert.pem()); let mut roots = rustls::RootCertStore::empty(); @@ -279,7 +296,7 @@ mod tests { .with_client_cert_verifier(verifier) .with_single_cert( vec![server_cert.der().clone()], - PrivateKeyDer::Pkcs8(server_key.serialize_der().into()), + PrivateKeyDer::Pkcs8(server_key.to_pkcs8().secret_pkcs8_der().to_vec().into()), ) .unwrap(); @@ -313,7 +330,7 @@ mod tests { .with_client_cert_verifier(verifier) .with_single_cert( vec![mesh_server_cert.der().clone()], - PrivateKeyDer::Pkcs8(mesh_server_key.serialize_der().into()), + PrivateKeyDer::Pkcs8(mesh_server_key.to_pkcs8().secret_pkcs8_der().to_vec().into()), ) .unwrap(); assert!( diff --git a/rs/moq-relay/src/main.rs b/rs/moq-relay/src/main.rs index 63c45416daa..39c9eb70058 100644 --- a/rs/moq-relay/src/main.rs +++ b/rs/moq-relay/src/main.rs @@ -6,7 +6,7 @@ static ALLOC: moq_tokio::jemalloc::tikv_jemallocator::Jemalloc = moq_tokio::jema #[tokio::main] async fn main() -> anyhow::Result<()> { - moq_tokio::crypto::install_default().expect("failed to install default crypto provider"); + moq_tokio::crypto::install_default()?; // The whole startup sequence lives in `Relay::load` rather than here, so an // embedder gets it by calling one function instead of copying this file. diff --git a/rs/moq-relay/src/relay.rs b/rs/moq-relay/src/relay.rs index 9165c6aa2e5..fe8cc106b97 100644 --- a/rs/moq-relay/src/relay.rs +++ b/rs/moq-relay/src/relay.rs @@ -136,6 +136,7 @@ impl Relay { /// the cache governor and stats publisher, is only stored, and no session is admitted until /// [`Self::run`] drives both. pub async fn load(config: Config) -> anyhow::Result { + moq_tokio::crypto::check()?; // Keep the large debug state machine off the embedder's main-thread stack. Box::pin(Self::load_inner(config)).await } diff --git a/rs/moq-relay/src/uring.rs b/rs/moq-relay/src/uring.rs index 8cd10800b80..0c8537601cc 100644 --- a/rs/moq-relay/src/uring.rs +++ b/rs/moq-relay/src/uring.rs @@ -983,7 +983,7 @@ mod tests { /// Unsupported listen settings fail before loading TLS or binding a socket. #[test] fn bind_refuses_preferred_addresses() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + moq_tokio::crypto::install_default().unwrap(); type Set = fn(&mut moq_tokio::listen::Config); let cases: [(&str, Set); 2] = [ ("listen.preferred_v4", |listen| { @@ -1011,7 +1011,7 @@ mod tests { /// The workers refuse what the tokio listener refuses, before binding a socket. #[test] fn bind_refuses_an_invalid_listen() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + moq_tokio::crypto::install_default().unwrap(); let mut server = moq_tokio::server::Config::default(); server.listen.bind = Some("127.0.0.1:0".parse().unwrap()); server.listen.tls.generate = vec!["localhost".into()]; @@ -1121,7 +1121,7 @@ mod tests { /// the workers waiting to serve instead of hanging on their join. #[tokio::test] async fn a_group_stopped_before_serving_joins() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + moq_tokio::crypto::install_default().unwrap(); if let Err(moq_uring::Error::Unsupported(reason)) = moq_uring::Worker::new(Default::default()) && std::env::var_os("CI_STRICT").is_none() { @@ -1148,7 +1148,7 @@ mod tests { /// An auth decision still pending at the drain deadline is abandoned by then. #[tokio::test] async fn pending_admission_is_abandoned_at_the_deadline() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + moq_tokio::crypto::install_default().unwrap(); if let Err(moq_uring::Error::Unsupported(reason)) = moq_uring::Worker::new(Default::default()) && std::env::var_os("CI_STRICT").is_none() { @@ -1157,14 +1157,22 @@ mod tests { } let dir = tempfile::tempdir().unwrap(); - let key = rcgen::KeyPair::generate().unwrap(); + let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap(); let cert = rcgen::CertificateParams::new(vec!["localhost".to_string()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) .unwrap() .self_signed(&key) .unwrap(); let (cert_path, key_path) = (dir.path().join("cert.pem"), dir.path().join("key.pem")); std::fs::write(&cert_path, cert.pem()).unwrap(); - std::fs::write(&key_path, key.serialize_pem()).unwrap(); + std::fs::write( + &key_path, + pem::encode(&pem::Pem::new("PRIVATE KEY", key.to_pkcs8().secret_pkcs8_der())), + ) + .unwrap(); let window = std::time::Duration::from_secs(1); let mut config = crate::Config::default(); @@ -1207,7 +1215,7 @@ mod tests { /// that never comes is abandoned at the handshake deadline. #[tokio::test] async fn pending_admission_is_abandoned_at_the_handshake_deadline() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + moq_tokio::crypto::install_default().unwrap(); if let Err(moq_uring::Error::Unsupported(reason)) = moq_uring::Worker::new(Default::default()) && std::env::var_os("CI_STRICT").is_none() { @@ -1216,14 +1224,22 @@ mod tests { } let dir = tempfile::tempdir().unwrap(); - let key = rcgen::KeyPair::generate().unwrap(); + let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap(); let cert = rcgen::CertificateParams::new(vec!["localhost".to_string()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) .unwrap() .self_signed(&key) .unwrap(); let (cert_path, key_path) = (dir.path().join("cert.pem"), dir.path().join("key.pem")); std::fs::write(&cert_path, cert.pem()).unwrap(); - std::fs::write(&key_path, key.serialize_pem()).unwrap(); + std::fs::write( + &key_path, + pem::encode(&pem::Pem::new("PRIVATE KEY", key.to_pkcs8().secret_pkcs8_der())), + ) + .unwrap(); let timeout = std::time::Duration::from_secs(1); let mut config = crate::Config::default(); diff --git a/rs/moq-relay/src/web.rs b/rs/moq-relay/src/web.rs index 5f438e228ef..d466df34519 100644 --- a/rs/moq-relay/src/web.rs +++ b/rs/moq-relay/src/web.rs @@ -1206,7 +1206,14 @@ mod tests { #[cfg(all(feature = "websocket", any(unix, windows)))] fn acceptor_state() -> Arc { let cluster = cluster::Cluster::spawn(crate::cluster::Options::default()).unwrap(); - let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap(); + let cert = (|| -> std::result::Result<_, rcgen::Error> { + let signing_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?; + let mut params = rcgen::CertificateParams::new(vec!["localhost".into()])?; + params.serial_number = Some(1u64.into()); + let cert = params.self_signed(&signing_key)?; + Ok(rcgen::CertifiedKey { cert, signing_key }) + })() + .unwrap(); let certificates = moq_tokio::tls::Certificates::from_pem(cert.cert.pem().as_bytes()).unwrap(); Web::new( crate::auth::Auth::refuse("test"), @@ -1216,7 +1223,8 @@ mod tests { ) .state } - use rcgen::{CertificateParams, KeyPair}; + use rcgen::CertificateParams; + use rind_rcgen::KeyPair; use std::io::Write; use tempfile::TempDir; use tokio::io::{AsyncRead, AsyncWrite}; @@ -1671,17 +1679,27 @@ mod tests { /// Generate a CA + server cert/key on disk and return the temp paths. /// Modeled after `auth.rs::mtls_fixture`. fn make_named_certs(dir: &TempDir, name: &str, hostname: &str) -> (PathBuf, PathBuf, PathBuf) { - let _ = moq_tokio::crypto::install_default(); + moq_tokio::crypto::install_default().unwrap(); - let ca_kp = KeyPair::generate().unwrap(); - let mut ca_params = CertificateParams::new(vec![]).unwrap(); + let ca_kp = KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap(); + let mut ca_params = CertificateParams::new(vec![]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .unwrap(); ca_params.distinguished_name.push(rcgen::DnType::CommonName, "Test CA"); ca_params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained); let ca_cert = ca_params.self_signed(&ca_kp).unwrap(); let ca_issuer = rcgen::Issuer::from_params(&ca_params, &ca_kp); - let server_kp = KeyPair::generate().unwrap(); - let mut server_params = CertificateParams::new(vec![hostname.to_string()]).unwrap(); + let server_kp = KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap(); + let mut server_params = CertificateParams::new(vec![hostname.to_string()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .unwrap(); server_params .distinguished_name .push(rcgen::DnType::CommonName, format!("test-{name}")); @@ -1692,7 +1710,11 @@ mod tests { let key_path = dir.path().join(format!("{name}.key.pem")); std::fs::write(&ca_path, ca_cert.pem()).unwrap(); std::fs::write(&cert_path, server_cert.pem()).unwrap(); - std::fs::write(&key_path, server_kp.serialize_pem()).unwrap(); + std::fs::write( + &key_path, + pem::encode(&pem::Pem::new("PRIVATE KEY", server_kp.to_pkcs8().secret_pkcs8_der())), + ) + .unwrap(); (ca_path, cert_path, key_path) } diff --git a/rs/moq-relay/tests/drills.rs b/rs/moq-relay/tests/drills.rs index f02c381762f..6ba8ce2dfbc 100644 --- a/rs/moq-relay/tests/drills.rs +++ b/rs/moq-relay/tests/drills.rs @@ -222,7 +222,7 @@ impl RelayHost { /// Bind a relay running `config` and wait for it to be ready to accept. async fn start(config: Config) -> Self { // Process-global; every drill in this binary races to be first. - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let runtime = tokio::runtime::Builder::new_multi_thread() .worker_threads(2) diff --git a/rs/moq-relay/tests/integration/auth_lifetime.rs b/rs/moq-relay/tests/integration/auth_lifetime.rs index fbbbad0c383..5e7b2b85dd3 100644 --- a/rs/moq-relay/tests/integration/auth_lifetime.rs +++ b/rs/moq-relay/tests/integration/auth_lifetime.rs @@ -183,7 +183,7 @@ async fn spawn_relay_config( cluster: cluster::Cluster, mut config: moq_tokio::listen::Config, ) -> (u16, tokio::task::JoinHandle<()>) { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); config.tcp.bind = Some("127.0.0.1:0".parse().expect("parse addr")); // Opt in to lite-07 beside the defaults, so a client pinned to it can reach the AUTH stream. config.version = moq_net::Versions::all() @@ -220,7 +220,7 @@ async fn spawn_ws_relay_with( auth: moq_relay::auth::Auth, cluster: cluster::Cluster, ) -> (u16, tokio::task::JoinHandle<()>) { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); // Stream listeners bind lazily, so this server never opens a socket; only // its certificate handle is used. @@ -379,7 +379,7 @@ async fn spawn_quic_relay_with( root: Option, cluster: cluster::Cluster, ) -> (std::net::SocketAddr, tokio::task::JoinHandle<()>) { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let mut config = moq_tokio::listen::Config::default(); config.bind = Some("127.0.0.1:0".parse().unwrap()); config.tls.generate = vec!["localhost".into()]; @@ -1211,7 +1211,7 @@ async fn the_drain_waits_for_a_closed_session_to_report_its_end() { /// with a client certificate, and over WebSocket where none can be presented. #[tokio::test] async fn a_certificate_admits_only_what_the_server_grants() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let dir = tempfile::tempdir().expect("tempdir"); let (root, client_cert, client_key) = signed_client(dir.path()); @@ -1305,7 +1305,7 @@ async fn an_mtls_client_ingests_here() { /// The source the relay records for a broadcast announced over a certificate /// session, admitted by `moq auth serve` with the peer link role when requested. async fn mtls_route_source(mtls_peer: bool) -> moq_net::origin::Source { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let dir = tempfile::tempdir().expect("tempdir"); let (root, client_cert, client_key) = signed_client(dir.path()); @@ -1354,8 +1354,13 @@ async fn mtls_route_source(mtls_peer: bool) -> moq_net::origin::Source { } fn signed_client(dir: &std::path::Path) -> (std::path::PathBuf, std::path::PathBuf, std::path::PathBuf) { - let ca_key = rcgen::KeyPair::generate().expect("ca keypair"); - let mut ca_params = rcgen::CertificateParams::new(Vec::new()).expect("ca params"); + let ca_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).expect("ca keypair"); + let mut ca_params = rcgen::CertificateParams::new(Vec::new()) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .expect("ca params"); ca_params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained); ca_params.key_usages = vec![rcgen::KeyUsagePurpose::KeyCertSign, rcgen::KeyUsagePurpose::CrlSign]; ca_params @@ -1363,8 +1368,13 @@ fn signed_client(dir: &std::path::Path) -> (std::path::PathBuf, std::path::PathB .push(rcgen::DnType::CommonName, "moq test ca"); let ca = rcgen::CertifiedIssuer::self_signed(ca_params, ca_key).expect("self-signed ca"); - let key = rcgen::KeyPair::generate().expect("client keypair"); - let mut params = rcgen::CertificateParams::new(vec!["client.localhost".to_string()]).expect("client params"); + let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).expect("client keypair"); + let mut params = rcgen::CertificateParams::new(vec!["client.localhost".to_string()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .expect("client params"); params.use_authority_key_identifier_extension = true; params.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::ClientAuth]; let cert = params.signed_by(&key, &ca).expect("signed client cert"); @@ -1374,7 +1384,11 @@ fn signed_client(dir: &std::path::Path) -> (std::path::PathBuf, std::path::PathB let key_path = dir.join("client.key.pem"); std::fs::write(&root_path, ca.pem()).expect("write ca"); std::fs::write(&cert_path, cert.pem()).expect("write client cert"); - std::fs::write(&key_path, key.serialize_pem()).expect("write client key"); + std::fs::write( + &key_path, + pem::encode(&pem::Pem::new("PRIVATE KEY", key.to_pkcs8().secret_pkcs8_der())), + ) + .expect("write client key"); (root_path, cert_path, key_path) } @@ -1563,7 +1577,7 @@ async fn closes_at_expires(clock: &kio::clock::Installed, consumer: moq_auth::le /// decider's grant admits sessions through the assembled relay. #[tokio::test] async fn a_relay_without_an_auth_source_is_decided_by_the_embedder() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let config = || { let mut config = Config::default(); config.listen.tcp.bind = Some("127.0.0.1:0".parse().expect("parse addr")); @@ -1606,7 +1620,7 @@ async fn connect_through_embedded_admission( auth::Admissions, tokio::task::JoinHandle>, ) { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let mut config = Config::default(); config.listen.tcp.bind = Some("127.0.0.1:0".parse().expect("parse addr")); config.listen.timeout = Some((timeout).into()); diff --git a/rs/moq-relay/tests/integration/bitrate_caps.rs b/rs/moq-relay/tests/integration/bitrate_caps.rs index 366683f4c68..a37938144e5 100644 --- a/rs/moq-relay/tests/integration/bitrate_caps.rs +++ b/rs/moq-relay/tests/integration/bitrate_caps.rs @@ -211,7 +211,7 @@ async fn window_opens_once_admitted(mut relay: Relay, port: u16) { } async fn tokio_relay() -> (Relay, u16, tempfile::TempDir) { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let dir = tempfile::tempdir().expect("tempdir"); let relay = Relay::load(config(dir.path())) .await @@ -235,7 +235,7 @@ async fn tokio_window_opens_once_admitted() { #[cfg(all(target_os = "linux", feature = "_uring"))] async fn uring_relay() -> Option<(Relay, u16, tempfile::TempDir)> { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); match moq_uring::Worker::new(Default::default()) { Ok(_) => {} Err(moq_uring::Error::Unsupported(reason)) if std::env::var_os("CI_STRICT").is_none() => { diff --git a/rs/moq-relay/tests/integration/cluster_close.rs b/rs/moq-relay/tests/integration/cluster_close.rs index 290d07f752b..fcb9b1a7ff1 100644 --- a/rs/moq-relay/tests/integration/cluster_close.rs +++ b/rs/moq-relay/tests/integration/cluster_close.rs @@ -60,7 +60,7 @@ async fn assert_closed_by_shutdown(conn: driver::connection::Connection) { #[tokio::test] async fn closing_a_cluster_closes_its_static_dials() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let (connect, quic) = dial_template(); let server = bare_server(&connect); @@ -127,7 +127,7 @@ async fn closing_a_cluster_ends_its_websocket_dials() { #[tokio::test] async fn a_relay_shutdown_closes_its_cluster_dials() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let (connect, quic) = dial_template(); let server = bare_server(&connect); diff --git a/rs/moq-relay/tests/integration/cluster_fresh_port.rs b/rs/moq-relay/tests/integration/cluster_fresh_port.rs index 0d0bbb17cbb..dd43dc458aa 100644 --- a/rs/moq-relay/tests/integration/cluster_fresh_port.rs +++ b/rs/moq-relay/tests/integration/cluster_fresh_port.rs @@ -132,7 +132,7 @@ fn an_unbounded_budget_still_leaves_the_dropped_port() { /// Dial through a proxy that drops the first flow, with `budget` as the /// configured backoff timeout and `effective` as the one a mesh dial runs. async fn dropped_flow_recovers(budget: Duration, effective: Duration) { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let peer = spawn_peer().await; let (proxy, sources) = spawn_proxy(peer).await; diff --git a/rs/moq-relay/tests/integration/cluster_idle.rs b/rs/moq-relay/tests/integration/cluster_idle.rs index 9841f4a75c4..4696495b809 100644 --- a/rs/moq-relay/tests/integration/cluster_idle.rs +++ b/rs/moq-relay/tests/integration/cluster_idle.rs @@ -90,7 +90,7 @@ fn silent_peer_detected_within_idle_timeout() { } async fn silent_peer_detected() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let (port, peer) = spawn_peer().await; diff --git a/rs/moq-relay/tests/integration/cluster_unknown.rs b/rs/moq-relay/tests/integration/cluster_unknown.rs index fb576f82429..829e76a78a6 100644 --- a/rs/moq-relay/tests/integration/cluster_unknown.rs +++ b/rs/moq-relay/tests/integration/cluster_unknown.rs @@ -29,7 +29,7 @@ struct Node { } async fn spawn_relay(id: u64, connect: Vec, cluster_version: Option) -> Node { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let mut config = Config::default(); config.listen.tcp.bind = Some("127.0.0.1:0".parse().expect("parse bind")); diff --git a/rs/moq-relay/tests/integration/embed.rs b/rs/moq-relay/tests/integration/embed.rs index c0522fdbda8..270a199a0c2 100644 --- a/rs/moq-relay/tests/integration/embed.rs +++ b/rs/moq-relay/tests/integration/embed.rs @@ -25,13 +25,22 @@ fn timed() -> moq_net::track::Info { const TIMEOUT: Duration = Duration::from_secs(10); fn certificate(dir: &std::path::Path) -> (std::path::PathBuf, std::path::PathBuf) { - let key = rcgen::KeyPair::generate().expect("keypair"); - let params = rcgen::CertificateParams::new(vec!["localhost".to_string()]).expect("cert params"); + let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).expect("keypair"); + let params = rcgen::CertificateParams::new(vec!["localhost".to_string()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .expect("cert params"); let cert = params.self_signed(&key).expect("self-signed cert"); let cert_path = dir.join("cert.pem"); let key_path = dir.join("key.pem"); std::fs::write(&cert_path, cert.pem()).expect("write cert"); - std::fs::write(&key_path, key.serialize_pem()).expect("write key"); + std::fs::write( + &key_path, + pem::encode(&pem::Pem::new("PRIVATE KEY", key.to_pkcs8().secret_pkcs8_der())), + ) + .expect("write key"); (cert_path, key_path) } @@ -151,7 +160,7 @@ async fn stop(trigger: moq_relay::shutdown::Trigger, running: tokio::task::JoinH /// Load, mount a custom route, clone the origin, run the owner, prove QUIC /// plus HTTP, then stop it through the trigger and prove its sockets closed. async fn embed_and_stop(mut config: Config) { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); // No drain window: the sessions are already gone by the time the owner // stops, and the test should not wait out the default. @@ -433,7 +442,7 @@ async fn uring_custom_route_and_quic() { /// The WebRTC media path on the QUIC port reaches the embedder's feed, whichever /// worker read it, and the feed's reply leaves from the QUIC port. async fn webrtc_feed(mut config: Config) { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); config.drain_timeout = Some((Duration::ZERO).into()); let relay = Relay::load(config).await.expect("load relay").with_signals(false); let quic = relay.quic_addr().expect("quic listener bound"); diff --git a/rs/moq-relay/tests/integration/goaway_cluster.rs b/rs/moq-relay/tests/integration/goaway_cluster.rs index 1e90d7fe9ba..9035e470b4f 100644 --- a/rs/moq-relay/tests/integration/goaway_cluster.rs +++ b/rs/moq-relay/tests/integration/goaway_cluster.rs @@ -113,7 +113,7 @@ fn drain_session_with_zero_timeout_closes_at_once() { /// the wire, so passing the window straight through left the session with no /// force-close at all and `drain_session` awaiting a peer that never leaves. async fn drain_session_with_zero_timeout_closes_at_once_inner() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let origin = moq_tokio::origin::spawn(); let (port, mut accepted, _handle) = spawn_upstream(origin).await; @@ -149,7 +149,7 @@ fn cluster_continues_a_group_split_by_goaway() { /// A GOAWAY that lands mid-group hands the rest of the group to the reader already /// holding it, and the next group after it, never the split group a second time. async fn cluster_continues_a_group_split_by_goaway_inner() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let upstream_origin = moq_tokio::origin::spawn(); let broadcast = upstream_origin.create_broadcast("cam").expect("create broadcast"); @@ -286,7 +286,7 @@ async fn spawn_upstream( /// never retracts on the cluster origin (route re-pricing and the sibling's /// announce surface as metadata updates, not churn). async fn cluster_migrates_on_upstream_goaway_inner() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); kio::clock::timeout(TEST_TIMEOUT, async { // ── the shared "live" broadcast both siblings can serve ───────── @@ -405,7 +405,7 @@ async fn spawn_relay_with_upstream( upstream_url: &str, accept_notify: Option>, ) -> (u16, tokio::task::JoinHandle<()>) { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let (port, mut server) = listen_tcp().await; @@ -479,7 +479,7 @@ async fn spawn_relay_with_upstream( /// 5. No GOAWAY leaks to the subscriber's own session, and the path never /// retracts under the subscriber. async fn cluster_diamond_goaway_seamless_failover_inner() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); // ── TOP: origin server serving the same broadcast to both mids ────── let top_origin = moq_tokio::origin::spawn(); @@ -786,7 +786,7 @@ fn goaway_handover_is_enforced_while_the_replacement_dial_hangs() { /// then says nothing, so the handshake hangs, and the predecessor must still be /// closed on schedule rather than held for as long as the dial takes. async fn goaway_handover_is_enforced_while_the_replacement_dial_hangs_inner() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let upstream_origin = moq_tokio::origin::spawn(); let (port, mut accepted, _handle) = spawn_upstream(upstream_origin).await; diff --git a/rs/moq-relay/tests/integration/hidden_cluster.rs b/rs/moq-relay/tests/integration/hidden_cluster.rs index 91e6ef17893..b030ce5da1e 100644 --- a/rs/moq-relay/tests/integration/hidden_cluster.rs +++ b/rs/moq-relay/tests/integration/hidden_cluster.rs @@ -49,7 +49,7 @@ fn old_peers_keep_hidden_paths() { /// The relay dials a peer pinned to `version`. The peer's announce request cannot /// carry the opt-in below lite-07, yet it discovers the relay's hidden broadcast. async fn old_peer_keeps_hidden_paths(version: moq_net::Version) { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); kio::clock::timeout(TEST_TIMEOUT, async { let (port, mut server) = listen_tcp(version).await; diff --git a/rs/moq-relay/tests/integration/implementation.rs b/rs/moq-relay/tests/integration/implementation.rs index 716e51ceb67..54ad586711a 100644 --- a/rs/moq-relay/tests/integration/implementation.rs +++ b/rs/moq-relay/tests/integration/implementation.rs @@ -14,7 +14,7 @@ fn relay_default() -> String { /// A relay on a loopback TCP listener, configured by `set`, whose admissions the test decides. async fn spawn_relay(set: impl FnOnce(&mut Config)) -> (u16, moq_relay::auth::Admissions, tokio::task::JoinHandle<()>) { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let mut config = Config::default(); config.listen.version = vec!["moq-lite-07-wip".parse().expect("lite-07")]; config.connect.version = config.listen.version.clone(); diff --git a/rs/moq-relay/tests/integration/lan_mesh.rs b/rs/moq-relay/tests/integration/lan_mesh.rs index bf792e127b2..3c2320ea997 100644 --- a/rs/moq-relay/tests/integration/lan_mesh.rs +++ b/rs/moq-relay/tests/integration/lan_mesh.rs @@ -26,7 +26,7 @@ use moq_relay::cluster; #[tokio::test] #[ignore = "needs multicast on the host network; run by just rs multicast"] async fn moq_import_cluster_lan_beside_a_relay() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let mut listen = moq_tokio::listen::Config::default(); listen.bind = Some("127.0.0.1:0".parse().unwrap()); diff --git a/rs/moq-relay/tests/integration/peer_limits.rs b/rs/moq-relay/tests/integration/peer_limits.rs index 56a16a65a10..1385122ed03 100644 --- a/rs/moq-relay/tests/integration/peer_limits.rs +++ b/rs/moq-relay/tests/integration/peer_limits.rs @@ -20,13 +20,22 @@ pub(crate) const BARE_IDLE: Duration = Duration::from_secs(300); /// A self-signed certificate on disk. fn certificate(dir: &std::path::Path) -> (std::path::PathBuf, std::path::PathBuf) { - let key = rcgen::KeyPair::generate().expect("keypair"); - let params = rcgen::CertificateParams::new(vec!["localhost".to_string()]).expect("cert params"); + let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).expect("keypair"); + let params = rcgen::CertificateParams::new(vec!["localhost".to_string()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .expect("cert params"); let cert = params.self_signed(&key).expect("self-signed cert"); let cert_path = dir.join("cert.pem"); let key_path = dir.join("key.pem"); std::fs::write(&cert_path, cert.pem()).expect("write cert"); - std::fs::write(&key_path, key.serialize_pem()).expect("write key"); + std::fs::write( + &key_path, + pem::encode(&pem::Pem::new("PRIVATE KEY", key.to_pkcs8().secret_pkcs8_der())), + ) + .expect("write key"); (cert_path, key_path) } @@ -151,7 +160,7 @@ async fn peer_widens_and_viewer_does_not(mut relay: Relay, port: u16) { #[tokio::test] async fn tokio_peer_session_widens_quic_limits() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let dir = tempfile::tempdir().expect("tempdir"); let relay = Relay::load(config(dir.path())) .await @@ -176,7 +185,7 @@ async fn refused_at_load(set: impl FnOnce(&mut Config)) -> String { /// and `[quic]` alike, rather than wedging the peer or the handshake later. #[tokio::test] async fn unadvertisable_quic_limits_are_refused_at_load() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let err = refused_at_load(|config| { config.limits.peer.quic.receive_window = std::num::NonZeroU64::new(1 << 62).unwrap(); }) @@ -220,8 +229,12 @@ async fn unadvertisable_quic_limits_are_refused_at_load() { /// limit is a transport parameter, so the handshake alone shows it. Its idle /// timeout is far past any test's, so only a close ends a link in time. pub(crate) fn bare_server(connect: &moq_tokio::connect::Config) -> driver::endpoint::Endpoint { - let key = rcgen::KeyPair::generate().expect("keypair"); + let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).expect("keypair"); let cert = rcgen::CertificateParams::new(vec!["localhost".to_string()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) .expect("cert params") .self_signed(&key) .expect("self-signed cert"); @@ -229,7 +242,7 @@ pub(crate) fn bare_server(connect: &moq_tokio::connect::Config) -> driver::endpo .with_no_client_auth() .with_single_cert( vec![cert.der().clone()], - rustls::pki_types::PrivateKeyDer::Pkcs8(key.serialize_der().into()), + rustls::pki_types::PrivateKeyDer::Pkcs8(key.to_pkcs8().secret_pkcs8_der().to_vec().into()), ) .expect("server tls"); tls.alpn_protocols = connect @@ -279,7 +292,7 @@ async fn static_dial( /// `[quic]` settings still advertises the peer limits from the handshake on. #[tokio::test] async fn cluster_dials_widen_a_plain_client() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let mut connect = moq_tokio::connect::Config::default(); connect.tls.insecure = Some(true); let server = bare_server(&connect); @@ -305,7 +318,7 @@ async fn cluster_dials_widen_a_plain_client() { /// admits cluster traffic by source port keeps working. #[tokio::test] async fn static_peer_dials_from_the_configured_bind() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let mut connect = moq_tokio::connect::Config::default(); connect.tls.insecure = Some(true); // Borrow a free port from the OS, then hand it to the dial template. @@ -329,7 +342,7 @@ async fn static_peer_dials_from_the_configured_bind() { #[cfg(target_os = "linux")] #[tokio::test] async fn tokio_worker_peer_session_widens_quic_limits() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let dir = tempfile::tempdir().expect("tempdir"); let mut config = config(dir.path()); config.runtime.workers = Some(1); @@ -342,7 +355,7 @@ async fn tokio_worker_peer_session_widens_quic_limits() { #[cfg(all(target_os = "linux", feature = "_uring"))] #[tokio::test] async fn uring_peer_session_widens_quic_limits() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); match moq_uring::Worker::new(Default::default()) { Ok(_) => {} Err(moq_uring::Error::Unsupported(reason)) if std::env::var_os("CI_STRICT").is_none() => { diff --git a/rs/moq-relay/tests/integration/public_rules.rs b/rs/moq-relay/tests/integration/public_rules.rs index 7b58ac99172..40a7ac83f3e 100644 --- a/rs/moq-relay/tests/integration/public_rules.rs +++ b/rs/moq-relay/tests/integration/public_rules.rs @@ -34,7 +34,7 @@ fn client() -> moq_tokio::Client { /// The relay's web stack with WebSocket and the HTTP routes, admitting through `auth`. async fn spawn_relay(auth: auth::Config) -> (u16, tokio::task::JoinHandle<()>) { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let auth = auth .init("test", &moq_tokio::tls::Connect::default(), false) .expect("auth init"); diff --git a/rs/moq-relay/tests/integration/refusals.rs b/rs/moq-relay/tests/integration/refusals.rs index 17f22c28a03..dc8f6ba30a9 100644 --- a/rs/moq-relay/tests/integration/refusals.rs +++ b/rs/moq-relay/tests/integration/refusals.rs @@ -11,13 +11,22 @@ use moq_relay::{Config, Relay}; const TIMEOUT: Duration = Duration::from_secs(10); fn certificate(dir: &std::path::Path) -> (std::path::PathBuf, std::path::PathBuf) { - let key = rcgen::KeyPair::generate().expect("keypair"); - let params = rcgen::CertificateParams::new(vec!["localhost".to_string()]).expect("cert params"); + let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).expect("keypair"); + let params = rcgen::CertificateParams::new(vec!["localhost".to_string()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .expect("cert params"); let cert = params.self_signed(&key).expect("self-signed cert"); let cert_path = dir.join("cert.pem"); let key_path = dir.join("key.pem"); std::fs::write(&cert_path, cert.pem()).expect("write cert"); - std::fs::write(&key_path, key.serialize_pem()).expect("write key"); + std::fs::write( + &key_path, + pem::encode(&pem::Pem::new("PRIVATE KEY", key.to_pkcs8().secret_pkcs8_der())), + ) + .expect("write key"); (cert_path, key_path) } @@ -53,7 +62,7 @@ struct Running { } async fn start(config: Config) -> Running { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let relay = Relay::load(config).await.expect("load relay").with_signals(false); let stats = relay.stats().registry().clone(); let origin = relay.cluster().origin.consume(); @@ -449,7 +458,7 @@ async fn web_peer(addr: SocketAddr, alpn: &str) -> moq_tokio::quic::web::Session async fn uri_setup_paths(io_uring: bool) { use moq_tokio::quic::web::{SessionError, WebTransportError}; - let _ = moq_tokio::crypto::install_default(); + moq_tokio::crypto::install_default().unwrap(); let versions: Vec = [ "moq-lite-05", "moq-lite-06", diff --git a/rs/moq-relay/tests/integration/runtime_uring.rs b/rs/moq-relay/tests/integration/runtime_uring.rs index e531f086b66..45119009d1d 100644 --- a/rs/moq-relay/tests/integration/runtime_uring.rs +++ b/rs/moq-relay/tests/integration/runtime_uring.rs @@ -38,8 +38,13 @@ pub(crate) fn supported() -> bool { /// A CA on disk plus a certificate it signed, for the mTLS test. Returns the /// root, the client's certificate, and its key. fn signed_client(dir: &std::path::Path) -> (std::path::PathBuf, std::path::PathBuf, std::path::PathBuf) { - let ca_key = rcgen::KeyPair::generate().expect("ca keypair"); - let mut ca_params = rcgen::CertificateParams::new(Vec::new()).expect("ca params"); + let ca_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).expect("ca keypair"); + let mut ca_params = rcgen::CertificateParams::new(Vec::new()) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .expect("ca params"); ca_params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained); ca_params.key_usages = vec![rcgen::KeyUsagePurpose::KeyCertSign, rcgen::KeyUsagePurpose::CrlSign]; ca_params @@ -47,8 +52,13 @@ fn signed_client(dir: &std::path::Path) -> (std::path::PathBuf, std::path::PathB .push(rcgen::DnType::CommonName, "moq test ca"); let ca = rcgen::CertifiedIssuer::self_signed(ca_params, ca_key).expect("self-signed ca"); - let key = rcgen::KeyPair::generate().expect("client keypair"); - let mut params = rcgen::CertificateParams::new(vec!["client.localhost".to_string()]).expect("client params"); + let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).expect("client keypair"); + let mut params = rcgen::CertificateParams::new(vec!["client.localhost".to_string()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .expect("client params"); params.use_authority_key_identifier_extension = true; params.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::ClientAuth]; let cert = params.signed_by(&key, &ca).expect("signed client cert"); @@ -58,19 +68,32 @@ fn signed_client(dir: &std::path::Path) -> (std::path::PathBuf, std::path::PathB let key_path = dir.join("client.key.pem"); std::fs::write(&root_path, ca.pem()).expect("write ca"); std::fs::write(&cert_path, cert.pem()).expect("write client cert"); - std::fs::write(&key_path, key.serialize_pem()).expect("write client key"); + std::fs::write( + &key_path, + pem::encode(&pem::Pem::new("PRIVATE KEY", key.to_pkcs8().secret_pkcs8_der())), + ) + .expect("write client key"); (root_path, cert_path, key_path) } /// A self-signed certificate on disk. fn certificate(dir: &std::path::Path) -> (std::path::PathBuf, std::path::PathBuf) { - let key = rcgen::KeyPair::generate().expect("keypair"); - let params = rcgen::CertificateParams::new(vec!["localhost".to_string()]).expect("cert params"); + let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).expect("keypair"); + let params = rcgen::CertificateParams::new(vec!["localhost".to_string()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .expect("cert params"); let cert = params.self_signed(&key).expect("self-signed cert"); let cert_path = dir.join("cert.pem"); let key_path = dir.join("key.pem"); std::fs::write(&cert_path, cert.pem()).expect("write cert"); - std::fs::write(&key_path, key.serialize_pem()).expect("write key"); + std::fs::write( + &key_path, + pem::encode(&pem::Pem::new("PRIVATE KEY", key.to_pkcs8().secret_pkcs8_der())), + ) + .expect("write key"); (cert_path, key_path) } @@ -117,7 +140,7 @@ async fn connect(client: moq_tokio::Client, url: url::Url) -> moq_tokio::Connect /// shared origin. #[tokio::test] async fn uring_workers_serve_webtransport_and_raw_quic() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); if !supported() { return; } @@ -212,7 +235,7 @@ async fn uring_workers_serve_webtransport_and_raw_quic() { /// each of which must negotiate exactly the version it was pinned to. #[tokio::test] async fn uring_workers_serve_every_configured_version() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); if !supported() { return; } @@ -303,7 +326,7 @@ async fn uring_workers_serve_every_configured_version() { /// sends no SNI, rather than the WebTransport CONNECT host. #[tokio::test] async fn uring_workers_report_link_facts() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); if !supported() { return; } @@ -365,7 +388,7 @@ async fn uring_workers_report_link_facts() { /// the whole window, and the arrival only what is left of it. #[tokio::test] async fn uring_workers_drain_on_the_trigger() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); if !supported() { return; } @@ -510,7 +533,7 @@ async fn http_get(addr: SocketAddr, path: &str) -> String { /// The advertised fingerprint pins fresh handshakes before and after rotation. #[tokio::test] async fn workers_publish_their_rotated_certificate_fingerprint() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); for io_uring in [false, true] { if io_uring && !supported() { continue; @@ -576,7 +599,7 @@ async fn workers_publish_their_rotated_certificate_fingerprint() { /// A generated worker identity is advertised once and accepted by pinned clients. #[tokio::test] async fn workers_share_a_generated_identity() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); for io_uring in [false, true] { if io_uring && !supported() { continue; @@ -627,7 +650,7 @@ async fn workers_share_a_generated_identity() { /// nothing else, so only the mTLS path can carry the round trip through. #[tokio::test] async fn an_mtls_client_authenticates_without_a_token() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); if !supported() { return; } @@ -723,7 +746,7 @@ async fn an_mtls_client_authenticates_without_a_token() { #[cfg(feature = "qlog")] #[tokio::test] async fn uring_workers_write_qlog_traces() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); if !supported() { return; } @@ -811,7 +834,7 @@ async fn uring_workers_write_qlog_traces() { /// refuses, over WebTransport and raw QUIC alike. #[tokio::test] async fn uring_refusals_reach_metrics() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); if !supported() { return; } @@ -903,7 +926,7 @@ async fn next_update(announced: &mut moq_net::announce::Consumer) -> Option<(moq async fn uring_forwards_the_setup_token() { use moq_tokio::quic::{driver, web}; - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); if !supported() { return; } @@ -995,7 +1018,7 @@ async fn uring_forwards_the_setup_token() { /// The embedded auth decider receives the same transport facts as the Tokio path. #[tokio::test] async fn uring_auth_reports_distinct_quic_and_webtransport() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); if !supported() { return; } @@ -1047,7 +1070,7 @@ async fn uring_auth_reports_distinct_quic_and_webtransport() { /// request would carry it. #[tokio::test] async fn uring_workers_offer_the_configured_extensions() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); if !supported() { return; } @@ -1123,7 +1146,7 @@ fn uring_workers_bound_stalled_handshakes() { const LISTEN: Duration = Duration::from_millis(200); - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); if !supported() { return; } @@ -1251,7 +1274,7 @@ async fn stall_after_hello(server: SocketAddr) -> (SocketAddr, tokio::sync::ones /// The harness keeps only the connection target, including its span on worker and shared tasks. #[tokio::test] async fn uring_sessions_log_their_close_under_a_connection_span() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); if !supported() { return; } @@ -1319,7 +1342,7 @@ async fn uring_startup_reports_the_memlock_limit() { if !test_env::Env::default().set("MOQ_TEST_MEMLOCK", "0").isolate() { return; } - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); if !supported() { return; } diff --git a/rs/moq-relay/tests/integration/runtime_workers.rs b/rs/moq-relay/tests/integration/runtime_workers.rs index d37757ac5f8..946dd29d249 100644 --- a/rs/moq-relay/tests/integration/runtime_workers.rs +++ b/rs/moq-relay/tests/integration/runtime_workers.rs @@ -22,13 +22,22 @@ const WORKERS: u16 = 4; /// A self-signed certificate on disk. Workers refuse `listen.tls.generate`, /// since each would generate one of its own and serve a different identity. fn certificate(dir: &std::path::Path) -> (std::path::PathBuf, std::path::PathBuf) { - let key = rcgen::KeyPair::generate().expect("keypair"); - let params = rcgen::CertificateParams::new(vec!["localhost".to_string()]).expect("cert params"); + let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).expect("keypair"); + let params = rcgen::CertificateParams::new(vec!["localhost".to_string()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .expect("cert params"); let cert = params.self_signed(&key).expect("self-signed cert"); let cert_path = dir.join("cert.pem"); let key_path = dir.join("key.pem"); std::fs::write(&cert_path, cert.pem()).expect("write cert"); - std::fs::write(&key_path, key.serialize_pem()).expect("write key"); + std::fs::write( + &key_path, + pem::encode(&pem::Pem::new("PRIVATE KEY", key.to_pkcs8().secret_pkcs8_der())), + ) + .expect("write key"); (cert_path, key_path) } @@ -73,7 +82,7 @@ async fn connect(client: moq_tokio::Client, url: url::Url) -> moq_tokio::Connect /// it is what this asserts, whichever way the placement lands. #[tokio::test] async fn workers_serve_quic_and_share_one_origin() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let dir = tempfile::tempdir().expect("tempdir"); let (cert, key) = certificate(dir.path()); diff --git a/rs/moq-relay/tests/integration/session_revalidate.rs b/rs/moq-relay/tests/integration/session_revalidate.rs index 991f3eac05e..cb58e328e4d 100644 --- a/rs/moq-relay/tests/integration/session_revalidate.rs +++ b/rs/moq-relay/tests/integration/session_revalidate.rs @@ -129,7 +129,7 @@ impl Fixture { } async fn spawn(auth: moq_relay::auth::Auth, websocket: bool) -> Self { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let sessions = moq_relay::session::Registry::new(); let mut internal_config = internal::Config::default(); internal_config.listen = Some("127.0.0.1:0".parse().unwrap()); diff --git a/rs/moq-relay/tests/integration/shutdown_signal.rs b/rs/moq-relay/tests/integration/shutdown_signal.rs index 48394c87934..edaa614f129 100644 --- a/rs/moq-relay/tests/integration/shutdown_signal.rs +++ b/rs/moq-relay/tests/integration/shutdown_signal.rs @@ -129,7 +129,7 @@ fn a_reconnecting_client_rides_out_a_restart() { } async fn sigint_drains_sessions_before_exiting_inner() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); // Install tokio's SIGINT handler before anything raises one: the default // disposition would kill the test process instead. Held for the whole test so @@ -181,7 +181,7 @@ async fn sigint_drains_sessions_before_exiting_inner() { } async fn a_signal_right_after_ready_drains_inner() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let relay = Relay::load(relay_config()).await.expect("load relay"); let port = relay.tcp_addr().expect("TCP listener bound").port(); @@ -211,7 +211,7 @@ async fn a_signal_right_after_ready_drains_inner() { } async fn a_failed_startup_leaves_the_signals_alone_inner() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); // The cluster starts last before the relay serves, and an unreadable token // fails it. @@ -233,7 +233,7 @@ async fn a_failed_startup_leaves_the_signals_alone_inner() { } async fn an_embedder_owns_the_signals_inner() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); // The embedder's own handler, which is also what keeps SIGINT from killing // the test process. @@ -294,7 +294,7 @@ async fn an_embedder_owns_the_signals_inner() { } async fn a_session_arriving_mid_drain_gets_what_is_left_inner() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let relay = Relay::load(relay_config()) .await @@ -359,7 +359,7 @@ async fn a_session_arriving_mid_drain_gets_what_is_left_inner() { } async fn a_drain_ends_once_every_session_leaves_inner() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); // A window the test would time out long before, so only an early exit passes. let mut config = relay_config(); @@ -392,7 +392,7 @@ async fn a_drain_ends_once_every_session_leaves_inner() { } async fn a_trigger_before_run_keeps_the_deadline_inner() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let relay = Relay::load(relay_config()) .await @@ -425,7 +425,7 @@ async fn a_trigger_before_run_keeps_the_deadline_inner() { /// Every one of those sessions served, so none counts against the retry window, and the /// publisher is still there to land on the relay that takes the address over. async fn a_reconnecting_client_rides_out_a_restart_inner() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let relay = Relay::load(relay_config()) .await diff --git a/rs/moq-relay/tests/integration/smoke.rs b/rs/moq-relay/tests/integration/smoke.rs index 5ee2da0b2cf..0f942450395 100644 --- a/rs/moq-relay/tests/integration/smoke.rs +++ b/rs/moq-relay/tests/integration/smoke.rs @@ -56,7 +56,7 @@ fn new_cluster() -> cluster::Cluster { async fn build_web_with(web_config: web::Config, cluster: cluster::Cluster) -> web::Web { // Crypto provider is process-global; reinstalls after the first one are // no-ops, but the test binary may run before any other moq code does. - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); // A public grant of `**` lets any path through. let mut auth_config = auth::Config::default(); @@ -431,13 +431,22 @@ async fn relay_web_serves_merged_routes() { async fn relay_https_terminates_tls() { let dir = tempfile::TempDir::new().expect("tempdir"); - let key = rcgen::KeyPair::generate().expect("keypair"); - let params = rcgen::CertificateParams::new(vec!["localhost".to_string()]).expect("cert params"); + let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).expect("keypair"); + let params = rcgen::CertificateParams::new(vec!["localhost".to_string()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .expect("cert params"); let cert = params.self_signed(&key).expect("self-signed cert"); let cert_path = dir.path().join("cert.pem"); let key_path = dir.path().join("key.pem"); std::fs::write(&cert_path, cert.pem()).expect("write cert"); - std::fs::write(&key_path, key.serialize_pem()).expect("write key"); + std::fs::write( + &key_path, + pem::encode(&pem::Pem::new("PRIVATE KEY", key.to_pkcs8().secret_pkcs8_der())), + ) + .expect("write key"); let mut config = web::Config::default(); config.ws = false; @@ -561,7 +570,7 @@ async fn spawn_accept_relay( Option, tokio::task::JoinHandle<()>, ) { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let server = config.init(Default::default()).expect("server init"); diff --git a/rs/moq-relay/tests/integration/stack.rs b/rs/moq-relay/tests/integration/stack.rs index 488168de0e7..b1e3d7b660e 100644 --- a/rs/moq-relay/tests/integration/stack.rs +++ b/rs/moq-relay/tests/integration/stack.rs @@ -6,7 +6,7 @@ use moq_relay::{Config, Relay}; async fn load_and_run() { // Process-wide: another test in this binary may have installed it first. - let _ = moq_tokio::crypto::install_default(); + moq_tokio::crypto::install_default().unwrap(); let mut config = Config::default(); config.listen.bind = Some("127.0.0.1:0".parse().unwrap()); config.listen.tls.generate = vec!["localhost".into()]; diff --git a/rs/moq-relay/tests/integration/tenant_matrix.rs b/rs/moq-relay/tests/integration/tenant_matrix.rs index 665a81661e2..a15cd2da643 100644 --- a/rs/moq-relay/tests/integration/tenant_matrix.rs +++ b/rs/moq-relay/tests/integration/tenant_matrix.rs @@ -128,7 +128,7 @@ struct Running { /// A relay admitting through [`Tenants`], serving QUIC from one io_uring worker /// when `io_uring`, else from the shared Tokio listener. async fn start(io_uring: bool) -> Running { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let tenants = Tenants::new(); let dir = tempfile::tempdir().expect("tempdir"); let mut config = config(dir.path(), false); diff --git a/rs/moq-relay/tests/integration/upstream_links.rs b/rs/moq-relay/tests/integration/upstream_links.rs index e7c4ca43cd7..3b8e3eab306 100644 --- a/rs/moq-relay/tests/integration/upstream_links.rs +++ b/rs/moq-relay/tests/integration/upstream_links.rs @@ -83,7 +83,7 @@ fn grant(path: &str) -> Grant { const LITE_07: &str = "moq-lite-07-wip"; async fn node(id: u64, connect: Vec) -> Node { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let mut tasks = tokio::task::JoinSet::new(); let mut listen = moq_tokio::listen::Config::default(); diff --git a/rs/moq-relay/tests/integration/wire_stats.rs b/rs/moq-relay/tests/integration/wire_stats.rs index 267f937a880..eea21f69838 100644 --- a/rs/moq-relay/tests/integration/wire_stats.rs +++ b/rs/moq-relay/tests/integration/wire_stats.rs @@ -18,17 +18,25 @@ fn presence(registry: &Registry) -> Presence { async fn wire_sources(io_uring: bool) { // Process-wide: another test in this binary may have installed it first. - let _ = moq_tokio::crypto::install_default(); + moq_tokio::crypto::install_default().unwrap(); let dir = tempfile::tempdir().unwrap(); - let key = rcgen::KeyPair::generate().unwrap(); + let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap(); let cert = rcgen::CertificateParams::new(vec!["localhost".into()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) .unwrap() .self_signed(&key) .unwrap(); let cert_path = dir.path().join("cert.pem"); let key_path = dir.path().join("key.pem"); std::fs::write(&cert_path, cert.pem()).unwrap(); - std::fs::write(&key_path, key.serialize_pem()).unwrap(); + std::fs::write( + &key_path, + pem::encode(&pem::Pem::new("PRIVATE KEY", key.to_pkcs8().secret_pkcs8_der())), + ) + .unwrap(); let mut config = Config::default(); config.listen.bind = Some("127.0.0.1:0".parse().unwrap()); config.listen.tls.cert = vec![cert_path]; diff --git a/rs/moq-rtmp/Cargo.toml b/rs/moq-rtmp/Cargo.toml index 08fb75b7d51..d28c5a6e31a 100644 --- a/rs/moq-rtmp/Cargo.toml +++ b/rs/moq-rtmp/Cargo.toml @@ -37,13 +37,12 @@ byteorder = "1" bytes = { workspace = true } futures = { workspace = true } hang = { workspace = true } -hmac = "0.13" kio = { workspace = true, features = ["runtime"] } moq-mux = { workspace = true } moq-net = { workspace = true } rand = { workspace = true } -rustls = { version = "0.23", default-features = false, features = ["aws-lc-rs"], optional = true } -sha2 = "0.11" +rind = { workspace = true } +rustls = { version = "0.23", default-features = false, features = ["std"], optional = true } # TCP keepalive on accepted sockets, so a half-open connection (a peer that # vanished without a FIN/RST) is reaped instead of pinning a broadcast forever. socket2 = { workspace = true } @@ -62,7 +61,8 @@ kio = { path = "../kio", features = ["sim"] } # `rustls::ServerConfig`. No transport feature: a QUIC backend here would be # unified into every other crate a `--workspace` build selects, which is exactly # what hid moq-tokio's backend-less build from the nightly feature matrix. -moq-tokio = { path = "../moq-tokio", default-features = false, features = ["aws-lc-rs", "net"] } +moq-tokio = { path = "../moq-tokio", default-features = false, features = ["net"] } +rind-rustls = { workspace = true } tokio = { workspace = true, features = ["test-util"] } tracing-test = { workspace = true } workspace-hack = { path = "../workspace-hack" } diff --git a/rs/moq-rtmp/MIGRATE.md b/rs/moq-rtmp/MIGRATE.md index 83468537f22..9d92d21446b 100644 --- a/rs/moq-rtmp/MIGRATE.md +++ b/rs/moq-rtmp/MIGRATE.md @@ -4,6 +4,12 @@ How to update your code for each breaking change, newest first. ## Unreleased +### Handshake cryptography uses rind + +RTMP handshake HMAC-SHA256 uses rind. `Server::bind` checks CPU support before binding; every stream handshake also checks before using crypto, including `accept_stream` and the dial client. +The `tls` feature no longer selects rustls' aws-lc provider; build the supplied TLS configuration with `rind_rustls::default_provider()?` or `moq_tokio::tls::Listen::server_config`. +RTMP and RTMPS wire formats are unchanged. + ### `with_max_age(None)` is unlimited ([#7729](https://github.com/moq-dev/moq/pull/7729)) The ingest builders' `with_max_age` still default to `hang::container::MAX_AGE` (30 s), but `None` now sets no publisher limit instead of keeping that default. diff --git a/rs/moq-rtmp/src/dial.rs b/rs/moq-rtmp/src/dial.rs index 4f1d73da809..1bfe60a142e 100644 --- a/rs/moq-rtmp/src/dial.rs +++ b/rs/moq-rtmp/src/dial.rs @@ -548,7 +548,7 @@ fn is_status_failure(code: &str) -> bool { /// handshake read can also carry the first RTMP chunks, so those `remaining_bytes` /// must be fed to the session or chunk parsing desyncs. async fn client_handshake(stream: &mut S) -> anyhow::Result> { - let mut handshake = Handshake::new(PeerType::Client); + let mut handshake = Handshake::new(PeerType::Client)?; let p0_p1 = handshake .generate_outbound_p0_and_p1() .map_err(|e| anyhow::anyhow!("rtmp handshake p0/p1: {e:?}"))?; diff --git a/rs/moq-rtmp/src/rml/handshake/mod.rs b/rs/moq-rtmp/src/rml/handshake/mod.rs index d61b8448a57..d0730d55d51 100644 --- a/rs/moq-rtmp/src/rml/handshake/mod.rs +++ b/rs/moq-rtmp/src/rml/handshake/mod.rs @@ -28,9 +28,8 @@ mod errors; pub use self::errors::HandshakeError; -use hmac::{Hmac, KeyInit, Mac}; use rand::RngExt; -use sha2::Sha256; +use rind::hmac; const RTMP_PACKET_SIZE: usize = 1536; const SHA256_DIGEST_LENGTH: usize = 32; @@ -108,8 +107,8 @@ enum Stage { /// ```ignore /// use rml_rtmp::handshake::{Handshake, PeerType, HandshakeProcessResult}; /// -/// let mut client = Handshake::new(PeerType::Client); -/// let mut server = Handshake::new(PeerType::Server); +/// let mut client = Handshake::new(PeerType::Client).unwrap(); +/// let mut server = Handshake::new(PeerType::Server).unwrap(); /// /// let c0_and_c1 = client.generate_outbound_p0_and_p1().unwrap(); /// let s0_s1_and_s2 = match server.process_bytes(&c0_and_c1[..]) { @@ -149,15 +148,16 @@ impl Handshake { /// The Flash Player 9 handshake requires generating a different packet 1 depending if you /// are the client or the server, and thus this must be specified when creating a new /// `Handshake` instance. - pub fn new(peer_type: PeerType) -> Handshake { - Handshake { + pub fn new(peer_type: PeerType) -> Result { + rind::cpu::check().map_err(std::io::Error::other)?; + Ok(Handshake { current_stage: Stage::NeedToSendP0AndP1, command_byte: 0_u8, input_buffer: Vec::with_capacity(RTMP_PACKET_SIZE), sent_p1: [0_u8; RTMP_PACKET_SIZE], peer_type, sent_digest: [0_u8; SHA256_DIGEST_LENGTH], - } + }) } /// Creates the packets 0 and 1 that should get sent to the peer. This is only strictly @@ -465,38 +465,16 @@ fn get_message_parts(handshake: &[u8; RTMP_PACKET_SIZE], digest_offset: u32) -> } fn calc_hmac_from_parts(part1: &[u8], part2: &[u8], key: &[u8]) -> [u8; SHA256_DIGEST_LENGTH] { - let mut inputs = Vec::with_capacity(part1.len() + part2.len()); - for index in 0..part1.len() { - inputs.push(part1[index]); - } - - for index in 0..part2.len() { - inputs.push(part2[index]); - } - - calc_hmac(&inputs, &key) + let key = hmac::Key::new(&hmac::HMAC_SHA256, key); + let mut mac = hmac::Context::with_key(&key); + mac.update(part1); + mac.update(part2); + mac.sign().as_ref().try_into().unwrap() } fn calc_hmac(input: &[u8], key: &[u8]) -> [u8; SHA256_DIGEST_LENGTH] { - let mut mac = Hmac::::new_from_slice(key).unwrap(); - mac.update(input); - - let result = mac.finalize(); - let array = result.into_bytes(); - - if array.len() != 32 { - panic!( - "Expected hmac signature to be 32 byte array, instead it was a {} byte array", - array.len() - ); - } - - let mut output = [0_u8; 32]; - for index in 0..32 { - output[index] = array[index]; - } - - output + let key = hmac::Key::new(&hmac::HMAC_SHA256, key); + hmac::sign(&key, input).as_ref().try_into().unwrap() } fn fill_with_random_data(buffer: &mut [u8]) { @@ -646,7 +624,7 @@ mod tests { #[test] fn bad_version_if_first_byte_is_not_a_3() { - let mut handshake = Handshake::new(PeerType::Server); + let mut handshake = Handshake::new(PeerType::Server).unwrap(); let input = [4_u8]; match handshake.process_bytes(&input) { @@ -658,7 +636,7 @@ mod tests { #[test] fn can_accept_jw_player_example_p0_and_p1() { - let mut handshake = Handshake::new(PeerType::Server); + let mut handshake = Handshake::new(PeerType::Server).unwrap(); let s0_and_s1 = match handshake.generate_outbound_p0_and_p1() { Err(x) => panic!("Unexpected error: {:?}", x), Ok(x) => x, @@ -706,7 +684,7 @@ mod tests { c0_and_c1[0] = 3; fill_with_random_data(&mut c0_and_c1[9..RTMP_PACKET_SIZE + 1]); - let mut handshake = Handshake::new(PeerType::Server); + let mut handshake = Handshake::new(PeerType::Server).unwrap(); let s0_and_s1 = match handshake.generate_outbound_p0_and_p1() { Err(x) => panic!("Unexpected error: {:?}", x), Ok(x) => x, @@ -739,8 +717,8 @@ mod tests { // This is the best way to verify we can handle the fp9 handshake method // without reimplementing the exact algorithims for the test. - let mut client = Handshake::new(PeerType::Client); - let mut server = Handshake::new(PeerType::Server); + let mut client = Handshake::new(PeerType::Client).unwrap(); + let mut server = Handshake::new(PeerType::Server).unwrap(); let c0_and_c1 = match client.generate_outbound_p0_and_p1() { Ok(bytes) => bytes, @@ -779,7 +757,7 @@ mod tests { #[test] fn sends_outbound_p0_p1_if_p0_received_and_outbound_p0_and_p1_not_yet_sent() { - let mut handshake = Handshake::new(PeerType::Server); + let mut handshake = Handshake::new(PeerType::Server).unwrap(); let input = [3_u8]; let response = match handshake.process_bytes(&input) { diff --git a/rs/moq-rtmp/src/server.rs b/rs/moq-rtmp/src/server.rs index e9e1a546b42..c46343d4efc 100644 --- a/rs/moq-rtmp/src/server.rs +++ b/rs/moq-rtmp/src/server.rs @@ -266,6 +266,7 @@ pub struct Server { impl Server { /// Bind an RTMP listener on `addr` (RTMP's well-known port is 1935). pub async fn bind(addr: SocketAddr) -> Result { + rind::cpu::check().map_err(std::io::Error::other)?; let listener = TcpListener::bind(addr).await?; Ok(Self { @@ -1469,7 +1470,7 @@ async fn feed_input( /// Perform the RTMP server handshake, returning any leftover bytes that followed /// the client's final handshake packet (the start of the chunk stream). async fn run_handshake(stream: &mut S, peer: SocketAddr) -> anyhow::Result> { - let mut handshake = Handshake::new(PeerType::Server); + let mut handshake = Handshake::new(PeerType::Server)?; let mut buffer = [0u8; 4096]; loop { let n = stream.read(&mut buffer).await?; @@ -1952,7 +1953,7 @@ mod tests { /// The client half of the RTMP handshake, returning the bytes read past it. async fn client_handshake(stream: &mut S) -> Vec { - let mut handshake = Handshake::new(PeerType::Client); + let mut handshake = Handshake::new(PeerType::Client).unwrap(); stream .write_all(&handshake.generate_outbound_p0_and_p1().unwrap()) .await @@ -2033,7 +2034,7 @@ mod tests { media: tokio::sync::mpsc::UnboundedSender, ) { // Handshake. - let mut handshake = Handshake::new(PeerType::Client); + let mut handshake = Handshake::new(PeerType::Client).unwrap(); stream .write_all(&handshake.generate_outbound_p0_and_p1().unwrap()) .await @@ -2121,7 +2122,7 @@ mod tests { None } - let mut handshake = Handshake::new(PeerType::Client); + let mut handshake = Handshake::new(PeerType::Client).unwrap(); stream .write_all(&handshake.generate_outbound_p0_and_p1().unwrap()) .await @@ -2862,7 +2863,7 @@ mod tests { let mut stream = TcpStream::connect(addr).await.unwrap(); // Client handshake. - let mut handshake = Handshake::new(PeerType::Client); + let mut handshake = Handshake::new(PeerType::Client).unwrap(); stream .write_all(&handshake.generate_outbound_p0_and_p1().unwrap()) .await @@ -3030,7 +3031,7 @@ mod tests { } } - let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider()); + let provider = Arc::new(rind_rustls::default_provider().unwrap()); let mut tls = moq_tokio::tls::Listen::default(); tls.generate = vec!["localhost".to_string()]; diff --git a/rs/moq-tokio/Cargo.toml b/rs/moq-tokio/Cargo.toml index 811bf17ed00..8041d042a7a 100644 --- a/rs/moq-tokio/Cargo.toml +++ b/rs/moq-tokio/Cargo.toml @@ -13,21 +13,21 @@ keywords = ["quic", "http3", "webtransport", "media", "live"] categories = ["multimedia", "network-programming", "web-programming"] [features] -default = ["net", "quic", "aws-lc-rs", "websocket", "tcp", "uds"] +default = ["net", "quic", "websocket", "tcp", "uds"] # MoQ sessions over moq-net: `Client`, `Server`, `origin`, and the `connect`, `listen`, # and `transport` modules. Every transport feature turns it on, since none works without it. -net = ["dep:moq-net"] +net = ["dep:moq-net", "_certs"] # The async QUIC driver alone (`quic::driver`): moq-quic on tokio, without moq-net or -# the MoQ backend. Needs a crypto-provider feature. -driver = ["dep:hmac", "dep:moq-congestion", "dep:moq-quic", "dep:rustc-hash", "dep:sha2"] +# the MoQ backend. Includes rind cryptography. +driver = ["_certs", "dep:moq-congestion", "dep:moq-quic", "dep:rustc-hash"] # QUIC and WebTransport over moq-quic, for `https://`, `moqt://`, and `moql://`. -quic = ["_transport", "_certs", "driver", "dep:http", "dep:web-transport-proto", "dep:reqwest", "watch", "dep:dns-lookup"] +quic = ["_transport", "driver", "dep:http", "dep:web-transport-proto", "dep:reqwest", "watch", "dep:dns-lookup"] # Server-side certificate handling: chains loaded from disk, self-signed generation, # in-memory identities, and per-SNI selection. Not one to enable on its own, since # nothing turns it into a listener: every QUIC backend needs it for its own TLS, and # so does the plain-TLS `tls::Listen::server_config` an RTMPS or HTTPS listener builds, -# which is why the crypto-provider features below turn it on too. -_certs = ["dep:rcgen", "dep:rustls-webpki"] +# enabled by every transport and the session API. +_certs = ["dep:rcgen", "dep:rind-rcgen", "dep:rustls-webpki"] # Private "any transport is compiled" marker. Not one to enable on its own: every # backend that can move bytes turns it on, and `uds` reaches it through `tcp`. _transport = ["net", "dep:moq-quic"] @@ -36,23 +36,17 @@ watch = ["dep:notify"] # Capture qlog traces (`--*-quic-qlog `). Off by default so production # builds do not pull in the qlog crate and its serde_json encoder. qlog = ["moq-quic?/qlog"] -# The QUIC backend pulls in its crypto provider from these features (default-features -# are off on the dependency), so a backend without aws-lc-rs/ring has no initial cipher. -# A provider is also all it takes to sign and serve certificates, so each turns on -# `_certs` even where there is no QUIC backend to serve them for. -aws-lc-rs = ["_certs", "rustls/aws-lc-rs", "rcgen/aws_lc_rs", "moq-quic?/rustls-aws-lc-rs"] # LAN peer discovery over mDNS (the `mdns` module). -mdns = ["dep:mdns-sd", "dep:hmac", "dep:sha2", "dep:subtle"] +mdns = ["dep:mdns-sd"] jemalloc = ["dep:tikv-jemallocator", "dep:tikv-jemalloc-ctl"] websocket = ["_transport", "dep:qmux", "watch", "dep:dns-lookup"] -# Qmux over TCP: plaintext `tcp://`, and `tls://` once a crypto provider is on. Server-side and client-side. +# Qmux over TCP: plaintext `tcp://`, and `tls://`. Server-side and client-side. tcp = ["_transport", "dep:qmux", "dep:dns-lookup", "dep:tokio-rustls"] # Unix-domain-socket qmux transport (`unix://`), unix-only. Adds peer-credential # inspection on accept. Pulls in `tcp` (shares qmux's stream transport). uds = ["tcp", "qmux/uds"] # Native WebRTC data channels over str0m, with a full ICE agent (the `webrtc` module). webrtc = ["_transport", "dep:qmux", "dep:moq-ice", "dep:str0m", "dep:if-addrs", "dep:mdns-sd"] -ring = ["_certs", "rustls/ring", "rcgen/ring", "moq-quic?/ring"] # Inside `kio::clock::sim::run`, detached tasks spawn on kio's deterministic simulator, # and with `driver`, `quic::driver::sim` carries datagrams over seeded, impaired # `moq_quic::sim::Link`s with no sockets. Turns on no transport of its own. Hidden from the @@ -66,18 +60,19 @@ bytes = "1" dns-lookup = { version = "4", optional = true } futures = "0.3" hex = { workspace = true } -hmac = { workspace = true, optional = true } http = { version = "1", optional = true } -humantime = "2.3" +humantime = { workspace = true } humantime-serde = { workspace = true } if-addrs = { workspace = true, optional = true } kio = { workspace = true, features = ["runtime"] } mdns-sd = { workspace = true, optional = true } moq-congestion = { workspace = true, optional = true } +# rind's rustls provider and the `UnsupportedCpu` error, re-exported as `crypto`. Needs no moq-net. +moq-crypto = { workspace = true, features = ["provider"] } # The ICE agent behind the `webrtc` module. Private, like str0m: neither appears in this crate's API. moq-ice = { workspace = true, optional = true } moq-net = { workspace = true, optional = true } -# The QUIC state machine `quic::driver` drives; the crypto-provider features pick its provider. +# The QUIC state machine `quic::driver` drives; rind supplies its cryptography. moq-quic = { workspace = true, optional = true } moq-sock = { workspace = true } notify = { version = "8", optional = true } @@ -85,16 +80,16 @@ qmux = { workspace = true, features = ["wss", "tls", "tcp"], optional = true } rand = "0.10.1" rcgen = { workspace = true, optional = true } reqwest = { version = "0.13", default-features = false, optional = true } +rind = { workspace = true } +rind-rcgen = { workspace = true, optional = true } rustc-hash = { workspace = true, optional = true } -rustls = "0.23" +rustls = { version = "0.23", default-features = false, features = ["std", "tls12"] } # OS-native server-cert verifier for the rustls backend. rustls-platform-verifier = "0.7" -rustls-webpki = { version = "0.103", features = ["aws-lc-rs"], optional = true } +rustls-webpki = { version = "0.103", default-features = false, features = ["std"], optional = true } serde = { version = "1", features = ["derive"] } serde_with = { version = "3", features = ["hex"] } -sha2 = { workspace = true, optional = true } str0m = { workspace = true, optional = true } -subtle = { workspace = true, optional = true } thiserror = "2" tikv-jemalloc-ctl = { version = "0.7", optional = true } tikv-jemallocator = { version = "0.7", features = ["profiling", "unprefixed_malloc_on_supported_platforms"], optional = true } @@ -139,10 +134,13 @@ moq-shaper = { path = "../moq-shaper" } # The tests run QUIC sessions on the simulator. Only `sim`, so a test build keeps the # features it was asked for. moq-tokio = { path = ".", default-features = false, features = ["sim"] } -rcgen = { workspace = true, features = ["pem", "aws_lc_rs"] } +pem = { workspace = true } +rcgen = { workspace = true, features = ["pem"] } # rustls without a provider, as another crate in the graph may build it, so the default test build covers an # `http://` dial's certificate fetch with no process default installed. reqwest = { workspace = true, features = ["rustls-no-provider"] } +rind-rcgen = { workspace = true } +rind-rustls = { workspace = true } # Sockets a test holds or inspects: which ones the process still holds, so the # worker tests can prove a stopped group closed its own, and port reservations # that never listen, so a test needn't release a port another test could take. @@ -175,7 +173,7 @@ required-features = ["net"] [[bench]] name = "fanout" harness = false -required-features = ["driver", "aws-lc-rs"] +required-features = ["driver"] [lints] workspace = true diff --git a/rs/moq-tokio/MIGRATE.md b/rs/moq-tokio/MIGRATE.md index d32d89227ed..d5abe02bd25 100644 --- a/rs/moq-tokio/MIGRATE.md +++ b/rs/moq-tokio/MIGRATE.md @@ -4,6 +4,20 @@ How to update your code for each breaking change, newest first. ## Unreleased +### Transport cryptography uses rind + +Remove the `aws-lc-rs` and `ring` Cargo features. rind is always enabled. +The `net` and `driver` features include certificate support, so an RTMPS-only embedder can use `net` without selecting a provider. +Self-signed certificates and mDNS/QUIC-LB authentication use rind. Wire formats are unchanged. + +`crypto` now re-exports moq-crypto's `provider` module, and a CPU missing a feature rind needs is reported as `crypto::UnsupportedCpu` (`moq_crypto::provider::UnsupportedCpu`), which names the feature: + +- `crypto::provider()` returns `Result`; add `?`. It always returns rind, independently of rustls' process default. +- `crypto::install_default()` returns `Result<(), UnsupportedCpu>` instead of `Result<(), Provider>`. A provider the process already installed is kept and is no longer an error, so replace `let _ = crypto::install_default();` with `crypto::install_default()?;`. +- `crypto::check()` refuses an unsupported CPU without building a provider; call it before using rind's primitives directly. +- `tls::Error::NoCryptoProvider` is removed. TLS setup returns `tls::Error::UnsupportedCpu` before generating keys or opening connections, and `quic::Error::UnsupportedCpu` reports the same from the QUIC backend. +- A failure to draw a self-signed certificate's random serial is `tls::Error::Rcgen`. + ### QUIC method names and polls match the transport layer On `quic::driver::connection::Connection` and `quic::web::Session`, rename `read_datagram()` to `recv_datagram()`. diff --git a/rs/moq-tokio/README.md b/rs/moq-tokio/README.md index 7b933d0b7ea..f7383a4b495 100644 --- a/rs/moq-tokio/README.md +++ b/rs/moq-tokio/README.md @@ -41,3 +41,8 @@ including in one-shot mode. With mixed `Addrs`, the target that establishes the session determines its redirect policy; unused pinned fallbacks do not restrict it. To refresh DNS, resolve and apply your address policy again before creating a new connection. Address filtering belongs to the caller. + +Transport cryptography always uses rind. Remove the `aws-lc-rs` and `ring` +features from dependencies. TLS setup checks support before using crypto: +x86\_64 needs no optional CPU extensions, aarch64 needs NEON, and armv7 is supported. +Raspberry Pi 4, CM4, and Zero 2 W use rind's paths without aarch64 crypto extensions. diff --git a/rs/moq-tokio/benches/fanout.rs b/rs/moq-tokio/benches/fanout.rs index bfb0f1add38..f8a49f0a385 100644 --- a/rs/moq-tokio/benches/fanout.rs +++ b/rs/moq-tokio/benches/fanout.rs @@ -53,8 +53,17 @@ impl Pair { let mut transport = transport::Config::default(); transport.limits = limits; - let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).expect("certificate"); - let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(cert.signing_key.serialize_der())); + let cert = (|| -> std::result::Result<_, rcgen::Error> { + let signing_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?; + let mut params = rcgen::CertificateParams::new(vec!["localhost".into()])?; + params.serial_number = Some(1u64.into()); + let cert = params.self_signed(&signing_key)?; + Ok(rcgen::CertifiedKey { cert, signing_key }) + })() + .expect("certificate"); + let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from( + cert.signing_key.to_pkcs8().secret_pkcs8_der().to_vec(), + )); let mut server_config = server::Config::with_single_cert(vec![cert.cert.der().clone()], key).expect("server config"); server_config.transport = transport.clone(); diff --git a/rs/moq-tokio/src/connection.rs b/rs/moq-tokio/src/connection.rs index 3eee1e7147a..09f8ee277eb 100644 --- a/rs/moq-tokio/src/connection.rs +++ b/rs/moq-tokio/src/connection.rs @@ -2636,7 +2636,7 @@ mod tests { /// A client that trusts the self-signed [`live`] listener. #[cfg(feature = "tcp")] fn client() -> Client { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + crate::crypto::install_default().unwrap(); let mut config = crate::connect::Config::default(); config.tls.insecure = Some(true); diff --git a/rs/moq-tokio/src/crypto.rs b/rs/moq-tokio/src/crypto.rs index cbbf71cfd33..e8a46028469 100644 --- a/rs/moq-tokio/src/crypto.rs +++ b/rs/moq-tokio/src/crypto.rs @@ -1,51 +1,12 @@ -//! Rustls crypto-provider selection shared by applications using moq-tokio. +//! rind cryptography shared by native MoQ applications. +//! +//! [`provider`] and [`install_default`] refuse a CPU that rind cannot run on with +//! [`UnsupportedCpu`], naming the missing feature. This module re-exports +//! `moq_crypto::provider`, so moq-quic, qmux, and moq-uring report the same type. -use rustls::crypto::hash::{self, HashAlgorithm}; -use std::sync::Arc; +pub use moq_crypto::provider::{Provider, UnsupportedCpu, check, install_default, provider}; -/// A shared rustls crypto provider. -pub type Provider = Arc; - -/// Return the installed provider, or the provider selected by crate features. -pub fn provider() -> Provider { - if let Some(provider) = rustls::crypto::CryptoProvider::get_default().cloned() { - return provider; - } - #[cfg(feature = "aws-lc-rs")] - 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()); - #[allow(unreachable_code, reason = "unreachable when a crypto feature returns above")] - { - panic!("no CryptoProvider available; install_default() or enable either the aws-lc-rs or ring feature"); - } -} - -/// Install the provider selected by crate features as rustls' process default. -pub fn install_default() -> Result<(), Provider> { - Arc::unwrap_or_clone(provider()).install_default() -} - -/// Helper function to compute SHA256 hash using the crypto provider -/// -/// This function tries to find a SHA256 hash implementation in the provided -/// crypto provider's cipher suites. If not found, it falls back to direct -/// implementations based on enabled features. -pub(crate) fn sha256(provider: &Provider, data: &[u8]) -> hash::Output { - // Try to find a SHA-256 hash provider from the cipher suites - 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 - } - }); - - // If a hash provider is found, use it - if let Some(hash_provider) = hash_provider { - return hash_provider.hash(data); - } - - panic!("SHA-256 hash provider not found"); +/// Hash certificate bytes independently of the configured TLS cipher suites. +pub(crate) fn sha256(data: &[u8]) -> rind::digest::Digest { + rind::digest::digest(&rind::digest::SHA256, data) } diff --git a/rs/moq-tokio/src/lib.rs b/rs/moq-tokio/src/lib.rs index e35980ed9d1..79169664e45 100644 --- a/rs/moq-tokio/src/lib.rs +++ b/rs/moq-tokio/src/lib.rs @@ -11,24 +11,16 @@ //! With `net`, `client::Client` connects to relays; transport features enable //! `server::Server` for accepting connections. The `mdns` feature finds peers on the local network. //! -//! With `default-features = false`, the `quic` backend must be paired -//! with the `aws-lc-rs` or `ring` crypto-provider feature. Every other subset -//! compiles, including no transport at all: such a build cannot connect to -//! anything, though a crypto provider on its own is still enough to configure TLS -//! and to build a plain-TLS listener's `rustls::ServerConfig` from -//! [`tls::Listen::server_config`]. +//! Cryptography always comes from rind. TLS setup checks CPU support and returns +//! an error naming a missing feature. Older x86_64 CPUs and aarch64 boards without +//! crypto extensions use rind's software paths; aarch64 requires NEON. Armv7 is supported. //! //! MoQ sessions need the `net` feature, which every transport turns on. Without -//! it, `driver` and a crypto provider build [`quic::driver`] alone: an async +//! it, `driver` builds [`quic::driver`] alone: an async //! QUIC stack for any application, MoQ or not. #![warn(missing_docs)] -// The protocol crates need a compiled provider for reset and retry-token keys. A rustls provider -// installed at runtime cannot supply constructors removed by their compile-time feature gates. -#[cfg(all(feature = "driver", not(any(feature = "aws-lc-rs", feature = "ring"))))] -compile_error!("a rustls QUIC backend requires a crypto provider: enable either the `aws-lc-rs` or `ring` feature"); - #[cfg(any(feature = "net", all(feature = "watch", feature = "_certs")))] mod abort; pub mod accept; diff --git a/rs/moq-tokio/src/listen.rs b/rs/moq-tokio/src/listen.rs index 1f2f7f1b977..6ba5ba4f24d 100644 --- a/rs/moq-tokio/src/listen.rs +++ b/rs/moq-tokio/src/listen.rs @@ -485,9 +485,9 @@ impl Config { let tcp_tls = self.tcp.tls == Some(true); #[cfg(not(feature = "tcp"))] let tcp_tls = false; - #[cfg(any(feature = "aws-lc-rs", feature = "ring"))] + #[cfg(feature = "_certs")] let identity = self.tls.identity.is_some(); - #[cfg(not(any(feature = "aws-lc-rs", feature = "ring")))] + #[cfg(not(feature = "_certs"))] let identity = false; let refused = [ diff --git a/rs/moq-tokio/src/mdns.rs b/rs/moq-tokio/src/mdns.rs index 3428373bfa2..6a36ffec435 100644 --- a/rs/moq-tokio/src/mdns.rs +++ b/rs/moq-tokio/src/mdns.rs @@ -30,10 +30,9 @@ use std::fmt; use std::net::{IpAddr, SocketAddr, SocketAddrV6}; use std::str::FromStr; -use hmac::{KeyInit, Mac}; use mdns_sd::{ServiceDaemon, ServiceEvent, ServiceInfo}; +use rind::hmac; use serde::{Deserialize, Deserializer, Serialize, Serializer}; -use subtle::ConstantTimeEq; use url::Url; use crate::secret::Secret; @@ -73,6 +72,8 @@ pub struct Error(ErrorKind); #[derive(Debug, thiserror::Error)] enum ErrorKind { + #[error(transparent)] + UnsupportedCpu(#[from] crate::crypto::UnsupportedCpu), #[error(transparent)] Mdns(#[from] mdns_sd::Error), @@ -191,7 +192,8 @@ struct Identity<'a> { /// An HMAC-SHA256 proof of knowing `secret`, bound to one listener's /// [`Identity`], plus a `context` separating the advertise and dial roles. fn proof(secret: &Secret, context: &str, id: &Identity<'_>) -> String { - let mut mac = hmac::Hmac::::new_from_slice(secret.as_bytes()).expect("HMAC accepts any key length"); + let key = hmac::Key::new(&hmac::HMAC_SHA256, secret.as_bytes()); + let mut mac = hmac::Context::with_key(&key); let port = id.port.to_string(); for field in [ context, @@ -205,13 +207,13 @@ fn proof(secret: &Secret, context: &str, id: &Identity<'_>) -> String { mac.update(field.as_bytes()); mac.update(&[0]); } - hex::encode(mac.finalize().into_bytes()) + hex::encode(mac.sign().as_ref()) } /// Constant-time equality, for comparing a credential against the expected one /// without leaking it byte-by-byte through timing. pub fn ct_eq(a: &str, b: &str) -> bool { - a.len() == b.len() && bool::from(a.as_bytes().ct_eq(b.as_bytes())) + rind::constant_time::verify(a.as_bytes(), b.as_bytes()).is_ok() } /// One peer's advertisement: the fields it published, plus the record they @@ -336,6 +338,7 @@ impl Config { /// returning, so a caller can treat success as "the mesh is live" and gate /// process readiness on it. Errors if no interface works within 5 seconds. pub async fn advertise(self) -> Result { + crate::crypto::check().map_err(|err| Error(err.into()))?; crate::runtime::scope(Discovery::new(self)).await } } diff --git a/rs/moq-tokio/src/quic/backend.rs b/rs/moq-tokio/src/quic/backend.rs index 31759394570..721435ca81a 100644 --- a/rs/moq-tokio/src/quic/backend.rs +++ b/rs/moq-tokio/src/quic/backend.rs @@ -97,6 +97,10 @@ pub enum Error { #[error("invalid quic config: {0}")] Config(#[from] driver::ConfigError), + /// This CPU lacks a feature that rind, MoQ's cryptography, requires. + #[error(transparent)] + UnsupportedCpu(#[from] crate::crypto::UnsupportedCpu), + /// The qlog trace file couldn't be created, usually a missing directory. #[cfg(feature = "qlog")] #[error("failed to create qlog file")] @@ -449,8 +453,7 @@ impl Client { // Even a plaintext fetch builds reqwest's TLS stack, which panics without a // process default when another crate in the graph builds it as `rustls-no-provider`. - // An error only means one is already installed. - let _ = crate::crypto::install_default(); + crate::crypto::install_default()?; let resp = reqwest::get(fingerprint.as_str()) .await diff --git a/rs/moq-tokio/src/quic/driver/endpoint.rs b/rs/moq-tokio/src/quic/driver/endpoint.rs index e2535d2cb9a..599996b1b51 100644 --- a/rs/moq-tokio/src/quic/driver/endpoint.rs +++ b/rs/moq-tokio/src/quic/driver/endpoint.rs @@ -1090,7 +1090,7 @@ struct PollProgress { keep_going: bool, } -#[cfg(all(test, any(unix, windows), any(feature = "ring", feature = "aws-lc-rs")))] +#[cfg(all(test, any(unix, windows), feature = "_certs"))] mod tests { use std::net::UdpSocket; diff --git a/rs/moq-tokio/src/quic/driver/forward.rs b/rs/moq-tokio/src/quic/driver/forward.rs index 55dce4bcaec..e18962d4645 100644 --- a/rs/moq-tokio/src/quic/driver/forward.rs +++ b/rs/moq-tokio/src/quic/driver/forward.rs @@ -18,10 +18,8 @@ use std::{ task::{Context, Poll, ready}, }; -use hmac::{KeyInit, Mac}; use moq_sock::udp::EcnCodepoint; - -type Hmac = hmac::Hmac; +use rind::hmac; /// Where a QUIC-LB connection ID carries its server ID: after the byte encoding its length. pub(crate) const ID_OFFSET: usize = 1; @@ -132,7 +130,6 @@ pub(crate) struct Unwrapped<'a> { } /// One server's forwarding: its server ID, its peers, and the socket forwards travel on. -#[derive(Debug)] pub(crate) struct Forward { socket: tokio::net::UdpSocket, /// The same socket, sending without waiting on the reactor to report it writable, which a @@ -140,11 +137,21 @@ pub(crate) struct Forward { send: std::net::UdpSocket, id: Box<[u8]>, peers: Peers, - key: Hmac, + key: hmac::Key, /// Scratch for one forward, sent or received. buf: Box<[u8]>, } +impl std::fmt::Debug for Forward { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Forward") + .field("socket", &self.socket) + .field("id", &self.id) + .field("peers", &self.peers) + .finish_non_exhaustive() + } +} + impl Forward { /// Forward on `socket` between the servers in `peers`, this one named `id` in its connection IDs. /// @@ -158,6 +165,7 @@ impl Forward { key: &[u8; 32], max_udp_payload_size: u16, ) -> io::Result { + crate::crypto::check().map_err(io::Error::other)?; socket.set_nonblocking(true)?; let send = socket.try_clone()?; let socket = { @@ -169,7 +177,7 @@ impl Forward { send, id: id.into(), peers, - key: Hmac::new_from_slice(key).expect("HMAC accepts any key length"), + key: hmac::Key::new(&hmac::HMAC_SHA256, key), buf: vec![0; usize::from(max_udp_payload_size) + OVERHEAD].into(), }) } @@ -226,8 +234,8 @@ impl Forward { buf[4..20].copy_from_slice(&ipv6(remote.ip()).octets()); buf[20..36].copy_from_slice(&local_ip.map_or(Ipv6Addr::UNSPECIFIED, ipv6).octets()); buf[OVERHEAD..].copy_from_slice(packet); - let tag = tag(&self.key, buf).finalize().into_bytes(); - buf[OVERHEAD - TAG_LEN..OVERHEAD].copy_from_slice(&tag[..TAG_LEN]); + let tag = tag(&self.key, buf); + buf[OVERHEAD - TAG_LEN..OVERHEAD].copy_from_slice(&tag.as_ref()[..TAG_LEN]); Some(buf.len()) } @@ -249,9 +257,8 @@ impl Forward { if len < OVERHEAD || buf[0] != VERSION { return None; } - tag(&self.key, buf) - .verify_truncated_left(&buf[OVERHEAD - TAG_LEN..OVERHEAD]) - .ok()?; + let expected = tag(&self.key, buf); + rind::constant_time::verify(&expected.as_ref()[..TAG_LEN], &buf[OVERHEAD - TAG_LEN..OVERHEAD]).ok()?; let packet = &buf[OVERHEAD..]; // Never forward again, and never answer for a connection another server owns: a peer @@ -283,11 +290,11 @@ impl Forward { } /// The MAC over `forward`'s header, short of the tag itself, and its packet. -fn tag(key: &Hmac, forward: &[u8]) -> Hmac { - let mut mac = key.clone(); +fn tag(key: &hmac::Key, forward: &[u8]) -> hmac::Tag { + let mut mac = hmac::Context::with_key(key); mac.update(&forward[..OVERHEAD - TAG_LEN]); mac.update(&forward[OVERHEAD..]); - mac + mac.sign() } fn ipv6(ip: IpAddr) -> Ipv6Addr { diff --git a/rs/moq-tokio/src/quic/driver/mod.rs b/rs/moq-tokio/src/quic/driver/mod.rs index 16b954a44ae..33a656afdaa 100644 --- a/rs/moq-tokio/src/quic/driver/mod.rs +++ b/rs/moq-tokio/src/quic/driver/mod.rs @@ -5,7 +5,7 @@ //! keep a prefix reliable, [`recv::Stream::poll_lease`] to hold receive credit until a message is //! complete, and [`connection::Connection::set_limits`] to change flow control on a live connection. //! -//! It needs no MoQ session: enable the `driver` feature (with `aws-lc-rs` or `ring`) and +//! It needs no MoQ session: enable the `driver` feature and //! `default-features = false` to build it without moq-net. The entry point is the //! [`endpoint::Endpoint`], built from an [`endpoint::Config`] and a UDP socket it owns; //! [`endpoint::Endpoint::connect`] dials with a [`client::Config`]. diff --git a/rs/moq-tokio/src/quic/driver/tests.rs b/rs/moq-tokio/src/quic/driver/tests.rs index 85b2736a5b3..c05c7c72a1f 100755 --- a/rs/moq-tokio/src/quic/driver/tests.rs +++ b/rs/moq-tokio/src/quic/driver/tests.rs @@ -1,9 +1,6 @@ -#![cfg(any(feature = "aws-lc-rs", feature = "ring"))] +#![cfg(feature = "_certs")] -#[cfg(all(feature = "aws-lc-rs", not(feature = "ring")))] -use rustls::crypto::aws_lc_rs::default_provider; -#[cfg(feature = "ring")] -use rustls::crypto::ring::default_provider; +use rind_rustls::default_provider; use std::{ future::Future, @@ -55,7 +52,14 @@ fn handshake_timeout() { }; // Avoid NoRootAnchors error - let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap(); + let cert = (|| -> std::result::Result<_, rcgen::Error> { + let signing_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?; + let mut params = rcgen::CertificateParams::new(vec!["localhost".into()])?; + params.serial_number = Some(1u64.into()); + let cert = params.self_signed(&signing_key)?; + Ok(rcgen::CertifiedKey { cert, signing_key }) + })() + .unwrap(); let mut roots = RootCertStore::empty(); roots.add(cert.cert.into()).unwrap(); @@ -92,7 +96,14 @@ async fn close_endpoint() { let _guard = subscribe(); // Avoid NoRootAnchors error - let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap(); + let cert = (|| -> std::result::Result<_, rcgen::Error> { + let signing_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?; + let mut params = rcgen::CertificateParams::new(vec!["localhost".into()])?; + params.serial_number = Some(1u64.into()); + let cert = params.self_signed(&signing_key)?; + Ok(rcgen::CertifiedKey { cert, signing_key }) + })() + .unwrap(); let mut roots = RootCertStore::empty(); roots.add(cert.cert.into()).unwrap(); @@ -128,7 +139,14 @@ async fn driver_panic_fails_connecting() { let _guard = subscribe(); // Avoid NoRootAnchors error - let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap(); + let cert = (|| -> std::result::Result<_, rcgen::Error> { + let signing_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?; + let mut params = rcgen::CertificateParams::new(vec!["localhost".into()])?; + params.serial_number = Some(1u64.into()); + let cert = params.self_signed(&signing_key)?; + Ok(rcgen::CertifiedKey { cert, signing_key }) + })() + .unwrap(); let mut roots = RootCertStore::empty(); roots.add(cert.cert.into()).unwrap(); @@ -262,14 +280,21 @@ fn endpoint_with_config(transport_config: transport::Config) -> Endpoint { /// Constructs endpoints suitable for connecting to themselves and each other struct EndpointFactory { - cert: rcgen::CertifiedKey, + cert: rcgen::CertifiedKey, endpoint_config: endpoint::Config, } impl EndpointFactory { fn new() -> Self { Self { - cert: rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap(), + cert: (|| -> std::result::Result<_, rcgen::Error> { + let signing_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?; + let mut params = rcgen::CertificateParams::new(vec!["localhost".into()])?; + params.serial_number = Some(1u64.into()); + let cert = params.self_signed(&signing_key)?; + Ok(rcgen::CertifiedKey { cert, signing_key }) + })() + .unwrap(), endpoint_config: endpoint::Config::default(), } } @@ -279,7 +304,7 @@ impl EndpointFactory { } fn server_config(&self, transport_config: transport::Config) -> server::Config { - let key = PrivateKeyDer::Pkcs8(self.cert.signing_key.serialize_der().into()); + let key = PrivateKeyDer::Pkcs8(self.cert.signing_key.to_pkcs8().secret_pkcs8_der().to_vec().into()); let mut server_config = crate::quic::driver::server::Config::with_single_cert(vec![self.cert.cert.der().clone()], key).unwrap(); server_config.transport = transport_config; @@ -432,8 +457,8 @@ fn blocking_server_pair( server_socket: Box, ) -> (Endpoint, Endpoint, Arc) { let factory = EndpointFactory::new(); - let key = PrivateKeyDer::Pkcs8(factory.cert.signing_key.serialize_der().into()); - let provider = Arc::new(default_provider()); + let key = PrivateKeyDer::Pkcs8(factory.cert.signing_key.to_pkcs8().secret_pkcs8_der().to_vec().into()); + let provider = Arc::new(default_provider().unwrap()); let key = rustls::sign::CertifiedKey::from_der(vec![factory.cert.cert.der().clone()], key, &provider).unwrap(); let blocker = Arc::new(HandshakeBlocker::default()); let mut server_crypto = rustls::ServerConfig::builder_with_provider(provider) @@ -462,9 +487,9 @@ fn blocking_server_pair( roots.add(factory.cert.cert.der().clone()).unwrap(); let client = client_endpoint(SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0)).unwrap(); // One classical key share keeps the ClientHello in the first Initial, so a handshake failure - // surfaces from `accept` itself. aws-lc-rs's default post-quantum share spills it into a + // surfaces from `accept` itself. rind's default post-quantum share spills it into a // second packet, which only reaches the connection after it is registered. - let mut provider = default_provider(); + let mut provider = default_provider().unwrap(); provider .kx_groups .retain(|group| group.name() == rustls::NamedGroup::X25519); @@ -666,8 +691,15 @@ async fn specific_v6_addr() { let _guard = subscribe(); let addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::LOCALHOST), 0); - let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap(); - let key = PrivatePkcs8KeyDer::from(cert.signing_key.serialize_der()); + let cert = (|| -> std::result::Result<_, rcgen::Error> { + let signing_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?; + let mut params = rcgen::CertificateParams::new(vec!["localhost".into()])?; + params.serial_number = Some(1u64.into()); + let cert = params.self_signed(&signing_key)?; + Ok(rcgen::CertifiedKey { cert, signing_key }) + })() + .unwrap(); + let key = PrivatePkcs8KeyDer::from(cert.signing_key.to_pkcs8().secret_pkcs8_der().to_vec()); let cert = CertificateDer::from(cert.cert); let server_config = server::Config::with_single_cert(vec![cert.clone()], key.into()).unwrap(); let server = server_endpoint(server_config, addr).unwrap(); @@ -769,8 +801,15 @@ fn run_echo(args: EchoArgs) { // We don't use the `endpoint` helper here because we want two different endpoints with // different addresses. - let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap(); - let key = PrivatePkcs8KeyDer::from(cert.signing_key.serialize_der()); + let cert = (|| -> std::result::Result<_, rcgen::Error> { + let signing_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?; + let mut params = rcgen::CertificateParams::new(vec!["localhost".into()])?; + params.serial_number = Some(1u64.into()); + let cert = params.self_signed(&signing_key)?; + Ok(rcgen::CertifiedKey { cert, signing_key }) + })() + .unwrap(); + let key = PrivatePkcs8KeyDer::from(cert.signing_key.to_pkcs8().secret_pkcs8_der().to_vec()); let cert = CertificateDer::from(cert.cert); let mut server_config = crate::quic::driver::server::Config::with_single_cert(vec![cert.clone()], key.into()).unwrap(); @@ -786,7 +825,7 @@ fn run_echo(args: EchoArgs) { let mut roots = RootCertStore::empty(); roots.add(cert).unwrap(); - let mut client_crypto = rustls::ClientConfig::builder_with_provider(default_provider().into()) + let mut client_crypto = rustls::ClientConfig::builder_with_provider(default_provider().unwrap().into()) .with_safe_default_protocol_versions() .unwrap() .with_root_certificates(roots) @@ -949,8 +988,15 @@ async fn retry_after_rebind() { async fn rebind_recv() { let _guard = subscribe(); - let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap(); - let key = PrivatePkcs8KeyDer::from(cert.signing_key.serialize_der()); + let cert = (|| -> std::result::Result<_, rcgen::Error> { + let signing_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?; + let mut params = rcgen::CertificateParams::new(vec!["localhost".into()])?; + params.serial_number = Some(1u64.into()); + let cert = params.self_signed(&signing_key)?; + Ok(rcgen::CertifiedKey { cert, signing_key }) + })() + .unwrap(); + let key = PrivatePkcs8KeyDer::from(cert.signing_key.to_pkcs8().secret_pkcs8_der().to_vec()); let cert = CertificateDer::from(cert.cert); let mut roots = RootCertStore::empty(); @@ -2346,7 +2392,14 @@ async fn unroutable_dial_fails_with_no_viable_path() { .unwrap(); let client = Endpoint::new(endpoint::Config::default(), UdpSocket::from(socket)).unwrap(); - let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap(); + let cert = (|| -> std::result::Result<_, rcgen::Error> { + let signing_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?; + let mut params = rcgen::CertificateParams::new(vec!["localhost".into()])?; + params.serial_number = Some(1u64.into()); + let cert = params.self_signed(&signing_key)?; + Ok(rcgen::CertifiedKey { cert, signing_key }) + })() + .unwrap(); let mut roots = RootCertStore::empty(); roots.add(cert.cert.into()).unwrap(); let client_config = client::Config::with_root_certificates(Arc::new(roots)).unwrap(); @@ -2417,7 +2470,7 @@ async fn unreachable_handshake_drains_while_held() { let _guard = subscribe(); let factory = EndpointFactory::new(); - let key = PrivateKeyDer::Pkcs8(factory.cert.signing_key.serialize_der().into()); + let key = PrivateKeyDer::Pkcs8(factory.cert.signing_key.to_pkcs8().secret_pkcs8_der().to_vec().into()); let server_config = crate::quic::driver::server::Config::with_single_cert(vec![factory.cert.cert.der().clone()], key).unwrap(); let outage = Arc::new(Outage::default()); diff --git a/rs/moq-tokio/src/quic/web/error.rs b/rs/moq-tokio/src/quic/web/error.rs index 9d0d36b4ef5..abc3c785891 100644 --- a/rs/moq-tokio/src/quic/web/error.rs +++ b/rs/moq-tokio/src/quic/web/error.rs @@ -217,7 +217,7 @@ pub enum ServerError { #[error("io error: {0}")] IoError(Arc), - #[cfg(any(feature = "aws-lc-rs", feature = "ring"))] + #[cfg(feature = "_certs")] /// The TLS configuration was invalid. #[error("rustls error: {0}")] Rustls(#[from] rustls::Error), diff --git a/rs/moq-tokio/src/quic/web/session.rs b/rs/moq-tokio/src/quic/web/session.rs index 16d0f80bd8f..9f5d77097bc 100644 --- a/rs/moq-tokio/src/quic/web/session.rs +++ b/rs/moq-tokio/src/quic/web/session.rs @@ -1114,7 +1114,7 @@ impl moq_net::transport::poll::Session for Session { } } -#[cfg(all(test, any(feature = "aws-lc-rs", feature = "ring")))] +#[cfg(all(test, feature = "_certs"))] mod tests { use std::{ io::{self, IoSliceMut}, @@ -1125,7 +1125,7 @@ mod tests { }, }; - use rcgen::{CertifiedKey, KeyPair}; + use rcgen::CertifiedKey; use rustls::pki_types::{PrivateKeyDer, PrivatePkcs8KeyDer}; use super::*; @@ -1230,11 +1230,19 @@ mod tests { [crate::quic::driver::endpoint::Endpoint; 2], Arc, ) { - #[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))); + crate::crypto::install_default().unwrap(); + + let CertifiedKey { cert, signing_key } = (|| -> std::result::Result<_, rcgen::Error> { + let signing_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?; + let mut params = rcgen::CertificateParams::new(vec!["localhost".into()])?; + params.serial_number = Some(1u64.into()); + let cert = params.self_signed(&signing_key)?; + Ok(rcgen::CertifiedKey { cert, signing_key }) + })() + .unwrap(); + let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from( + signing_key.to_pkcs8().secret_pkcs8_der().to_vec(), + )); let mut server_config = crate::quic::driver::server::Config::with_single_cert(vec![cert.der().clone()], key).unwrap(); diff --git a/rs/moq-tokio/src/runtime.rs b/rs/moq-tokio/src/runtime.rs index eace56c315a..45c56b8e1af 100644 --- a/rs/moq-tokio/src/runtime.rs +++ b/rs/moq-tokio/src/runtime.rs @@ -16,7 +16,7 @@ pub(crate) fn enter() -> Option> { } /// Where detached tasks run, captured once so tasks spawned later land beside the first. -#[cfg(any(feature = "driver", feature = "net"))] +#[cfg(feature = "driver")] #[derive(Debug, Clone)] pub(crate) enum Spawner { /// The caller's tokio runtime, else the fallback. @@ -26,7 +26,7 @@ pub(crate) enum Spawner { Sim, } -#[cfg(any(feature = "driver", feature = "net"))] +#[cfg(feature = "driver")] impl Spawner { /// The `kio::clock` simulator when called inside one, else the caller's runtime or the fallback. pub(crate) fn current() -> Self { @@ -52,7 +52,7 @@ impl Spawner { } /// Run `future` in the background with nobody to join it, where [`Spawner::current`] picks. -#[cfg(feature = "net")] +#[cfg(feature = "quic")] pub(crate) fn detach(future: F) where F: Future + Send + 'static, diff --git a/rs/moq-tokio/src/server.rs b/rs/moq-tokio/src/server.rs index d9a523ba828..42621ed52e7 100644 --- a/rs/moq-tokio/src/server.rs +++ b/rs/moq-tokio/src/server.rs @@ -3052,7 +3052,15 @@ mod tests { async fn client_auth_without_a_tls_listener_is_rejected() { let dir = tempfile::tempdir().unwrap(); let ca = dir.path().join("ca.pem"); - let cert = rcgen::generate_simple_self_signed(["ca".to_string()]).unwrap().cert; + let cert = (|| -> std::result::Result<_, rcgen::Error> { + let signing_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?; + let mut params = rcgen::CertificateParams::new(["ca".to_string()])?; + params.serial_number = Some(1u64.into()); + let cert = params.self_signed(&signing_key)?; + Ok(rcgen::CertifiedKey { cert, signing_key }) + })() + .unwrap() + .cert; std::fs::write(&ca, cert.pem()).unwrap(); type Set = Box; diff --git a/rs/moq-tokio/src/tcp.rs b/rs/moq-tokio/src/tcp.rs index 03ea6e30e64..243a28a53e7 100644 --- a/rs/moq-tokio/src/tcp.rs +++ b/rs/moq-tokio/src/tcp.rs @@ -470,10 +470,9 @@ mod tests { /// A `tls://` dial carries qmux and the request target over TLS, and a client /// that does not trust the certificate is refused. - #[cfg(feature = "aws-lc-rs")] #[tokio::test] async fn tls_carries_qmux_and_refuses_an_untrusted_certificate() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + crate::crypto::install_default().unwrap(); let mut listen = crate::listen::Config::default(); listen.tcp.bind = Some("127.0.0.1:0".parse().unwrap()); listen.tcp.tls = Some(true); @@ -485,12 +484,12 @@ mod tests { /// as QUIC does: CA roots accept a chained certificate or a token-only client, /// pinned peers require a pinned certificate. The request reports the chain /// and the SNI. - #[cfg(feature = "aws-lc-rs")] #[tokio::test] async fn tls_verifies_a_client_certificate() { - use rcgen::{BasicConstraints, CertificateParams, ExtendedKeyUsagePurpose, IsCa, Issuer, KeyPair}; + use rcgen::{BasicConstraints, CertificateParams, ExtendedKeyUsagePurpose, IsCa, Issuer}; + use rind_rcgen::KeyPair; - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + crate::crypto::install_default().unwrap(); let dir = tempfile::tempdir().unwrap(); let write = |name: &str, contents: String| { let path = dir.path().join(name); @@ -498,13 +497,23 @@ mod tests { path }; - let ca_key = KeyPair::generate().unwrap(); - let mut ca_params = CertificateParams::new(Vec::new()).unwrap(); + let ca_key = KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap(); + let mut ca_params = CertificateParams::new(Vec::new()) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .unwrap(); ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); let ca_cert = ca_params.self_signed(&ca_key).unwrap(); let issuer = Issuer::from_params(&ca_params, &ca_key); - let client_key = KeyPair::generate().unwrap(); - let mut client_params = CertificateParams::new(vec!["client.example".to_string()]).unwrap(); + let client_key = KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap(); + let mut client_params = CertificateParams::new(vec!["client.example".to_string()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .unwrap(); client_params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth]; let client_cert = client_params.signed_by(&client_key, &issuer).unwrap(); let fingerprint = crate::tls::PeerIdentity::from_chain(vec![client_cert.der().clone()]) @@ -513,7 +522,10 @@ mod tests { let ca = write("ca.pem", ca_cert.pem()); let cert = ( write("client.pem", client_cert.pem()), - write("client.key", client_key.serialize_pem()), + write( + "client.key", + pem::encode(&pem::Pem::new("PRIVATE KEY", client_key.to_pkcs8().secret_pkcs8_der())), + ), ); let listen = |set: &dyn Fn(&mut crate::listen::Config)| { @@ -563,7 +575,6 @@ mod tests { /// Dial `server` over `tls://localhost`, presenting `cert` (a PEM cert and key) /// if given. Returns the server with the accepted request's identity and SNI, /// or `None` when the dial is refused. - #[cfg(feature = "aws-lc-rs")] async fn mtls_dial( mut server: crate::Listener, cert: Option<&(std::path::PathBuf, std::path::PathBuf)>, @@ -600,7 +611,6 @@ mod tests { Some((server, identity, sni)) } - #[cfg(feature = "aws-lc-rs")] async fn tls_round_trip(listen: crate::listen::Config) { let mut server = listen.init(Default::default()).unwrap().listen().await.unwrap(); let port = server.tcp_local_addr().unwrap().port(); diff --git a/rs/moq-tokio/src/tls.rs b/rs/moq-tokio/src/tls.rs index 5a81a28b960..5c3937ee29f 100644 --- a/rs/moq-tokio/src/tls.rs +++ b/rs/moq-tokio/src/tls.rs @@ -19,7 +19,7 @@ use std::path::{Path, PathBuf}; use std::sync::{Arc, RwLock}; use std::{fs, io}; -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] +#[cfg(feature = "_certs")] use rustls::pki_types::PrivatePkcs8KeyDer; /// Errors loading or generating TLS certificates and keys. @@ -164,9 +164,9 @@ pub enum Error { #[error("failed to generate a self-signed certificate: {0}")] Rcgen(String), - /// The crate was built without a crypto provider, so no TLS is possible. - #[error("no crypto provider available; enable aws-lc-rs or ring feature")] - NoCryptoProvider, + /// This CPU lacks a feature that rind, MoQ's cryptography, requires. + #[error(transparent)] + UnsupportedCpu(#[from] crypto::UnsupportedCpu), /// The section was parsed from released spellings that no longer work. The /// payload is the migration to print. @@ -285,14 +285,14 @@ impl fmt::Debug for Certified { /// Set it on [`Listen::identity`] to serve it and [`Connect::identity`] to /// present it. Generated in memory and never written to disk, so it lasts as /// long as the process and a restart is a new principal. -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] +#[cfg(feature = "_certs")] #[derive(Clone)] pub struct Identity { key: Arc, fingerprint: String, } -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] +#[cfg(feature = "_certs")] impl Identity { /// Generate a fresh identity, valid for `hostnames`. /// @@ -301,9 +301,9 @@ impl Identity { /// placeholder name is enough there. pub fn generate(hostnames: impl IntoIterator>) -> Result { let hostnames: Vec = hostnames.into_iter().map(Into::into).collect(); - let provider = crypto::provider(); + let provider = crypto::provider()?; let key = Arc::new(generate(&provider, &hostnames)?); - let fingerprint = hex::encode(crypto::sha256(&provider, key.leaf().as_ref())); + let fingerprint = hex::encode(crypto::sha256(key.leaf().as_ref())); Ok(Self { key, fingerprint }) } @@ -322,7 +322,7 @@ impl Identity { } } -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] +#[cfg(feature = "_certs")] impl fmt::Debug for Identity { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter @@ -333,11 +333,11 @@ impl fmt::Debug for Identity { } /// Presents one fixed [`Identity`] whenever a server asks for a client certificate. -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] +#[cfg(feature = "_certs")] #[derive(Debug)] struct IdentityResolver(Arc); -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] +#[cfg(feature = "_certs")] impl rustls::client::ResolvesClientCert for IdentityResolver { fn resolve( &self, @@ -492,7 +492,7 @@ pub struct Connect { /// generates its identity at startup rather than loading one from disk. /// Setting both is an error. Not settable from the CLI or a config file, /// since it never exists on disk. - #[cfg(any(feature = "aws-lc-rs", feature = "ring"))] + #[cfg(feature = "_certs")] #[usage(skip)] #[serde(skip)] pub identity: Option, @@ -990,7 +990,7 @@ impl Connect { /// released `--tls-*` / `--client-tls-*` spellings rather than building one that /// silently ignored them. pub fn build(&self) -> Result { - let provider = crypto::provider(); + let provider = crypto::provider()?; let verification = self.verification()?; if let Some(name) = &self.host_name { server_name(name)?; @@ -1114,7 +1114,7 @@ impl Connect { &self, builder: rustls::ConfigBuilder, ) -> Result { - #[cfg(any(feature = "aws-lc-rs", feature = "ring"))] + #[cfg(feature = "_certs")] if let Some(identity) = &self.identity { if self.cert.is_some() || self.key.is_some() { return Err(Error::ConflictingClientAuth); @@ -1147,28 +1147,25 @@ impl Connect { /// Valid for two weeks starting yesterday: WebTransport refuses anything longer, /// and the backdating absorbs clock drift between two hosts that have never /// agreed on a time source. -#[cfg(any(feature = "aws-lc-rs", feature = "ring"))] +#[cfg(feature = "_certs")] fn generate(provider: &crypto::Provider, hostnames: &[String]) -> Result { - let key_pair = rcgen::KeyPair::generate()?; + let key_pair = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?; let mut params = rcgen::CertificateParams::new(hostnames)?; + let mut serial = [0; 16]; + rind::rand::fill(&mut serial).map_err(|err| Error::Rcgen(format!("random serial: {err}")))?; + params.serial_number = Some(rcgen::SerialNumber::from_slice(&serial)); params.not_before = ::time::OffsetDateTime::now_utc() - ::time::Duration::days(1); params.not_after = params.not_before + ::time::Duration::days(14); let cert = params.self_signed(&key_pair)?; // Convert the rcgen types to the rustls ones. - let key = PrivatePkcs8KeyDer::from(key_pair.serialized_der().to_vec()); + let key = PrivatePkcs8KeyDer::from(key_pair.to_pkcs8().secret_pkcs8_der().to_vec()); Certified::new(provider, vec![cert.into()], key.into()) } -/// Refuse at runtime when no crypto provider can sign a fresh certificate. -#[cfg(all(feature = "_certs", not(any(feature = "aws-lc-rs", feature = "ring"))))] -fn generate(_provider: &crypto::Provider, _hostnames: &[String]) -> Result { - Err(Error::NoCryptoProvider) -} - /// Build a [`rustls::RootCertStore`] from a list of custom PEM roots. fn root_store(custom: &[CertificateDer<'static>]) -> Result { let mut roots = rustls::RootCertStore::empty(); @@ -1256,7 +1253,7 @@ pub struct Listen { /// The programmatic alternative to `generate`, for a peer that hands the same /// identity to [`Connect::identity`] so both roles share one fingerprint. Not /// settable from the CLI or a config file, since it never exists on disk. - #[cfg(any(feature = "aws-lc-rs", feature = "ring"))] + #[cfg(feature = "_certs")] #[usage(skip)] #[serde(skip)] pub identity: Option, @@ -1359,7 +1356,7 @@ impl Listen { #[cfg(feature = "_certs")] pub fn load(&self) -> Result { self.refuse_deprecated()?; - let provider = crypto::provider(); + let provider = crypto::provider()?; let certs = Arc::new(ServeCerts::new(provider.clone())); certs.load_certs(self)?; let verifier = self.client_auth(provider)?; @@ -1382,11 +1379,11 @@ impl Listen { || !self.root.is_empty() || self.peers.is_some() || { - #[cfg(any(feature = "aws-lc-rs", feature = "ring"))] + #[cfg(feature = "_certs")] { self.identity.is_some() } - #[cfg(not(any(feature = "aws-lc-rs", feature = "ring")))] + #[cfg(not(feature = "_certs"))] { false } @@ -1540,7 +1537,7 @@ impl Listen { #[cfg(feature = "_certs")] pub fn server_config(&self, alpn: Vec>) -> Result> { self.refuse_deprecated()?; - let provider = crypto::provider(); + let provider = crypto::provider()?; let certs = ServeCerts::new(provider.clone()); certs.load_certs(self)?; @@ -1599,14 +1596,14 @@ impl Serve { /// usual verification and reload behavior. External certificates have no reported fingerprints. pub fn resolver(resolver: Arc, policy: &Listen) -> Result { policy.refuse_deprecated()?; - #[cfg(any(feature = "aws-lc-rs", feature = "ring"))] + #[cfg(feature = "_certs")] let in_memory = policy.identity.is_some(); - #[cfg(not(any(feature = "aws-lc-rs", feature = "ring")))] + #[cfg(not(feature = "_certs"))] let in_memory = false; if !policy.cert.is_empty() || !policy.key.is_empty() || !policy.generate.is_empty() || in_memory { return Err(Error::ConflictingResolver); } - let provider = crypto::provider(); + let provider = crypto::provider()?; let certs = Arc::new(ServeCerts::new(provider.clone())); let verifier = policy.client_auth(provider)?; #[cfg(feature = "watch")] @@ -1628,7 +1625,7 @@ impl Serve { /// Build a TLS policy with these ALPNs and the shared identity and client verifier. pub fn config(&self, alpn: Vec>) -> Result> { let builder = - rustls::ServerConfig::builder_with_provider(crypto::provider()).with_safe_default_protocol_versions()?; + rustls::ServerConfig::builder_with_provider(crypto::provider()?).with_safe_default_protocol_versions()?; let verifier = self.0.verifier.as_ref(); let mut config = match verifier { Some(verifier) => builder @@ -1690,7 +1687,7 @@ impl PeerIdentity { /// caller matches it against whatever it discovered them by. pub fn fingerprint(&self) -> Option { let leaf = self.chain.first()?; - Some(hex::encode(crypto::sha256(&crypto::provider(), leaf.as_ref()))) + Some(hex::encode(crypto::sha256(leaf.as_ref()))) } /// The peer's name: the leaf's first SAN DNS name, else its CN, else its @@ -1777,16 +1774,17 @@ impl Certificates { pub fn from_pem(chain: &[u8]) -> Result { use rustls::pki_types::pem::PemObject; + crypto::check()?; + let certs: Vec> = CertificateDer::pem_slice_iter(chain) .collect::>() .map_err(Error::Read)?; if certs.is_empty() { return Err(Error::Empty); } - let provider = crypto::provider(); let fingerprints = certs .iter() - .map(|cert| hex::encode(crypto::sha256(&provider, cert.as_ref()))) + .map(|cert| hex::encode(crypto::sha256(cert.as_ref()))) .collect(); Ok(Self::new(Arc::new(RwLock::new(Info { #[cfg(feature = "_certs")] @@ -2027,7 +2025,7 @@ impl rustls::server::danger::ClientCertVerifier for PeerVerifier { _intermediates: &[CertificateDer<'_>], _now: UnixTime, ) -> std::result::Result { - let fingerprint = crypto::sha256(&self.provider, end_entity); + let fingerprint = crypto::sha256(end_entity); match self.peers.contains_raw(fingerprint.as_ref()) { true => Ok(rustls::server::danger::ClientCertVerified::assertion()), false => Err(rustls::Error::General("unknown peer fingerprint".into())), @@ -2080,7 +2078,7 @@ impl rustls::client::danger::ServerCertVerifier for FingerprintVerifier { _ocsp: &[u8], _now: UnixTime, ) -> std::result::Result { - let fingerprint = crypto::sha256(&self.provider, end_entity); + let fingerprint = crypto::sha256(end_entity); if self.fingerprints.iter().any(|fp| fingerprint.as_ref() == fp.as_slice()) { Ok(rustls::client::danger::ServerCertVerified::assertion()) } else { @@ -2112,7 +2110,7 @@ impl rustls::client::danger::ServerCertVerifier for FingerprintVerifier { } #[cfg(test)] -#[cfg(all(feature = "quic", feature = "aws-lc-rs"))] +#[cfg(feature = "quic")] mod tests { #[tokio::test] async fn resolved_config_keeps_reload_owner_alive() { @@ -2135,13 +2133,21 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let cert_path = dir.path().join("cert.pem"); let key_path = dir.path().join("key.pem"); - let key = rcgen::KeyPair::generate().unwrap(); + let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap(); let cert = rcgen::CertificateParams::new(vec!["localhost".into()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) .unwrap() .self_signed(&key) .unwrap(); std::fs::write(&cert_path, cert.pem()).unwrap(); - std::fs::write(&key_path, key.serialize_pem()).unwrap(); + std::fs::write( + &key_path, + pem::encode(&pem::Pem::new("PRIVATE KEY", key.to_pkcs8().secret_pkcs8_der())), + ) + .unwrap(); let config = Listen { cert: vec![cert_path.clone()], key: vec![key_path.clone()], @@ -2155,8 +2161,12 @@ mod tests { let first = serving.config(Vec::new()).unwrap(); let second = sibling.config(Vec::new()).unwrap(); assert!(Arc::ptr_eq(&first.cert_resolver, &second.cert_resolver)); - let next_key = rcgen::KeyPair::generate().unwrap(); + let next_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap(); let next_cert = rcgen::CertificateParams::new(vec!["localhost".into()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) .unwrap() .self_signed(&next_key) .unwrap(); @@ -2166,7 +2176,11 @@ mod tests { "a half-written pair must not replace the snapshot" ); assert_eq!(certificates.fingerprints(), previous); - std::fs::write(&key_path, next_key.serialize_pem()).unwrap(); + std::fs::write( + &key_path, + pem::encode(&pem::Pem::new("PRIVATE KEY", next_key.to_pkcs8().secret_pkcs8_der())), + ) + .unwrap(); serving.0.certs.load_certs(&config).unwrap(); assert_ne!(certificates.fingerprints(), previous); assert_eq!(certificates.fingerprints(), serving.certificates().fingerprints()); @@ -2184,13 +2198,21 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let cert_path = dir.path().join("cert.pem"); let key_path = dir.path().join("key.pem"); - let key = rcgen::KeyPair::generate().unwrap(); + let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap(); let cert = rcgen::CertificateParams::new(vec!["localhost".into()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) .unwrap() .self_signed(&key) .unwrap(); std::fs::write(&cert_path, cert.pem()).unwrap(); - std::fs::write(&key_path, key.serialize_pem()).unwrap(); + std::fs::write( + &key_path, + pem::encode(&pem::Pem::new("PRIVATE KEY", key.to_pkcs8().secret_pkcs8_der())), + ) + .unwrap(); Listen { cert: vec![cert_path], key: vec![key_path], @@ -2210,7 +2232,7 @@ mod tests { key: vec![missing.clone()], ..Default::default() }; - let error = Reload::spawn(Arc::new(ServeCerts::new(crypto::provider())), config).unwrap_err(); + let error = Reload::spawn(Arc::new(ServeCerts::new(crypto::provider().unwrap())), config).unwrap_err(); assert!(matches!(error, Error::Watch(_))); let initial = rustls::server::WebPkiClientVerifier::no_client_auth(); let reload = initial.clone(); @@ -2273,8 +2295,13 @@ mod tests { use rustls::server::danger::ClientCertVerifier; fn self_signed() -> CertificateDer<'static> { - let key = rcgen::KeyPair::generate().unwrap(); - let params = rcgen::CertificateParams::new(vec!["localhost".to_string()]).unwrap(); + let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap(); + let params = rcgen::CertificateParams::new(vec!["localhost".to_string()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .unwrap(); params.self_signed(&key).unwrap().into() } @@ -2283,8 +2310,13 @@ mod tests { // notAfter at a whole second so the round-trip is exact. let not_after = ::time::OffsetDateTime::from_unix_timestamp(2_000_000_000).unwrap(); - let key = rcgen::KeyPair::generate().unwrap(); - let mut params = rcgen::CertificateParams::new(vec!["localhost".to_string()]).unwrap(); + let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap(); + let mut params = rcgen::CertificateParams::new(vec!["localhost".to_string()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .unwrap(); params.not_after = not_after; let cert: CertificateDer<'static> = params.self_signed(&key).unwrap().into(); @@ -2305,8 +2337,13 @@ mod tests { (18_446_744_074, last), (67_090_118_400, last), ] { - let key = rcgen::KeyPair::generate().unwrap(); - let mut params = rcgen::CertificateParams::new(vec!["localhost".to_string()]).unwrap(); + let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap(); + let mut params = rcgen::CertificateParams::new(vec!["localhost".to_string()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .unwrap(); params.not_after = ::time::OffsetDateTime::from_unix_timestamp(seconds).unwrap(); let cert = params.self_signed(&key).unwrap().into(); let peer = PeerIdentity { chain: vec![cert] }; @@ -2316,9 +2353,9 @@ mod tests { #[test] fn fingerprint_verifier_matches_and_rejects() { - let provider = crypto::provider(); + let provider = crypto::provider().unwrap(); let cert = self_signed(); - let fingerprint = crypto::sha256(&provider, cert.as_ref()).as_ref().to_vec(); + let fingerprint = crypto::sha256(cert.as_ref()).as_ref().to_vec(); let name = ServerName::try_from("localhost").unwrap(); let now = UnixTime::now(); @@ -2334,7 +2371,7 @@ mod tests { #[test] fn build_installs_fingerprint_verifier() { let cert = self_signed(); - let fingerprint = hex::encode(crypto::sha256(&crypto::provider(), cert.as_ref())); + let fingerprint = hex::encode(crypto::sha256(cert.as_ref())); // A bogus hash still builds; verification happens at handshake time. let config = Connect { @@ -2350,7 +2387,7 @@ mod tests { fn identity_serves_the_fingerprint_it_presents() { let identity = Identity::generate(["mesh.invalid"]).unwrap(); - let certs = ServeCerts::new(crypto::provider()); + let certs = ServeCerts::new(crypto::provider().unwrap()); certs .load_certs(&Listen { identity: Some(identity.clone()), @@ -2376,14 +2413,21 @@ mod tests { fn generated_certificate_survives_a_reload() { use std::io::Write; - let key = rcgen::KeyPair::generate().unwrap(); - let params = rcgen::CertificateParams::new(vec!["file.invalid".to_string()]).unwrap(); + let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap(); + let params = rcgen::CertificateParams::new(vec!["file.invalid".to_string()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .unwrap(); let cert = params.self_signed(&key).unwrap(); let mut cert_file = tempfile::NamedTempFile::new().unwrap(); cert_file.write_all(cert.pem().as_bytes()).unwrap(); let mut key_file = tempfile::NamedTempFile::new().unwrap(); - key_file.write_all(key.serialize_pem().as_bytes()).unwrap(); + key_file + .write_all(pem::encode(&pem::Pem::new("PRIVATE KEY", key.to_pkcs8().secret_pkcs8_der())).as_bytes()) + .unwrap(); let config = Listen { cert: vec![cert_file.path().to_path_buf()], @@ -2392,7 +2436,7 @@ mod tests { ..Default::default() }; - let certs = ServeCerts::new(crypto::provider()); + let certs = ServeCerts::new(crypto::provider().unwrap()); certs.load_certs(&config).unwrap(); let before = Certificates::new(certs.info.clone()).fingerprints(); @@ -2411,8 +2455,13 @@ mod tests { #[cfg(all(feature = "watch", feature = "quic"))] #[tokio::test] async fn dropping_the_reload_guard_stops_the_watcher() { - let key = rcgen::KeyPair::generate().unwrap(); - let params = rcgen::CertificateParams::new(vec!["file.invalid".to_string()]).unwrap(); + let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap(); + let params = rcgen::CertificateParams::new(vec!["file.invalid".to_string()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .unwrap(); let cert = params.self_signed(&key).unwrap(); // A dedicated directory, not `/tmp`: the watcher registers the parent, and @@ -2422,7 +2471,11 @@ mod tests { let cert_path = dir.path().join("cert.pem"); let key_path = dir.path().join("key.pem"); std::fs::write(&cert_path, cert.pem()).unwrap(); - std::fs::write(&key_path, key.serialize_pem()).unwrap(); + std::fs::write( + &key_path, + pem::encode(&pem::Pem::new("PRIVATE KEY", key.to_pkcs8().secret_pkcs8_der())), + ) + .unwrap(); // File-backed, so the watcher actually parks rather than returning early. let config = Listen { @@ -2431,7 +2484,7 @@ mod tests { ..Default::default() }; - let certs = Arc::new(ServeCerts::new(crypto::provider())); + let certs = Arc::new(ServeCerts::new(crypto::provider().unwrap())); certs.load_certs(&config).unwrap(); let weak = Arc::downgrade(&certs); @@ -2487,7 +2540,7 @@ mod tests { ..Default::default() }; assert!(matches!( - config.client_auth(crypto::provider()), + config.client_auth(crypto::provider().unwrap()), Err(Error::PeersWithRoots) )); } @@ -2496,7 +2549,7 @@ mod tests { /// `root` only because the two together are already refused. #[test] fn client_auth_is_off_until_configured() { - let provider = crypto::provider(); + let provider = crypto::provider().unwrap(); assert!(Listen::default().client_auth(provider.clone()).unwrap().is_none()); let pinned = Listen { @@ -2518,7 +2571,7 @@ mod tests { fn peers_are_checked_live() { let identity = Identity::generate(["mesh.invalid"]).unwrap(); let peers = Peers::new(); - let verifier = PeerVerifier::new(crypto::provider(), peers.clone()); + let verifier = PeerVerifier::new(crypto::provider().unwrap(), peers.clone()); let leaf = identity.certified().leaf().clone(); let now = UnixTime::since_unix_epoch(std::time::Duration::from_secs(1_700_000_000)); @@ -2677,7 +2730,7 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let root = dir.path().join("root.pem"); std::fs::write(&root, ca).unwrap(); - let provider = crypto::provider(); + let provider = crypto::provider().unwrap(); let key = rustls::sign::CertifiedKey::from_der(vec![server_cert], server_key, &provider).unwrap(); #[derive(Debug)] struct Fixed(Arc); @@ -2794,7 +2847,7 @@ mod tests { // Same for fingerprint pinning. let cert = self_signed(); - let fingerprint = hex::encode(crypto::sha256(&crypto::provider(), cert.as_ref())); + let fingerprint = hex::encode(crypto::sha256(cert.as_ref())); let config = Connect { system_roots: Some(false), fingerprint: vec![fingerprint], @@ -2806,7 +2859,7 @@ mod tests { #[test] fn build_rejects_fingerprint_with_roots() { let cert = self_signed(); - let fingerprint = hex::encode(crypto::sha256(&crypto::provider(), cert.as_ref())); + let fingerprint = hex::encode(crypto::sha256(cert.as_ref())); // Fingerprint pinning bypasses the CA chain, so combining it with roots // is rejected rather than silently ignoring one of them. @@ -2831,8 +2884,13 @@ mod tests { /// handle alongside its path. fn self_signed_root() -> (tempfile::NamedTempFile, PathBuf) { use std::io::Write; - let key = rcgen::KeyPair::generate().unwrap(); - let params = rcgen::CertificateParams::new(vec!["localhost".to_string()]).unwrap(); + let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap(); + let params = rcgen::CertificateParams::new(vec!["localhost".to_string()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .unwrap(); let cert = params.self_signed(&key).unwrap(); let mut file = tempfile::NamedTempFile::new().unwrap(); file.write_all(cert.pem().as_bytes()).unwrap(); @@ -2850,21 +2908,36 @@ mod tests { ) { use rcgen::{BasicConstraints, ExtendedKeyUsagePurpose, IsCa, Issuer}; - let ca_key = rcgen::KeyPair::generate().unwrap(); - let mut ca_params = rcgen::CertificateParams::new(Vec::::new()).unwrap(); + let ca_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap(); + let mut ca_params = rcgen::CertificateParams::new(Vec::::new()) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .unwrap(); ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); let ca = ca_params.self_signed(&ca_key).unwrap(); let issuer = Issuer::from_params(&ca_params, &ca_key); - let server_key = rcgen::KeyPair::generate().unwrap(); - let server_key_der = PrivatePkcs8KeyDer::from(server_key.serialize_der()); - let mut server_params = rcgen::CertificateParams::new(vec!["localhost".to_string()]).unwrap(); + let server_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap(); + let server_key_der = PrivatePkcs8KeyDer::from(server_key.to_pkcs8().secret_pkcs8_der().to_vec()); + let mut server_params = rcgen::CertificateParams::new(vec!["localhost".to_string()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .unwrap(); server_params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth]; let server = server_params.signed_by(&server_key, &issuer).unwrap(); - let client_key = rcgen::KeyPair::generate().unwrap(); - let client_key_der = PrivatePkcs8KeyDer::from(client_key.serialize_der()); - let mut client_params = rcgen::CertificateParams::new(Vec::::new()).unwrap(); + let client_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap(); + let client_key_der = PrivatePkcs8KeyDer::from(client_key.to_pkcs8().secret_pkcs8_der().to_vec()); + let mut client_params = rcgen::CertificateParams::new(Vec::::new()) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .unwrap(); client_params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth]; let client = client_params.signed_by(&client_key, &issuer).unwrap(); @@ -2918,7 +2991,7 @@ mod tests { let mut root_file = tempfile::NamedTempFile::new().unwrap(); root_file.write_all(ca.as_bytes()).unwrap(); let roots = read_roots(&[root_file.path().to_path_buf()]).unwrap(); - let provider = crypto::provider(); + let provider = crypto::provider().unwrap(); let control = rustls::ClientConfig::builder_with_provider(provider.clone()) .with_safe_default_protocol_versions() @@ -2972,7 +3045,7 @@ mod tests { let root_path = dir.path().join("root.pem"); std::fs::write(&root_path, ca_a).unwrap(); let paths = vec![root_path.clone()]; - let provider = crypto::provider(); + let provider = crypto::provider().unwrap(); let build_client = |cert, key| { rustls::ClientConfig::builder_with_provider(provider.clone()) @@ -3049,7 +3122,7 @@ mod tests { let root_path = dir.path().join("root.pem"); std::fs::write(&root_path, ca_a).unwrap(); let paths = vec![root_path.clone()]; - let provider = crypto::provider(); + let provider = crypto::provider().unwrap(); let custom = CustomRoots::new(paths.clone()).unwrap(); let initial = Connect::build_root_server_verifier(&custom.current(), false, &provider).unwrap(); @@ -3169,9 +3242,9 @@ impl ServeCerts { } // An in-memory identity is a certificate source like the other two, so a // listener configured with only that one still has something to serve. - #[cfg(any(feature = "aws-lc-rs", feature = "ring"))] + #[cfg(feature = "_certs")] let in_memory = config.identity.is_some(); - #[cfg(not(any(feature = "aws-lc-rs", feature = "ring")))] + #[cfg(not(feature = "_certs"))] let in_memory = false; if config.cert.is_empty() && config.generate.is_empty() && !in_memory { return Err(Error::NoCertSource); @@ -3189,7 +3262,7 @@ impl ServeCerts { certs.push(self.generated(&config.generate)?); } - #[cfg(any(feature = "aws-lc-rs", feature = "ring"))] + #[cfg(feature = "_certs")] if let Some(identity) = &config.identity { certs.push(identity.certified()); } @@ -3239,7 +3312,7 @@ impl ServeCerts { let fingerprints = certs .iter() .map(|ck| { - let fingerprint = crate::crypto::sha256(&self.provider, ck.leaf().as_ref()); + let fingerprint = crate::crypto::sha256(ck.leaf().as_ref()); hex::encode(fingerprint) }) .collect(); diff --git a/rs/moq-tokio/src/websocket.rs b/rs/moq-tokio/src/websocket.rs index 88708730cc3..f38cf2b2088 100644 --- a/rs/moq-tokio/src/websocket.rs +++ b/rs/moq-tokio/src/websocket.rs @@ -916,10 +916,19 @@ mod tests { // Clients send SNI only for DNS names, never for IP addresses. let expected_sni = name.parse::().is_err().then_some(name); - let rcgen::CertifiedKey { cert, signing_key } = rcgen::generate_simple_self_signed([name.to_string()]).unwrap(); + let rcgen::CertifiedKey { cert, signing_key } = (|| -> std::result::Result<_, rcgen::Error> { + let signing_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?; + let mut params = rcgen::CertificateParams::new([name.to_string()])?; + params.serial_number = Some(1u64.into()); + let cert = params.self_signed(&signing_key)?; + Ok(rcgen::CertifiedKey { cert, signing_key }) + })() + .unwrap(); let cert = CertificateDer::from(cert); - let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(signing_key.serialize_der())); - let provider = crate::crypto::provider(); + let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from( + signing_key.to_pkcs8().secret_pkcs8_der().to_vec(), + )); + let provider = crate::crypto::provider().unwrap(); let server_tls = rustls::ServerConfig::builder_with_provider(provider.clone()) .with_safe_default_protocol_versions() .unwrap() diff --git a/rs/moq-tokio/tests/integration/backend.rs b/rs/moq-tokio/tests/integration/backend.rs index 6b51a452911..425a7781c1a 100644 --- a/rs/moq-tokio/tests/integration/backend.rs +++ b/rs/moq-tokio/tests/integration/backend.rs @@ -229,8 +229,13 @@ async fn connect_test(config: ConnectTest<'_>) { fn write_self_signed(dir: &std::path::Path, stem: &str, name: &str) -> (std::path::PathBuf, std::path::PathBuf) { use std::io::Write; - let key = rcgen::KeyPair::generate().expect("key"); - let params = rcgen::CertificateParams::new(vec![name.to_string()]).expect("params"); + let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).expect("key"); + let params = rcgen::CertificateParams::new(vec![name.to_string()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .expect("params"); let cert = params.self_signed(&key).expect("cert"); let write = |name: String, contents: String| { @@ -242,7 +247,10 @@ fn write_self_signed(dir: &std::path::Path, stem: &str, name: &str) -> (std::pat ( write(format!("{stem}.pem"), cert.pem()), - write(format!("{stem}.key"), key.serialize_pem()), + write( + format!("{stem}.key"), + pem::encode(&pem::Pem::new("PRIVATE KEY", key.to_pkcs8().secret_pkcs8_der())), + ), ) } @@ -383,16 +391,20 @@ async fn reload_test() { /// five paths so the caller can wire them into the TLS configs. #[cfg(feature = "quic")] fn generate_mtls_certs() -> (tempfile::TempDir, MtlsPaths) { - use rcgen::{ - BasicConstraints, CertificateParams, DnType, ExtendedKeyUsagePurpose, IsCa, Issuer, KeyPair, KeyUsagePurpose, - }; + use rcgen::{BasicConstraints, CertificateParams, DnType, ExtendedKeyUsagePurpose, IsCa, Issuer, KeyUsagePurpose}; + use rind_rcgen::KeyPair; use std::io::Write; let dir = tempfile::tempdir().expect("failed to create tempdir"); // Self-signed CA that signs both the server and client leaf certs. - let ca_key = KeyPair::generate().expect("ca key"); - let mut ca_params = CertificateParams::new(Vec::new()).expect("ca params"); + let ca_key = KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).expect("ca key"); + let mut ca_params = CertificateParams::new(Vec::new()) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .expect("ca params"); ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); ca_params.distinguished_name.push(DnType::CommonName, "moq test CA"); ca_params.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign]; @@ -400,15 +412,25 @@ fn generate_mtls_certs() -> (tempfile::TempDir, MtlsPaths) { let issuer = Issuer::from_params(&ca_params, &ca_key); // Server leaf with a localhost SAN so the client can verify the name. - let server_key = KeyPair::generate().expect("server key"); - let mut server_params = CertificateParams::new(vec!["localhost".to_string()]).expect("server params"); + let server_key = KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).expect("server key"); + let mut server_params = CertificateParams::new(vec!["localhost".to_string()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .expect("server params"); server_params.distinguished_name.push(DnType::CommonName, "localhost"); server_params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth]; let server_cert = server_params.signed_by(&server_key, &issuer).expect("server cert"); // Client leaf presented during the handshake for mTLS. - let client_key = KeyPair::generate().expect("client key"); - let mut client_params = CertificateParams::new(vec!["client.example".to_string()]).expect("client params"); + let client_key = KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).expect("client key"); + let mut client_params = CertificateParams::new(vec!["client.example".to_string()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .expect("client params"); client_params .distinguished_name .push(DnType::CommonName, "client.example"); @@ -425,9 +447,15 @@ fn generate_mtls_certs() -> (tempfile::TempDir, MtlsPaths) { let paths = MtlsPaths { ca: write("ca.pem", ca_cert.pem()), server_cert: write("server.pem", server_cert.pem()), - server_key: write("server.key", server_key.serialize_pem()), + server_key: write( + "server.key", + pem::encode(&pem::Pem::new("PRIVATE KEY", server_key.to_pkcs8().secret_pkcs8_der())), + ), client_cert: write("client.pem", client_cert.pem()), - client_key: write("client.key", client_key.serialize_pem()), + client_key: write( + "client.key", + pem::encode(&pem::Pem::new("PRIVATE KEY", client_key.to_pkcs8().secret_pkcs8_der())), + ), }; (dir, paths) diff --git a/rs/moq-tokio/tests/integration/datagram_delivery.rs b/rs/moq-tokio/tests/integration/datagram_delivery.rs index 10340deadd0..26be2486335 100644 --- a/rs/moq-tokio/tests/integration/datagram_delivery.rs +++ b/rs/moq-tokio/tests/integration/datagram_delivery.rs @@ -194,7 +194,7 @@ impl Report { /// Publish datagrams at `cell`'s rate to a loopback viewer and a bufferbloated one. async fn measure(version: &str, cell: Cell) { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let version: moq_net::Version = version.parse().expect("version"); let publisher = moq_tokio::origin::spawn(); diff --git a/rs/moq-tokio/tests/integration/receive_credit.rs b/rs/moq-tokio/tests/integration/receive_credit.rs index d9914511456..0cefefda3d1 100644 --- a/rs/moq-tokio/tests/integration/receive_credit.rs +++ b/rs/moq-tokio/tests/integration/receive_credit.rs @@ -77,7 +77,7 @@ async fn setup_through( transport: driver::transport::Config, profile: Option, ) -> Setup { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let version: moq_net::Version = version.parse().expect("version"); let publisher = moq_tokio::origin::spawn(); @@ -415,13 +415,19 @@ struct Reversed { } async fn reversed(version: &str) -> Reversed { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let version: moq_net::Version = version.parse().expect("version"); let alpn = version.alpn().as_bytes().to_vec(); - let rcgen::CertifiedKey { cert, signing_key } = - rcgen::generate_simple_self_signed(["localhost".to_string()]).expect("certificate"); - let key = rustls::pki_types::PrivatePkcs8KeyDer::from(signing_key.serialize_der()); + let rcgen::CertifiedKey { cert, signing_key } = (|| -> std::result::Result<_, rcgen::Error> { + let signing_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?; + let mut params = rcgen::CertificateParams::new(["localhost".to_string()])?; + params.serial_number = Some(1u64.into()); + let cert = params.self_signed(&signing_key)?; + Ok(rcgen::CertifiedKey { cert, signing_key }) + })() + .expect("certificate"); + let key = rustls::pki_types::PrivatePkcs8KeyDer::from(signing_key.to_pkcs8().secret_pkcs8_der().to_vec()); let mut tls = rustls::ServerConfig::builder() .with_no_client_auth() .with_single_cert(vec![cert.der().clone()], key.into()) @@ -781,16 +787,22 @@ async fn javascript_exhausts( /// declared twice that size. The receiver evicts it, a high-priority frame completes, and a /// later low group arrives. async fn javascript_partial_frame_gives_way(version: &str) { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let version: moq_net::Version = version.parse().expect("version"); // The sender pins this certificate, so it needs no name or CA. - let rcgen::CertifiedKey { cert, signing_key } = - rcgen::generate_simple_self_signed(["localhost".to_string()]).expect("certificate"); + let rcgen::CertifiedKey { cert, signing_key } = (|| -> std::result::Result<_, rcgen::Error> { + let signing_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?; + let mut params = rcgen::CertificateParams::new(["localhost".to_string()])?; + params.serial_number = Some(1u64.into()); + let cert = params.self_signed(&signing_key)?; + Ok(rcgen::CertifiedKey { cert, signing_key }) + })() + .expect("certificate"); let dir = tempfile::tempdir().expect("tempdir"); let pem = dir.path().join("cert.pem"); std::fs::write(&pem, cert.pem()).expect("write certificate"); - let key = rustls::pki_types::PrivatePkcs8KeyDer::from(signing_key.serialize_der()); + let key = rustls::pki_types::PrivatePkcs8KeyDer::from(signing_key.to_pkcs8().secret_pkcs8_der().to_vec()); let mut tls = rustls::ServerConfig::builder() .with_no_client_auth() .with_single_cert(vec![cert.der().clone()], key.into()) @@ -1210,7 +1222,8 @@ impl rustls::client::danger::ServerCertVerifier for AnyCert { } fn supported_verify_schemes(&self) -> Vec { - rustls::crypto::aws_lc_rs::default_provider() + rind_rustls::default_provider() + .unwrap() .signature_verification_algorithms .supported_schemes() } diff --git a/rs/moq-tokio/tests/integration/receive_ts.rs b/rs/moq-tokio/tests/integration/receive_ts.rs index 388f43f6ae9..5826d8d37e9 100644 --- a/rs/moq-tokio/tests/integration/receive_ts.rs +++ b/rs/moq-tokio/tests/integration/receive_ts.rs @@ -104,8 +104,15 @@ struct Run { async fn run(preset: &str) -> Run { let preset = moq_shaper::Preset::load(preset).expect("preset"); - let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap(); - let key = rustls::pki_types::PrivatePkcs8KeyDer::from(cert.signing_key.serialize_der()); + let cert = (|| -> std::result::Result<_, rcgen::Error> { + let signing_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?; + let mut params = rcgen::CertificateParams::new(vec!["localhost".into()])?; + params.serial_number = Some(1u64.into()); + let cert = params.self_signed(&signing_key)?; + Ok(rcgen::CertifiedKey { cert, signing_key }) + })() + .unwrap(); + let key = rustls::pki_types::PrivatePkcs8KeyDer::from(cert.signing_key.to_pkcs8().secret_pkcs8_der().to_vec()); let server_config = driver::server::Config::with_single_cert(vec![cert.cert.into()], key.into()).expect("server config"); let server = driver::endpoint::Endpoint::new( @@ -285,7 +292,7 @@ fn slope(span: &[Reading]) -> Option { /// Runs `preset` and prints its rows of the table, under the same header as the others async fn report(preset: &str) { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let run = run(preset).await; println!( "| preset | signal | readings/s | noise σ | ceiling | detect @ceiling | detect @{THRESHOLD} | false alarms @{THRESHOLD} |" diff --git a/rs/moq-tokio/tests/integration/reset_secret.rs b/rs/moq-tokio/tests/integration/reset_secret.rs index 058f15bf75c..1384fcaddd2 100644 --- a/rs/moq-tokio/tests/integration/reset_secret.rs +++ b/rs/moq-tokio/tests/integration/reset_secret.rs @@ -24,8 +24,12 @@ struct Fixture { impl Fixture { fn new() -> Self { let dir = tempfile::tempdir().expect("tempdir"); - let key = rcgen::KeyPair::generate().expect("key"); + let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).expect("key"); let cert = rcgen::CertificateParams::new(vec!["localhost".to_string()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) .expect("params") .self_signed(&key) .expect("cert"); @@ -37,7 +41,10 @@ impl Fixture { Self { cert: cert.der().clone(), cert_path: write("server.pem", cert.pem().as_bytes()), - key_path: write("server.key", key.serialize_pem().as_bytes()), + key_path: write( + "server.key", + pem::encode(&pem::Pem::new("PRIVATE KEY", key.to_pkcs8().secret_pkcs8_der())).as_bytes(), + ), reset_secret: write("reset.key", format!("{RESET_SECRET}\n").as_bytes()), _dir: dir, } @@ -82,7 +89,7 @@ impl Fixture { /// Connect, crash the server and restart it on the same port, then report how the /// client's connection ended once it next sent something. fn restart(reset_secret: bool) -> Result { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let fixture = Fixture::new(); let client = tokio::runtime::Builder::new_current_thread() .enable_all() diff --git a/rs/moq-tokio/tests/integration/scream.rs b/rs/moq-tokio/tests/integration/scream.rs index 0f868ac6472..f234c0dfa19 100644 --- a/rs/moq-tokio/tests/integration/scream.rs +++ b/rs/moq-tokio/tests/integration/scream.rs @@ -154,8 +154,15 @@ struct Run { } async fn run(preset: &moq_shaper::Preset) -> Run { - let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap(); - let key = rustls::pki_types::PrivatePkcs8KeyDer::from(cert.signing_key.serialize_der()); + let cert = (|| -> std::result::Result<_, rcgen::Error> { + let signing_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?; + let mut params = rcgen::CertificateParams::new(vec!["localhost".into()])?; + params.serial_number = Some(1u64.into()); + let cert = params.self_signed(&signing_key)?; + Ok(rcgen::CertifiedKey { cert, signing_key }) + })() + .unwrap(); + let key = rustls::pki_types::PrivatePkcs8KeyDer::from(cert.signing_key.to_pkcs8().secret_pkcs8_der().to_vec()); let server_config = driver::server::Config::with_single_cert(vec![cert.cert.into()], key.into()).expect("server config"); let server = driver::endpoint::Endpoint::new( @@ -316,7 +323,7 @@ fn triple(sorted: &[Duration]) -> String { /// Runs `preset` and prints its row of the table, under the same header as the others async fn report(name: &str) { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let preset = moq_shaper::Preset::load(name).expect("preset"); let setup = preset.setup("127.0.0.1:0".parse().unwrap(), "127.0.0.1:1".parse().unwrap()); // The uplink's rate over each phase, from its start; none on a path with no rate limit diff --git a/rs/moq-tokio/tests/integration/sim.rs b/rs/moq-tokio/tests/integration/sim.rs index c4f39266dc9..66bcb82e6cb 100644 --- a/rs/moq-tokio/tests/integration/sim.rs +++ b/rs/moq-tokio/tests/integration/sim.rs @@ -247,10 +247,16 @@ fn transport(seed: u64) -> driver::transport::Config { /// A self-signed certificate for `localhost`, and the configs that serve and trust it with /// `version`'s ALPN fn tls(version: Version) -> (driver::server::Config, driver::client::Config) { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); - let rcgen::CertifiedKey { cert, signing_key } = - rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap(); - let key = rustls::pki_types::PrivateKeyDer::Pkcs8(signing_key.serialize_der().into()); + let _ = rind_rustls::default_provider().unwrap().install_default(); + let rcgen::CertifiedKey { cert, signing_key } = (|| -> std::result::Result<_, rcgen::Error> { + let signing_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?; + let mut params = rcgen::CertificateParams::new(vec!["localhost".into()])?; + params.serial_number = Some(1u64.into()); + let cert = params.self_signed(&signing_key)?; + Ok(rcgen::CertifiedKey { cert, signing_key }) + })() + .unwrap(); + let key = rustls::pki_types::PrivateKeyDer::Pkcs8(signing_key.to_pkcs8().secret_pkcs8_der().to_vec().into()); let alpn = vec![version.alpn().as_bytes().to_vec()]; let mut server = rustls::ServerConfig::builder() diff --git a/rs/moq-tokio/tests/integration/stream_code.rs b/rs/moq-tokio/tests/integration/stream_code.rs index 1a98d5da02c..d6ef659383a 100644 --- a/rs/moq-tokio/tests/integration/stream_code.rs +++ b/rs/moq-tokio/tests/integration/stream_code.rs @@ -25,8 +25,12 @@ async fn serve() -> Server { use std::io::Write; let dir = tempfile::tempdir().expect("tempdir"); - let key = rcgen::KeyPair::generate().expect("key"); + let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).expect("key"); let cert = rcgen::CertificateParams::new(vec!["localhost".to_string()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) .expect("params") .self_signed(&key) .expect("cert"); @@ -41,7 +45,10 @@ async fn serve() -> Server { let mut config = moq_tokio::server::Config::default(); config.listen.bind = Some("127.0.0.1:0".parse().unwrap()); config.listen.tls.cert = vec![write("server.pem", cert.pem())]; - config.listen.tls.key = vec![write("server.key", key.serialize_pem())]; + config.listen.tls.key = vec![write( + "server.key", + pem::encode(&pem::Pem::new("PRIVATE KEY", key.to_pkcs8().secret_pkcs8_der())), + )]; let mut listener = config .init() .expect("failed to init server") @@ -69,7 +76,7 @@ async fn serve() -> Server { /// Dial the server over raw QUIC with `alpn`, send an empty SETUP and a GROUP for an /// unknown subscription, and return the code the server stopped the GROUP with. async fn refused_code(server: &Server, alpn: &str) -> Option { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let mut roots = rustls::RootCertStore::empty(); roots.add(server.cert.clone()).expect("root"); diff --git a/rs/moq-tokio/tests/integration/worker.rs b/rs/moq-tokio/tests/integration/worker.rs index 48a98be1f56..37b184a32b1 100644 --- a/rs/moq-tokio/tests/integration/worker.rs +++ b/rs/moq-tokio/tests/integration/worker.rs @@ -74,13 +74,22 @@ fn open_sockets() -> std::collections::HashSet { /// A self-signed certificate on disk. fn certificate(dir: &std::path::Path) -> (std::path::PathBuf, std::path::PathBuf) { - let key = rcgen::KeyPair::generate().expect("keypair"); - let params = rcgen::CertificateParams::new(vec!["localhost".to_string()]).expect("cert params"); + let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).expect("keypair"); + let params = rcgen::CertificateParams::new(vec!["localhost".to_string()]) + .map(|mut params| { + params.serial_number = Some(1u64.into()); + params + }) + .expect("cert params"); let cert = params.self_signed(&key).expect("self-signed cert"); let cert_path = dir.join("cert.pem"); let key_path = dir.join("key.pem"); std::fs::write(&cert_path, cert.pem()).expect("write cert"); - std::fs::write(&key_path, key.serialize_pem()).expect("write key"); + std::fs::write( + &key_path, + pem::encode(&pem::Pem::new("PRIVATE KEY", key.to_pkcs8().secret_pkcs8_der())), + ) + .expect("write key"); (cert_path, key_path) } @@ -115,7 +124,7 @@ fn config(count: u16) -> worker::Config { /// has to actually release the port. #[tokio::test] async fn dropping_the_workers_releases_the_port() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let dir = tempfile::tempdir().expect("tempdir"); let (cert, key) = certificate(dir.path()); @@ -144,7 +153,7 @@ async fn dropping_the_workers_releases_the_port() { /// leaves, and the peer only notices at its idle timeout. #[tokio::test] async fn stopping_the_group_closes_its_sessions() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let dir = tempfile::tempdir().unwrap(); let (cert, key) = certificate(dir.path()); let workers = bind_workers(listen_config(&cert, &key, 0), Default::default(), config(WORKERS)).unwrap(); @@ -189,7 +198,7 @@ async fn stopping_the_group_closes_its_sessions() { /// onto the same task set. #[tokio::test] async fn spawner_runs_a_send_less_future() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let dir = tempfile::tempdir().expect("tempdir"); let (cert, key) = certificate(dir.path()); @@ -222,7 +231,7 @@ async fn spawner_runs_a_send_less_future() { /// worker thread: the group keeps running and the next future still starts. #[tokio::test] async fn spawner_contains_a_factory_panic() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let dir = tempfile::tempdir().expect("tempdir"); let (cert, key) = certificate(dir.path()); @@ -246,7 +255,7 @@ async fn spawner_contains_a_factory_panic() { /// detaching it to run unreachable until the group stops. #[tokio::test] async fn spawner_abort_reaches_the_worker() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let dir = tempfile::tempdir().expect("tempdir"); let (cert, key) = certificate(dir.path()); @@ -280,7 +289,7 @@ async fn spawner_abort_reaches_the_worker() { /// it: a caller that aborts while the handle is still in flight cancels it. #[tokio::test] async fn spawner_abort_races_the_handoff() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let dir = tempfile::tempdir().expect("tempdir"); let (cert, key) = certificate(dir.path()); @@ -313,7 +322,7 @@ async fn spawner_abort_races_the_handoff() { /// alternative to, so both are covered. #[tokio::test] async fn dropping_unserved_workers_releases_the_port() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let dir = tempfile::tempdir().expect("tempdir"); let (cert, key) = certificate(dir.path()); @@ -331,7 +340,7 @@ async fn dropping_unserved_workers_releases_the_port() { /// unreachable behind an address that reads as bound. #[tokio::test] async fn an_ephemeral_port_is_shared_by_the_group() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let dir = tempfile::tempdir().expect("tempdir"); let (cert, key) = certificate(dir.path()); @@ -359,7 +368,7 @@ async fn an_ephemeral_port_is_shared_by_the_group() { /// startup failure it is without workers. #[tokio::test] async fn an_occupied_port_is_refused() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let dir = tempfile::tempdir().expect("tempdir"); let (cert, key) = certificate(dir.path()); @@ -388,7 +397,7 @@ async fn an_occupied_port_is_refused() { /// lock has to catch this, not the probe, so the error is asserted exactly. #[tokio::test] async fn the_other_wildcard_spelling_is_refused() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let dir = tempfile::tempdir().expect("tempdir"); let (cert, key) = certificate(dir.path()); @@ -417,7 +426,7 @@ async fn the_other_wildcard_spelling_is_refused() { /// (the probe would let two specific addresses coexist). #[tokio::test] async fn a_shared_port_is_refused_across_addresses() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let dir = tempfile::tempdir().expect("tempdir"); let (cert, key) = certificate(dir.path()); @@ -445,7 +454,7 @@ async fn a_shared_port_is_refused_across_addresses() { /// a plain bind refuses a port any socket holds, reuseport or not. #[tokio::test] async fn a_foreign_reuseport_group_is_refused() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let dir = tempfile::tempdir().expect("tempdir"); let (cert, key) = certificate(dir.path()); @@ -465,7 +474,7 @@ async fn a_foreign_reuseport_group_is_refused() { /// left to spend. #[tokio::test] async fn an_unaddressable_group_is_refused() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let dir = tempfile::tempdir().expect("tempdir"); let (cert, key) = certificate(dir.path()); @@ -481,7 +490,7 @@ async fn an_unaddressable_group_is_refused() { /// Generated certificates are minted once and shared by the whole worker group. #[tokio::test] async fn generated_certificates_are_shared() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let mut listen = moq_tokio::listen::Config::default(); listen.bind = Some("127.0.0.1:0".parse().unwrap()); listen.tls.generate = vec!["localhost".to_string()]; @@ -514,7 +523,7 @@ async fn generated_certificates_are_shared() { /// worker that never failed. #[tokio::test] async fn dropping_a_server_keeps_its_socket() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let dir = tempfile::tempdir().expect("tempdir"); let (cert, key) = certificate(dir.path()); @@ -562,7 +571,7 @@ async fn dropping_a_server_keeps_its_socket() { /// and the threads join, rather than leaving a resized reuseport group behind. #[tokio::test] async fn completing_a_member_stops_its_siblings() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let dir = tempfile::tempdir().expect("tempdir"); let (cert, key) = certificate(dir.path()); @@ -612,7 +621,7 @@ async fn completing_a_member_stops_its_siblings() { /// Cancelling one serving member ends serving for the whole group. #[tokio::test] async fn cancelling_a_member_stops_its_siblings() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let dir = tempfile::tempdir().expect("tempdir"); let (cert, key) = certificate(dir.path()); @@ -657,7 +666,7 @@ async fn cancelling_a_member_stops_its_siblings() { /// still reaches its own handle. #[tokio::test] async fn a_panicking_member_stops_its_siblings() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let dir = tempfile::tempdir().expect("tempdir"); let (cert, key) = certificate(dir.path()); @@ -701,7 +710,7 @@ async fn a_panicking_member_stops_its_siblings() { /// Explicit shutdown with work in flight stops every worker and joins. #[tokio::test] async fn shutdown_with_work_in_flight_joins() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let dir = tempfile::tempdir().expect("tempdir"); let (cert, key) = certificate(dir.path()); @@ -731,7 +740,7 @@ async fn shutdown_with_work_in_flight_joins() { /// the calling thread. #[tokio::test] async fn dropping_the_group_with_work_in_flight_stops() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let dir = tempfile::tempdir().expect("tempdir"); let (cert, key) = certificate(dir.path()); @@ -767,7 +776,7 @@ async fn dropping_the_group_with_work_in_flight_stops() { #[cfg(feature = "watch")] #[tokio::test] async fn rotated_identity_reaches_every_worker() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let dir = tempfile::tempdir().unwrap(); let (cert, key) = certificate(dir.path()); let workers = bind_workers(listen_config(&cert, &key, 0), Default::default(), config(WORKERS)).unwrap(); @@ -843,7 +852,7 @@ async fn rotated_identity_reaches_every_worker() { /// reaches through moq-tokio's fallback. #[test] fn shutting_down_outside_a_runtime_joins_the_workers() { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let dir = tempfile::tempdir().expect("tempdir"); let (cert, key) = certificate(dir.path()); diff --git a/rs/moq-transcode/Cargo.toml b/rs/moq-transcode/Cargo.toml index 0289b9b0f51..8bbfebd8399 100644 --- a/rs/moq-transcode/Cargo.toml +++ b/rs/moq-transcode/Cargo.toml @@ -49,7 +49,7 @@ criterion = { package = "bench-harness", path = "../bench-harness" } # `join_all`, so the ladder bench feeds every rung at once like the rung tasks do. futures = { workspace = true } kio = { workspace = true, features = ["manual", "runtime", "sim"] } -moq-tokio = { path = "../moq-tokio", default-features = false, features = ["quic", "aws-lc-rs", "websocket"] } +moq-tokio = { path = "../moq-tokio", default-features = false, features = ["quic", "websocket"] } # The tests encode with OpenH264, the one encoder a GPU-less host has, so they # turn it on without making it a default of the library. moq-video = { path = "../moq-video", features = ["openh264"] } diff --git a/rs/moq-uring/Cargo.toml b/rs/moq-uring/Cargo.toml index e33552224f3..67a133e14ff 100644 --- a/rs/moq-uring/Cargo.toml +++ b/rs/moq-uring/Cargo.toml @@ -15,7 +15,7 @@ categories = ["asynchronous", "network-programming", "os::linux-apis"] [features] default = ["quic"] # QUIC and WebTransport on moq-quic, with TLS through rustls. -quic = ["dep:moq-congestion", "dep:moq-quic", "dep:rustls", "dep:rustls-platform-verifier"] +quic = ["dep:moq-congestion", "dep:moq-crypto", "dep:moq-quic", "dep:rustls", "dep:rustls-platform-verifier"] # Capture qlog traces (`quic::Transport::qlog`). Off by default: it compiles the # qlog crate and its serde_json encoder into moq-quic, which a production build has # no use for. @@ -33,11 +33,13 @@ io-uring = { workspace = true } kio = { workspace = true, features = ["runtime"] } libc = { workspace = true } moq-congestion = { workspace = true, optional = true } +# rind's rustls provider and the `UnsupportedCpu` error the transport crates share. +moq-crypto = { workspace = true, features = ["provider"], optional = true } moq-net = { workspace = true } -moq-quic = { workspace = true, features = ["rustls-aws-lc-rs"], optional = true } +moq-quic = { workspace = true, features = [], optional = true } moq-sock = { workspace = true } rustc-hash = { workspace = true } -rustls = { version = "0.23", optional = true } +rustls = { version = "0.23", default-features = false, features = ["std"], optional = true } # OS-native server-cert verifier for the rustls backends. Version matched to # the copy moq-tokio pulls in, to avoid duplication. rustls-platform-verifier = { version = "0.7", optional = true } @@ -54,6 +56,7 @@ anyhow = "1" bytes = { workspace = true } criterion = { package = "bench-harness", path = "../bench-harness" } moq-net = { path = "../moq-net" } +pem = { workspace = true } thiserror = { workspace = true } tokio = { workspace = true, features = ["macros", "net", "rt", "sync", "time"] } workspace-hack = { path = "../workspace-hack" } @@ -63,12 +66,14 @@ io-uring = { workspace = true } libc = { workspace = true } # The socket-queue benchmark's rate-limited path. moq-shaper = { path = "../moq-shaper" } -moq-tokio = { path = "../moq-tokio", default-features = false, features = ["quic", "aws-lc-rs"] } +moq-tokio = { path = "../moq-tokio", default-features = false, features = ["quic"] } # Tests run workers on a manual clock. moq-uring = { path = ".", features = ["_manual"] } nix = { workspace = true } -rcgen = { workspace = true, features = ["pem", "aws_lc_rs"] } -rustls = "0.23" +rcgen = { workspace = true, features = ["pem"] } +rind-rcgen = { workspace = true } +rind-rustls = { workspace = true } +rustls = { version = "0.23", default-features = false, features = ["std", "tls12"] } # The qlog test parses every record of a trace, which is what catches a # truncated or interleaved write. serde_json = { workspace = true } diff --git a/rs/moq-uring/MIGRATE.md b/rs/moq-uring/MIGRATE.md index cee3b9a0ff4..5dadb2ddfd2 100644 --- a/rs/moq-uring/MIGRATE.md +++ b/rs/moq-uring/MIGRATE.md @@ -4,6 +4,13 @@ How to update your code for each breaking change, newest first. ## Unreleased +### Transport cryptography uses rind + +TLS configuration uses rind's rustls provider, and QUIC reset and token keys use rind through moq-quic. +A CPU missing a feature rind needs fails configuration with `quic::Error::UnsupportedCpu`, wrapping `moq_crypto::provider::UnsupportedCpu`, which names the feature; it used to arrive as `quic::Error::Tls`. +Build caller-supplied rustls configurations on `moq_crypto::provider::provider()?` or `moq_tokio::crypto::provider()?`. +No wire format changes. + ### QUIC method names and signatures match the core and Tokio driver Construct an endpoint with `quic::Endpoint::new(config, socket)` instead of `new(socket, config)`. diff --git a/rs/moq-uring/benches/echo_quic.rs b/rs/moq-uring/benches/echo_quic.rs index 4b736c3aa32..66094f95dda 100644 --- a/rs/moq-uring/benches/echo_quic.rs +++ b/rs/moq-uring/benches/echo_quic.rs @@ -67,9 +67,9 @@ mod linux { // poll the endpoint again, leaving the peer to time out mid-CONNECT. let (start_tx, start_rx) = std::sync::mpsc::channel::>(); let client = std::thread::spawn(move || { - // Enabling `ring` beside `aws-lc-rs` (as `--all-features` does) leaves rustls no implicit - // default, and the builder would panic on this thread while the server waits forever. - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + // rustls has no implicit default provider; without one the client builder would panic on + // this thread while the server waits forever. + let _ = rind_rustls::default_provider().unwrap().install_default(); let runtime = tokio::runtime::Builder::new_current_thread() .enable_all() .build() diff --git a/rs/moq-uring/benches/worker_turns.rs b/rs/moq-uring/benches/worker_turns.rs index de902a60913..6e015ea8403 100644 --- a/rs/moq-uring/benches/worker_turns.rs +++ b/rs/moq-uring/benches/worker_turns.rs @@ -21,7 +21,7 @@ fn request_reply(c: &mut criterion::Criterion) { use moq_uring::{Config, Worker, quic, udp}; const ALPN: &str = "worker-turns"; - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let certs = support::certs().expect("certificates"); let tls = quic::Identity::open(&certs.cert, &certs.key) .expect("identity") diff --git a/rs/moq-uring/src/quic/driver/mod.rs b/rs/moq-uring/src/quic/driver/mod.rs index 0ffb2abac61..6dff4ed3a8a 100644 --- a/rs/moq-uring/src/quic/driver/mod.rs +++ b/rs/moq-uring/src/quic/driver/mod.rs @@ -89,17 +89,6 @@ impl From for Error { } } -/// The crypto provider every config here is built from. -/// -/// Built explicitly rather than read from the process-wide default, so a -/// consumer that never installed one still gets working TLS. -fn provider() -> Arc { - static PROVIDER: std::sync::OnceLock> = std::sync::OnceLock::new(); - PROVIDER - .get_or_init(|| Arc::new(rustls::crypto::aws_lc_rs::default_provider())) - .clone() -} - /// The endpoint-wide configuration: how connection ids are minted, the reset key, and what to /// serve. pub(crate) fn endpoint_config( @@ -128,7 +117,9 @@ pub(crate) fn endpoint_config( /// Dial as `config` says. pub(crate) fn client_config(config: &client::Config) -> Result { - let provider = provider(); + // Built explicitly rather than read from the process-wide default, so a + // consumer that never installed one still gets working TLS. + let provider = moq_crypto::provider::provider()?; let builder = rustls::ClientConfig::builder_with_provider(provider.clone()) .with_protocol_versions(&[&rustls::version::TLS13]) .map_err(|err| Error::Tls(err.to_string()))?; @@ -178,6 +169,7 @@ pub(crate) fn client_config(config: &client::Config) -> Result Result { + moq_crypto::provider::check()?; let mut server = moq_quic::server::Config::new(config.tls.clone()); server.transport = transport_config(&config.transport)?; #[cfg(feature = "qlog")] @@ -191,7 +183,9 @@ pub(crate) fn identity_server_config( alpn: Vec>, auth: &server::ClientAuth, ) -> Result, Error> { - let provider = provider(); + // Built explicitly rather than read from the process-wide default, so a + // consumer that never installed one still gets working TLS. + let provider = moq_crypto::provider::provider()?; let builder = rustls::ServerConfig::builder_with_provider(provider.clone()) .with_protocol_versions(&[&rustls::version::TLS13]) .map_err(|err| Error::Tls(err.to_string()))?; diff --git a/rs/moq-uring/src/quic/mod.rs b/rs/moq-uring/src/quic/mod.rs index 2b9fa779719..31e5630828b 100644 --- a/rs/moq-uring/src/quic/mod.rs +++ b/rs/moq-uring/src/quic/mod.rs @@ -172,6 +172,9 @@ pub enum Error { /// The TLS material a connection needs could not be loaded. #[error("tls error: {0}")] Tls(String), + /// This CPU lacks a feature that rind, MoQ's cryptography, requires. + #[error(transparent)] + UnsupportedCpu(#[from] moq_crypto::provider::UnsupportedCpu), /// The socket died underneath the connection. #[error("socket error: {0}")] Io(String), diff --git a/rs/moq-uring/tests/integration/echo.rs b/rs/moq-uring/tests/integration/echo.rs index d372abce107..e2f853946e6 100644 --- a/rs/moq-uring/tests/integration/echo.rs +++ b/rs/moq-uring/tests/integration/echo.rs @@ -67,9 +67,9 @@ fn echo_tokio_peer() { let (done_tx, done_rx) = tokio::sync::oneshot::channel(); let client = std::thread::spawn(move || { - // Enabling `ring` beside `aws-lc-rs` (as `--all-features` does) leaves rustls no implicit - // default, and the builder would panic on this thread while the server waits forever. - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + // rustls has no implicit default provider; without one the client builder would panic on + // this thread while the server waits forever. + let _ = rind_rustls::default_provider().unwrap().install_default(); let runtime = tokio::runtime::Builder::new_current_thread() .enable_all() .build() diff --git a/rs/moq-uring/tests/integration/local_addr.rs b/rs/moq-uring/tests/integration/local_addr.rs index 61bb91a9ba1..a27e6a9ca8a 100644 --- a/rs/moq-uring/tests/integration/local_addr.rs +++ b/rs/moq-uring/tests/integration/local_addr.rs @@ -168,8 +168,8 @@ fn a_wildcard_endpoint_handshakes_on_a_secondary_address() { let (done_tx, done_rx) = tokio::sync::oneshot::channel(); let client = std::thread::spawn(move || { - // Enabling `ring` beside `aws-lc-rs` leaves rustls no implicit default. - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + // rustls has no implicit default provider; the client builder needs one installed. + let _ = rind_rustls::default_provider().unwrap().install_default(); let runtime = tokio::runtime::Builder::new_current_thread() .enable_all() .build() diff --git a/rs/moq-uring/tests/integration/support.rs b/rs/moq-uring/tests/integration/support.rs index e7143502042..2dba95514f9 100644 --- a/rs/moq-uring/tests/integration/support.rs +++ b/rs/moq-uring/tests/integration/support.rs @@ -10,12 +10,24 @@ pub struct Certs { } pub fn certs() -> anyhow::Result { - let signed = rcgen::generate_simple_self_signed(vec!["localhost".into(), "127.0.0.1".into()])?; + let signed = (|| -> std::result::Result<_, rcgen::Error> { + let signing_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?; + let mut params = rcgen::CertificateParams::new(vec!["localhost".into(), "127.0.0.1".into()])?; + params.serial_number = Some(1u64.into()); + let cert = params.self_signed(&signing_key)?; + Ok(rcgen::CertifiedKey { cert, signing_key }) + })()?; let dir = tempfile::tempdir()?; let cert = dir.path().join("cert.pem"); let key = dir.path().join("key.pem"); std::fs::write(&cert, signed.cert.pem())?; - std::fs::write(&key, signed.signing_key.serialize_pem())?; + std::fs::write( + &key, + pem::encode(&pem::Pem::new( + "PRIVATE KEY", + signed.signing_key.to_pkcs8().secret_pkcs8_der(), + )), + )?; Ok(Certs { dir, cert, key }) } @@ -32,9 +44,12 @@ pub struct Bundle { /// Build one, for a test that a root file is loaded whole rather than to its /// first certificate. pub fn bundle() -> anyhow::Result { - let ca = |name: &str| -> anyhow::Result> { - let key = rcgen::KeyPair::generate()?; - let mut params = rcgen::CertificateParams::new(Vec::new())?; + let ca = |name: &str| -> anyhow::Result> { + let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?; + let mut params = rcgen::CertificateParams::new(Vec::new()).map(|mut params| { + params.serial_number = Some(1u64.into()); + params + })?; params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained); params.key_usages = vec![rcgen::KeyUsagePurpose::KeyCertSign, rcgen::KeyUsagePurpose::CrlSign]; params.distinguished_name.push(rcgen::DnType::CommonName, name); @@ -43,8 +58,11 @@ pub fn bundle() -> anyhow::Result { let unrelated = ca("moq unrelated ca")?; let signer = ca("moq signing ca")?; - let key = rcgen::KeyPair::generate()?; - let mut params = rcgen::CertificateParams::new(vec!["localhost".into()])?; + let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?; + let mut params = rcgen::CertificateParams::new(vec!["localhost".into()]).map(|mut params| { + params.serial_number = Some(1u64.into()); + params + })?; params.use_authority_key_identifier_extension = true; let cert = params.signed_by(&key, &signer)?; @@ -53,7 +71,10 @@ pub fn bundle() -> anyhow::Result { let key_path = dir.path().join("key.pem"); let roots_path = dir.path().join("roots.pem"); std::fs::write(&cert_path, cert.pem())?; - std::fs::write(&key_path, key.serialize_pem())?; + std::fs::write( + &key_path, + pem::encode(&pem::Pem::new("PRIVATE KEY", key.to_pkcs8().secret_pkcs8_der())), + )?; // The signer is second on purpose: reading only the first certificate // leaves the store unable to verify anything this server presents. std::fs::write(&roots_path, format!("{}{}", unrelated.pem(), signer.pem()))?; diff --git a/rs/moq-uring/tests/integration/web.rs b/rs/moq-uring/tests/integration/web.rs index e37a260d864..57fd5d015ba 100644 --- a/rs/moq-uring/tests/integration/web.rs +++ b/rs/moq-uring/tests/integration/web.rs @@ -58,7 +58,7 @@ fn tokio_client( ) -> std::thread::JoinHandle<()> { std::thread::spawn(move || { // May already be installed by a sibling test; either way one exists. - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let rt = tokio::runtime::Builder::new_current_thread() .enable_all() .build() @@ -532,7 +532,7 @@ async fn within(handle: &moq_uring::Handle, what: &str, future: impl Future std::thread::JoinHandle { std::thread::spawn(move || { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let rt = tokio::runtime::Builder::new_current_thread() .enable_all() .build() @@ -872,7 +872,7 @@ fn a_reset_stream_keeps_its_header_without_credit() { let addr = endpoint.local_addr(); let client = std::thread::spawn(move || { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let rt = tokio::runtime::Builder::new_current_thread() .enable_all() .build() diff --git a/rs/moq-uring/tests/integration/web_headers.rs b/rs/moq-uring/tests/integration/web_headers.rs index 5963efeff2f..a8894fa35eb 100644 --- a/rs/moq-uring/tests/integration/web_headers.rs +++ b/rs/moq-uring/tests/integration/web_headers.rs @@ -35,7 +35,7 @@ pub fn run(pending: usize, ready: usize, iterations: u64) -> Duration { let (start_tx, mut start_rx) = tokio::sync::mpsc::channel::>(1); let (acked, acknowledgement) = tokio::sync::oneshot::channel(); let client = std::thread::spawn(move || { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let _ = rind_rustls::default_provider().unwrap().install_default(); let runtime = tokio::runtime::Builder::new_current_thread() .enable_all() .build() diff --git a/rs/qmux/Cargo.toml b/rs/qmux/Cargo.toml index a963848c868..6cb74c91361 100644 --- a/rs/qmux/Cargo.toml +++ b/rs/qmux/Cargo.toml @@ -18,16 +18,19 @@ tcp = ["tokio/net"] tls = ["tcp", "dep:tokio-rustls", "dep:rustls"] uds = ["tokio/net"] ws = ["dep:tokio-tungstenite", "dep:futures"] -wss = ["ws", "dep:rustls", "tokio-tungstenite/rustls-tls-native-roots"] +wss = ["ws", "dep:rustls-native-certs", "dep:rustls", "tokio-tungstenite/rustls-tls-native-roots"] [dependencies] bytes = { workspace = true } futures = { workspace = true, optional = true } kio = { workspace = true, features = ["runtime"] } +# rind's rustls provider and the `UnsupportedCpu` error the transport crates share. +moq-crypto = { workspace = true, features = ["provider"] } moq-net = { workspace = true } # The stream state machine, shared with QUIC. `mux` drives it over a reliable transport. moq-quic = { workspace = true, features = ["mux"] } rustls = { version = "0.23", default-features = false, optional = true } +rustls-native-certs = { workspace = true, optional = true } thiserror = { workspace = true } tokio = { workspace = true } tokio-rustls = { workspace = true, optional = true } @@ -44,8 +47,9 @@ anyhow = { workspace = true } # The last release before this crate moved here, for wire interop tests only. qmux06 = { package = "qmux", version = "0.6.3", default-features = false, features = ["tcp", "ws"] } # A self-signed identity and the relay's crypto provider, for the bench example's TLS transports. -rcgen = { workspace = true, features = ["aws_lc_rs"] } -rustls = { version = "0.23", default-features = false, features = ["aws-lc-rs", "std"] } +rcgen = { workspace = true, features = ["pem"] } +rind-rcgen = { workspace = true } +rustls = { version = "0.23", default-features = false, features = ["std"] } tokio = { workspace = true, features = ["full", "test-util"] } # The 0.6 release's stream API, for driving it in the interop tests. web-transport-trait = { workspace = true } diff --git a/rs/qmux/MIGRATE.md b/rs/qmux/MIGRATE.md index 9d85216bede..f0470550424 100644 --- a/rs/qmux/MIGRATE.md +++ b/rs/qmux/MIGRATE.md @@ -4,6 +4,13 @@ How to update your code for each breaking change, newest first. ## Unreleased +### TLS cryptography uses rind + +Default WSS connections build an explicit rind rustls configuration and use native roots, without relying on a process-wide provider. +Build caller-supplied TLS configurations and WSS connectors on `moq_crypto::provider::provider()?` or `moq_tokio::crypto::provider()?`. +A CPU missing a feature rind needs fails TLS connects and default WSS connects with `Error::UnsupportedCpu`, wrapping `moq_crypto::provider::UnsupportedCpu`, which names the feature; it used to arrive as `Error::Io`. +No QMux or WebSocket wire format changes. + ### `RecvStream` leases its credit ([#7624](https://github.com/moq-dev/moq/pull/7624)) `RecvStream` keeps leased bytes' connection credit until `Lease::release`, rather than returning it as it reads through `poll::Buffered`, so `receive_window` bounds what incomplete messages hold together. When they fill it and no reader can progress, the lowest priority stream is evicted and its next lease fails with `Error::Evicted`. Its lease type is now `RecvLease`. diff --git a/rs/qmux/examples/bench.rs b/rs/qmux/examples/bench.rs index f62e820ee27..3266cb0293c 100644 --- a/rs/qmux/examples/bench.rs +++ b/rs/qmux/examples/bench.rs @@ -130,11 +130,19 @@ struct Tls { impl Tls { fn new() -> anyhow::Result { - let identity = rcgen::generate_simple_self_signed(vec!["localhost".into()])?; + let identity = (|| -> std::result::Result<_, rcgen::Error> { + let signing_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?; + let mut params = rcgen::CertificateParams::new(vec!["localhost".into()])?; + params.serial_number = Some(1u64.into()); + let cert = params.self_signed(&signing_key)?; + Ok(rcgen::CertifiedKey { cert, signing_key }) + })()?; let cert = CertificateDer::from(identity.cert.der().to_vec()); - let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(identity.signing_key.serialize_der())); + let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from( + identity.signing_key.to_pkcs8().secret_pkcs8_der().to_vec(), + )); // The relay's provider, so the TLS share matches what it pays. - let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider()); + let provider = moq_crypto::provider::provider().unwrap(); let mut server = rustls::ServerConfig::builder_with_provider(provider.clone()) .with_safe_default_protocol_versions()? diff --git a/rs/qmux/src/error.rs b/rs/qmux/src/error.rs index 891f01c67ef..b1e476387fb 100644 --- a/rs/qmux/src/error.rs +++ b/rs/qmux/src/error.rs @@ -98,6 +98,10 @@ pub enum Error { #[error(transparent)] Io(Arc), + /// This CPU lacks a feature that rind, MoQ's cryptography, requires. + #[error(transparent)] + UnsupportedCpu(#[from] moq_crypto::provider::UnsupportedCpu), + /// The WebSocket failed. #[cfg(feature = "ws")] #[error(transparent)] diff --git a/rs/qmux/src/tls.rs b/rs/qmux/src/tls.rs index d07eda93f8b..1496b4fca6d 100644 --- a/rs/qmux/src/tls.rs +++ b/rs/qmux/src/tls.rs @@ -73,6 +73,7 @@ impl Client { addr: impl ToSocketAddrs, server_name: &str, ) -> Result<(Session, Driver>>), Error> { + moq_crypto::provider::check()?; let stream = TcpStream::connect(&addr).await?; // Adopt the socket before TLS takes ownership; the kernel's view of the TCP // connection is the same either side of the encryption. diff --git a/rs/qmux/src/ws.rs b/rs/qmux/src/ws.rs index d2f7a700ce2..427fe6feb04 100644 --- a/rs/qmux/src/ws.rs +++ b/rs/qmux/src/ws.rs @@ -299,7 +299,36 @@ impl Client { // `true` disables Nagle: records are already batched, see `Server::accept`. #[cfg(feature = "wss")] let (ws_stream, response) = { - tokio_tungstenite::connect_async_tls_with_config(request, Some(ws_config), true, self.connector.clone()) + let connector = match ( + &self.connector, + request + .uri() + .scheme_str() + .is_some_and(|scheme| scheme.eq_ignore_ascii_case("wss")), + ) { + (Some(connector), _) => Some(connector.clone()), + (None, true) => { + let provider = moq_crypto::provider::provider()?; + let native = rustls_native_certs::load_native_certs(); + if native.certs.is_empty() { + return Err(std::io::Error::new( + std::io::ErrorKind::NotFound, + format!("no native root CA certificates found: {:?}", native.errors), + ) + .into()); + } + let mut roots = rustls::RootCertStore::empty(); + roots.add_parsable_certificates(native.certs); + let config = rustls::ClientConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + .map_err(std::io::Error::other)? + .with_root_certificates(roots) + .with_no_client_auth(); + Some(tokio_tungstenite::Connector::Rustls(std::sync::Arc::new(config))) + } + (None, false) => None, + }; + tokio_tungstenite::connect_async_tls_with_config(request, Some(ws_config), true, connector) .await .map_err(Error::from)? }; diff --git a/rs/workspace-hack/Cargo.toml b/rs/workspace-hack/Cargo.toml index 7eed8186016..81ab240e62f 100644 --- a/rs/workspace-hack/Cargo.toml +++ b/rs/workspace-hack/Cargo.toml @@ -27,7 +27,8 @@ publish = false anyhow = { version = "1", features = ["backtrace"] } aws-lc-rs = { version = "1", features = ["prebuilt-nasm"] } aws-lc-sys = { version = "0.46", default-features = false, features = ["prebuilt-nasm"] } -base64 = { version = "0.23" } +base64-2b5c6dc72f624058 = { package = "base64", version = "0.23" } +base64-3c51e837cfc5589a = { package = "base64", version = "0.22" } bytemuck = { version = "1", default-features = false, features = ["derive", "extern_crate_alloc", "min_const_generics"] } byteorder = { version = "1" } bytes = { version = "1", features = ["serde"] } @@ -57,7 +58,6 @@ futures-executor = { version = "0.3" } futures-sink = { version = "0.3" } futures-task = { version = "0.3", default-features = false, features = ["std"] } futures-util = { version = "0.3", features = ["channel", "io", "sink"] } -getrandom-6f8ce4dd05d13bba = { package = "getrandom", version = "0.2", default-features = false, features = ["std"] } hashbrown = { version = "0.17", default-features = false, features = ["default-hasher", "inline-more"] } hex = { version = "0.4" } hmac = { version = "0.12", default-features = false, features = ["reset"] } @@ -90,13 +90,12 @@ proptest = { version = "1", default-features = false, features = ["handle-panics rand-274715c4dabd11b0 = { package = "rand", version = "0.9" } rand-c38e5c1d305a1b54 = { package = "rand", version = "0.8" } rand_chacha = { version = "0.3", default-features = false, features = ["std"] } -rcgen = { version = "0.14", default-features = false, features = ["aws_lc_rs", "pem", "ring"] } +rcgen = { version = "0.14", default-features = false, features = ["aws_lc_rs", "pem"] } regex-automata = { version = "0.4", default-features = false, features = ["dfa-build", "dfa-onepass", "hybrid", "meta", "nfa-backtrack", "perf-inline", "perf-literal", "std", "unicode"] } regex-syntax = { version = "0.8" } reqwest = { version = "0.13", default-features = false, features = ["gzip", "http2", "json", "rustls", "rustls-no-provider", "stream"] } -rustls = { version = "0.23", features = ["ring"] } +rustls = { version = "0.23", default-features = false, features = ["std", "tls12"] } rustls-pki-types = { version = "1", features = ["std"] } -rustls-webpki = { version = "0.103", features = ["aws-lc-rs", "ring"] } semver = { version = "1", features = ["serde"] } serde = { version = "1", features = ["alloc", "derive"] } serde_core = { version = "1", features = ["alloc"] } @@ -137,7 +136,8 @@ zeroize = { version = "1", features = ["derive"] } anyhow = { version = "1", features = ["backtrace"] } aws-lc-rs = { version = "1", features = ["prebuilt-nasm"] } aws-lc-sys = { version = "0.46", default-features = false, features = ["prebuilt-nasm"] } -base64 = { version = "0.23" } +base64-2b5c6dc72f624058 = { package = "base64", version = "0.23" } +base64-3c51e837cfc5589a = { package = "base64", version = "0.22" } bytemuck = { version = "1", default-features = false, features = ["derive", "extern_crate_alloc", "min_const_generics"] } byteorder = { version = "1" } bytes = { version = "1", features = ["serde"] } @@ -170,7 +170,6 @@ futures-executor = { version = "0.3" } futures-sink = { version = "0.3" } futures-task = { version = "0.3", default-features = false, features = ["std"] } futures-util = { version = "0.3", features = ["channel", "io", "sink"] } -getrandom-6f8ce4dd05d13bba = { package = "getrandom", version = "0.2", default-features = false, features = ["std"] } hashbrown = { version = "0.17", default-features = false, features = ["default-hasher", "inline-more"] } hex = { version = "0.4" } hmac = { version = "0.12", default-features = false, features = ["reset"] } @@ -205,13 +204,12 @@ quote = { version = "1" } rand-274715c4dabd11b0 = { package = "rand", version = "0.9" } rand-c38e5c1d305a1b54 = { package = "rand", version = "0.8" } rand_chacha = { version = "0.3", default-features = false, features = ["std"] } -rcgen = { version = "0.14", default-features = false, features = ["aws_lc_rs", "pem", "ring"] } +rcgen = { version = "0.14", default-features = false, features = ["aws_lc_rs", "pem"] } regex-automata = { version = "0.4", default-features = false, features = ["dfa-build", "dfa-onepass", "hybrid", "meta", "nfa-backtrack", "perf-inline", "perf-literal", "std", "unicode"] } regex-syntax = { version = "0.8" } reqwest = { version = "0.13", default-features = false, features = ["gzip", "http2", "json", "rustls", "rustls-no-provider", "stream"] } -rustls = { version = "0.23", features = ["ring"] } +rustls = { version = "0.23", default-features = false, features = ["std", "tls12"] } rustls-pki-types = { version = "1", features = ["std"] } -rustls-webpki = { version = "0.103", features = ["aws-lc-rs", "ring"] } semver = { version = "1", features = ["serde"] } serde = { version = "1", features = ["alloc", "derive"] } serde_core = { version = "1", features = ["alloc"] } @@ -258,7 +256,7 @@ crossbeam-epoch = { version = "0.9" } dispatch2 = { version = "0.3" } errno = { version = "0.3" } flate2 = { version = "1", features = ["zlib-rs"] } -getrandom-9fbad63c4bcf4a8f = { package = "getrandom", version = "0.4", default-features = false, features = ["std", "sys_rng"] } +getrandom-468e82937335b1c9 = { package = "getrandom", version = "0.3", default-features = false, features = ["std"] } half = { version = "2", default-features = false, features = ["num-traits"] } hyper-rustls = { version = "0.27", default-features = false, features = ["aws-lc-rs", "http1", "http2", "tls12"] } hyper-util = { version = "0.1", default-features = false, features = ["client-legacy", "client-proxy"] } @@ -275,6 +273,8 @@ objc2-metal = { version = "0.3" } objc2-quartz-core = { version = "0.3", default-features = false, features = ["CALayer", "CAMediaTiming", "CAMetalLayer", "objc2-core-foundation", "objc2-core-graphics", "objc2-metal", "std"] } regex = { version = "1" } rustix = { version = "1", features = ["fs", "termios"] } +rustls = { version = "0.23", default-features = false, features = ["aws-lc-rs", "aws_lc_rs"] } +rustls-webpki = { version = "0.103", default-features = false, features = ["aws-lc-rs", "std"] } security-framework-sys = { version = "2" } tokio-rustls = { version = "0.26", default-features = false, features = ["aws-lc-rs", "tls12"] } tower = { version = "0.5", default-features = false, features = ["retry", "timeout"] } @@ -288,7 +288,7 @@ crossbeam-epoch = { version = "0.9" } dispatch2 = { version = "0.3" } errno = { version = "0.3" } flate2 = { version = "1", features = ["zlib-rs"] } -getrandom-9fbad63c4bcf4a8f = { package = "getrandom", version = "0.4", default-features = false, features = ["std", "sys_rng"] } +getrandom-468e82937335b1c9 = { package = "getrandom", version = "0.3", default-features = false, features = ["std"] } half = { version = "2", default-features = false, features = ["num-traits"] } hyper-rustls = { version = "0.27", default-features = false, features = ["aws-lc-rs", "http1", "http2", "tls12"] } hyper-util = { version = "0.1", default-features = false, features = ["client-legacy", "client-proxy"] } @@ -305,6 +305,8 @@ objc2-metal = { version = "0.3" } objc2-quartz-core = { version = "0.3", default-features = false, features = ["CALayer", "CAMediaTiming", "CAMetalLayer", "objc2-core-foundation", "objc2-core-graphics", "objc2-metal", "std"] } regex = { version = "1" } rustix = { version = "1", features = ["fs", "termios"] } +rustls = { version = "0.23", default-features = false, features = ["aws-lc-rs", "aws_lc_rs"] } +rustls-webpki = { version = "0.103", default-features = false, features = ["aws-lc-rs", "std"] } security-framework-sys = { version = "2" } tokio-rustls = { version = "0.26", default-features = false, features = ["aws-lc-rs", "tls12"] } tower = { version = "0.5", default-features = false, features = ["retry", "timeout"] } @@ -320,11 +322,10 @@ event-listener = { version = "5" } event-listener-strategy = { version = "0.5" } flate2 = { version = "1", features = ["zlib-rs"] } futures-io = { version = "0.3" } -getrandom-9fbad63c4bcf4a8f = { package = "getrandom", version = "0.4", default-features = false, features = ["std", "sys_rng"] } +getrandom-468e82937335b1c9 = { package = "getrandom", version = "0.3", default-features = false, features = ["std"] } half = { version = "2", default-features = false, features = ["num-traits"] } hyper-rustls = { version = "0.27", default-features = false, features = ["aws-lc-rs", "http1", "http2", "tls12"] } hyper-util = { version = "0.1", default-features = false, features = ["client-legacy", "client-proxy"] } -itertools = { version = "0.13" } libc = { version = "0.2", features = ["extra_traits"] } libspa = { version = "0.10", default-features = false, features = ["v0_3_33"] } linux-raw-sys = { version = "0.12", features = ["auxvec", "elf", "if_ether", "ioctl", "net", "netlink", "no_std", "prctl", "system", "xdp"] } @@ -338,6 +339,8 @@ quote = { version = "1" } regex = { version = "1" } rustc-hash = { version = "1" } rustix = { version = "1", features = ["event", "net", "param", "pipe", "process", "shm", "system", "termios", "thread", "time"] } +rustls = { version = "0.23", default-features = false, features = ["aws-lc-rs", "aws_lc_rs"] } +rustls-webpki = { version = "0.103", default-features = false, features = ["aws-lc-rs", "std"] } syn-7b89eefb6aaa9bf3 = { package = "syn", version = "3", features = ["extra-traits", "fold", "full", "visit", "visit-mut"] } tokio = { version = "1", default-features = false, features = ["tracing"] } tokio-rustls = { version = "0.26", default-features = false, features = ["aws-lc-rs", "tls12"] } @@ -356,11 +359,10 @@ event-listener = { version = "5" } event-listener-strategy = { version = "0.5" } flate2 = { version = "1", features = ["zlib-rs"] } futures-io = { version = "0.3" } -getrandom-9fbad63c4bcf4a8f = { package = "getrandom", version = "0.4", default-features = false, features = ["std", "sys_rng"] } +getrandom-468e82937335b1c9 = { package = "getrandom", version = "0.3", default-features = false, features = ["std"] } half = { version = "2", default-features = false, features = ["num-traits"] } hyper-rustls = { version = "0.27", default-features = false, features = ["aws-lc-rs", "http1", "http2", "tls12"] } hyper-util = { version = "0.1", default-features = false, features = ["client-legacy", "client-proxy"] } -itertools = { version = "0.13" } libc = { version = "0.2", features = ["extra_traits"] } libspa = { version = "0.10", default-features = false, features = ["v0_3_33"] } linux-raw-sys = { version = "0.12", features = ["auxvec", "elf", "if_ether", "ioctl", "net", "netlink", "no_std", "prctl", "system", "xdp"] } @@ -372,6 +374,8 @@ quick-xml = { version = "0.41", features = ["overlapped-lists", "serialize"] } regex = { version = "1" } rustc-hash = { version = "1" } rustix = { version = "1", features = ["event", "net", "param", "pipe", "process", "shm", "system", "termios", "thread", "time"] } +rustls = { version = "0.23", default-features = false, features = ["aws-lc-rs", "aws_lc_rs"] } +rustls-webpki = { version = "0.103", default-features = false, features = ["aws-lc-rs", "std"] } tokio = { version = "1", default-features = false, features = ["tracing"] } tokio-rustls = { version = "0.26", default-features = false, features = ["aws-lc-rs", "tls12"] } tower = { version = "0.5", default-features = false, features = ["retry", "timeout"] } @@ -382,11 +386,14 @@ zerocopy = { version = "0.8", default-features = false, features = ["derive", "s [target.x86_64-pc-windows-msvc.dependencies] crossbeam-epoch = { version = "0.9" } flate2 = { version = "1", features = ["zlib-rs"] } +getrandom-468e82937335b1c9 = { package = "getrandom", version = "0.3", default-features = false, features = ["std"] } getrandom-9fbad63c4bcf4a8f = { package = "getrandom", version = "0.4", default-features = false, features = ["std", "sys_rng"] } half = { version = "2", default-features = false, features = ["num-traits"] } hyper-rustls = { version = "0.27", default-features = false, features = ["aws-lc-rs", "http1", "http2", "tls12"] } hyper-util = { version = "0.1", default-features = false, features = ["client-legacy", "client-proxy"] } regex = { version = "1" } +rustls = { version = "0.23", default-features = false, features = ["aws-lc-rs", "aws_lc_rs"] } +rustls-webpki = { version = "0.103", default-features = false, features = ["aws-lc-rs", "std"] } tokio-rustls = { version = "0.26", default-features = false, features = ["aws-lc-rs", "tls12"] } tower = { version = "0.5", default-features = false, features = ["retry", "timeout"] } tower-http = { version = "0.6", default-features = false, features = ["decompression-gzip", "follow-redirect"] } @@ -400,11 +407,14 @@ zerocopy = { version = "0.8", default-features = false, features = ["derive", "s [target.x86_64-pc-windows-msvc.build-dependencies] crossbeam-epoch = { version = "0.9" } flate2 = { version = "1", features = ["zlib-rs"] } +getrandom-468e82937335b1c9 = { package = "getrandom", version = "0.3", default-features = false, features = ["std"] } getrandom-9fbad63c4bcf4a8f = { package = "getrandom", version = "0.4", default-features = false, features = ["std", "sys_rng"] } half = { version = "2", default-features = false, features = ["num-traits"] } hyper-rustls = { version = "0.27", default-features = false, features = ["aws-lc-rs", "http1", "http2", "tls12"] } hyper-util = { version = "0.1", default-features = false, features = ["client-legacy", "client-proxy"] } regex = { version = "1" } +rustls = { version = "0.23", default-features = false, features = ["aws-lc-rs", "aws_lc_rs"] } +rustls-webpki = { version = "0.103", default-features = false, features = ["aws-lc-rs", "std"] } tokio-rustls = { version = "0.26", default-features = false, features = ["aws-lc-rs", "tls12"] } tower = { version = "0.5", default-features = false, features = ["retry", "timeout"] } tower-http = { version = "0.6", default-features = false, features = ["decompression-gzip", "follow-redirect"] } @@ -424,11 +434,10 @@ event-listener = { version = "5" } event-listener-strategy = { version = "0.5" } flate2 = { version = "1", features = ["zlib-rs"] } futures-io = { version = "0.3" } -getrandom-9fbad63c4bcf4a8f = { package = "getrandom", version = "0.4", default-features = false, features = ["std", "sys_rng"] } +getrandom-468e82937335b1c9 = { package = "getrandom", version = "0.3", default-features = false, features = ["std"] } half = { version = "2", default-features = false, features = ["num-traits"] } hyper-rustls = { version = "0.27", default-features = false, features = ["aws-lc-rs", "http1", "http2", "tls12"] } hyper-util = { version = "0.1", default-features = false, features = ["client-legacy", "client-proxy"] } -itertools = { version = "0.13" } libc = { version = "0.2", features = ["extra_traits"] } libspa = { version = "0.10", default-features = false, features = ["v0_3_33"] } linux-raw-sys = { version = "0.12", features = ["auxvec", "elf", "if_ether", "ioctl", "net", "netlink", "no_std", "prctl", "system", "xdp"] } @@ -442,6 +451,8 @@ quote = { version = "1" } regex = { version = "1" } rustc-hash = { version = "1" } rustix = { version = "1", features = ["event", "net", "param", "pipe", "process", "shm", "system", "termios", "thread", "time"] } +rustls = { version = "0.23", default-features = false, features = ["aws-lc-rs", "aws_lc_rs"] } +rustls-webpki = { version = "0.103", default-features = false, features = ["aws-lc-rs", "std"] } syn-7b89eefb6aaa9bf3 = { package = "syn", version = "3", features = ["extra-traits", "fold", "full", "visit", "visit-mut"] } tokio = { version = "1", default-features = false, features = ["tracing"] } tokio-rustls = { version = "0.26", default-features = false, features = ["aws-lc-rs", "tls12"] } @@ -460,11 +471,10 @@ event-listener = { version = "5" } event-listener-strategy = { version = "0.5" } flate2 = { version = "1", features = ["zlib-rs"] } futures-io = { version = "0.3" } -getrandom-9fbad63c4bcf4a8f = { package = "getrandom", version = "0.4", default-features = false, features = ["std", "sys_rng"] } +getrandom-468e82937335b1c9 = { package = "getrandom", version = "0.3", default-features = false, features = ["std"] } half = { version = "2", default-features = false, features = ["num-traits"] } hyper-rustls = { version = "0.27", default-features = false, features = ["aws-lc-rs", "http1", "http2", "tls12"] } hyper-util = { version = "0.1", default-features = false, features = ["client-legacy", "client-proxy"] } -itertools = { version = "0.13" } libc = { version = "0.2", features = ["extra_traits"] } libspa = { version = "0.10", default-features = false, features = ["v0_3_33"] } linux-raw-sys = { version = "0.12", features = ["auxvec", "elf", "if_ether", "ioctl", "net", "netlink", "no_std", "prctl", "system", "xdp"] } @@ -476,6 +486,8 @@ quick-xml = { version = "0.41", features = ["overlapped-lists", "serialize"] } regex = { version = "1" } rustc-hash = { version = "1" } rustix = { version = "1", features = ["event", "net", "param", "pipe", "process", "shm", "system", "termios", "thread", "time"] } +rustls = { version = "0.23", default-features = false, features = ["aws-lc-rs", "aws_lc_rs"] } +rustls-webpki = { version = "0.103", default-features = false, features = ["aws-lc-rs", "std"] } tokio = { version = "1", default-features = false, features = ["tracing"] } tokio-rustls = { version = "0.26", default-features = false, features = ["aws-lc-rs", "tls12"] } tower = { version = "0.5", default-features = false, features = ["retry", "timeout"] } diff --git a/sh/rs/select.test.py b/sh/rs/select.test.py index 3bd914e0e81..0f12ee508e5 100644 --- a/sh/rs/select.test.py +++ b/sh/rs/select.test.py @@ -462,11 +462,11 @@ def test_net_rejects_async_from_test_dependencies(self): calls = self.trace("net", net_features=f'moq-net feature "{feature}"', expected_returncode=1) self.assertTrue(all(call.startswith("tree ") for call in calls), calls) - def test_tokio_keeps_extremes_and_crypto_contracts(self): + def test_tokio_keeps_extremes_and_transport_contracts(self): boundary = self.trace("tokio") exhaustive = self.trace("tokio", "--all") self.assertEqual(sum(call.startswith("clippy ") for call in boundary), 3) - self.assertEqual(sum(call.startswith("clippy ") for call in exhaustive), 12) + self.assertEqual(sum(call.startswith("clippy ") for call in exhaustive), 9) self.assertTrue(any(" --tests " in call for call in boundary)) self.assertFalse(any(" --all-targets " in call for call in boundary)) self.assertTrue(any(" --all-targets " in call for call in exhaustive)) @@ -490,10 +490,6 @@ def test_media_keeps_dependency_contracts_and_vpx_tests(self): CARGO_STUB = r"""#!/usr/bin/env bash printf '%s\n' "$*" >> "$FEATURE_CALLS" -if [[ "$*" == 'check --locked -p moq-tokio --no-default-features --features quic' ]]; then - echo 'a rustls QUIC backend requires a crypto provider: enable either the `aws-lc-rs` or `ring` feature' >&2 - exit 1 -fi if [[ $1 == tree ]]; then if [[ "$*" == *'-i moq-net'* ]]; then printf '%s\n' "${FEATURE_NET_FEATURES:-}" diff --git a/sh/rs/tokio-features.sh b/sh/rs/tokio-features.sh index 9352b0811d1..871779252fa 100755 --- a/sh/rs/tokio-features.sh +++ b/sh/rs/tokio-features.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash # Compile moq-tokio by itself at the feature extremes and as a bare QUIC driver; -# --all also isolates each crypto and transport permutation. The default-feature +# --all also isolates each transport permutation. The default-feature # build is already in the ordinary gate, which can hide missing feature gates # through unification. set -euo pipefail @@ -24,7 +24,7 @@ cargo clippy --locked -p moq-tokio --all-features -- -D warnings # The QUIC driver is public API for applications without a MoQ session, so its # build must not reach moq-net, the MoQ backend's dependencies, or another QUIC stack. -driver=(--no-default-features --features "driver,aws-lc-rs") +driver=(--no-default-features --features "driver") targets=(--tests) if ((all)); then targets=(--all-targets); fi cargo clippy --locked -p moq-tokio "${targets[@]}" "${driver[@]}" -- -D warnings @@ -36,27 +36,12 @@ if leaked=$(grep -E '^(moq-net|reqwest|notify|quinn[a-z-]*|noq[a-z-]*|web-transp fi # Every isolated permutation, which `just rs features` asks for. if ((all)); then - cargo clippy --locked -p moq-tokio --no-default-features --features quic,aws-lc-rs -- -D warnings - cargo clippy --locked -p moq-tokio --no-default-features --features quic,ring -- -D warnings - - for feature in net aws-lc-rs ring tcp uds websocket webrtc; do + for feature in net quic tcp uds websocket webrtc; do cargo clippy --locked -p moq-tokio --no-default-features --features "$feature" -- -D warnings done fi -# shellcheck disable=SC2016 # the backticks are literal, as rustc prints them -want='a rustls QUIC backend requires a crypto provider: enable either the `aws-lc-rs` or `ring` feature' -if output=$(cargo check --locked -p moq-tokio --no-default-features --features quic 2>&1); then - echo "rs: moq-tokio with only quic should reject its missing crypto provider" >&2 - exit 1 -fi -if ! grep -qF "$want" <<<"$output"; then - echo "rs: moq-tokio with only quic should fail on: $want" >&2 - echo "$output" | grep -E '^error' >&2 || true - exit 1 -fi - # Crypto support alone must not make a transport-less server load a QUIC identity. bash sh/rs/nextest.sh cargo nextest run --locked -p moq-tokio --lib \ - --no-default-features --features tcp,aws-lc-rs \ + --no-default-features --features tcp \ -E 'test(no_quic_backend_needs_no_served_identity)'