diff --git a/Cargo.lock b/Cargo.lock index 9201bbed1e2..5d881ad9752 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5304,33 +5304,32 @@ version = "0.3.12" dependencies = [ "aes 0.9.4", "arrayvec", - "aws-lc-rs", "axum", "base64ct", "bytes", "ccm", "combine", "crc", - "der 0.8.2", "fastrand", "futures", "hang", "if-addrs", "kio", "mdns-sd", + "moq-crypto", "moq-mux", "moq-net", "moq-tokio", "nom 8.0.0", "once_cell", "pcap-file", - "pkcs8 0.11.0", "qmux 0.7.0", "rand 0.10.3", "rcgen", "reqwest", + "rind", + "rind-rcgen", "rustc-hash 2.1.3", - "sec1", "serde", "serde_json", "slab", @@ -7305,11 +7304,9 @@ version = "0.14.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8" dependencies = [ - "aws-lc-rs", "pem 4.0.0", "rustls-pki-types", "time", - "x509-parser", "yasna", ] @@ -10902,9 +10899,9 @@ dependencies = [ "anyhow", "aws-lc-rs", "aws-lc-sys", - "base16ct", "base64 0.22.1", "base64 0.23.1", + "base64ct", "bitflags 2.13.2", "block2 0.6.2", "bytemuck", @@ -11007,7 +11004,6 @@ dependencies = [ "rustls", "rustls-pki-types", "rustls-webpki", - "sec1", "security-framework-sys", "semver", "serde", @@ -11130,7 +11126,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202" dependencies = [ "asn1-rs", - "aws-lc-rs", "data-encoding", "der-parser", "lazy_static", diff --git a/Cargo.toml b/Cargo.toml index 1ee715bc17f..c169ca2d5eb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -73,7 +73,6 @@ anyhow = "1" arrayvec = "0.7.6" ash = "0.38" async-trait = "0.1" -aws-lc-rs = "1" # Keep axum's defaults except tower-log, which enables tracing-to-log macros workspace-wide. axum = { version = "0.8", default-features = false, features = [ "form", @@ -102,7 +101,6 @@ crc = "3" # (`fallback-dynamic-loading`), so nothing links against libcuda at build time. cudarc = { version = "0.19", default-features = false, features = ["driver", "fallback-dynamic-loading", "cuda-12020"] } data-encoding = "2.11" -der = "0.8" dispatch2 = "0.3.1" ebml-iterable = "0.7.1" fastrand = "2" @@ -221,7 +219,6 @@ rind-rustls = "0.1.12" rustc-hash = "2.1.3" rustls-native-certs = "0.8.5" sd-notify = "0.5" -sec1 = "0.8" send_wrapper = "0.6" serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/doc/bin/rtc.md b/doc/bin/rtc.md index d225b896872..a1637561746 100644 --- a/doc/bin/rtc.md +++ b/doc/bin/rtc.md @@ -43,5 +43,5 @@ Once the original publisher leaves, the session ends with an error, and the player or `export rtc --connect` must reconnect to reach the replacement. `--connect` runs until its session ends. -Built on a vendored, trimmed copy of [str0m](https://github.com/algesten/str0m); the library is +Built on a vendored, trimmed copy of [str0m](https://github.com/algesten/str0m), with DTLS and SRTP on [rind](https://github.com/moq-dev/rind); the library is [`moq-webrtc`](https://github.com/moq-dev/moq/tree/main/rs/moq-webrtc). diff --git a/quest/m1/rind/README.md b/quest/m1/rind/README.md index 0334768c0b3..d76ed06fb84 100644 --- a/quest/m1/rind/README.md +++ b/quest/m1/rind/README.md @@ -1,4 +1,4 @@ -# MoQ on rind +# [M] MoQ on rind ## Goal @@ -49,8 +49,8 @@ instead, so every crate drops C, not just the relay. CPUs without the crypto extensions (e2ee, which no binary links, switched on 0.1.0). Relay ACME, the one area that waited on `rind-instant-acme`, is removed for now instead (maintainer, 2026-11-03), and returns on rind in m5. - aws-lc-rs stays in the workspace until - the last area lands, which is when this epic removes it. + Every area has landed, and the workspace declares no aws-lc-rs dependency; + the epic's own work below removes what still reaches it. - Split per area, each landing once rind covers it. Docs a change makes stale (CPU requirements, removed features) are edited inline in that area's PR; no separate docs page. @@ -62,7 +62,3 @@ The epic's own work, once every child has merged: crate. - Add an `armv7-unknown-linux-gnueabihf` moq-cli release with v4l2, and point `doc/bin/cli.md`'s board note at it for boards running a 32-bit OS. - -## Required - -- [moq-webrtc on rind](/quest/m1/rind/rtc.md) - str0m and dimpl run DTLS, SRTP, and STUN on rind diff --git a/quest/m1/rind/rtc.md b/quest/m1/rind/rtc.md deleted file mode 100644 index f227b902691..00000000000 --- a/quest/m1/rind/rtc.md +++ /dev/null @@ -1,29 +0,0 @@ -# [M] moq-webrtc on rind - -## Goal - -moq-webrtc runs the vendored str0m and dimpl on rind: -DTLS 1.2, SRTP (AES-CM-HMAC-SHA1-80 and AEAD AES-128/256-GCM), STUN -MESSAGE-INTEGRITY, and DTLS certificates through `rind-rcgen`. Their graphs -hold no aws-lc-rs or str0m-aws-lc-rs, and a browser still connects. - -## Plan - -Decided with the maintainer on 2026-10-26; see the -[epic](/quest/m1/rind/README.md). The vendored stack drops its aws-lc-rs -backend (`str0m_aws_lc_rs` and dimpl's `crypto/aws_lc_rs`), the test-only -HMAC-SHA1 in `server/mux.rs` moves to rind, and reqwest switches to its -no-provider feature. The existing browser interop tests prove the switch. - -Decided 2026-10-30 (maintainer): the stack is vendored into moq-webrtc -([epic](/quest/m3/webrtc/README.md)) with DTLS 1.2 only, so this quest -changes the vendored crypto provider directly and offers no DTLS 1.3. - -Decided 2026-10-31 (maintainer): the vendored crates are private modules, so -rind's published adapters can't plug into them. Port the provider code from -moq-dev/rind's `rind-dimpl` and its deleted `rind-str0m` (git history) into -the vendored stack. The vendor pins the revision those adapters targeted, so -the code drops in unchanged. No str0m release is needed. - -Public API: none. Wire: unchanged; the same SRTP profiles and DTLS suites are -offered. diff --git a/quest/m3/webrtc/README.md b/quest/m3/webrtc/README.md index 01c6a95c132..b067898bf5e 100644 --- a/quest/m3/webrtc/README.md +++ b/quest/m3/webrtc/README.md @@ -13,7 +13,7 @@ Decided 2026-10-30 with the maintainer (planning interview), after the str0m wor - **Vendor, then replace.** Copy the upstream crates in, trim them, and fix them in-tree. Replacing a layer with our own (SDP, RTP/RTCP, SRTP, SCTP) is a later child once a concrete need appears; none is planned yet. - **One crate.** The ICE driver (once `moq-ice`) and moq-tokio's former `webrtc` data-channel transport live in `moq-webrtc`, which depends on moq-tokio rather than the reverse, so moq-tokio needs no ICE or SCTP. The vendored crates become private modules, not separate published crates, keeping their MIT/Apache-2.0 notices (str0m's `packet/` carries webrtc-rs's Apache notice). - **What goes** (from the 2026-10-30 inventory: we use frame mode, full ICE, and DTLS 1.2, and never enable str0m's BWE, pacer, or stats): GCC bandwidth estimation (8k lines; GCC is ported into `moq-congestion` as `moq_congestion::gcc`), the leaky pacer (replaced by moq-congestion's pacer, made public by [rtc-pacing](/quest/m3/rtc-pacing.md)), H.266, RED, DTMF, G.7xx and comfort noise, VLA and simulcast layers, RTCP app feedback, stats, internal test exports, and dimpl's DTLS 1.3 and version auto-selection. RTCP XR stays: its RRTR/DLRR blocks are the receive side's only RTT measurement, which sets NACK retries and the video recovery deadline. Roughly 17k of str0m's 72k lines and 11k of dimpl's 33k. -- **DTLS 1.2 only.** Every browser negotiates 1.2 today. [moq-webrtc on rind](/quest/m1/rind/rtc.md) narrows to 1.2 to match. +- **DTLS 1.2 only.** Every browser negotiates 1.2 today, and the vendored rind crypto provider offers 1.2 only to match. - **SCTP stays**, for browser data channels in [P2P](/quest/m4/p2p/README.md), but compiles only with the data-channel feature, so WHIP/WHEP builds carry none of it. Vendored, it can later be simplified or put on moq-congestion. - **Upstream fixes:** after vendoring, nobody merges upstream automatically. Record the vendored upstream versions in the crate docs; the release-cut audit checks the upstream changelogs for security fixes (malformed SRTP/RTCP input, for example) and ports them. - Docs a change makes stale (crate names, `doc/lib/rs`, `doc/setup/upgrade.md`, other quests naming a crate or module) change in the PR that makes them stale. @@ -26,9 +26,8 @@ Decided 2026-10-30 with the maintainer (planning interview), after the str0m wor - [The stack takes kio clock time](/quest/m3/webrtc/clock.md) - the vendored code takes `kio::clock::Instant`, so sim tests drive it directly - [WHIP/WHEP builds carry no SCTP](/quest/m3/webrtc/sctp-feature.md) - SCTP compiles only with the `p2p` feature - [The vendored stack keeps only what browsers negotiate](/quest/m3/webrtc/browser-only.md) - PSK suites, `ccm`, and anything else no browser uses are gone -- [The vendored stack exposes only what moq-webrtc calls](/quest/m3/webrtc/dead-api.md) - dead upstream API is deleted once rind and clock settle the seams +- [The vendored stack exposes only what moq-webrtc calls](/quest/m3/webrtc/dead-api.md) - dead upstream API is deleted once clock settles the time seams ## Related - [moq-webrtc paces WHEP viewers](/quest/m3/rtc-pacing.md) - adds the NACK hook and the shared pacer on the vendored stack -- [moq-webrtc on rind](/quest/m1/rind/rtc.md) - the vendored DTLS and SRTP take rind's crypto diff --git a/quest/m3/webrtc/dead-api.md b/quest/m3/webrtc/dead-api.md index 9d97a358e07..4153d888898 100644 --- a/quest/m3/webrtc/dead-api.md +++ b/quest/m3/webrtc/dead-api.md @@ -9,8 +9,8 @@ tests; dead upstream API is deleted. Planned 2026-11-07 (maintainer, /quest-complete), a follow-up of [moq-dev/moq#8163](https://github.com/moq-dev/moq/pull/8163). It waits on -the rind and clock quests, since both reshape the seams moq-webrtc calls -through. The vendored tree opens with `#![allow(warnings, reason = "vendored +the clock quest, which reshapes the time seams moq-webrtc calls through, as +the move to rind already did the crypto seams. The vendored tree opens with `#![allow(warnings, reason = "vendored upstream code")]` (`rs/moq-webrtc/src/vendor/mod.rs`), so first narrow that allow to let `dead_code` fire, then delete what the report shows unreached, keeping upstream's tests for what stays. @@ -19,5 +19,4 @@ Public API: none. Wire: none. ## Required -- [moq-webrtc on rind](/quest/m1/rind/rtc.md) - settles the crypto seams - [The stack takes kio clock time](/quest/m3/webrtc/clock.md) - settles the time seams diff --git a/rs/moq-cli/src/rtc.rs b/rs/moq-cli/src/rtc.rs index 2065dc1f6f3..fd0353bb7ea 100644 --- a/rs/moq-cli/src/rtc.rs +++ b/rs/moq-cli/src/rtc.rs @@ -108,7 +108,7 @@ pub async fn connect_import(target: ImportTarget, url: Url, instance: moq_net::I let mut config = moq_webrtc::client::Config::default(); config.max_age = target.max_age; config.bandwidth = target.bandwidth; - let client = moq_webrtc::Client::new(config); + let client = moq_webrtc::Client::new(config)?; client.subscribe(url, route.broadcast().clone()).await?; Ok(()) } @@ -128,7 +128,7 @@ pub async fn connect_export(origin: moq_net::origin::Consumer, url: Url, name: S tracing::info!(url = %RedactedUrl::new(&url), %name, "WHIP client pushing"); notify_ready(); - let client = moq_webrtc::Client::new(moq_webrtc::client::Config::default()); + let client = moq_webrtc::Client::new(moq_webrtc::client::Config::default())?; client.publish(url, source).await?; Ok(()) } diff --git a/rs/moq-relay/src/auth.rs b/rs/moq-relay/src/auth.rs index 5e0bb770b67..bd73749822f 100644 --- a/rs/moq-relay/src/auth.rs +++ b/rs/moq-relay/src/auth.rs @@ -1778,14 +1778,14 @@ mod tests { fn a_peer_reports_its_lineage_to_the_listener_root() { let root_key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap(); let mut root_params = rcgen::CertificateParams::new(Vec::::new()).unwrap(); + root_params.serial_number = Some(1u64.into()); root_params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained); let root = root_params.self_signed(&root_key).unwrap(); let issuer = rcgen::Issuer::new(root_params, root_key); let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap(); - let leaf = rcgen::CertificateParams::new(vec!["edge0.invalid".to_string()]) - .unwrap() - .signed_by(&key, &issuer) - .unwrap(); + let mut leaf = rcgen::CertificateParams::new(vec!["edge0.invalid".to_string()]).unwrap(); + leaf.serial_number = Some(2u64.into()); + let leaf = leaf.signed_by(&key, &issuer).unwrap(); let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("root.pem"); diff --git a/rs/moq-relay/tests/integration/main.rs b/rs/moq-relay/tests/integration/main.rs index 769ba11f69f..42c1bfa9b06 100644 --- a/rs/moq-relay/tests/integration/main.rs +++ b/rs/moq-relay/tests/integration/main.rs @@ -47,10 +47,9 @@ mod wire_stats; /// A certificate handle for a web stack, which only reads it to publish fingerprints. fn certificates() -> moq_tokio::tls::Certificates { let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).expect("keypair"); - let cert = rcgen::CertificateParams::new(vec!["localhost".into()]) - .expect("cert params") - .self_signed(&key) - .expect("self-signed cert"); + let mut params = rcgen::CertificateParams::new(vec!["localhost".into()]).expect("cert params"); + params.serial_number = Some(1u64.into()); + let cert = params.self_signed(&key).expect("self-signed cert"); moq_tokio::tls::Certificates::from_pem(cert.pem().as_bytes()).expect("certificates") } diff --git a/rs/moq-tokio/src/tls.rs b/rs/moq-tokio/src/tls.rs index 678246a6297..01b20a9237a 100644 --- a/rs/moq-tokio/src/tls.rs +++ b/rs/moq-tokio/src/tls.rs @@ -3060,6 +3060,7 @@ mod tests { ) -> (CertificateDer<'static>, rcgen::Issuer<'static, rind_rcgen::KeyPair>) { let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap(); let mut params = rcgen::CertificateParams::new(Vec::::new()).unwrap(); + params.serial_number = Some(1u64.into()); params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained); let cert = match parent { Some(parent) => params.signed_by(&key, parent).unwrap(), @@ -3070,7 +3071,8 @@ mod tests { fn lineage_leaf(issuer: &rcgen::Issuer<'_, rind_rcgen::KeyPair>) -> CertificateDer<'static> { let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap(); - let params = rcgen::CertificateParams::new(vec!["client.invalid".to_string()]).unwrap(); + let mut params = rcgen::CertificateParams::new(vec!["client.invalid".to_string()]).unwrap(); + params.serial_number = Some(1u64.into()); params.signed_by(&key, issuer).unwrap().into() } diff --git a/rs/moq-webrtc/Cargo.toml b/rs/moq-webrtc/Cargo.toml index 1571812e988..ddab8a5e522 100644 --- a/rs/moq-webrtc/Cargo.toml +++ b/rs/moq-webrtc/Cargo.toml @@ -31,8 +31,6 @@ p2p = ["dep:if-addrs", "dep:mdns-sd", "dep:qmux", "moq-tokio/qmux"] # The vendored stack's AES-CCM DTLS suites. aes = { workspace = true } arrayvec = { workspace = true } -# The vendored stack's crypto provider: DTLS, SRTP, and STUN MESSAGE-INTEGRITY. -aws-lc-rs = { workspace = true } axum = { workspace = true, optional = true } base64ct = { workspace = true } bytes = { workspace = true } @@ -40,14 +38,14 @@ ccm = { workspace = true } # The vendored stack's SDP parser. combine = { workspace = true } crc = { workspace = true } -# The vendored DTLS's certificate and key parsing. -der = { workspace = true } fastrand = { workspace = true } hang = { workspace = true } if-addrs = { workspace = true, optional = true } # Drives each WebRTC connection over its UDP socket. kio = { workspace = true, features = ["runtime"] } mdns-sd = { workspace = true, optional = true } +# Refuses a CPU rind can't run on, and gives the WHIP/WHEP client rind's rustls provider. +moq-crypto = { workspace = true, features = ["provider"] } moq-mux = { workspace = true, features = ["async"] } moq-net = { workspace = true } # `RedactedUrl` keeps a dialed URL's query token and userinfo out of the logs, and with @@ -56,14 +54,15 @@ moq-tokio = { workspace = true } # The vendored DTLS's record parser. nom = { workspace = true } once_cell = { workspace = true } -pkcs8 = { workspace = true, features = ["pem"] } qmux = { workspace = true, optional = true } rand = { workspace = true } # The vendored DTLS's self-signed certificates. -rcgen = { workspace = true, features = ["aws_lc_rs"] } -reqwest = { workspace = true, features = ["rustls"] } +rcgen = { workspace = true } +reqwest = { workspace = true, features = ["rustls-no-provider"] } +# The vendored stack's crypto: DTLS, SRTP, and STUN MESSAGE-INTEGRITY. +rind = { workspace = true } +rind-rcgen = { workspace = true } rustc-hash = { workspace = true } -sec1 = { workspace = true } serde = { workspace = true } slab = { workspace = true } spki = { workspace = true } @@ -76,6 +75,7 @@ tokio = { workspace = true, features = ["full"] } tracing = { workspace = true } url = { workspace = true } uuid = { version = "1", features = ["v4"] } +# The vendored DTLS's certificate parsing. x509-cert = { workspace = true } [dev-dependencies] diff --git a/rs/moq-webrtc/src/client/mod.rs b/rs/moq-webrtc/src/client/mod.rs index 8acb15a54ed..1a2eb9af40b 100644 --- a/rs/moq-webrtc/src/client/mod.rs +++ b/rs/moq-webrtc/src/client/mod.rs @@ -60,11 +60,17 @@ impl Client { /// [`reqwest::Client`] (with its connection pool and rustls config) is created /// once here and reused across every [`subscribe`](Self::subscribe) / /// [`publish`](Self::publish) call. - pub fn new(config: Config) -> Self { - Self { + /// + /// Fails with [`Error::UnsupportedCpu`](crate::Error::UnsupportedCpu) on a CPU + /// rind can't run on. + pub fn new(config: Config) -> crate::Result { + // reqwest reads rustls's process default and panics without one, so install rind's + // unless the host already chose a provider. + moq_crypto::provider::install_default()?; + Ok(Self { config, - http: reqwest::Client::new(), - } + http: reqwest::Client::builder().build()?, + }) } pub(crate) fn config(&self) -> &Config { @@ -111,6 +117,7 @@ mod tests { .parse() .expect("WHEP URL"); let err = Client::new(Config::default()) + .unwrap() .subscribe(url, broadcast.broadcast().clone()) .await .expect_err("dial a closed port"); diff --git a/rs/moq-webrtc/src/client/whep.rs b/rs/moq-webrtc/src/client/whep.rs index 7cdbb8a65ab..cea48a0c579 100644 --- a/rs/moq-webrtc/src/client/whep.rs +++ b/rs/moq-webrtc/src/client/whep.rs @@ -8,7 +8,7 @@ use crate::vendor::str0m; use str0m::{ - Candidate, Rtc, + Candidate, change::SdpAnswer, media::{Direction, MediaKind}, }; @@ -23,7 +23,7 @@ pub(crate) async fn dial(client: &Client, url: Url, broadcast: moq_net::broadcas let sink = Box::new(IngestSink::new(broadcast, config)?); let socket = session::bind_udp(&client.config().ice_candidates).await?; - let mut rtc = Rtc::new(kio::clock::now().into_std()); + let mut rtc = session::rtc_config()?.build(kio::clock::now().into_std()); for addr in socket.locals() { let cand = Candidate::host(*addr, "udp").map_err(Error::rtc)?; rtc.add_local_candidate(cand); diff --git a/rs/moq-webrtc/src/client/whip.rs b/rs/moq-webrtc/src/client/whip.rs index c254ffdffb9..adad3d92a35 100644 --- a/rs/moq-webrtc/src/client/whip.rs +++ b/rs/moq-webrtc/src/client/whip.rs @@ -28,7 +28,7 @@ pub(crate) async fn dial(client: &Client, url: Url, source: moq_mux::Source) -> let socket = session::bind_udp(&client.config().ice_candidates).await?; // Restrict to codecs the catalog can actually source so the remote // answer doesn't pick a codec we have no rendition for. - let mut rtc = session::rtc_with_codecs(&codecs); + let mut rtc = session::rtc_with_codecs(&codecs)?; for addr in socket.locals() { let cand = Candidate::host(*addr, "udp").map_err(Error::rtc)?; rtc.add_local_candidate(cand); diff --git a/rs/moq-webrtc/src/error.rs b/rs/moq-webrtc/src/error.rs index 254e6e33a1a..b6dc77d9ef6 100644 --- a/rs/moq-webrtc/src/error.rs +++ b/rs/moq-webrtc/src/error.rs @@ -74,6 +74,10 @@ pub enum Error { /// An internal video bridge could not be initialized. #[error("video bridge initialization failed")] BridgeFailed, + + /// This CPU lacks a feature rind, the crypto under DTLS, SRTP, and HTTPS, requires. + #[error(transparent)] + UnsupportedCpu(#[from] moq_crypto::cpu::UnsupportedCpu), } impl From for Error { diff --git a/rs/moq-webrtc/src/lib.rs b/rs/moq-webrtc/src/lib.rs index 4f3014534da..bd576e7a46a 100644 --- a/rs/moq-webrtc/src/lib.rs +++ b/rs/moq-webrtc/src/lib.rs @@ -225,7 +225,7 @@ mod tests { .route("output", moq_net::origin::RouteOptions::hidden()) .expect("create output broadcast"); let output_consumer = output.broadcast().consume(); - let client = Client::new(client::Config::default()); + let client = Client::new(client::Config::default()).unwrap(); let url = format!("http://{address}/whep/source").parse().expect("WHEP URL"); let fill = output.broadcast().clone(); let viewer = tokio::spawn(async move { client.subscribe(url, fill).await }); @@ -285,7 +285,7 @@ mod tests { ); let (address, http) = serve(app).await; - let client = Client::new(client::Config::default()); + let client = Client::new(client::Config::default()).unwrap(); let url = format!("http://{address}/whip/ingested").parse().expect("WHIP URL"); let source = origin.consume(); let broadcast = source.request("source", None).await.unwrap(); @@ -354,7 +354,7 @@ mod tests { origin: &moq_net::origin::Producer, address: std::net::SocketAddr, ) -> tokio::task::JoinHandle> { - let client = Client::new(client::Config::default()); + let client = Client::new(client::Config::default()).unwrap(); let url = format!("http://{address}/whip/ingested").parse().expect("WHIP URL"); let source = origin.consume(); let broadcast = source.request("source", None).await.unwrap(); @@ -518,7 +518,7 @@ mod tests { ); let (address, http) = serve(app).await; - let client = Client::new(client::Config::default()); + let client = Client::new(client::Config::default()).unwrap(); // Credentials in the dialed URLs must never reach the client's connect logs. let whip = format!("http://user:pass@{address}/whip/ingested?jwt=canary-7f3e") .parse() diff --git a/rs/moq-webrtc/src/p2p/mod.rs b/rs/moq-webrtc/src/p2p/mod.rs index fdadebcfb00..755aba406ad 100644 --- a/rs/moq-webrtc/src/p2p/mod.rs +++ b/rs/moq-webrtc/src/p2p/mod.rs @@ -88,6 +88,10 @@ pub enum Error { #[error("rtc error: {0}")] Rtc(String), + /// This CPU lacks a feature rind, the stack's crypto, requires. + #[error(transparent)] + UnsupportedCpu(#[from] moq_crypto::cpu::UnsupportedCpu), + /// A session description failed to parse or apply. #[error("invalid session description: {0}")] Sdp(String), @@ -898,7 +902,7 @@ async fn next_write(writes: Option<&mut channel::Outbox>) -> Option { /// A str0m connection with this socket's host candidates. fn rtc(locals: &[SocketAddr]) -> Result { - let mut rtc = Rtc::builder().build(kio::clock::now().into_std()); + let mut rtc = crate::session::rtc_config()?.build(kio::clock::now().into_std()); for &addr in locals { let candidate = str0m::Candidate::host(addr, "udp").map_err(|err| Error::Candidate(err.to_string()))?; rtc.add_local_candidate(candidate); diff --git a/rs/moq-webrtc/src/server/mux.rs b/rs/moq-webrtc/src/server/mux.rs index 365855d69fd..af9e98c572f 100644 --- a/rs/moq-webrtc/src/server/mux.rs +++ b/rs/moq-webrtc/src/server/mux.rs @@ -213,9 +213,9 @@ mod tests { /// SHA1-HMAC for a STUN MESSAGE-INTEGRITY, matching what str0m signs with. fn sha1_hmac(key: &[u8], payloads: &[&[u8]]) -> [u8; 20] { - use aws_lc_rs::hmac; + use rind::hmac; - let key = hmac::Key::new(hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY, key); + let key = hmac::Key::new(&hmac::legacy::HMAC_SHA1, key); let mut ctx = hmac::Context::with_key(&key); for payload in payloads { ctx.update(payload); diff --git a/rs/moq-webrtc/src/server/whep.rs b/rs/moq-webrtc/src/server/whep.rs index b7ff6837624..eeead4ca655 100644 --- a/rs/moq-webrtc/src/server/whep.rs +++ b/rs/moq-webrtc/src/server/whep.rs @@ -155,7 +155,7 @@ pub async fn accept( // fulfil; set the mux's known ICE credentials on the same config. let mux = server.mux().await?; let (creds, inbound, registration) = mux.register(); - let mut rtc = session::rtc_config_with_codecs(&codecs) + let mut rtc = session::rtc_config_with_codecs(&codecs)? .set_local_ice_credentials(creds) .build(kio::clock::now().into_std()); for addr in mux.candidates() { diff --git a/rs/moq-webrtc/src/server/whip.rs b/rs/moq-webrtc/src/server/whip.rs index 0ef8551253f..6c22a0e6a3c 100644 --- a/rs/moq-webrtc/src/server/whip.rs +++ b/rs/moq-webrtc/src/server/whip.rs @@ -14,7 +14,7 @@ use axum::{ response::{IntoResponse, Response as HttpResponse}, routing::post, }; -use str0m::{Candidate, RtcConfig}; +use str0m::Candidate; use crate::{Error, Result, ingest::IngestSink, rate, sdp, server::Server, session}; @@ -171,7 +171,7 @@ pub async fn accept(server: &Server, request: Request<'_>) -> Result { // and a guard the session task holds for its lifetime (unregisters on exit). let mux = server.mux().await?; let (creds, inbound, registration) = mux.register(); - let mut rtc = RtcConfig::new() + let mut rtc = session::rtc_config()? .set_local_ice_credentials(creds) .build(kio::clock::now().into_std()); for addr in mux.candidates() { @@ -250,7 +250,7 @@ mod tests { /// An encoder's offer to send one Opus track. fn offer() -> String { - let mut rtc = session::rtc_with_codecs(&[Codec::Opus]); + let mut rtc = session::rtc_with_codecs(&[Codec::Opus]).unwrap(); let mut api = rtc.sdp_api(); api.add_media(MediaKind::Audio, Direction::SendOnly, None, None, None); let (offer, _pending) = api.apply().expect("an offer"); diff --git a/rs/moq-webrtc/src/session.rs b/rs/moq-webrtc/src/session.rs index bd8b3623cb7..385472754b5 100644 --- a/rs/moq-webrtc/src/session.rs +++ b/rs/moq-webrtc/src/session.rs @@ -648,14 +648,14 @@ impl Bridges { /// can't fulfil (WHEP server). For both, the negotiated SDP intersects with /// what we can actually deliver, so `MediaAdded` only fires for codecs that /// [`crate::egress::EgressSource`] can match to a rendition. -pub fn rtc_config_with_codecs(codecs: &[str0m::format::Codec]) -> str0m::RtcConfig { +pub fn rtc_config_with_codecs(codecs: &[str0m::format::Codec]) -> Result { use str0m::format::Codec; // str0m fulfils NACK resends from the video send buffer (default 1000 // packets). MoQ has no PLI path back to the publisher, so a late joiner's // recovery is whatever the peer can NACK out of this buffer while the current // group is still in flight. Widen it so a large keyframe plus the rest of the // group stays recoverable instead of aging out after ~1000 packets. - let mut config = str0m::RtcConfig::new() + let mut config = rtc_config()? .clear_codecs() .set_send_buffer_video(EGRESS_SEND_BUFFER_VIDEO); for c in codecs { @@ -670,15 +670,23 @@ pub fn rtc_config_with_codecs(codecs: &[str0m::format::Codec]) -> str0m::RtcConf _ => config, }; } - config + Ok(config) +} + +/// A str0m config, refusing a CPU that rind, the stack's crypto, cannot run on. +/// +/// str0m falls back on rind's provider, which panics on such a CPU instead. +pub(crate) fn rtc_config() -> std::result::Result { + moq_crypto::cpu::check()?; + Ok(str0m::RtcConfig::new()) } /// Build a codec-restricted [`Rtc`] for the client egress path (which lets /// str0m mint its own ICE credentials). The server egress path uses /// [`rtc_config_with_codecs`] directly so it can inject the mux's known /// credentials before building. -pub fn rtc_with_codecs(codecs: &[str0m::format::Codec]) -> Rtc { - rtc_config_with_codecs(codecs).build(kio::clock::now().into_std()) +pub fn rtc_with_codecs(codecs: &[str0m::format::Codec]) -> Result { + Ok(rtc_config_with_codecs(codecs)?.build(kio::clock::now().into_std())) } /// Bind an ephemeral UDP socket for a single client session, read by its own diff --git a/rs/moq-webrtc/src/vendor/dimpl/buffer.rs b/rs/moq-webrtc/src/vendor/dimpl/buffer.rs index b3f7fe3ebf2..708ee957bee 100644 --- a/rs/moq-webrtc/src/vendor/dimpl/buffer.rs +++ b/rs/moq-webrtc/src/vendor/dimpl/buffer.rs @@ -91,7 +91,7 @@ impl Buf { } } -// aws-lc-rs AEAD operations require Extend<&u8> for appending authentication tags +// AEAD backends may append their authentication tags through Extend<&u8> impl<'a> Extend<&'a u8> for Buf { fn extend>(&mut self, iter: T) { self.data.extend(iter.into_iter().copied()); diff --git a/rs/moq-webrtc/src/vendor/dimpl/certificate.rs b/rs/moq-webrtc/src/vendor/dimpl/certificate.rs index f4e324d1736..16ac1350138 100644 --- a/rs/moq-webrtc/src/vendor/dimpl/certificate.rs +++ b/rs/moq-webrtc/src/vendor/dimpl/certificate.rs @@ -3,9 +3,8 @@ //! This module provides helpers to generate self-signed certificates suitable for DTLS, //! compute fingerprints, and format them for display. -use aws_lc_rs::digest; -use rand::random; -use rcgen::{CertificateParams, DistinguishedName, DnType, IsCa, KeyPair, PKCS_ECDSA_P256_SHA256}; +use rcgen::{CertificateParams, DistinguishedName, DnType, IsCa, PKCS_ECDSA_P256_SHA256, SerialNumber}; +use rind::digest; use std::fmt; /// Certificate utility error types @@ -33,12 +32,11 @@ impl std::error::Error for CertificateError {} pub use crate::vendor::dimpl::DtlsCertificate; -/// Generate a self-signed certificate for DTLS -/// -/// This function requires the `rcgen` feature to be enabled. +/// Generate a self-signed ECDSA P-256 certificate for DTLS, valid for a year. pub fn generate_self_signed_certificate() -> Result { // Create a key pair for the certificate - let key_pair = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).map_err(|_| CertificateError::GenerationFailed)?; + let key_pair = + rind_rcgen::KeyPair::generate(&PKCS_ECDSA_P256_SHA256).map_err(|_| CertificateError::GenerationFailed)?; // Set up certificate parameters let mut params = CertificateParams::new(Vec::::new()).map_err(|_| CertificateError::GenerationFailed)?; @@ -62,8 +60,9 @@ pub fn generate_self_signed_certificate() -> Result Result Result Vec { // Use SHA-256 to calculate the fingerprint digest::digest(&digest::SHA256, cert_der).as_ref().to_vec() diff --git a/rs/moq-webrtc/src/vendor/dimpl/config.rs b/rs/moq-webrtc/src/vendor/dimpl/config.rs index 9db460db1ae..5c03feab5bc 100644 --- a/rs/moq-webrtc/src/vendor/dimpl/config.rs +++ b/rs/moq-webrtc/src/vendor/dimpl/config.rs @@ -52,8 +52,6 @@ pub enum Psk { }, } -use crate::vendor::dimpl::crypto::aws_lc_rs; - /// DTLS configuration shared by all connections. /// /// Build with [`Config::builder()`] or use [`Config::default()`]. @@ -369,8 +367,7 @@ impl ConfigBuilder { /// Set a custom crypto provider. /// - /// If not set, the default aws-lc-rs provider will be used, if the feature - /// flag `aws-lc-rs` is enabled. + /// If not set, the process default or else rind's provider is used. pub fn with_crypto_provider(mut self, provider: CryptoProvider) -> Self { self.crypto_provider = Some(provider); self @@ -438,7 +435,7 @@ impl ConfigBuilder { /// The crypto provider is selected in the following priority order: /// 1. Explicit provider set via `with_crypto_provider()` /// 2. Default provider installed via `CryptoProvider::install_default()` - /// 3. The aws-lc-rs provider + /// 3. rind's provider, refusing a CPU rind cannot run on pub fn build(self) -> Result { if self.handshake_timeout.is_zero() || self.handshake_timeout > MAX_TIMING_DURATION { return Err(ConfigError::InvalidHandshakeTimeout.into()); @@ -447,10 +444,10 @@ impl ConfigBuilder { return Err(ConfigError::InvalidFlightStartRto.into()); } - let crypto_provider = self - .crypto_provider - .or_else(|| CryptoProvider::get_default().cloned()) - .unwrap_or_else(aws_lc_rs::default_provider); + let crypto_provider = match self.crypto_provider.or_else(|| CryptoProvider::get_default().cloned()) { + Some(provider) => provider, + None => crate::vendor::dimpl::crypto::rind::default_provider().map_err(ConfigError::UnsupportedCpu)?, + }; // Always validate the crypto provider crypto_provider.validate()?; @@ -850,7 +847,7 @@ mod tests { fn filter_with_explicit_provider() { { let config = Config::builder() - .with_crypto_provider(aws_lc_rs::default_provider()) + .with_crypto_provider(crate::vendor::dimpl::crypto::rind::default_provider().unwrap()) .dtls12_cipher_suites(&[Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384]) .kx_groups(&[NamedGroup::X25519, NamedGroup::Secp256r1]) .build() diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/aws_lc_rs/cipher_suite.rs b/rs/moq-webrtc/src/vendor/dimpl/crypto/aws_lc_rs/cipher_suite.rs deleted file mode 100644 index 8ac31eb79d2..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/crypto/aws_lc_rs/cipher_suite.rs +++ /dev/null @@ -1,298 +0,0 @@ -//! Cipher suite implementations using aws-lc-rs. - -use aws_lc_rs::aead::{AES_128_GCM, AES_256_GCM, CHACHA20_POLY1305, UnboundKey}; -use aws_lc_rs::aead::{Aad as AwsAad, LessSafeKey, Nonce as AwsNonce}; - -use super::super::{Cipher, SupportedDtls12CipherSuite}; -use crate::vendor::dimpl::buffer::{Buf, TmpBuf}; -use crate::vendor::dimpl::crypto::{Aad, Nonce}; -use crate::vendor::dimpl::dtls12::message::Dtls12CipherSuite; -use crate::vendor::dimpl::error::bounded_error_len; -use crate::vendor::dimpl::types::HashAlgorithm; -use crate::vendor::dimpl::{CryptoError, CryptoOperation}; - -/// AES-GCM cipher implementation using aws-lc-rs. -struct AesGcm { - key: LessSafeKey, -} - -impl std::fmt::Debug for AesGcm { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("AesGcm").finish_non_exhaustive() - } -} - -impl AesGcm { - fn new(key: &[u8]) -> Result { - let algorithm = match key.len() { - 16 => &AES_128_GCM, - 32 => &AES_256_GCM, - _ => { - return Err(CryptoError::InvalidAesGcmKeySize { - actual: bounded_error_len(key.len()), - }); - } - }; - - let unbound_key = - UnboundKey::new(algorithm, key).map_err(|_| CryptoError::OperationFailed(CryptoOperation::CreateCipher))?; - - Ok(AesGcm { - key: LessSafeKey::new(unbound_key), - }) - } -} - -impl Cipher for AesGcm { - fn encrypt(&mut self, plaintext: &mut Buf, aad: Aad, nonce: Nonce) -> Result<(), CryptoError> { - let aws_nonce = AwsNonce::try_assume_unique_for_key(&nonce).map_err(|_| CryptoError::InvalidNonce)?; - - let aws_aad = AwsAad::from(&aad[..]); - - self.key - .seal_in_place_append_tag(aws_nonce, aws_aad, plaintext) - .map_err(|_| CryptoError::OperationFailed(CryptoOperation::Encrypt))?; - - Ok(()) - } - - fn decrypt(&mut self, ciphertext: &mut TmpBuf, aad: Aad, nonce: Nonce) -> Result<(), CryptoError> { - if ciphertext.len() < 16 { - return Err(CryptoError::CiphertextTooShort { - minimum: 16, - actual: ciphertext.len() as u8, - }); - } - - let aws_nonce = AwsNonce::try_assume_unique_for_key(&nonce).map_err(|_| CryptoError::InvalidNonce)?; - - let aws_aad = AwsAad::from(&aad[..]); - - let plaintext = self - .key - .open_in_place(aws_nonce, aws_aad, ciphertext.as_mut()) - .map_err(|_| CryptoError::OperationFailed(CryptoOperation::Decrypt))?; - - let plaintext_len = plaintext.len(); - ciphertext.truncate(plaintext_len); - - Ok(()) - } -} - -/// ChaCha20-Poly1305 cipher implementation using aws-lc-rs. -struct ChaCha20Poly1305Cipher { - key: LessSafeKey, -} - -impl std::fmt::Debug for ChaCha20Poly1305Cipher { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("ChaCha20Poly1305Cipher").finish_non_exhaustive() - } -} - -impl ChaCha20Poly1305Cipher { - fn new(key: &[u8]) -> Result { - // The UnboundKey::new call also validates length, but doesnt give us - // a reasonable error message. This makes it equivalent to RustCrypto - if key.len() != 32 { - return Err(CryptoError::InvalidChacha20Poly1305KeySize { - actual: bounded_error_len(key.len()), - }); - } - let unbound_key = UnboundKey::new(&CHACHA20_POLY1305, key) - .map_err(|_| CryptoError::OperationFailed(CryptoOperation::CreateCipher))?; - - Ok(ChaCha20Poly1305Cipher { - key: LessSafeKey::new(unbound_key), - }) - } -} - -impl Cipher for ChaCha20Poly1305Cipher { - fn encrypt(&mut self, plaintext: &mut Buf, aad: Aad, nonce: Nonce) -> Result<(), CryptoError> { - let aws_nonce = AwsNonce::try_assume_unique_for_key(&nonce).map_err(|_| CryptoError::InvalidNonce)?; - - let aws_aad = AwsAad::from(&aad[..]); - - self.key - .seal_in_place_append_tag(aws_nonce, aws_aad, plaintext) - .map_err(|_| CryptoError::OperationFailed(CryptoOperation::Encrypt))?; - - Ok(()) - } - - fn decrypt(&mut self, ciphertext: &mut TmpBuf, aad: Aad, nonce: Nonce) -> Result<(), CryptoError> { - if ciphertext.len() < 16 { - return Err(CryptoError::CiphertextTooShort { - minimum: 16, - actual: ciphertext.len() as u8, - }); - } - - let aws_nonce = AwsNonce::try_assume_unique_for_key(&nonce).map_err(|_| CryptoError::InvalidNonce)?; - - let aws_aad = AwsAad::from(&aad[..]); - - let plaintext = self - .key - .open_in_place(aws_nonce, aws_aad, ciphertext.as_mut()) - .map_err(|_| CryptoError::OperationFailed(CryptoOperation::Decrypt))?; - - let plaintext_len = plaintext.len(); - ciphertext.truncate(plaintext_len); - - Ok(()) - } -} - -/// TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 cipher suite. -#[derive(Debug)] -struct Aes128GcmSha256; - -impl SupportedDtls12CipherSuite for Aes128GcmSha256 { - fn suite(&self) -> Dtls12CipherSuite { - Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256 - } - - fn hash_algorithm(&self) -> HashAlgorithm { - HashAlgorithm::SHA256 - } - - fn key_lengths(&self) -> (usize, usize, usize) { - (0, 16, 4) // (mac_key_len, enc_key_len, fixed_iv_len) - } - - fn explicit_nonce_len(&self) -> usize { - 8 - } - - fn tag_len(&self) -> usize { - 16 - } - - fn create_cipher(&self, key: &[u8]) -> Result, CryptoError> { - Ok(Box::new(AesGcm::new(key)?)) - } -} - -/// TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 cipher suite. -#[derive(Debug)] -struct Aes256GcmSha384; - -impl SupportedDtls12CipherSuite for Aes256GcmSha384 { - fn suite(&self) -> Dtls12CipherSuite { - Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384 - } - - fn hash_algorithm(&self) -> HashAlgorithm { - HashAlgorithm::SHA384 - } - - fn key_lengths(&self) -> (usize, usize, usize) { - (0, 32, 4) // (mac_key_len, enc_key_len, fixed_iv_len) - } - - fn explicit_nonce_len(&self) -> usize { - 8 - } - - fn tag_len(&self) -> usize { - 16 - } - - fn create_cipher(&self, key: &[u8]) -> Result, CryptoError> { - Ok(Box::new(AesGcm::new(key)?)) - } -} - -/// TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 cipher suite. -#[derive(Debug)] -struct ChaCha20Poly1305Sha256; - -impl SupportedDtls12CipherSuite for ChaCha20Poly1305Sha256 { - fn suite(&self) -> Dtls12CipherSuite { - Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256 - } - - fn hash_algorithm(&self) -> HashAlgorithm { - HashAlgorithm::SHA256 - } - - fn key_lengths(&self) -> (usize, usize, usize) { - (0, 32, 12) // (mac_key_len, enc_key_len, fixed_iv_len) - } - - fn explicit_nonce_len(&self) -> usize { - 0 - } - - fn tag_len(&self) -> usize { - 16 - } - - fn create_cipher(&self, key: &[u8]) -> Result, CryptoError> { - Ok(Box::new(ChaCha20Poly1305Cipher::new(key)?)) - } -} - -/// TLS_PSK_WITH_AES_128_CCM_8 cipher suite. -#[derive(Debug)] -struct PskAes128Ccm8; - -impl SupportedDtls12CipherSuite for PskAes128Ccm8 { - fn suite(&self) -> Dtls12CipherSuite { - Dtls12CipherSuite::PSK_AES128_CCM_8 - } - - fn hash_algorithm(&self) -> HashAlgorithm { - HashAlgorithm::SHA256 - } - - fn key_lengths(&self) -> (usize, usize, usize) { - (0, 16, 4) // (mac_key_len, enc_key_len, fixed_iv_len) - } - - fn explicit_nonce_len(&self) -> usize { - 8 - } - - fn tag_len(&self) -> usize { - 8 - } - - fn create_cipher(&self, key: &[u8]) -> Result, CryptoError> { - Ok(Box::new(crate::vendor::dimpl::crypto::ccm_cipher::AesCcm8Cipher::new( - key, - )?)) - } -} - -/// Static instances of supported DTLS 1.2 cipher suites. -static AES_128_GCM_SHA256: Aes128GcmSha256 = Aes128GcmSha256; -static AES_256_GCM_SHA384: Aes256GcmSha384 = Aes256GcmSha384; -static CHACHA20_POLY1305_SHA256: ChaCha20Poly1305Sha256 = ChaCha20Poly1305Sha256; -static PSK_AES_128_CCM_8: PskAes128Ccm8 = PskAes128Ccm8; - -/// All supported DTLS 1.2 cipher suites. -pub(super) static ALL_CIPHER_SUITES: &[&dyn SupportedDtls12CipherSuite] = &[ - &AES_128_GCM_SHA256, - &AES_256_GCM_SHA384, - &CHACHA20_POLY1305_SHA256, - &PSK_AES_128_CCM_8, -]; - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn chacha20_poly1305_key_len_validation() { - // incorrect length (should be 32) - let result = ChaCha20Poly1305Cipher::new(&[0, 1, 2, 3, 4, 5]); - assert_eq!( - CryptoError::InvalidChacha20Poly1305KeySize { actual: 6 }, - result.unwrap_err() - ); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/aws_lc_rs/hash.rs b/rs/moq-webrtc/src/vendor/dimpl/crypto/aws_lc_rs/hash.rs deleted file mode 100644 index 4d994402e6b..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/crypto/aws_lc_rs/hash.rs +++ /dev/null @@ -1,48 +0,0 @@ -//! Hash implementations using aws-lc-rs. - -use aws_lc_rs::digest::{Context, SHA256, SHA384}; - -use super::super::{HashContext, HashProvider}; -use crate::vendor::dimpl::buffer::Buf; -use crate::vendor::dimpl::types::HashAlgorithm; - -/// Hash context implementation using aws-lc-rs. -struct AwsLcHashContext { - context: Context, -} - -impl std::fmt::Debug for AwsLcHashContext { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("AwsLcHashContext").finish_non_exhaustive() - } -} - -impl HashContext for AwsLcHashContext { - fn update(&mut self, data: &[u8]) { - self.context.update(data); - } - - fn clone_and_finalize(&self, out: &mut Buf) { - let digest = self.context.clone().finish(); - out.clear(); - out.extend_from_slice(digest.as_ref()); - } -} - -/// Hash provider implementation. -#[derive(Debug)] -pub(super) struct AwsLcHashProvider; - -impl HashProvider for AwsLcHashProvider { - fn create_hash(&self, algorithm: HashAlgorithm) -> Box { - let context = match algorithm { - HashAlgorithm::SHA256 => Context::new(&SHA256), - HashAlgorithm::SHA384 => Context::new(&SHA384), - _ => panic!("Unsupported hash algorithm: {:?}", algorithm), - }; - Box::new(AwsLcHashContext { context }) - } -} - -/// Static instance of the hash provider. -pub(super) static HASH_PROVIDER: AwsLcHashProvider = AwsLcHashProvider; diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/aws_lc_rs/hmac.rs b/rs/moq-webrtc/src/vendor/dimpl/crypto/aws_lc_rs/hmac.rs deleted file mode 100644 index ce7c26e4dfc..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/crypto/aws_lc_rs/hmac.rs +++ /dev/null @@ -1,34 +0,0 @@ -//! HMAC implementation using aws-lc-rs. - -use aws_lc_rs::hmac; - -use super::super::HmacProvider; -use crate::vendor::dimpl::CryptoError; -use crate::vendor::dimpl::types::HashAlgorithm; - -/// Get HMAC algorithm from hash algorithm. -fn hmac_algorithm(hash: HashAlgorithm) -> Result { - match hash { - HashAlgorithm::SHA256 => Ok(hmac::HMAC_SHA256), - HashAlgorithm::SHA384 => Ok(hmac::HMAC_SHA384), - _ => Err(CryptoError::UnsupportedHmacHash(hash)), - } -} - -/// HMAC provider implementation. -#[derive(Debug)] -pub(crate) struct AwsLcHmacProvider; - -impl HmacProvider for AwsLcHmacProvider { - fn hmac(&self, hash: HashAlgorithm, key: &[u8], data: &[u8], out: &mut [u8]) -> Result { - let algorithm = hmac_algorithm(hash)?; - let hmac_key = hmac::Key::new(algorithm, key); - let tag = hmac::sign(&hmac_key, data); - let len = tag.as_ref().len(); - out[..len].copy_from_slice(tag.as_ref()); - Ok(len) - } -} - -/// Static instance of the HMAC provider. -pub(crate) static HMAC_PROVIDER: AwsLcHmacProvider = AwsLcHmacProvider; diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/aws_lc_rs/kx_group.rs b/rs/moq-webrtc/src/vendor/dimpl/crypto/aws_lc_rs/kx_group.rs deleted file mode 100644 index 0748741e855..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/crypto/aws_lc_rs/kx_group.rs +++ /dev/null @@ -1,151 +0,0 @@ -//! Key exchange group implementations using aws-lc-rs. - -use aws_lc_rs::agreement::{ECDH_P256, ECDH_P384, UnparsedPublicKey, X25519}; -use aws_lc_rs::agreement::{EphemeralPrivateKey, agree_ephemeral}; - -use super::super::{ActiveKeyExchange, SupportedKxGroup}; -use crate::vendor::dimpl::buffer::Buf; -use crate::vendor::dimpl::types::NamedGroup; -use crate::vendor::dimpl::{CryptoError, CryptoOperation}; - -/// ECDHE key exchange implementation. -struct EcdhKeyExchange { - group: NamedGroup, - private_key: EphemeralPrivateKey, - public_key: Buf, -} - -impl std::fmt::Debug for EcdhKeyExchange { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("EcdhKeyExchange") - .field("group", &self.group) - .field("public_key_len", &self.public_key.len()) - .finish_non_exhaustive() - } -} - -impl EcdhKeyExchange { - fn new(group: NamedGroup, mut buf: Buf) -> Result { - let algorithm = match group { - NamedGroup::X25519 => &X25519, - NamedGroup::Secp256r1 => &ECDH_P256, - NamedGroup::Secp384r1 => &ECDH_P384, - _ => return Err(CryptoError::UnsupportedKeyExchangeGroup(group)), - }; - - let rng = aws_lc_rs::rand::SystemRandom::new(); - let private_key = EphemeralPrivateKey::generate(algorithm, &rng) - .map_err(|_| CryptoError::OperationFailed(CryptoOperation::GenerateEphemeralKey))?; - - let pk = private_key - .compute_public_key() - .map_err(|_| CryptoError::OperationFailed(CryptoOperation::ComputePublicKey))?; - - buf.clear(); - buf.extend_from_slice(pk.as_ref()); - - Ok(EcdhKeyExchange { - group, - private_key, - public_key: buf, - }) - } - - fn algorithm(&self) -> &'static aws_lc_rs::agreement::Algorithm { - match self.group { - NamedGroup::X25519 => &X25519, - NamedGroup::Secp256r1 => &ECDH_P256, - NamedGroup::Secp384r1 => &ECDH_P384, - _ => unreachable!("Unsupported group"), - } - } -} - -impl ActiveKeyExchange for EcdhKeyExchange { - fn pub_key(&self) -> &[u8] { - &self.public_key - } - - fn complete(self: Box, peer_pub: &[u8], out: &mut Buf) -> Result<(), CryptoError> { - let algorithm = self.algorithm(); - let peer_key = UnparsedPublicKey::new(algorithm, peer_pub); - - // RFC 7748 ยง6.1: agree_ephemeral rejects non-contributory shared secrets internally - agree_ephemeral(self.private_key, peer_key, "ECDH agreement failed", |secret| { - out.clear(); - out.extend_from_slice(secret); - Ok(()) - }) - .map_err(|_| CryptoError::InvalidPublicKey(self.group)) - } - - fn group(&self) -> NamedGroup { - self.group - } -} - -/// X25519 key exchange group. -#[derive(Debug)] -struct X25519Kx; - -impl SupportedKxGroup for X25519Kx { - fn name(&self) -> NamedGroup { - NamedGroup::X25519 - } - - fn start_exchange(&self, buf: Buf) -> Result, CryptoError> { - Ok(Box::new(EcdhKeyExchange::new(NamedGroup::X25519, buf)?)) - } -} - -/// P-256 (secp256r1) key exchange group. -#[derive(Debug)] -struct P256; - -impl SupportedKxGroup for P256 { - fn name(&self) -> NamedGroup { - NamedGroup::Secp256r1 - } - - fn start_exchange(&self, buf: Buf) -> Result, CryptoError> { - Ok(Box::new(EcdhKeyExchange::new(NamedGroup::Secp256r1, buf)?)) - } -} - -/// P-384 (secp384r1) key exchange group. -#[derive(Debug)] -struct P384; - -impl SupportedKxGroup for P384 { - fn name(&self) -> NamedGroup { - NamedGroup::Secp384r1 - } - - fn start_exchange(&self, buf: Buf) -> Result, CryptoError> { - Ok(Box::new(EcdhKeyExchange::new(NamedGroup::Secp384r1, buf)?)) - } -} - -/// Static instances of supported key exchange groups. -static KX_GROUP_X25519: X25519Kx = X25519Kx; -static KX_GROUP_P256: P256 = P256; -static KX_GROUP_P384: P384 = P384; - -/// All supported key exchange groups. -pub(super) static ALL_KX_GROUPS: &[&dyn SupportedKxGroup] = &[&KX_GROUP_X25519, &KX_GROUP_P256, &KX_GROUP_P384]; - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn x25519_non_contributory_peer_key_returns_invalid_public_key() { - let exchange = X25519Kx.start_exchange(Buf::new()).expect("start key exchange"); - let mut out = Buf::new(); - - assert_eq!( - exchange.complete(&[0; 32], &mut out), - Err(CryptoError::InvalidPublicKey(NamedGroup::X25519)) - ); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/aws_lc_rs/mod.rs b/rs/moq-webrtc/src/vendor/dimpl/crypto/aws_lc_rs/mod.rs deleted file mode 100644 index 0d942c997aa..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/crypto/aws_lc_rs/mod.rs +++ /dev/null @@ -1,108 +0,0 @@ -//! AWS-LC-RS cryptographic provider implementation for dimpl. -//! -//! This module provides the default cryptographic backend for dimpl using -//! [aws-lc-rs](https://github.com/aws/aws-lc-rs), Amazon's cryptographic library -//! based on AWS-LC (a fork of BoringSSL). -//! -//! # Usage -//! -//! The default provider is used automatically when no custom provider is specified: -//! -//! ```ignore -//! # #[cfg(all())] -//! # fn main() { -//! use std::sync::Arc; -//! use std::time::Instant; -//! use crate::vendor::dimpl::{Config, Dtls, certificate}; -//! -//! let cert = certificate::generate_self_signed_certificate().unwrap(); -//! // Implicitly uses aws-lc-rs default provider -//! let config = Arc::new(Config::default()); -//! let dtls = Dtls::new_12(config, cert, Instant::now()); -//! # } -//! # #[cfg(not(all()))] -//! # fn main() {} -//! ``` -//! -//! Or explicitly: -//! -//! ```ignore -//! # #[cfg(all())] -//! # fn main() { -//! use std::sync::Arc; -//! use std::time::Instant; -//! use crate::vendor::dimpl::{Config, Dtls, certificate}; -//! use crate::vendor::dimpl::crypto::aws_lc_rs; -//! -//! let cert = certificate::generate_self_signed_certificate().unwrap(); -//! let config = Arc::new( -//! Config::builder() -//! .with_crypto_provider(aws_lc_rs::default_provider()) -//! .build() -//! .unwrap() -//! ); -//! let dtls = Dtls::new_12(config, cert, Instant::now()); -//! # } -//! # #[cfg(not(all()))] -//! # fn main() {} -//! ``` - -mod cipher_suite; -mod hash; -pub(crate) mod hmac; -mod kx_group; -mod random; -mod sign; - -use super::CryptoProvider; - -/// Get the default aws-lc-rs based crypto provider. -/// -/// This provider implements all cryptographic operations required for DTLS 1.2 -/// using the aws-lc-rs library (AWS's cryptographic library based on BoringSSL/AWS-LC). -/// -/// # Supported Cipher Suites -/// -/// - `TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256` (0xC02B) -/// - `TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384` (0xC02C) -/// - `TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256` (0xCCA9) -/// -/// # Supported Key Exchange Groups -/// -/// - `x25519` (X25519 / Curve25519) -/// - `secp256r1` (P-256, NIST Curve) -/// - `secp384r1` (P-384, NIST Curve) -/// -/// # Supported Signature Algorithms -/// -/// - ECDSA with P-256 and SHA-256 -/// - ECDSA with P-384 and SHA-384 -/// -/// # Supported Hash Algorithms -/// -/// - SHA-256 -/// - SHA-384 -/// -/// # Key Formats -/// -/// The key provider supports loading private keys in: -/// - PKCS#8 DER format (most common) -/// - SEC1 DER format (OpenSSL EC private key format) -/// - PEM encoded versions of the above -/// -/// # Random Number Generation -/// -/// Uses `SystemRandom` from aws-lc-rs for cryptographically secure random number generation. -pub fn default_provider() -> CryptoProvider { - CryptoProvider { - // Shared components - kx_groups: kx_group::ALL_KX_GROUPS, - signature_verification: &sign::SIGNATURE_VERIFIER, - key_provider: &sign::KEY_PROVIDER, - secure_random: &random::SECURE_RANDOM, - hash_provider: &hash::HASH_PROVIDER, - hmac_provider: &hmac::HMAC_PROVIDER, - // DTLS 1.2 components - cipher_suites: cipher_suite::ALL_CIPHER_SUITES, - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/aws_lc_rs/random.rs b/rs/moq-webrtc/src/vendor/dimpl/crypto/aws_lc_rs/random.rs deleted file mode 100644 index 61fef99e8c0..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/crypto/aws_lc_rs/random.rs +++ /dev/null @@ -1,20 +0,0 @@ -//! Secure random number generation using aws-lc-rs. - -use super::super::SecureRandom; -use crate::vendor::dimpl::{CryptoError, CryptoOperation}; - -/// Secure random number generator implementation. -#[derive(Debug)] -pub(super) struct AwsLcSecureRandom; - -impl SecureRandom for AwsLcSecureRandom { - fn fill(&self, buf: &mut [u8]) -> Result<(), CryptoError> { - use aws_lc_rs::rand::SecureRandom as _; - let rng = aws_lc_rs::rand::SystemRandom::new(); - rng.fill(buf) - .map_err(|_| CryptoError::OperationFailed(CryptoOperation::FillRandom)) - } -} - -/// Static instance of the secure random generator. -pub(super) static SECURE_RANDOM: AwsLcSecureRandom = AwsLcSecureRandom; diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/aws_lc_rs/sign.rs b/rs/moq-webrtc/src/vendor/dimpl/crypto/aws_lc_rs/sign.rs deleted file mode 100644 index 45a0ff43cfc..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/crypto/aws_lc_rs/sign.rs +++ /dev/null @@ -1,285 +0,0 @@ -//! Signing and key loading implementations using aws-lc-rs. - -use std::str; - -use aws_lc_rs::signature::ECDSA_P384_SHA384_ASN1_SIGNING; -use aws_lc_rs::signature::{ECDSA_P256_SHA256_ASN1, ECDSA_P256_SHA384_ASN1}; -use aws_lc_rs::signature::{ECDSA_P256_SHA256_ASN1_SIGNING, UnparsedPublicKey}; -use aws_lc_rs::signature::{ECDSA_P384_SHA256_ASN1, ECDSA_P384_SHA384_ASN1}; -use aws_lc_rs::signature::{EcdsaKeyPair, EcdsaSigningAlgorithm, EcdsaVerificationAlgorithm}; -use der::{Decode, Encode}; -use spki::ObjectIdentifier; -use x509_cert::Certificate as X509Certificate; - -use super::super::{KeyProvider, SignatureVerifier, SigningKey, check_verify_scheme}; -use super::super::{OID_P256, OID_P384}; -use crate::vendor::dimpl::buffer::Buf; -use crate::vendor::dimpl::types::{HashAlgorithm, NamedGroup, SignatureAlgorithm}; -use crate::vendor::dimpl::{CryptoError, CryptoOperation}; - -/// ECDSA signing key implementation. -struct EcdsaSigningKey { - key_pair: EcdsaKeyPair, - signing_algorithm: &'static EcdsaSigningAlgorithm, -} - -impl std::fmt::Debug for EcdsaSigningKey { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("EcdsaSigningKey") - .field("signing_algorithm", &self.signing_algorithm) - .finish() - } -} - -impl SigningKey for EcdsaSigningKey { - fn sign(&mut self, data: &[u8], hash_alg: HashAlgorithm, buf: &mut Buf) -> Result<(), CryptoError> { - let key_hash = self.hash_algorithm(); - if hash_alg != key_hash { - return Err(CryptoError::SigningKeyHashMismatch { - key_hash, - requested: hash_alg, - }); - } - let rng = aws_lc_rs::rand::SystemRandom::new(); - let signature = self - .key_pair - .sign(&rng, data) - .map_err(|_| CryptoError::OperationFailed(CryptoOperation::Sign))?; - buf.clear(); - buf.extend_from_slice(signature.as_ref()); - Ok(()) - } - - fn algorithm(&self) -> SignatureAlgorithm { - SignatureAlgorithm::ECDSA - } - - fn hash_algorithm(&self) -> HashAlgorithm { - if self.signing_algorithm == &ECDSA_P256_SHA256_ASN1_SIGNING { - HashAlgorithm::SHA256 - } else if self.signing_algorithm == &ECDSA_P384_SHA384_ASN1_SIGNING { - HashAlgorithm::SHA384 - } else { - panic!("Unsupported signing algorithm") - } - } - - fn supported_hash_algorithms(&self) -> &[HashAlgorithm] { - // aws-lc-rs locks the hash at key-load time; only one is supported. - if self.signing_algorithm == &ECDSA_P256_SHA256_ASN1_SIGNING { - &[HashAlgorithm::SHA256] - } else if self.signing_algorithm == &ECDSA_P384_SHA384_ASN1_SIGNING { - &[HashAlgorithm::SHA384] - } else { - panic!("Unsupported signing algorithm") - } - } -} - -/// Key provider implementation. -#[derive(Debug)] -pub(super) struct AwsLcKeyProvider; - -impl KeyProvider for AwsLcKeyProvider { - fn load_private_key(&self, key_der: &[u8]) -> Result, CryptoError> { - // Try PKCS#8 DER format first (most common) - if let Ok(key_pair) = EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING, key_der) { - return Ok(Box::new(EcdsaSigningKey { - key_pair, - signing_algorithm: &ECDSA_P256_SHA256_ASN1_SIGNING, - })); - } - if let Ok(key_pair) = EcdsaKeyPair::from_pkcs8(&ECDSA_P384_SHA384_ASN1_SIGNING, key_der) { - return Ok(Box::new(EcdsaSigningKey { - key_pair, - signing_algorithm: &ECDSA_P384_SHA384_ASN1_SIGNING, - })); - } - - // Try parsing as SEC1 DER format (OpenSSL EC private key format) - if let Ok(ec_key) = sec1::EcPrivateKey::try_from(key_der) { - let private_key_len = ec_key.private_key.len(); - - let curve_oid = if let Some(params) = &ec_key.parameters { - match params { - sec1::EcParameters::NamedCurve(oid) => Some(*oid), - } - } else if private_key_len == 32 { - Some(ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7")) // P-256 - } else if private_key_len == 48 { - Some(ObjectIdentifier::new_unwrap("1.3.132.0.34")) // P-384 - } else { - None - }; - - if let Some(curve_oid) = curve_oid { - let ec_alg_oid = ObjectIdentifier::new_unwrap("1.2.840.10045.2.1"); - let curve_params_der = curve_oid - .to_der() - .map_err(|_| CryptoError::OperationFailed(CryptoOperation::EncodeKey))?; - let curve_params_any = der::asn1::AnyRef::try_from(curve_params_der.as_slice()) - .map_err(|_| CryptoError::OperationFailed(CryptoOperation::EncodeKey))?; - - let algorithm = spki::AlgorithmIdentifierRef { - oid: ec_alg_oid, - parameters: Some(curve_params_any), - }; - - let private_key = der::asn1::OctetStringRef::new(key_der) - .map_err(|_| CryptoError::OperationFailed(CryptoOperation::EncodeKey))?; - let pkcs8 = pkcs8::PrivateKeyInfoRef { - algorithm, - private_key, - public_key: None, - }; - - let pkcs8_der = pkcs8 - .to_der() - .map_err(|_| CryptoError::OperationFailed(CryptoOperation::EncodeKey))?; - - let p256_curve = ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7"); - if curve_oid == p256_curve - && let Ok(key_pair) = EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING, &pkcs8_der) - { - return Ok(Box::new(EcdsaSigningKey { - key_pair, - signing_algorithm: &ECDSA_P256_SHA256_ASN1_SIGNING, - })); - } - - let p384_curve = ObjectIdentifier::new_unwrap("1.3.132.0.34"); - if curve_oid == p384_curve - && let Ok(key_pair) = EcdsaKeyPair::from_pkcs8(&ECDSA_P384_SHA384_ASN1_SIGNING, &pkcs8_der) - { - return Ok(Box::new(EcdsaSigningKey { - key_pair, - signing_algorithm: &ECDSA_P384_SHA384_ASN1_SIGNING, - })); - } - } - } - - // Check if it's a PEM encoded key - if let Ok(pem_str) = str::from_utf8(key_der) - && pem_str.contains("-----BEGIN") - && let Ok((_label, doc)) = pkcs8::Document::from_pem(pem_str) - { - return self.load_private_key(doc.as_bytes()); - } - - Err(CryptoError::InvalidPrivateKey) - } -} - -/// Signature verifier implementation. -#[derive(Debug)] -pub(super) struct AwsLcSignatureVerifier; - -impl SignatureVerifier for AwsLcSignatureVerifier { - fn verify_signature( - &self, - cert_der: &[u8], - data: &[u8], - signature: &[u8], - hash_alg: HashAlgorithm, - sig_alg: SignatureAlgorithm, - ) -> Result<(), CryptoError> { - if sig_alg != SignatureAlgorithm::ECDSA { - return Err(CryptoError::UnsupportedSignatureAlgorithm(sig_alg)); - } - - let cert = X509Certificate::from_der(cert_der).map_err(|_| CryptoError::CertificateParseFailed)?; - let spki = cert.tbs_certificate().subject_public_key_info(); - - const OID_EC_PUBLIC_KEY: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.2.1"); - - if spki.algorithm.oid != OID_EC_PUBLIC_KEY { - return Err(CryptoError::UnsupportedPublicKeyAlgorithm); - } - - let pubkey_bytes = spki - .subject_public_key - .as_bytes() - .ok_or(CryptoError::InvalidSubjectPublicKey)?; - - let curve_oid: ObjectIdentifier = spki - .algorithm - .parameters - .as_ref() - .ok_or(CryptoError::MissingEcCurveParameter)? - .decode_as() - .map_err(|_| CryptoError::InvalidEcCurveParameter)?; - - let group = match curve_oid { - OID_P256 => NamedGroup::Secp256r1, - OID_P384 => NamedGroup::Secp384r1, - _ => return Err(CryptoError::UnsupportedEcCurve), - }; - - check_verify_scheme(sig_alg, hash_alg, group)?; - - let algorithm: &EcdsaVerificationAlgorithm = match (group, hash_alg) { - (NamedGroup::Secp256r1, HashAlgorithm::SHA256) => &ECDSA_P256_SHA256_ASN1, - (NamedGroup::Secp256r1, HashAlgorithm::SHA384) => &ECDSA_P256_SHA384_ASN1, - (NamedGroup::Secp384r1, HashAlgorithm::SHA256) => &ECDSA_P384_SHA256_ASN1, - (NamedGroup::Secp384r1, HashAlgorithm::SHA384) => &ECDSA_P384_SHA384_ASN1, - // unreachable: check_verify_scheme already validated - _ => unreachable!(), - }; - - let public_key = UnparsedPublicKey::new(algorithm, pubkey_bytes); - public_key - .verify(data, signature) - .map_err(|_| CryptoError::SignatureVerificationFailed { - signature: sig_alg, - hash: hash_alg, - group, - }) - } -} - -/// Static instance of the key provider. -pub(super) static KEY_PROVIDER: AwsLcKeyProvider = AwsLcKeyProvider; - -/// Static instance of the signature verifier. -pub(super) static SIGNATURE_VERIFIER: AwsLcSignatureVerifier = AwsLcSignatureVerifier; - -#[cfg(test)] -mod tests { - use super::*; - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - #[test] - fn invalid_signature_returns_structured_verification_error() { - let cert = generate_self_signed_certificate().expect("generate cert"); - let mut key = KEY_PROVIDER - .load_private_key(&cert.private_key) - .expect("load private key"); - let data = b"signed data"; - let mut signature = Buf::new(); - key.sign(data, HashAlgorithm::SHA256, &mut signature) - .expect("sign data"); - - let last = signature.len() - 1; - signature[last] ^= 0x01; - - let err = SIGNATURE_VERIFIER - .verify_signature( - &cert.certificate, - data, - &signature, - HashAlgorithm::SHA256, - SignatureAlgorithm::ECDSA, - ) - .expect_err("corrupt signature should fail"); - - assert_eq!( - err, - CryptoError::SignatureVerificationFailed { - signature: SignatureAlgorithm::ECDSA, - hash: HashAlgorithm::SHA256, - group: NamedGroup::Secp256r1, - } - ); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/ccm_cipher.rs b/rs/moq-webrtc/src/vendor/dimpl/crypto/ccm_cipher.rs index be19a18c1a0..026dce094fc 100644 --- a/rs/moq-webrtc/src/vendor/dimpl/crypto/ccm_cipher.rs +++ b/rs/moq-webrtc/src/vendor/dimpl/crypto/ccm_cipher.rs @@ -1,7 +1,6 @@ //! AES-128-CCM-8 cipher implementation using the RustCrypto `ccm` crate. //! -//! Used by the aws-lc-rs backend since aws-lc-rs does not expose CCM in its -//! high-level API. +//! Backs the rind provider's PSK suite, since rind has no AES-CCM. use ccm::aead::AeadInOut; use ccm::aead::KeyInit; diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/mod.rs b/rs/moq-webrtc/src/vendor/dimpl/crypto/mod.rs index 0fb5e2e3f4f..e8bf265ab0e 100644 --- a/rs/moq-webrtc/src/vendor/dimpl/crypto/mod.rs +++ b/rs/moq-webrtc/src/vendor/dimpl/crypto/mod.rs @@ -6,7 +6,7 @@ use std::ops::Deref; mod keying; // Provider traits and implementations -pub mod aws_lc_rs; +pub mod rind; pub(crate) mod ccm_cipher; diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/prf_hkdf.rs b/rs/moq-webrtc/src/vendor/dimpl/crypto/prf_hkdf.rs index 0baa772ac82..75d7033d7bf 100644 --- a/rs/moq-webrtc/src/vendor/dimpl/crypto/prf_hkdf.rs +++ b/rs/moq-webrtc/src/vendor/dimpl/crypto/prf_hkdf.rs @@ -126,7 +126,7 @@ mod tests { /// We need a concrete HmacProvider for tests. fn hmac_provider() -> &'static dyn HmacProvider { - &crate::vendor::dimpl::crypto::aws_lc_rs::hmac::HMAC_PROVIDER + &crate::vendor::dimpl::crypto::rind::HMAC } // ======================================================================== diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/provider.rs b/rs/moq-webrtc/src/vendor/dimpl/crypto/provider.rs index acec6dccf4d..f3c5b12cddb 100644 --- a/rs/moq-webrtc/src/vendor/dimpl/crypto/provider.rs +++ b/rs/moq-webrtc/src/vendor/dimpl/crypto/provider.rs @@ -31,16 +31,16 @@ //! use std::sync::Arc; //! use std::time::Instant; //! use crate::vendor::dimpl::{Config, Dtls, certificate}; -//! use crate::vendor::dimpl::crypto::aws_lc_rs; +//! use crate::vendor::dimpl::crypto::rind; //! //! let cert = certificate::generate_self_signed_certificate().unwrap(); -//! // Use the default aws-lc-rs provider (implicit) +//! // Use the default rind provider (implicit) //! let config = Arc::new(Config::default()); //! //! // Or explicitly set the provider //! let config = Arc::new( //! Config::builder() -//! .with_crypto_provider(aws_lc_rs::default_provider()) +//! .with_crypto_provider(rind::default_provider().unwrap()) //! .build() //! .unwrap() //! ); @@ -213,7 +213,7 @@ pub trait SigningKey: CryptoSafe { /// /// Used during negotiation to intersect with the peer's offered /// algorithms. Backends that lock the hash at key-load time (e.g. - /// aws-lc-rs) return only the locked hash; backends that support + /// rind) return only the locked hash; backends that support /// arbitrary prehash signing (e.g. RustCrypto) may return several. fn supported_hash_algorithms(&self) -> &[HashAlgorithm]; } @@ -370,7 +370,7 @@ pub trait HmacProvider: CryptoSafe { /// /// This struct holds references to all cryptographic components needed /// for DTLS. Users can provide custom implementations of each component -/// to replace the default aws-lc-rs-based provider. +/// to replace the default rind-based provider. /// /// # Components /// @@ -388,10 +388,10 @@ pub trait HmacProvider: CryptoSafe { /// ```ignore /// # #[cfg(all())] /// # fn main() { -/// use crate::vendor::dimpl::crypto::{CryptoProvider, aws_lc_rs}; +/// use crate::vendor::dimpl::crypto::{CryptoProvider, rind}; /// /// // Use the default provider -/// let provider = aws_lc_rs::default_provider(); +/// let provider = rind::default_provider().unwrap(); /// /// // Or build a custom one (using defaults for demonstration) /// let custom_provider = CryptoProvider { @@ -466,10 +466,10 @@ impl CryptoProvider { /// ```ignore /// # #[cfg(all())] /// # fn main() { - /// use crate::vendor::dimpl::crypto::{CryptoProvider, aws_lc_rs}; + /// use crate::vendor::dimpl::crypto::{CryptoProvider, rind}; /// /// // Install a default provider (can only be called once per process) - /// CryptoProvider::install_default(aws_lc_rs::default_provider()); + /// CryptoProvider::install_default(rind::default_provider().unwrap()); /// # } /// # #[cfg(not(all()))] /// # fn main() {} diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/rind/digest.rs b/rs/moq-webrtc/src/vendor/dimpl/crypto/rind/digest.rs new file mode 100644 index 00000000000..c0108529e11 --- /dev/null +++ b/rs/moq-webrtc/src/vendor/dimpl/crypto/rind/digest.rs @@ -0,0 +1,74 @@ +use std::fmt; + +use crate::vendor::dimpl::crypto::{Buf, HashAlgorithm, HashProvider, HmacProvider, SecureRandom}; +use crate::vendor::dimpl::{CryptoError, CryptoOperation}; +use rind::{digest, hmac}; + +#[derive(Debug)] +pub(crate) struct Hasher; + +pub(crate) static HASH: Hasher = Hasher; + +impl HashProvider for Hasher { + fn create_hash(&self, algorithm: HashAlgorithm) -> Box { + // dimpl only asks for the hash of a suite this provider offers. + let algorithm = match algorithm { + HashAlgorithm::SHA256 => &digest::SHA256, + HashAlgorithm::SHA384 => &digest::SHA384, + _ => panic!("no suite uses {algorithm:?}"), + }; + Box::new(Running(digest::Context::new(algorithm))) + } +} + +struct Running(digest::Context); + +impl fmt::Debug for Running { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Running").finish_non_exhaustive() + } +} + +impl crate::vendor::dimpl::crypto::HashContext for Running { + fn update(&mut self, data: &[u8]) { + self.0.update(data); + } + + fn clone_and_finalize(&self, out: &mut Buf) { + let digest = self.0.clone().finish(); + out.clear(); + out.extend_from_slice(digest.as_ref()); + } +} + +#[derive(Debug)] +pub(crate) struct Mac; + +pub(crate) static HMAC: Mac = Mac; + +impl HmacProvider for Mac { + fn hmac(&self, hash: HashAlgorithm, key: &[u8], data: &[u8], out: &mut [u8]) -> Result { + let algorithm = match hash { + HashAlgorithm::SHA256 => &hmac::HMAC_SHA256, + HashAlgorithm::SHA384 => &hmac::HMAC_SHA384, + _ => return Err(CryptoError::UnsupportedHmacHash(hash)), + }; + let tag = hmac::sign(&hmac::Key::new(algorithm, key), data); + let tag = tag.as_ref(); + out.get_mut(..tag.len()) + .ok_or(CryptoError::OperationFailed(CryptoOperation::ComputeHmac))? + .copy_from_slice(tag); + Ok(tag.len()) + } +} + +#[derive(Debug)] +pub(crate) struct Random; + +pub(crate) static RANDOM: Random = Random; + +impl SecureRandom for Random { + fn fill(&self, buf: &mut [u8]) -> Result<(), CryptoError> { + rind::rand::fill(buf).map_err(|_| CryptoError::OperationFailed(CryptoOperation::FillRandom)) + } +} diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/rind/kx.rs b/rs/moq-webrtc/src/vendor/dimpl/crypto/rind/kx.rs new file mode 100644 index 00000000000..0f0f1966100 --- /dev/null +++ b/rs/moq-webrtc/src/vendor/dimpl/crypto/rind/kx.rs @@ -0,0 +1,81 @@ +use std::fmt; + +use crate::vendor::dimpl::crypto::{ActiveKeyExchange, Buf, NamedGroup, SupportedKxGroup}; +use crate::vendor::dimpl::{CryptoError, CryptoOperation}; +use rind::agreement::{self, PrivateKey}; + +#[derive(Debug)] +struct Group { + name: NamedGroup, + algorithm: &'static agreement::Algorithm, +} + +/// Key exchange groups, in order of preference. +pub(crate) static ALL: &[&dyn SupportedKxGroup] = &[ + &Group { + name: NamedGroup::X25519, + algorithm: &agreement::X25519, + }, + &Group { + name: NamedGroup::Secp256r1, + algorithm: &agreement::ECDH_P256, + }, + &Group { + name: NamedGroup::Secp384r1, + algorithm: &agreement::ECDH_P384, + }, +]; + +impl SupportedKxGroup for Group { + fn name(&self) -> NamedGroup { + self.name + } + + fn start_exchange(&self, mut pub_key: Buf) -> Result, CryptoError> { + let key = PrivateKey::generate(self.algorithm) + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::GenerateEphemeralKey))?; + pub_key.clear(); + pub_key.extend_from_slice(key.public_key().as_ref()); + Ok(Box::new(Exchange { + group: self.name, + key, + pub_key, + })) + } +} + +struct Exchange { + group: NamedGroup, + key: PrivateKey, + pub_key: Buf, +} + +impl fmt::Debug for Exchange { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Exchange") + .field("group", &self.group()) + .finish_non_exhaustive() + } +} + +impl ActiveKeyExchange for Exchange { + fn pub_key(&self) -> &[u8] { + &self.pub_key + } + + fn complete(self: Box, peer_pub: &[u8], out: &mut Buf) -> Result<(), CryptoError> { + // Covers a malformed or off-curve point, and X25519's all-zero output + // from a low-order point (RFC 7748 section 6.1). + let secret = self + .key + .agree(peer_pub) + .map_err(|_| CryptoError::InvalidPublicKey(self.group))?; + out.clear(); + out.extend_from_slice(secret.as_ref()); + Ok(()) + } + + fn group(&self) -> NamedGroup { + self.group + } +} diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/rind/mod.rs b/rs/moq-webrtc/src/vendor/dimpl/crypto/rind/mod.rs new file mode 100644 index 00000000000..a41e2aeee86 --- /dev/null +++ b/rs/moq-webrtc/src/vendor/dimpl/crypto/rind/mod.rs @@ -0,0 +1,40 @@ +//! rind's cryptographic provider for dimpl. +//! +//! Ported from moq-dev/rind's `rind-dimpl` 0.1.12, trimmed to DTLS 1.2, with +//! dimpl's PSK AES-128-CCM-8 suite kept from the provider it replaces. + +mod digest; +mod kx; +mod sign; +mod suite; + +use super::CryptoProvider; + +#[cfg(test)] +pub(crate) use digest::HMAC; + +/// Returns a dimpl [`CryptoProvider`] backed by rind, or the CPU feature rind +/// requires that this CPU lacks. +/// +/// It negotiates DTLS 1.2 ECDHE-ECDSA with AES-128-GCM, AES-256-GCM, and +/// ChaCha20-Poly1305 over X25519, P-256, and P-384, plus PSK with +/// AES-128-CCM-8, and signs with ECDSA P-256 or P-384 keys in PKCS#8 or SEC1 +/// DER. It prefers ChaCha20-Poly1305 where rind runs AES without CPU +/// instructions. +pub fn default_provider() -> Result { + rind::cpu::check()?; + let cipher_suites = if rind::cpu::has_aes_hardware() { + suite::DTLS12 + } else { + suite::DTLS12_CHACHA20_FIRST + }; + Ok(CryptoProvider { + kx_groups: kx::ALL, + signature_verification: &sign::VERIFIER, + key_provider: &sign::KEYS, + secure_random: &digest::RANDOM, + hash_provider: &digest::HASH, + hmac_provider: &digest::HMAC, + cipher_suites, + }) +} diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/rind/sign.rs b/rs/moq-webrtc/src/vendor/dimpl/crypto/rind/sign.rs new file mode 100644 index 00000000000..3d3b28b420f --- /dev/null +++ b/rs/moq-webrtc/src/vendor/dimpl/crypto/rind/sign.rs @@ -0,0 +1,162 @@ +use std::fmt; + +use crate::vendor::dimpl::crypto::{ + Buf, HashAlgorithm, KeyProvider, NamedGroup, OID_P256, OID_P384, SignatureAlgorithm, SignatureVerifier, SigningKey, + check_verify_scheme, +}; +use crate::vendor::dimpl::{CryptoError, CryptoOperation}; +use rind::signature::{EcdsaKeyPair, EcdsaSigningAlgorithm, PublicKey, VerificationAlgorithm, sign, verify}; +use x509_cert::Certificate; +use x509_cert::der::Decode; +use x509_cert::spki::ObjectIdentifier; + +const ID_EC_PUBLIC_KEY: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.2.1"); + +/// Each curve, and the one hash its key signs with. +/// +/// A key is bound to its hash when loaded, so each curve signs with its own +/// hash only. +const CURVES: [(NamedGroup, HashAlgorithm, &EcdsaSigningAlgorithm); 2] = [ + ( + NamedGroup::Secp256r1, + HashAlgorithm::SHA256, + &sign::ECDSA_P256_SHA256_ASN1, + ), + ( + NamedGroup::Secp384r1, + HashAlgorithm::SHA384, + &sign::ECDSA_P384_SHA384_ASN1, + ), +]; + +#[derive(Debug)] +pub(crate) struct Keys; + +pub(crate) static KEYS: Keys = Keys; + +impl KeyProvider for Keys { + fn load_private_key(&self, der: &[u8]) -> Result, CryptoError> { + type Load = fn(&'static EcdsaSigningAlgorithm, &[u8]) -> Result; + let load = |load: Load| { + CURVES.into_iter().find_map(|(group, hash, algorithm)| { + let key = load(algorithm, der).ok()?; + Some(Box::new(Key { key, group, hash }) as Box) + }) + }; + load(EcdsaKeyPair::from_pkcs8) + .or_else(|| load(EcdsaKeyPair::from_sec1)) + .ok_or(CryptoError::InvalidPrivateKey) + } +} + +struct Key { + key: EcdsaKeyPair, + group: NamedGroup, + hash: HashAlgorithm, +} + +impl fmt::Debug for Key { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Key") + .field("group", &self.group) + .field("hash", &self.hash) + .finish_non_exhaustive() + } +} + +impl SigningKey for Key { + fn sign(&mut self, data: &[u8], hash: HashAlgorithm, out: &mut Buf) -> Result<(), CryptoError> { + if hash != self.hash { + return Err(CryptoError::SigningKeyHashMismatch { + key_hash: self.hash, + requested: hash, + }); + } + let signature = self + .key + .sign(data) + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::Sign))?; + out.clear(); + out.extend_from_slice(signature.as_ref()); + Ok(()) + } + + fn algorithm(&self) -> SignatureAlgorithm { + SignatureAlgorithm::ECDSA + } + + fn hash_algorithm(&self) -> HashAlgorithm { + self.hash + } + + fn supported_hash_algorithms(&self) -> &[HashAlgorithm] { + core::slice::from_ref(&self.hash) + } +} + +#[derive(Debug)] +pub(crate) struct Verifier; + +pub(crate) static VERIFIER: Verifier = Verifier; + +impl SignatureVerifier for Verifier { + fn verify_signature( + &self, + cert_der: &[u8], + data: &[u8], + signature: &[u8], + hash: HashAlgorithm, + algorithm: SignatureAlgorithm, + ) -> Result<(), CryptoError> { + if algorithm != SignatureAlgorithm::ECDSA { + return Err(CryptoError::UnsupportedSignatureAlgorithm(algorithm)); + } + + let cert = Certificate::from_der(cert_der).map_err(|_| CryptoError::CertificateParseFailed)?; + let spki = cert.tbs_certificate().subject_public_key_info(); + if spki.algorithm.oid != ID_EC_PUBLIC_KEY { + return Err(CryptoError::UnsupportedPublicKeyAlgorithm); + } + let curve: ObjectIdentifier = spki + .algorithm + .parameters + .as_ref() + .ok_or(CryptoError::MissingEcCurveParameter)? + .decode_as() + .map_err(|_| CryptoError::InvalidEcCurveParameter)?; + let group = match curve { + OID_P256 => NamedGroup::Secp256r1, + OID_P384 => NamedGroup::Secp384r1, + _ => return Err(CryptoError::UnsupportedEcCurve), + }; + check_verify_scheme(algorithm, hash, group)?; + + // DTLS 1.2 may pair either curve with either hash. + let verification: &'static VerificationAlgorithm = match (group, hash) { + (NamedGroup::Secp256r1, HashAlgorithm::SHA256) => &verify::ECDSA_P256_SHA256_ASN1, + (NamedGroup::Secp256r1, HashAlgorithm::SHA384) => &verify::ECDSA_P256_SHA384_ASN1, + (NamedGroup::Secp384r1, HashAlgorithm::SHA256) => &verify::ECDSA_P384_SHA256_ASN1, + (NamedGroup::Secp384r1, HashAlgorithm::SHA384) => &verify::ECDSA_P384_SHA384_ASN1, + _ => { + return Err(CryptoError::UnsupportedSignatureVerification { + signature: algorithm, + hash, + group, + }); + } + }; + + let point = spki + .subject_public_key + .as_bytes() + .ok_or(CryptoError::InvalidSubjectPublicKey)?; + PublicKey::new(verification, point) + .map_err(|_| CryptoError::InvalidPublicKey(group))? + .verify(data, signature) + .map_err(|_| CryptoError::SignatureVerificationFailed { + signature: algorithm, + hash, + group, + }) + } +} diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/rind/suite.rs b/rs/moq-webrtc/src/vendor/dimpl/crypto/rind/suite.rs new file mode 100644 index 00000000000..bab10398a1f --- /dev/null +++ b/rs/moq-webrtc/src/vendor/dimpl/crypto/rind/suite.rs @@ -0,0 +1,183 @@ +use std::fmt; + +use crate::vendor::dimpl::crypto::{ + Aad, Buf, Cipher, Dtls12CipherSuite, HashAlgorithm, Nonce, SupportedDtls12CipherSuite, TmpBuf, +}; +use crate::vendor::dimpl::{CryptoError, CryptoOperation}; +use rind::aead; + +const TAG_LEN: usize = 16; + +/// The AEAD behind a suite. +#[derive(Debug, Clone, Copy)] +enum Algorithm { + Aes128Gcm, + Aes256Gcm, + ChaCha20Poly1305, +} + +impl Algorithm { + fn aead(self) -> &'static aead::Algorithm { + match self { + Self::Aes128Gcm => &aead::AES_128_GCM, + Self::Aes256Gcm => &aead::AES_256_GCM, + Self::ChaCha20Poly1305 => &aead::CHACHA20_POLY1305, + } + } + + fn cipher(self, key: &[u8]) -> Result, CryptoError> { + let actual = key.len().min(u16::MAX as usize) as u16; + let key = aead::Key::new(self.aead(), key).map_err(|_| match self { + Self::Aes128Gcm | Self::Aes256Gcm => CryptoError::InvalidAesGcmKeySize { actual }, + Self::ChaCha20Poly1305 => CryptoError::InvalidChacha20Poly1305KeySize { actual }, + })?; + Ok(Box::new(Aead(key))) + } +} + +struct Aead(aead::Key); + +impl fmt::Debug for Aead { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("Aead") + } +} + +impl Cipher for Aead { + fn encrypt(&mut self, plaintext: &mut Buf, aad: Aad, nonce: Nonce) -> Result<(), CryptoError> { + self.0 + .seal_in_place_append_tag(aead::Nonce::assume_unique_for_key(nonce.0), &aad, plaintext) + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::Encrypt)) + } + + fn decrypt(&mut self, ciphertext: &mut TmpBuf, aad: Aad, nonce: Nonce) -> Result<(), CryptoError> { + let len = ciphertext.len(); + let Some(plaintext_len) = len.checked_sub(TAG_LEN) else { + return Err(CryptoError::CiphertextTooShort { + minimum: TAG_LEN as u8, + actual: len as u8, + }); + }; + + self.0 + .open_in_place(aead::Nonce::assume_unique_for_key(nonce.0), &aad, ciphertext.as_mut()) + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::Decrypt))?; + + ciphertext.truncate(plaintext_len); + Ok(()) + } +} + +#[derive(Debug)] +struct Dtls12 { + suite: Dtls12CipherSuite, + hash: HashAlgorithm, + algorithm: Algorithm, +} + +impl SupportedDtls12CipherSuite for Dtls12 { + fn suite(&self) -> Dtls12CipherSuite { + self.suite + } + + fn hash_algorithm(&self) -> HashAlgorithm { + self.hash + } + + fn key_lengths(&self) -> (usize, usize, usize) { + // (MAC key, encryption key, fixed IV): RFC 5288 and RFC 7905. + let fixed_iv_len = match self.algorithm { + Algorithm::Aes128Gcm | Algorithm::Aes256Gcm => 4, + Algorithm::ChaCha20Poly1305 => 12, + }; + (0, self.algorithm.aead().key_len(), fixed_iv_len) + } + + fn explicit_nonce_len(&self) -> usize { + match self.algorithm { + Algorithm::Aes128Gcm | Algorithm::Aes256Gcm => 8, + Algorithm::ChaCha20Poly1305 => 0, + } + } + + fn tag_len(&self) -> usize { + TAG_LEN + } + + fn create_cipher(&self, key: &[u8]) -> Result, CryptoError> { + self.algorithm.cipher(key) + } +} + +/// TLS_PSK_WITH_AES_128_CCM_8, on dimpl's own AES-CCM. +#[derive(Debug)] +struct PskAes128Ccm8; + +impl SupportedDtls12CipherSuite for PskAes128Ccm8 { + fn suite(&self) -> Dtls12CipherSuite { + Dtls12CipherSuite::PSK_AES128_CCM_8 + } + + fn hash_algorithm(&self) -> HashAlgorithm { + HashAlgorithm::SHA256 + } + + fn key_lengths(&self) -> (usize, usize, usize) { + (0, 16, 4) // (mac_key_len, enc_key_len, fixed_iv_len) + } + + fn explicit_nonce_len(&self) -> usize { + 8 + } + + fn tag_len(&self) -> usize { + 8 + } + + fn create_cipher(&self, key: &[u8]) -> Result, CryptoError> { + Ok(Box::new(crate::vendor::dimpl::crypto::ccm_cipher::AesCcm8Cipher::new( + key, + )?)) + } +} + +const AES_128_GCM: &dyn SupportedDtls12CipherSuite = &Dtls12 { + suite: Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256, + hash: HashAlgorithm::SHA256, + algorithm: Algorithm::Aes128Gcm, +}; +const AES_256_GCM: &dyn SupportedDtls12CipherSuite = &Dtls12 { + suite: Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384, + hash: HashAlgorithm::SHA384, + algorithm: Algorithm::Aes256Gcm, +}; +const CHACHA20_POLY1305: &dyn SupportedDtls12CipherSuite = &Dtls12 { + suite: Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256, + hash: HashAlgorithm::SHA256, + algorithm: Algorithm::ChaCha20Poly1305, +}; +const PSK_AES_128_CCM_8: &dyn SupportedDtls12CipherSuite = &PskAes128Ccm8; + +/// DTLS 1.2 suites, in order of preference where rind runs AES on CPU instructions. +pub(super) static DTLS12: &[&dyn SupportedDtls12CipherSuite] = + &[AES_128_GCM, AES_256_GCM, CHACHA20_POLY1305, PSK_AES_128_CCM_8]; + +/// [`DTLS12`] with ChaCha20-Poly1305 first, which outruns AES without AES +/// instructions. +pub(super) static DTLS12_CHACHA20_FIRST: &[&dyn SupportedDtls12CipherSuite] = + &[CHACHA20_POLY1305, AES_128_GCM, AES_256_GCM, PSK_AES_128_CCM_8]; + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn chacha20_poly1305_key_len_validation() { + // incorrect length (should be 32) + let result = Algorithm::ChaCha20Poly1305.cipher(&[0, 1, 2, 3, 4, 5]); + assert_eq!( + CryptoError::InvalidChacha20Poly1305KeySize { actual: 6 }, + result.unwrap_err() + ); + } +} diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/validation/mod.rs b/rs/moq-webrtc/src/vendor/dimpl/crypto/validation/mod.rs index 5c0442182e0..6e0c14f48e5 100644 --- a/rs/moq-webrtc/src/vendor/dimpl/crypto/validation/mod.rs +++ b/rs/moq-webrtc/src/vendor/dimpl/crypto/validation/mod.rs @@ -335,20 +335,20 @@ const VALIDATION_P384_CERT: &[u8] = include_bytes!("p384_cert.der"); const VALIDATION_P384_SHA384_SIG: &[u8] = include_bytes!("p384_sha384_sig.der"); #[cfg(test)] -mod tests_aws_lc_rs { +mod tests_rind { use super::*; - use crate::vendor::dimpl::crypto::aws_lc_rs; + use crate::vendor::dimpl::crypto::rind; use crate::vendor::dimpl::dtls12::message::Dtls12CipherSuite; #[test] fn test_default_provider_validates() { - let provider = aws_lc_rs::default_provider(); + let provider = rind::default_provider().unwrap(); assert!(provider.validate().is_ok()); } #[test] fn test_default_provider_has_cipher_suites() { - let provider = aws_lc_rs::default_provider(); + let provider = rind::default_provider().unwrap(); let count = provider.supported_cipher_suites().count(); // ECDHE: AES-128, AES-256, ChaCha20 // PSK: CCM-8 @@ -357,20 +357,20 @@ mod tests_aws_lc_rs { #[test] fn test_default_provider_has_kx_groups() { - let provider = aws_lc_rs::default_provider(); + let provider = rind::default_provider().unwrap(); let count = provider.supported_kx_groups().count(); assert_eq!(count, 3); // X25519, P-256, and P-384 } #[test] fn test_default_provider_has_ecdh() { - let provider = aws_lc_rs::default_provider(); + let provider = rind::default_provider().unwrap(); assert!(provider.has_ecdh()); } #[test] fn test_supported_cipher_suites_for_signature_algorithm() { - let provider = aws_lc_rs::default_provider(); + let provider = rind::default_provider().unwrap(); let ecdsa_suites: Vec<_> = provider .supported_cipher_suites_for_signature_algorithm(SignatureAlgorithm::ECDSA) .map(|cs| cs.suite()) diff --git a/rs/moq-webrtc/src/vendor/dimpl/error.rs b/rs/moq-webrtc/src/vendor/dimpl/error.rs index 1158b6fc800..d3fe5ba8403 100644 --- a/rs/moq-webrtc/src/vendor/dimpl/error.rs +++ b/rs/moq-webrtc/src/vendor/dimpl/error.rs @@ -242,6 +242,8 @@ pub enum CryptoOperation { ComputeCookie, /// Encode a key. EncodeKey, + /// Compute an HMAC. + ComputeHmac, } /// Fine-grained reason for an [`Error::CertificateError`]. @@ -357,6 +359,8 @@ pub enum ConfigError { NoDtls12KeyExchangeGroupsAfterFiltering, /// Crypto provider validation failed. CryptoProvider(CryptoProviderValidationError), + /// No provider was given, and rind's default refuses this CPU. + UnsupportedCpu(rind::cpu::MissingFeature), } /// Fine-grained reason for crypto provider validation failure. @@ -687,6 +691,7 @@ impl fmt::Display for CryptoOperation { Self::FillRandom => "random generation", Self::ComputeCookie => "cookie computation", Self::EncodeKey => "key encoding", + Self::ComputeHmac => "HMAC computation", }; write!(f, "{text}") } @@ -817,6 +822,7 @@ impl fmt::Display for ConfigError { ) ), Self::CryptoProvider(err) => write!(f, "crypto provider validation failed: {err}"), + Self::UnsupportedCpu(missing) => write!(f, "unsupported CPU: {missing}"), } } } diff --git a/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/handshake.rs b/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/handshake.rs index f8667ff7240..08ba513a03c 100644 --- a/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/handshake.rs +++ b/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/handshake.rs @@ -699,13 +699,13 @@ fn dtls12_handshake_secp384r1_key_exchange() { //! and verify both sides reach connected. use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - use crate::vendor::dimpl::crypto::aws_lc_rs; + use crate::vendor::dimpl::crypto::rind; let client_cert = generate_self_signed_certificate().expect("gen client cert"); let server_cert = generate_self_signed_certificate().expect("gen server cert"); // Build a crypto provider with only the P-384 key exchange group. - let mut provider = aws_lc_rs::default_provider(); + let mut provider = rind::default_provider().unwrap(); let p384_vec: Vec<&'static dyn crate::vendor::dimpl::crypto::SupportedKxGroup> = provider .kx_groups .iter() @@ -838,14 +838,14 @@ fn dtls12_handshake_p384_certificate() { //! same hash algorithm it advertises on the wire (SHA-384 for P-384). let p384 = || { - let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P384_SHA384).expect("P-384 key"); - let cert = rcgen::CertificateParams::new(vec!["WebRTC".to_string()]) - .expect("certificate params") - .self_signed(&key) - .expect("self-signed certificate"); + let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P384_SHA384).expect("P-384 key"); + let mut params = rcgen::CertificateParams::new(vec!["WebRTC".to_string()]).expect("certificate params"); + // rcgen draws no serial number without its own crypto backend. + params.serial_number = Some(1u64.into()); + let cert = params.self_signed(&key).expect("self-signed certificate"); crate::vendor::dimpl::DtlsCertificate { certificate: cert.der().to_vec(), - private_key: key.serialize_der(), + private_key: key.to_pkcs8().secret_pkcs8_der().to_vec(), } }; diff --git a/rs/moq-webrtc/src/vendor/is/hmac_provider.rs b/rs/moq-webrtc/src/vendor/is/hmac_provider.rs index 7d2be54f9fd..e3b7c0af0df 100644 --- a/rs/moq-webrtc/src/vendor/is/hmac_provider.rs +++ b/rs/moq-webrtc/src/vendor/is/hmac_provider.rs @@ -1,4 +1,4 @@ -/// HMAC-SHA1 for the ICE agent's own tests, from the aws-lc-rs provider str0m runs on. +/// HMAC-SHA1 for the ICE agent's own tests, from the rind provider str0m runs on. #[cfg(test)] #[derive(Debug)] pub struct DefaultSha1HmacProvider; @@ -6,7 +6,8 @@ pub struct DefaultSha1HmacProvider; #[cfg(test)] impl crate::vendor::str0m_proto::Sha1HmacProvider for DefaultSha1HmacProvider { fn sha1_hmac(&self, key: &[u8], payloads: &[&[u8]]) -> [u8; 20] { - crate::vendor::str0m_aws_lc_rs::default_provider() + crate::vendor::str0m_rind::default_provider() + .unwrap() .sha1_hmac_provider .sha1_hmac(key, payloads) } diff --git a/rs/moq-webrtc/src/vendor/is/stun.rs b/rs/moq-webrtc/src/vendor/is/stun.rs index 8cd91e4d71d..5b3a65288f5 100644 --- a/rs/moq-webrtc/src/vendor/is/stun.rs +++ b/rs/moq-webrtc/src/vendor/is/stun.rs @@ -1421,8 +1421,8 @@ mod test { use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6}; fn sha1_hmac(key: &[u8], payloads: &[&[u8]]) -> [u8; 20] { - use aws_lc_rs::hmac; - let key = hmac::Key::new(hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY, key); + use rind::hmac; + let key = hmac::Key::new(&hmac::legacy::HMAC_SHA1, key); let mut ctx = hmac::Context::with_key(&key); for p in payloads { ctx.update(p); diff --git a/rs/moq-webrtc/src/vendor/mod.rs b/rs/moq-webrtc/src/vendor/mod.rs index c87543f8f7e..7d27022f18b 100644 --- a/rs/moq-webrtc/src/vendor/mod.rs +++ b/rs/moq-webrtc/src/vendor/mod.rs @@ -10,8 +10,8 @@ //! file covers the other crates from its repository, which ship none of their //! own), `dimpl`, and `sctp_proto`, and `str0m/packet/LICENSE-APACHE.txt` keeps //! webrtc-rs's notice on `str0m::packet`: -//! - `str0m` (0.24.1+), `str0m_proto` (0.7.0), `is` (0.11.1), `str0m_aws_lc_rs` -//! (0.6.0), and the test-only `netem` (0.4.0): +//! - `str0m` (0.24.1+), `str0m_proto` (0.7.0), `is` (0.11.1), and the test-only +//! `netem` (0.4.0): //! at [`dc317173`](https://github.com/algesten/str0m/commit/dc317173b16fc6ed86633e6b08b229c9195deb87) //! (2026-10-26), the main-branch revision on dimpl 0.9 with str0m's pluggable //! crypto provider. @@ -19,6 +19,11 @@ //! ([`c17b3b8`](https://github.com/algesten/dimpl/commit/c17b3b8b971b6eb2ecf7284f5dc0ecb86680ac4d)). //! - `sctp_proto`: 0.10.7, as published //! on crates.io. +//! - `str0m_rind` and dimpl's `crypto::rind`, the stack's crypto providers: +//! 's `rind-str0m` (as of +//! [`86567aad`](https://github.com/moq-dev/rind/commit/86567aadabc22d2b2ac23ea534598a0fffc66538), +//! which targeted the str0m revision above) and `rind-dimpl` 0.1.12, ported to +//! the rind release the workspace pins. //! //! Nobody merges upstream automatically: the release-cut vendor audit reads each //! upstream's changes since these revisions and ports the fixes MoQ needs. @@ -47,7 +52,7 @@ mod netem; mod sctp_proto; #[path = "str0m/lib.rs"] pub(crate) mod str0m; -#[path = "str0m_aws_lc_rs/lib.rs"] -mod str0m_aws_lc_rs; #[path = "str0m_proto/lib.rs"] mod str0m_proto; +#[path = "str0m_rind/lib.rs"] +mod str0m_rind; diff --git a/rs/moq-webrtc/src/vendor/str0m/crypto/mod.rs b/rs/moq-webrtc/src/vendor/str0m/crypto/mod.rs index 033c6eba435..f6c1347b77b 100644 --- a/rs/moq-webrtc/src/vendor/str0m/crypto/mod.rs +++ b/rs/moq-webrtc/src/vendor/str0m/crypto/mod.rs @@ -26,9 +26,11 @@ pub(crate) fn test_default_provider() -> &'static CryptoProvider { TEST_PROVIDER.get_or_init(from_feature_flags) } -/// The default crypto provider: aws-lc-rs, the only backend kept in the vendored copy. +/// The default crypto provider: rind, the only backend kept in the vendored copy. +/// +/// Panics on a CPU rind refuses, so moq-webrtc checks the CPU before building an `Rtc`. pub fn from_feature_flags() -> CryptoProvider { - crate::vendor::str0m_aws_lc_rs::default_provider() + crate::vendor::str0m_rind::default_provider().expect("rind refuses this CPU") } mod finger; diff --git a/rs/moq-webrtc/src/vendor/str0m/lib.rs b/rs/moq-webrtc/src/vendor/str0m/lib.rs index c141019aaca..7ed73e7b453 100644 --- a/rs/moq-webrtc/src/vendor/str0m/lib.rs +++ b/rs/moq-webrtc/src/vendor/str0m/lib.rs @@ -339,8 +339,8 @@ //! //! # Crypto backends //! -//! The vendored copy keeps only the aws-lc-rs backend (`str0m_aws_lc_rs`, DTLS -//! from dimpl), which is the default. The `CryptoProvider` trait stays so another +//! The vendored copy keeps only the rind backend (`str0m_rind`, DTLS from +//! dimpl), which is the default. The `CryptoProvider` trait stays so another //! backend can be installed process-wide or per instance: //! //! ```ignore @@ -1143,7 +1143,7 @@ impl Rtc { .clone() // If crypto_provider is not set in config, check process default .or_else(|| CryptoProvider::get_default().cloned().map(Arc::new)) - // Or fall back on the vendored aws-lc-rs backend + // Or fall back on the vendored rind backend .unwrap_or_else(|| Arc::new(from_feature_flags())); let session = Session::new(&config); diff --git a/rs/moq-webrtc/src/vendor/str0m/rtp/srtp.rs b/rs/moq-webrtc/src/vendor/str0m/rtp/srtp.rs index a9531b50c99..2f6c7ff224a 100644 --- a/rs/moq-webrtc/src/vendor/str0m/rtp/srtp.rs +++ b/rs/moq-webrtc/src/vendor/str0m/rtp/srtp.rs @@ -35,14 +35,10 @@ const MAX_TAG_LEN: usize = AeadAes256Gcm::TAG_LEN; pub const SRTCP_OVERHEAD: usize = MAX_TAG_LEN + SRTCP_INDEX_LEN; pub const SRTP_OVERHEAD: usize = MAX_TAG_LEN; -// aws-lc-rs CTR mode requires output buffer to be input.len() + block_len - 1 -// This adds 15 bytes of padding that we truncate after encryption -const CTR_BUFFER_PADDING: usize = SRTP_BLOCK_SIZE - 1; - /// Initial capacity for the RTP decryption scratch buffer. Sized to fit the -/// largest possible received datagram plus the CTR padding the AES-CM cipher -/// needs, so `unprotect_rtp` never has to grow the buffer in practice. -const RX_SCRATCH_CAPACITY: usize = DATAGRAM_MAX_PACKET_SIZE + CTR_BUFFER_PADDING; +/// largest possible received datagram, so `unprotect_rtp` never has to grow +/// the buffer in practice. +const RX_SCRATCH_CAPACITY: usize = DATAGRAM_MAX_PACKET_SIZE; /// Start repeated warnings here, then double the failure count between reports. const DECRYPT_WARN_INITIAL_COUNT: u64 = 4_096; @@ -251,15 +247,10 @@ impl SrtpContext { match &mut self.rtp { Derived::Aes128CmSha1_80 { key, salt, enc, .. } => { - // arbitrary body lengths are fine: the output buffer below is - // allocated with the CTR scratch the ciphers need and truncated - // after encryption, so no 16-byte alignment is required. + // Counter mode takes arbitrary body lengths, so no 16-byte alignment is required. let iv = Aes128CmSha1_80::rtp_iv(*salt, *header.ssrc, srtp_index); - // Allocate buffer with CTR padding (aws-lc-rs requirement) - // HMAC_TAG_LEN is 10, CTR_BUFFER_PADDING is 15, so we need 5 extra bytes - let padding_needed = CTR_BUFFER_PADDING.saturating_sub(Aes128CmSha1_80::HMAC_TAG_LEN); - let mut output = vec![0_u8; buf.len() + Aes128CmSha1_80::HMAC_TAG_LEN + padding_needed]; + let mut output = vec![0_u8; buf.len() + Aes128CmSha1_80::HMAC_TAG_LEN]; enc.encrypt(&iv, input, &mut output[hlen..]).expect("rtp encrypt"); @@ -269,7 +260,6 @@ impl SrtpContext { let sha1_hmac = |k: &[u8], p: &[&[u8]]| self.sha1_hmac_provider.sha1_hmac(k, p); Aes128CmSha1_80::rtp_hmac(sha1_hmac, key, &mut output, srtp_index, hmac_start); - output.truncate(buf.len() + Aes128CmSha1_80::HMAC_TAG_LEN); output } Derived::AeadAes128Gcm { salt, enc, .. } => { @@ -332,8 +322,7 @@ impl SrtpContext { let iv = Aes128CmSha1_80::rtp_iv(*salt, *header.ssrc, srtp_index); let input = &buf[header.header_len..hmac_start]; - // Sized with CTR padding (aws-lc-rs requirement). - self.rx_scratch.resize(input.len() + CTR_BUFFER_PADDING, 0); + self.rx_scratch.resize(input.len(), 0); if let Err(e) = dec.decrypt(&iv, input, &mut self.rx_scratch) { trace!( @@ -437,10 +426,7 @@ impl SrtpContext { let iv = Aes128CmSha1_80::rtp_iv(*salt, ssrc, srtcp_index as u64); let final_size = buf.len() + SRTCP_INDEX_LEN + Aes128CmSha1_80::HMAC_TAG_LEN; - // Allocate buffer with CTR padding (aws-lc-rs requirement) - // SRTCP_INDEX_LEN + HMAC_TAG_LEN is 14, CTR_BUFFER_PADDING is 15, so we need 1 extra byte - let padding_needed = CTR_BUFFER_PADDING.saturating_sub(SRTCP_INDEX_LEN + Aes128CmSha1_80::HMAC_TAG_LEN); - let mut output = vec![0_u8; final_size + padding_needed]; + let mut output = vec![0_u8; final_size]; output[0..8].copy_from_slice(&buf[0..8]); let input = &buf[8..]; @@ -453,7 +439,6 @@ impl SrtpContext { let sha1_hmac = |k: &[u8], p: &[&[u8]]| self.sha1_hmac_provider.sha1_hmac(k, p); Aes128CmSha1_80::rtcp_hmac(sha1_hmac, key, &mut output, hmac_index); - output.truncate(final_size); output } Derived::AeadAes128Gcm { salt, enc, .. } => { @@ -556,8 +541,7 @@ impl SrtpContext { // first RTCP packet, i.e., from the ninth (9) octet to the end of the // compound packet. let input = &buf[8..idx_start]; - // Allocate buffer with CTR padding (aws-lc-rs requirement) - let mut output = vec![0_u8; input.len() + 8 + CTR_BUFFER_PADDING]; + let mut output = vec![0_u8; input.len() + 8]; output[0..8].copy_from_slice(&buf[0..8]); if let Err(e) = dec.decrypt(&iv, input, &mut output[8..]) { @@ -566,7 +550,6 @@ impl SrtpContext { return None; } - output.truncate(input.len() + 8); Some(output) } Derived::AeadAes128Gcm { salt, dec, .. } => { diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/common.rs b/rs/moq-webrtc/src/vendor/str0m/tests/common.rs index ffd15fbc937..4792b30791a 100644 --- a/rs/moq-webrtc/src/vendor/str0m/tests/common.rs +++ b/rs/moq-webrtc/src/vendor/str0m/tests/common.rs @@ -444,11 +444,11 @@ pub fn init_crypto_default() { crate::vendor::str0m::crypto::from_feature_flags().install_process_default(); } -/// Create a crypto provider from a string name. Only "aws-lc-rs" is vendored. +/// Create a crypto provider from a string name. Only "rind" is vendored. fn get_crypto_provider_by_name(name: &str) -> CryptoProvider { match name { - "aws-lc-rs" | "aws" => crate::vendor::str0m_aws_lc_rs::default_provider(), - _ => panic!("Unknown or unavailable crypto provider '{name}'. Available providers: [aws-lc-rs]"), + "rind" => crate::vendor::str0m_rind::default_provider().unwrap(), + _ => panic!("Unknown or unavailable crypto provider '{name}'. Available providers: [rind]"), } } diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/dtls-fingerprint.rs b/rs/moq-webrtc/src/vendor/str0m/tests/dtls-fingerprint.rs index f14f7885d75..4b505d28c48 100644 --- a/rs/moq-webrtc/src/vendor/str0m/tests/dtls-fingerprint.rs +++ b/rs/moq-webrtc/src/vendor/str0m/tests/dtls-fingerprint.rs @@ -75,7 +75,7 @@ fn connect_with_provider(expected: impl Fn(&[u8]) -> Fingerprint, provider: Cryp } fn reference_sha1(data: &[u8]) -> [u8; 20] { - aws_lc_rs::digest::digest(&aws_lc_rs::digest::SHA1_FOR_LEGACY_USE_ONLY, data) + rind::digest::digest(&rind::digest::legacy::SHA1, data) .as_ref() .try_into() .unwrap() diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/handshake-direct.rs b/rs/moq-webrtc/src/vendor/str0m/tests/handshake-direct.rs index cf66da57e04..0eba35e1011 100644 --- a/rs/moq-webrtc/src/vendor/str0m/tests/handshake-direct.rs +++ b/rs/moq-webrtc/src/vendor/str0m/tests/handshake-direct.rs @@ -44,7 +44,7 @@ pub fn handshake_direct_api_snap() -> Result<(), RtcError> { /// Returns the name of the default crypto provider, matching /// `crate::vendor::str0m::crypto::from_feature_flags()`. fn default_crypto_name() -> &'static str { - "aws-lc-rs" + "rind" } /// Shared implementation for both standard and SNAP direct API handshake tests. diff --git a/rs/moq-webrtc/src/vendor/str0m_aws_lc_rs/dtls.rs b/rs/moq-webrtc/src/vendor/str0m_aws_lc_rs/dtls.rs deleted file mode 100644 index 0577aaf2bc0..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m_aws_lc_rs/dtls.rs +++ /dev/null @@ -1,115 +0,0 @@ -//! DTLS implementation using dimpl with AWS-LC-RS backend. - -use std::sync::Arc; -use std::time::Instant; - -use crate::vendor::str0m_proto::crypto::CryptoError; -use crate::vendor::str0m_proto::crypto::dtls::ProtocolVersion; -use crate::vendor::str0m_proto::crypto::dtls::{DtlsCert, DtlsImplError, DtlsInstance, DtlsOutput, DtlsProvider}; - -// ============================================================================ -// DTLS Provider Implementation -// ============================================================================ - -#[derive(Debug)] -pub(super) struct AwsLcRsDtlsProvider; - -impl DtlsProvider for AwsLcRsDtlsProvider { - fn generate_certificate(&self) -> Option { - // Use dimpl's rcgen-based certificate generation (with aws-lc-rs backend) - crate::vendor::dimpl::certificate::generate_self_signed_certificate() - .ok() - .map(|cert| DtlsCert { - certificate: cert.certificate, - private_key: cert.private_key, - }) - } - - fn new_dtls( - &self, - cert: &DtlsCert, - now: Instant, - mtu: Option, - ) -> Result, CryptoError> { - let dimpl_cert = crate::vendor::dimpl::DtlsCertificate { - certificate: cert.certificate.clone(), - private_key: cert.private_key.clone(), - }; - - // Create a default dimpl Config with AWS-LC-RS crypto provider - // ICE verifies return routability before DTLS, making server cookies redundant. - let mut builder = crate::vendor::dimpl::Config::builder().use_server_cookie(false); - if let Some(mtu) = mtu { - builder = builder.mtu(mtu); - } - if self.is_test() { - // We need the DTLS impl to be deterministic for the BWE tests. - builder = builder.dangerously_set_rng_seed(42); - } - - let config = builder - .build() - .map_err(|e| CryptoError::Other(format!("dimpl config creation failed: {}", e)))?; - - let config = Arc::new(config); - let dtls = crate::vendor::dimpl::Dtls::new_12(config, dimpl_cert, now); - - Ok(Box::new(AwsLcRsDtlsInstance { dtls })) - } -} - -// ============================================================================ -// DTLS Instance Wrapper -// ============================================================================ - -struct AwsLcRsDtlsInstance { - dtls: crate::vendor::dimpl::Dtls, -} - -impl std::fmt::Debug for AwsLcRsDtlsInstance { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("AwsLcRsDtlsInstance").finish() - } -} - -impl DtlsInstance for AwsLcRsDtlsInstance { - fn set_active(&mut self, active: bool) { - self.dtls.set_active(active); - } - - fn handle_packet(&mut self, packet: &[u8]) -> Result<(), DtlsImplError> { - self.dtls.handle_packet(packet) - } - - fn poll_output<'a>(&mut self, buf: &'a mut [u8]) -> DtlsOutput<'a> { - self.dtls.poll_output(buf) - } - - fn handle_timeout(&mut self, now: Instant) -> Result<(), DtlsImplError> { - self.dtls.handle_timeout(now) - } - - fn send_application_data(&mut self, data: &[u8]) -> Result { - self.dtls.send_application_data(data) - } - - fn is_active(&self) -> bool { - self.dtls.is_active() - } - - fn protocol_version(&self) -> Option { - self.dtls.protocol_version() - } - - fn is_closing(&self) -> bool { - self.dtls.is_closing() - } - - fn is_closed(&self) -> bool { - self.dtls.is_closed() - } - - fn close(&mut self) -> Result<(), DtlsImplError> { - self.dtls.close() - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m_aws_lc_rs/lib.rs b/rs/moq-webrtc/src/vendor/str0m_aws_lc_rs/lib.rs deleted file mode 100644 index 63f1f8494a8..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m_aws_lc_rs/lib.rs +++ /dev/null @@ -1,64 +0,0 @@ -//! AWS-LC-RS implementation of cryptographic functions. -//! DTLS via dimpl with AWS-LC-RS as crypto backend. - -// Avoid rewriting existing code: nested conditions are often more readable than long if-chains. -#![allow(clippy::collapsible_if)] - -mod dtls; -mod sha1; -mod sha256; -mod srtp; - -use crate::vendor::str0m_proto::crypto::CryptoProvider; -use dtls::AwsLcRsDtlsProvider; -use sha1::{AwsLcRsSha1HmacProvider, AwsLcRsSha1Provider}; -use sha256::AwsLcRsSha256Provider; -use srtp::AwsLcRsSrtpProvider; - -/// Create the default AWS-LC-RS crypto provider. -/// -/// This provider implements all cryptographic operations required for WebRTC: -/// - DTLS 1.2 for secure key exchange (using dimpl protocol + AWS-LC-RS) -/// - SRTP for encrypted media -/// - SHA1-HMAC for STUN message integrity -/// - SHA-1 and SHA-256 for certificate fingerprints -/// -/// # Supported SRTP Profiles -/// -/// - `SRTP_AES128_CM_SHA1_80` -/// - `SRTP_AEAD_AES_128_GCM` -/// - `SRTP_AEAD_AES_256_GCM` -pub fn default_provider() -> CryptoProvider { - static SRTP: AwsLcRsSrtpProvider = AwsLcRsSrtpProvider; - static SHA1_HMAC: AwsLcRsSha1HmacProvider = AwsLcRsSha1HmacProvider; - static SHA1: AwsLcRsSha1Provider = AwsLcRsSha1Provider; - static SHA256: AwsLcRsSha256Provider = AwsLcRsSha256Provider; - static DTLS: AwsLcRsDtlsProvider = AwsLcRsDtlsProvider; - - CryptoProvider { - srtp_provider: &SRTP, - sha1_hmac_provider: &SHA1_HMAC, - sha1_provider: &SHA1, - sha256_provider: &SHA256, - dtls_provider: &DTLS, - } -} - -/// Create the AWS-LC-RS crypto provider used by the Dimpl DTLS backend. -/// -/// This allows callers that need non-default Dimpl configuration to construct -/// `crate::vendor::dimpl::Config` directly while retaining the AWS-LC-RS implementation. -pub fn dimpl_crypto_provider() -> crate::vendor::dimpl::crypto::CryptoProvider { - crate::vendor::dimpl::crypto::aws_lc_rs::default_provider() -} - -#[cfg(test)] -mod tests { - #[test] - fn exposed_dimpl_provider_builds_config() { - crate::vendor::dimpl::Config::builder() - .with_crypto_provider(super::dimpl_crypto_provider()) - .build() - .expect("AWS-LC-RS Dimpl provider should build a valid config"); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m_aws_lc_rs/sha1.rs b/rs/moq-webrtc/src/vendor/str0m_aws_lc_rs/sha1.rs deleted file mode 100644 index 6bd0ebea9ba..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m_aws_lc_rs/sha1.rs +++ /dev/null @@ -1,45 +0,0 @@ -//! SHA-1 hash and HMAC implementations using AWS-LC-RS. - -use aws_lc_rs::{digest, hmac}; - -use crate::vendor::str0m_proto::crypto::{Sha1HmacProvider, Sha1Provider}; - -#[derive(Debug)] -pub(super) struct AwsLcRsSha1Provider; - -impl Sha1Provider for AwsLcRsSha1Provider { - fn sha1(&self, data: &[u8]) -> [u8; 20] { - let digest = digest::digest(&digest::SHA1_FOR_LEGACY_USE_ONLY, data); - let mut output = [0u8; 20]; - output.copy_from_slice(digest.as_ref()); - output - } -} - -// ============================================================================ -// SHA1 HMAC Provider Implementation -// ============================================================================ - -pub(super) struct AwsLcRsSha1HmacProvider; - -impl std::fmt::Debug for AwsLcRsSha1HmacProvider { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("AwsLcRsSha1HmacProvider").finish() - } -} - -impl Sha1HmacProvider for AwsLcRsSha1HmacProvider { - fn sha1_hmac(&self, key: &[u8], payloads: &[&[u8]]) -> [u8; 20] { - let key = hmac::Key::new(hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY, key); - let mut ctx = hmac::Context::with_key(&key); - - for payload in payloads { - ctx.update(payload); - } - - let tag = ctx.sign(); - let mut result = [0u8; 20]; - result.copy_from_slice(tag.as_ref()); - result - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m_aws_lc_rs/sha256.rs b/rs/moq-webrtc/src/vendor/str0m_aws_lc_rs/sha256.rs deleted file mode 100644 index de9f3ef6bdd..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m_aws_lc_rs/sha256.rs +++ /dev/null @@ -1,18 +0,0 @@ -//! AWS-LC-RS SHA-256 implementation. - -use aws_lc_rs::digest; - -use crate::vendor::str0m_proto::crypto::Sha256Provider; - -/// AWS-LC-RS-based SHA-256 provider. -#[derive(Debug)] -pub struct AwsLcRsSha256Provider; - -impl Sha256Provider for AwsLcRsSha256Provider { - fn sha256(&self, data: &[u8]) -> [u8; 32] { - let hash = digest::digest(&digest::SHA256, data); - let mut result = [0u8; 32]; - result.copy_from_slice(hash.as_ref()); - result - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m_aws_lc_rs/srtp.rs b/rs/moq-webrtc/src/vendor/str0m_aws_lc_rs/srtp.rs deleted file mode 100644 index e31b755573d..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m_aws_lc_rs/srtp.rs +++ /dev/null @@ -1,309 +0,0 @@ -//! SRTP cipher implementations using AWS-LC-RS. - -use aws_lc_rs::aead::{AES_128_GCM, AES_256_GCM, Aad, LessSafeKey, Nonce, UnboundKey}; -use aws_lc_rs::cipher::{AES_128, EncryptingKey, EncryptionContext, UnboundCipherKey}; - -use crate::vendor::str0m_proto::crypto::CryptoError; -use crate::vendor::str0m_proto::crypto::{AeadAes128Gcm, AeadAes128GcmCipher, AeadAes256Gcm}; -use crate::vendor::str0m_proto::crypto::{AeadAes256GcmCipher, Aes128CmSha1_80Cipher}; -use crate::vendor::str0m_proto::crypto::{SrtpProvider, SupportedAeadAes128Gcm}; -use crate::vendor::str0m_proto::crypto::{SupportedAeadAes256Gcm, SupportedAes128CmSha1_80}; - -// ============================================================================ -// AES-128-CM-SHA1-80 Cipher -// ============================================================================ - -struct AwsLcRsAes128CmSha1_80Cipher { - key: [u8; 16], -} - -impl std::fmt::Debug for AwsLcRsAes128CmSha1_80Cipher { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("AwsLcRsAes128CmSha1_80Cipher").finish() - } -} - -impl Aes128CmSha1_80Cipher for AwsLcRsAes128CmSha1_80Cipher { - fn encrypt(&mut self, iv: &[u8; 16], input: &[u8], output: &mut [u8]) -> Result<(), CryptoError> { - // AES-128 Counter Mode (CTR) - let unbound_key = UnboundCipherKey::new(&AES_128, &self.key).expect("valid key"); - let encrypting_key = EncryptingKey::ctr(unbound_key).expect("CTR mode"); - - // For CTR mode, we need the full 16-byte IV as the counter - let context = EncryptionContext::Iv128(aws_lc_rs::iv::FixedLength::try_from(iv.as_ref()).expect("16-byte IV")); - - // Copy input to output buffer for in-place encryption - output[..input.len()].copy_from_slice(input); - - encrypting_key - .less_safe_encrypt(&mut output[..input.len()], context) - .map_err(|e| CryptoError::Other(format!("AES-CTR encrypt failed: {}", e)))?; - - Ok(()) - } - - fn decrypt(&mut self, iv: &[u8; 16], input: &[u8], output: &mut [u8]) -> Result<(), CryptoError> { - // AES-CTR mode is symmetric, so we can use the same operation - self.encrypt(iv, input, output) - } -} - -// ============================================================================ -// AEAD-AES-128-GCM Cipher -// ============================================================================ - -struct AwsLcRsAeadAes128GcmCipher { - key: LessSafeKey, -} - -impl std::fmt::Debug for AwsLcRsAeadAes128GcmCipher { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("AwsLcRsAeadAes128GcmCipher").finish() - } -} - -impl AeadAes128GcmCipher for AwsLcRsAeadAes128GcmCipher { - fn encrypt( - &mut self, - iv: &[u8; AeadAes128Gcm::IV_LEN], - aad: &[u8], - input: &[u8], - output: &mut [u8], - ) -> Result<(), CryptoError> { - assert!(aad.len() >= 12, "Associated data length MUST be at least 12 octets"); - - let nonce = - Nonce::try_assume_unique_for_key(iv).map_err(|e| CryptoError::Other(format!("Invalid nonce: {}", e)))?; - - let len = input.len(); - output[..len].copy_from_slice(input); - let tag = self - .key - .seal_in_place_separate_tag(nonce, Aad::from(aad), &mut output[..len]) - .map_err(|e| CryptoError::Other(format!("AES-GCM encrypt failed: {}", e)))?; - - // Copy the result tag to the output - output[len..len + AeadAes128Gcm::TAG_LEN].copy_from_slice(tag.as_ref()); - Ok(()) - } - - fn decrypt( - &mut self, - iv: &[u8; AeadAes128Gcm::IV_LEN], - aads: &[&[u8]], - input: &[u8], - output: &mut [u8], - ) -> Result { - // Caller contract: `SrtpContext::unprotect_rtp` and `unprotect_rtcp` guarantee - // the input holds at least the auth tag. A shorter buffer is a bug in str0m, - // not bad input, so fail fast rather than hiding it in an error. - assert!(input.len() >= AeadAes128Gcm::TAG_LEN); - - let nonce = - Nonce::try_assume_unique_for_key(iv).map_err(|e| CryptoError::Other(format!("Invalid nonce: {}", e)))?; - - // Concatenate AAD slices if needed - let aad_data: Vec; - let aad = if aads.len() == 1 { - Aad::from(aads[0]) - } else { - aad_data = aads.concat(); - Aad::from(aad_data.as_slice()) - }; - - let ct_len = input.len() - AeadAes128Gcm::TAG_LEN; - let (ciphertext, tag) = input.split_at(ct_len); - self.key - .open_separate_gather(nonce, aad, ciphertext, tag, &mut output[..ct_len]) - .map_err(|e| CryptoError::Other(format!("AES-GCM decrypt failed: {}", e)))?; - - Ok(ct_len) - } -} - -// ============================================================================ -// AEAD-AES-256-GCM Cipher -// ============================================================================ - -struct AwsLcRsAeadAes256GcmCipher { - key: LessSafeKey, -} - -impl std::fmt::Debug for AwsLcRsAeadAes256GcmCipher { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("AwsLcRsAeadAes256GcmCipher").finish() - } -} - -impl AeadAes256GcmCipher for AwsLcRsAeadAes256GcmCipher { - fn encrypt( - &mut self, - iv: &[u8; AeadAes256Gcm::IV_LEN], - aad: &[u8], - input: &[u8], - output: &mut [u8], - ) -> Result<(), CryptoError> { - assert!(aad.len() >= 12, "Associated data length MUST be at least 12 octets"); - - let nonce = - Nonce::try_assume_unique_for_key(iv).map_err(|e| CryptoError::Other(format!("Invalid nonce: {}", e)))?; - - let len = input.len(); - output[..len].copy_from_slice(input); - let tag = self - .key - .seal_in_place_separate_tag(nonce, Aad::from(aad), &mut output[..len]) - .map_err(|e| CryptoError::Other(format!("AES-GCM encrypt failed: {}", e)))?; - - // Copy the result tag to the output - output[len..len + AeadAes256Gcm::TAG_LEN].copy_from_slice(tag.as_ref()); - Ok(()) - } - - fn decrypt( - &mut self, - iv: &[u8; AeadAes256Gcm::IV_LEN], - aads: &[&[u8]], - input: &[u8], - output: &mut [u8], - ) -> Result { - // Caller contract: `SrtpContext::unprotect_rtp` and `unprotect_rtcp` guarantee - // the input holds at least the auth tag. A shorter buffer is a bug in str0m, - // not bad input, so fail fast rather than hiding it in an error. - assert!(input.len() >= AeadAes256Gcm::TAG_LEN); - - let nonce = - Nonce::try_assume_unique_for_key(iv).map_err(|e| CryptoError::Other(format!("Invalid nonce: {}", e)))?; - - // Concatenate AAD slices if needed - let aad_data: Vec; - let aad = if aads.len() == 1 { - Aad::from(aads[0]) - } else { - aad_data = aads.concat(); - Aad::from(aad_data.as_slice()) - }; - - let ct_len = input.len() - AeadAes256Gcm::TAG_LEN; - let (ciphertext, tag) = input.split_at(ct_len); - self.key - .open_separate_gather(nonce, aad, ciphertext, tag, &mut output[..ct_len]) - .map_err(|e| CryptoError::Other(format!("AES-GCM decrypt failed: {}", e)))?; - - Ok(ct_len) - } -} - -// ============================================================================ -// SRTP Profile Support Implementations -// ============================================================================ - -struct AwsLcRsSupportedAes128CmSha1_80; - -impl std::fmt::Debug for AwsLcRsSupportedAes128CmSha1_80 { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("AwsLcRsSupportedAes128CmSha1_80").finish() - } -} - -impl SupportedAes128CmSha1_80 for AwsLcRsSupportedAes128CmSha1_80 { - fn create_cipher(&self, key: [u8; 16], _encrypt: bool) -> Box { - Box::new(AwsLcRsAes128CmSha1_80Cipher { key }) - } -} - -struct AwsLcRsSupportedAeadAes128Gcm; - -impl std::fmt::Debug for AwsLcRsSupportedAeadAes128Gcm { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("AwsLcRsSupportedAeadAes128Gcm").finish() - } -} - -impl SupportedAeadAes128Gcm for AwsLcRsSupportedAeadAes128Gcm { - fn create_cipher(&self, key: [u8; 16], _encrypt: bool) -> Box { - let unbound_key = UnboundKey::new(&AES_128_GCM, &key).expect("valid AES-128-GCM key"); - let less_safe_key = LessSafeKey::new(unbound_key); - - Box::new(AwsLcRsAeadAes128GcmCipher { key: less_safe_key }) - } -} - -struct AwsLcRsSupportedAeadAes256Gcm; - -impl std::fmt::Debug for AwsLcRsSupportedAeadAes256Gcm { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("AwsLcRsSupportedAeadAes256Gcm").finish() - } -} - -impl SupportedAeadAes256Gcm for AwsLcRsSupportedAeadAes256Gcm { - fn create_cipher(&self, key: [u8; 32], _encrypt: bool) -> Box { - let unbound_key = UnboundKey::new(&AES_256_GCM, &key).expect("valid AES-256-GCM key"); - let less_safe_key = LessSafeKey::new(unbound_key); - - Box::new(AwsLcRsAeadAes256GcmCipher { key: less_safe_key }) - } -} - -// ============================================================================ -// SRTP Provider Implementation -// ============================================================================ - -pub(super) struct AwsLcRsSrtpProvider; - -impl std::fmt::Debug for AwsLcRsSrtpProvider { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("AwsLcRsSrtpProvider").finish() - } -} - -impl SrtpProvider for AwsLcRsSrtpProvider { - fn aes_128_cm_sha1_80(&self) -> &'static dyn SupportedAes128CmSha1_80 { - &AwsLcRsSupportedAes128CmSha1_80 - } - - fn aead_aes_128_gcm(&self) -> &'static dyn SupportedAeadAes128Gcm { - &AwsLcRsSupportedAeadAes128Gcm - } - - fn aead_aes_256_gcm(&self) -> &'static dyn SupportedAeadAes256Gcm { - &AwsLcRsSupportedAeadAes256Gcm - } - - fn srtp_aes_128_ecb_round(&self, key: &[u8], input: &[u8], output: &mut [u8]) { - use aws_lc_rs::cipher::{AES_128, EncryptingKey, EncryptionContext, UnboundCipherKey}; - - let unbound_key = UnboundCipherKey::new(&AES_128, key).expect("valid key"); - let encrypting_key = EncryptingKey::ecb(unbound_key).expect("ECB mode"); - - // Copy input to output buffer for in-place encryption - output[..input.len()].copy_from_slice(input); - - // ECB mode uses EncryptionContext::None - let _decryption_context = encrypting_key - .less_safe_encrypt(&mut output[..input.len()], EncryptionContext::None) - .expect("AES-128-ECB encryption"); - - // The less_safe_encrypt returns a DecryptionContext which includes the padding info - // For ECB with PKCS7 padding, 16 bytes input becomes 32 bytes output - } - - fn srtp_aes_256_ecb_round(&self, key: &[u8], input: &[u8], output: &mut [u8]) { - use aws_lc_rs::cipher::{AES_256, EncryptingKey, EncryptionContext, UnboundCipherKey}; - - let unbound_key = UnboundCipherKey::new(&AES_256, key).expect("valid key"); - let encrypting_key = EncryptingKey::ecb(unbound_key).expect("ECB mode"); - - // Copy input to output buffer for in-place encryption - output[..input.len()].copy_from_slice(input); - - // ECB mode uses EncryptionContext::None - let _decryption_context = encrypting_key - .less_safe_encrypt(&mut output[..input.len()], EncryptionContext::None) - .expect("AES-256-ECB encryption"); - - // The less_safe_encrypt returns a DecryptionContext which includes the padding info - // For ECB with PKCS7 padding, 16 bytes input becomes 32 bytes output - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m_rind/dtls.rs b/rs/moq-webrtc/src/vendor/str0m_rind/dtls.rs new file mode 100644 index 00000000000..32c1fec62d8 --- /dev/null +++ b/rs/moq-webrtc/src/vendor/str0m_rind/dtls.rs @@ -0,0 +1,106 @@ +use std::sync::Arc; +use std::time::Instant; + +use crate::vendor::dimpl; +use crate::vendor::str0m_proto::crypto::CryptoError; +use crate::vendor::str0m_proto::crypto::dtls::{ + DtlsCert, DtlsImplError, DtlsInstance, DtlsOutput, DtlsProvider, ProtocolVersion, +}; + +pub(super) static DTLS: RindDtls = RindDtls; + +#[derive(Debug)] +pub(super) struct RindDtls; + +impl DtlsProvider for RindDtls { + fn generate_certificate(&self) -> Option { + // Only a failing system random source fails it, on which str0m panics. + dimpl::certificate::generate_self_signed_certificate().ok() + } + + fn new_dtls( + &self, + cert: &DtlsCert, + now: Instant, + mtu: Option, + ) -> Result, CryptoError> { + let provider = dimpl::crypto::rind::default_provider().map_err(|e| CryptoError::Other(e.to_string()))?; + + // dimpl panics on an empty certificate or a key it cannot load, and + // `RtcConfig::set_dtls_cert` takes both from the caller. + if cert.certificate.is_empty() { + return Err(CryptoError::Other("empty DTLS certificate".into())); + } + provider + .key_provider + .load_private_key(&cert.private_key) + .map_err(|e| CryptoError::Other(format!("DTLS private key: {e}")))?; + + // ICE checks return routability before DTLS starts, so a server cookie + // adds a round trip without protecting anything. + let mut builder = dimpl::Config::builder() + .with_crypto_provider(provider) + .use_server_cookie(false); + if let Some(mtu) = mtu { + builder = builder.mtu(mtu); + } + if self.is_test() { + // Deterministic handshakes for the stack's own tests. + builder = builder.dangerously_set_rng_seed(42); + } + let config = Arc::new(builder.build().map_err(|e| CryptoError::Other(e.to_string()))?); + + Ok(Box::new(Dtls(dimpl::Dtls::new_12(config, cert.clone(), now)))) + } +} + +/// A dimpl connection, forwarded as is. +struct Dtls(dimpl::Dtls); + +impl std::fmt::Debug for Dtls { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Dtls").finish_non_exhaustive() + } +} + +impl DtlsInstance for Dtls { + fn set_active(&mut self, active: bool) { + self.0.set_active(active); + } + + fn handle_packet(&mut self, packet: &[u8]) -> Result<(), DtlsImplError> { + self.0.handle_packet(packet) + } + + fn poll_output<'a>(&mut self, buf: &'a mut [u8]) -> DtlsOutput<'a> { + self.0.poll_output(buf) + } + + fn handle_timeout(&mut self, now: Instant) -> Result<(), DtlsImplError> { + self.0.handle_timeout(now) + } + + fn send_application_data(&mut self, data: &[u8]) -> Result { + self.0.send_application_data(data) + } + + fn is_active(&self) -> bool { + self.0.is_active() + } + + fn protocol_version(&self) -> Option { + self.0.protocol_version() + } + + fn is_closing(&self) -> bool { + self.0.is_closing() + } + + fn is_closed(&self) -> bool { + self.0.is_closed() + } + + fn close(&mut self) -> Result<(), DtlsImplError> { + self.0.close() + } +} diff --git a/rs/moq-webrtc/src/vendor/str0m_rind/hash.rs b/rs/moq-webrtc/src/vendor/str0m_rind/hash.rs new file mode 100644 index 00000000000..554cb3353ad --- /dev/null +++ b/rs/moq-webrtc/src/vendor/str0m_rind/hash.rs @@ -0,0 +1,39 @@ +use rind::{digest, hmac}; + +use crate::vendor::str0m_proto::crypto::{Sha1HmacProvider, Sha1Provider, Sha256Provider}; + +pub(super) static SHA1_HMAC: RindSha1Hmac = RindSha1Hmac; +pub(super) static SHA1: RindSha1 = RindSha1; +pub(super) static SHA256: RindSha256 = RindSha256; + +#[derive(Debug)] +pub(super) struct RindSha1Hmac; + +impl Sha1HmacProvider for RindSha1Hmac { + fn sha1_hmac(&self, key: &[u8], payloads: &[&[u8]]) -> [u8; 20] { + let key = hmac::Key::new(&hmac::legacy::HMAC_SHA1, key); + let mut ctx = hmac::Context::with_key(&key); + for payload in payloads { + ctx.update(payload); + } + ctx.sign().as_ref().try_into().unwrap() + } +} + +#[derive(Debug)] +pub(super) struct RindSha1; + +impl Sha1Provider for RindSha1 { + fn sha1(&self, data: &[u8]) -> [u8; 20] { + digest::digest(&digest::legacy::SHA1, data).as_ref().try_into().unwrap() + } +} + +#[derive(Debug)] +pub(super) struct RindSha256; + +impl Sha256Provider for RindSha256 { + fn sha256(&self, data: &[u8]) -> [u8; 32] { + digest::digest(&digest::SHA256, data).as_ref().try_into().unwrap() + } +} diff --git a/rs/moq-webrtc/src/vendor/str0m_rind/lib.rs b/rs/moq-webrtc/src/vendor/str0m_rind/lib.rs new file mode 100644 index 00000000000..297d0240cbb --- /dev/null +++ b/rs/moq-webrtc/src/vendor/str0m_rind/lib.rs @@ -0,0 +1,28 @@ +//! rind's cryptographic provider for str0m. +//! +//! Ported from moq-dev/rind's `rind-str0m`, trimmed to DTLS 1.2, with its DTLS +//! on dimpl's rind provider. + +mod dtls; +mod hash; +mod srtp; + +use crate::vendor::str0m_proto::crypto::CryptoProvider; + +/// Returns a str0m [`CryptoProvider`] backed by rind, or the CPU feature rind +/// requires that this CPU lacks. +/// +/// It protects SRTP with AES-128-CM-HMAC-SHA1-80, AEAD-AES-128-GCM, and +/// AEAD-AES-256-GCM, signs STUN with HMAC-SHA1, hashes certificate +/// fingerprints with SHA-1 and SHA-256, and runs DTLS 1.2 through dimpl with a +/// self-signed ECDSA P-256 certificate. +pub fn default_provider() -> Result { + rind::cpu::check()?; + Ok(CryptoProvider { + srtp_provider: &srtp::SRTP, + sha1_hmac_provider: &hash::SHA1_HMAC, + sha1_provider: &hash::SHA1, + sha256_provider: &hash::SHA256, + dtls_provider: &dtls::DTLS, + }) +} diff --git a/rs/moq-webrtc/src/vendor/str0m_rind/srtp.rs b/rs/moq-webrtc/src/vendor/str0m_rind/srtp.rs new file mode 100644 index 00000000000..ef74709c625 --- /dev/null +++ b/rs/moq-webrtc/src/vendor/str0m_rind/srtp.rs @@ -0,0 +1,202 @@ +use std::fmt; + +use rind::aead::{self, Nonce, Tag}; +use rind::cipher::{self, Aes, AesCtr}; + +use crate::vendor::str0m_proto::crypto::{ + AeadAes128GcmCipher, AeadAes256GcmCipher, Aes128CmSha1_80Cipher, CryptoError, SrtpProvider, SupportedAeadAes128Gcm, + SupportedAeadAes256Gcm, SupportedAes128CmSha1_80, +}; + +const TAG_LEN: usize = 16; + +pub(super) static SRTP: RindSrtp = RindSrtp; + +#[derive(Debug)] +pub(super) struct RindSrtp; + +impl SrtpProvider for RindSrtp { + fn aes_128_cm_sha1_80(&self) -> &'static dyn SupportedAes128CmSha1_80 { + &RindSrtp + } + + fn aead_aes_128_gcm(&self) -> &'static dyn SupportedAeadAes128Gcm { + &RindSrtp + } + + fn aead_aes_256_gcm(&self) -> &'static dyn SupportedAeadAes256Gcm { + &RindSrtp + } + + /// Encrypts one SRTP key derivation block. + /// + /// Panics unless `key` is 16 bytes, `input` 16, and `output` at least 16: + /// the trait returns `()`, so there is no error to report. + fn srtp_aes_128_ecb_round(&self, key: &[u8], input: &[u8], output: &mut [u8]) { + ecb_round(&cipher::AES_128, key, input, output); + } + + /// Encrypts one SRTP key derivation block. + /// + /// Panics unless `key` is 32 bytes, `input` 16, and `output` at least 16: + /// the trait returns `()`, so there is no error to report. + fn srtp_aes_256_ecb_round(&self, key: &[u8], input: &[u8], output: &mut [u8]) { + ecb_round(&cipher::AES_256, key, input, output); + } +} + +// str0m sizes these from fixed arrays, never from a packet, so a mismatch is a +// str0m bug worth a panic. +fn ecb_round(algorithm: &'static cipher::Algorithm, key: &[u8], input: &[u8], output: &mut [u8]) { + let aes = Aes::new(algorithm, key).expect("SRTP master key length"); + let mut block: [u8; 16] = input.try_into().expect("SRTP key derivation block"); + aes.encrypt_block(&mut block); + output[..16].copy_from_slice(&block); +} + +impl SupportedAes128CmSha1_80 for RindSrtp { + fn create_cipher(&self, key: [u8; 16], _encrypt: bool) -> Box { + Box::new(Cm(AesCtr::new(&cipher::AES_128, &key).unwrap())) + } +} + +impl SupportedAeadAes128Gcm for RindSrtp { + fn create_cipher(&self, key: [u8; 16], _encrypt: bool) -> Box { + Box::new(Gcm::new(&aead::AES_128_GCM, &key)) + } +} + +impl SupportedAeadAes256Gcm for RindSrtp { + fn create_cipher(&self, key: [u8; 32], _encrypt: bool) -> Box { + Box::new(Gcm::new(&aead::AES_256_GCM, &key)) + } +} + +/// AES counter mode, keyed for one SRTP or SRTCP direction. +struct Cm(AesCtr); + +impl fmt::Debug for Cm { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Cm").finish_non_exhaustive() + } +} + +impl Cm { + fn apply(&self, iv: &[u8; 16], input: &[u8], output: &mut [u8]) -> Result<(), CryptoError> { + let output = output + .get_mut(..input.len()) + .ok_or_else(|| CryptoError::Other("AES-CM output too short".into()))?; + output.copy_from_slice(input); + + // SRTP's 128-bit counter block splits into rind's 96-bit nonce and + // 32-bit counter. str0m's IVs leave the low 16 bits zero, so a packet + // never carries past the counter; one that would is refused. + let (nonce, counter) = iv.split_first_chunk::<12>().unwrap(); + let counter = u32::from_be_bytes(counter.try_into().unwrap()); + self.0 + .apply_keystream(nonce, counter, output) + .map_err(|e| CryptoError::Other(format!("AES-CM failed: {e:?}"))) + } +} + +impl Aes128CmSha1_80Cipher for Cm { + fn encrypt(&mut self, iv: &[u8; 16], input: &[u8], output: &mut [u8]) -> Result<(), CryptoError> { + self.apply(iv, input, output) + } + + fn decrypt(&mut self, iv: &[u8; 16], input: &[u8], output: &mut [u8]) -> Result<(), CryptoError> { + self.apply(iv, input, output) + } +} + +/// AES-GCM, keyed for one SRTP or SRTCP direction. +struct Gcm(aead::Key); + +impl fmt::Debug for Gcm { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Gcm").finish_non_exhaustive() + } +} + +impl Gcm { + /// str0m passes the profile's key length. + fn new(algorithm: &'static aead::Algorithm, key: &[u8]) -> Self { + Self(aead::Key::new(algorithm, key).unwrap()) + } + + /// Writes the ciphertext then the tag into `output`. + fn seal(&self, iv: &[u8; 12], aad: &[u8], input: &[u8], output: &mut [u8]) -> Result<(), CryptoError> { + let output = output + .get_mut(..input.len() + TAG_LEN) + .ok_or_else(|| CryptoError::Other("AES-GCM output too short".into()))?; + let (ciphertext, tag_out) = output.split_at_mut(input.len()); + ciphertext.copy_from_slice(input); + let tag = self + .0 + .seal_in_place_separate_tag(Nonce::assume_unique_for_key(*iv), aad, ciphertext) + .map_err(|e| CryptoError::Other(format!("AES-GCM failed: {e:?}")))?; + tag_out.copy_from_slice(tag.as_ref()); + Ok(()) + } + + /// Opens `input`, the ciphertext then the tag, and returns the plaintext length. + fn open(&self, iv: &[u8; 12], aads: &[&[u8]], input: &[u8], output: &mut [u8]) -> Result { + let ciphertext_len = input + .len() + .checked_sub(TAG_LEN) + .ok_or_else(|| CryptoError::Other("AES-GCM input shorter than its tag".into()))?; + let (ciphertext, tag) = input.split_at(ciphertext_len); + let tag = Tag::try_from(tag).expect("split at the tag length"); + let plaintext = output + .get_mut(..ciphertext.len()) + .ok_or_else(|| CryptoError::Other("AES-GCM output too short".into()))?; + plaintext.copy_from_slice(ciphertext); + + // str0m splits the AAD only for unencrypted SRTCP. + let joined; + let aad = match aads { + [aad] => aad, + _ => { + joined = aads.concat(); + joined.as_slice() + } + }; + + self.0 + .open_in_place_separate_tag(Nonce::assume_unique_for_key(*iv), aad, tag, plaintext) + .map_err(|e| CryptoError::Other(format!("AES-GCM failed: {e:?}")))?; + Ok(ciphertext.len()) + } +} + +impl AeadAes128GcmCipher for Gcm { + fn encrypt(&mut self, iv: &[u8; 12], aad: &[u8], input: &[u8], output: &mut [u8]) -> Result<(), CryptoError> { + self.seal(iv, aad, input, output) + } + + fn decrypt( + &mut self, + iv: &[u8; 12], + aads: &[&[u8]], + input: &[u8], + output: &mut [u8], + ) -> Result { + self.open(iv, aads, input, output) + } +} + +impl AeadAes256GcmCipher for Gcm { + fn encrypt(&mut self, iv: &[u8; 12], aad: &[u8], input: &[u8], output: &mut [u8]) -> Result<(), CryptoError> { + self.seal(iv, aad, input, output) + } + + fn decrypt( + &mut self, + iv: &[u8; 12], + aads: &[&[u8]], + input: &[u8], + output: &mut [u8], + ) -> Result { + self.open(iv, aads, input, output) + } +} diff --git a/rs/workspace-hack/Cargo.toml b/rs/workspace-hack/Cargo.toml index f5e4680c1e9..838cb68d234 100644 --- a/rs/workspace-hack/Cargo.toml +++ b/rs/workspace-hack/Cargo.toml @@ -26,9 +26,9 @@ publish = false [dependencies] anyhow = { version = "1", features = ["backtrace"] } aws-lc-rs = { version = "1" } -base16ct = { version = "1", default-features = false, features = ["alloc"] } base64-2b5c6dc72f624058 = { package = "base64", version = "0.23" } base64-3c51e837cfc5589a = { package = "base64", version = "0.22" } +base64ct = { version = "1", default-features = false, features = ["alloc"] } bytemuck = { version = "1", default-features = false, features = ["derive", "extern_crate_alloc", "min_const_generics"] } byteorder = { version = "1" } bytes = { version = "1", features = ["serde"] } @@ -89,13 +89,12 @@ ppv-lite86 = { version = "0.2", default-features = false, features = ["simd", "s proptest = { version = "1", default-features = false, features = ["handle-panics"] } 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"] } +rcgen = { version = "0.14", default-features = false, features = ["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", default-features = false, features = ["std", "tls12"] } rustls-pki-types = { version = "1", features = ["std"] } -sec1 = { version = "0.8", features = ["ctutils", "pem", "std", "subtle"] } semver = { version = "1", features = ["serde"] } serde = { version = "1", features = ["alloc", "derive", "rc"] } serde_core = { version = "1", features = ["alloc", "rc"] } @@ -135,9 +134,9 @@ zeroize = { version = "1", features = ["derive"] } [build-dependencies] anyhow = { version = "1", features = ["backtrace"] } aws-lc-rs = { version = "1" } -base16ct = { version = "1", default-features = false, features = ["alloc"] } base64-2b5c6dc72f624058 = { package = "base64", version = "0.23" } base64-3c51e837cfc5589a = { package = "base64", version = "0.22" } +base64ct = { version = "1", default-features = false, features = ["alloc"] } bytemuck = { version = "1", default-features = false, features = ["derive", "extern_crate_alloc", "min_const_generics"] } byteorder = { version = "1" } bytes = { version = "1", features = ["serde"] } @@ -203,13 +202,12 @@ proptest = { version = "1", default-features = false, features = ["handle-panics quote = { version = "1" } 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"] } +rcgen = { version = "0.14", default-features = false, features = ["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", default-features = false, features = ["std", "tls12"] } rustls-pki-types = { version = "1", features = ["std"] } -sec1 = { version = "0.8", features = ["ctutils", "pem", "std", "subtle"] } semver = { version = "1", features = ["serde"] } serde = { version = "1", features = ["alloc", "derive", "rc"] } serde_core = { version = "1", features = ["alloc", "rc"] }