From 0e78651557ba3c49cf3ff84f63b7ef14fb6d2f8e Mon Sep 17 00:00:00 2001 From: Matt McGill Date: Thu, 3 Dec 2026 13:15:34 -0500 Subject: [PATCH] feat: add TLS support for X25519MLKEM768 Compile aws-lc-rs into the binary alongside ring, which remains the default. Set EDGE_RUNTIME_TLS_CRYPTO_PROVIDER=aws-lc-rs to globally register aws-lc-rs with X25519MLKEM768 as the prefered key exchange group. Addresses #791. --- Cargo.lock | 71 +++++++- Cargo.toml | 2 +- cli/src/env.rs | 24 +++ cli/src/main.rs | 4 + crates/base/src/runtime/mod.rs | 5 + crates/base/src/utils/mod.rs | 1 + crates/base/src/utils/tls.rs | 130 ++++++++++++++ .../base/test_cases/tls-key-exchange/index.ts | 17 ++ .../base/tests/tls_crypto_provider_tests.rs | 162 ++++++++++++++++++ 9 files changed, 407 insertions(+), 9 deletions(-) create mode 100644 crates/base/src/utils/tls.rs create mode 100644 crates/base/test_cases/tls-key-exchange/index.ts create mode 100644 crates/base/tests/tls_crypto_provider_tests.rs diff --git a/Cargo.lock b/Cargo.lock index 492f5128..7d8c2606 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -435,6 +435,29 @@ dependencies = [ "zeroize", ] +[[package]] +name = "aws-lc-rs" +version = "1.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce2b2dcc879c3bae0d371e77c99f2238400ef24ec001394befa67b6e543add9e" +dependencies = [ + "aws-lc-sys", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f09fae7be8bb3174e05c6afdb34199e6dc0c7c04ba9fa237b1967adfbde27483" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + [[package]] name = "aws-runtime" version = "1.4.3" @@ -1322,10 +1345,13 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.16" +version = "1.2.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be714c154be609ec7f5dad223a33bf1482fff90472de28f7362806e6d4832b8c" +checksum = "ac9fe6cdbb24b6ade63616c0a0688e45bb56732262c158df3c0c4bea4ca47cb7" dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", "shlex", ] @@ -1475,9 +1501,9 @@ dependencies = [ [[package]] name = "cmake" -version = "0.1.52" +version = "0.1.54" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c682c223677e0e5b6b7f63a64b9351844c3f1b1678a68b7ee617e30fb082620e" +checksum = "e7caa3f9de89ddbe2c607f4101924c5abec803763ae9534e4f4d7d8f84aa81f0" dependencies = [ "cc", ] @@ -2903,6 +2929,12 @@ dependencies = [ "zeroize", ] +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + [[package]] name = "dyn-clone" version = "1.0.16" @@ -3487,6 +3519,12 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "find-msvc-tools" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8" + [[package]] name = "fixedbitset" version = "0.4.2" @@ -3662,6 +3700,12 @@ dependencies = [ "winapi", ] +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + [[package]] name = "fsevent-sys" version = "4.1.0" @@ -4791,6 +4835,15 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130" +[[package]] +name = "jobserver" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48d1dbcbbeb6a7fec7e059840aa538bd62aaccf972c7346c4d9d2059312853d0" +dependencies = [ + "libc", +] + [[package]] name = "js-sys" version = "0.3.69" @@ -6043,9 +6096,9 @@ dependencies = [ [[package]] name = "pkg-config" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec" +checksum = "953ec861398dccce10c670dfeaf3ec4911ca479e9c02154b3a215178c5f566f2" [[package]] name = "png" @@ -6861,6 +6914,7 @@ version = "0.23.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0ebcbd2f03de0fc1122ad9bb24b127a5a6cd51d72604a3f3c50ac459762b6cc" dependencies = [ + "aws-lc-rs", "log", "once_cell", "ring 0.17.14", @@ -6975,6 +7029,7 @@ version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ + "aws-lc-rs", "ring 0.17.14", "rustls-pki-types", "untrusted 0.9.0", @@ -9629,9 +9684,9 @@ dependencies = [ [[package]] name = "zeroize" -version = "1.7.0" +version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "525b4ec142c6b68a2d10f01f7bbf6755599ca3f81ea53b8431b7dd348f5fdb2d" +checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde" dependencies = [ "zeroize_derive", ] diff --git a/Cargo.toml b/Cargo.toml index c701326f..ce778c96 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -163,7 +163,7 @@ regex = "^1.7.0" reqwest = { version = "0.12.5", default-features = false, features = ["rustls-tls", "stream", "gzip", "brotli", "socks", "json", "http2"] } # pinned because of https://github.com/seanmonstar/reqwest/pull/1955 reqwest_v011 = { package = "reqwest", version = "0.11", features = ["stream", "json", "multipart"] } ring = "^0.17.14" -rustls = { version = "0.23.31", default-features = false, features = ["logging", "std", "tls12", "ring"] } +rustls = { version = "0.23.31", default-features = false, features = ["logging", "std", "tls12", "ring", "aws_lc_rs", "prefer-post-quantum"] } rustls-pemfile = "2" rustls-tokio-stream = "=0.3.0" rustls-webpki = "0.103.16" diff --git a/cli/src/env.rs b/cli/src/env.rs index 6ac67264..1854a8b8 100644 --- a/cli/src/env.rs +++ b/cli/src/env.rs @@ -1,4 +1,7 @@ +use anyhow::bail; +use anyhow::Context; use base::runtime; +use base::utils::tls::CryptoProviderKind; use clap::builder::BoolishValueParser; use clap::builder::TypedValueParser; use clap::value_parser; @@ -68,3 +71,24 @@ pub(super) fn resolve_deno_runtime_env() { &runtime::EVENT_WORKER_MAX_HEAP_SIZE_MIB, ); } + +const TLS_CRYPTO_PROVIDER_ENV: &str = "EDGE_RUNTIME_TLS_CRYPTO_PROVIDER"; + +/// rustls has both ring and aws-lc-rs compiled in, so the process-wide +/// provider must be chosen before anything builds a TLS config. Unset or empty +/// means ring. +pub(super) fn install_tls_crypto_provider() -> anyhow::Result +{ + let kind = match std::env::var_os(TLS_CRYPTO_PROVIDER_ENV) { + None => CryptoProviderKind::default(), + Some(value) => match value.to_str() { + Some("") => CryptoProviderKind::default(), + Some(value) => value + .parse() + .with_context(|| format!("can't parse {TLS_CRYPTO_PROVIDER_ENV}"))?, + None => bail!("{TLS_CRYPTO_PROVIDER_ENV} is not valid UTF-8"), + }, + }; + let _ = kind.install_default(); + Ok(kind) +} diff --git a/cli/src/main.rs b/cli/src/main.rs index d561cd0d..35819f38 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -30,6 +30,7 @@ use deno_facade::extract_from_file; use deno_facade::generate_binary_eszip; use deno_facade::EmitterFactory; use deno_facade::Metadata; +use env::install_tls_crypto_provider; use env::resolve_deno_runtime_env; use flags::get_cli; use flags::EszipV2ChecksumKind; @@ -83,6 +84,9 @@ fn main() -> Result { } } + let tls_crypto_provider = install_tls_crypto_provider()?; + log::debug!("TLS crypto provider: {tls_crypto_provider}"); + #[allow(clippy::single_match)] #[allow(clippy::arc_with_non_send_sync)] let exit_code = match matches.subcommand() { diff --git a/crates/base/src/runtime/mod.rs b/crates/base/src/runtime/mod.rs index 0cf2d01e..8ff9b3bc 100644 --- a/crates/base/src/runtime/mod.rs +++ b/crates/base/src/runtime/mod.rs @@ -118,6 +118,7 @@ use tracing::Span; use crate::inspector_server::Inspector; use crate::snapshot; use crate::utils::json; +use crate::utils::tls::ensure_default_crypto_provider; use crate::utils::units::bytes_to_display; use crate::utils::units::mib_to_bytes; use crate::utils::units::percentage_value; @@ -441,6 +442,10 @@ where #[allow(clippy::unnecessary_literal_unwrap)] #[allow(clippy::arc_with_non_send_sync)] pub(crate) async fn new(mut worker: Worker) -> Result { + // Everything that builds a rustls config (fetch, `Deno.connectTls`, + // `Deno.listenTls`, module downloads) runs inside a runtime. + ensure_default_crypto_provider(); + let init_opts = worker.init_opts.take(); let flags = worker.flags.clone(); let event_metadata = worker.event_metadata.clone(); diff --git a/crates/base/src/utils/mod.rs b/crates/base/src/utils/mod.rs index a2578dbb..78a93499 100644 --- a/crates/base/src/utils/mod.rs +++ b/crates/base/src/utils/mod.rs @@ -1,4 +1,5 @@ pub mod dirs; pub mod json; pub mod test_utils; +pub mod tls; pub mod units; diff --git a/crates/base/src/utils/tls.rs b/crates/base/src/utils/tls.rs new file mode 100644 index 00000000..eca2b141 --- /dev/null +++ b/crates/base/src/utils/tls.rs @@ -0,0 +1,130 @@ +use std::fmt; +use std::str::FromStr; +use std::sync::Arc; + +use deno::deno_tls::rustls; +use rustls::crypto::CryptoProvider; + +/// The rustls crypto provider: the backend for key exchange, cipher suites +/// and certificate signature verification on every TLS connection configured +/// through rustls 0.23 in this process. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum CryptoProviderKind { + /// Classical key exchange only (X25519, P-256, P-384). This is what every + /// build before aws-lc-rs was added used. + #[default] + Ring, + /// Offers hybrid post-quantum X25519MLKEM768 first, then the classical + /// groups. + AwsLcRs, +} + +#[derive(Debug, thiserror::Error)] +#[error( + "invalid TLS crypto provider {0:?}: expected \"ring\" or \"aws-lc-rs\"" +)] +pub struct InvalidCryptoProvider(String); + +impl CryptoProviderKind { + pub fn provider(self) -> CryptoProvider { + match self { + Self::Ring => rustls::crypto::ring::default_provider(), + Self::AwsLcRs => rustls::crypto::aws_lc_rs::default_provider(), + } + } + + /// Installs this provider as the process-wide default. Fails, returning the + /// installed one, if a default was already installed. + pub fn install_default(self) -> Result<(), Arc> { + self.provider().install_default() + } +} + +impl FromStr for CryptoProviderKind { + type Err = InvalidCryptoProvider; + + fn from_str(s: &str) -> Result { + match s.to_ascii_lowercase().as_str() { + "ring" => Ok(Self::Ring), + "aws-lc-rs" | "aws_lc_rs" => Ok(Self::AwsLcRs), + _ => Err(InvalidCryptoProvider(s.into())), + } + } +} + +impl fmt::Display for CryptoProviderKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::Ring => "ring", + Self::AwsLcRs => "aws-lc-rs", + }) + } +} + +/// rustls is built with both ring (which rustls-tokio-stream and reqwest +/// require) and aws-lc-rs, so it can't choose a default provider on its own, +/// and `ClientConfig::builder()` / `ServerConfig::builder()` panic until one +/// is installed. The CLI installs the one its configuration names at startup; +/// this is the fallback for embedders that don't install one themselves. +pub fn ensure_default_crypto_provider() { + if CryptoProvider::get_default().is_none() { + // Losing a race to another installer is fine. + let _ = CryptoProviderKind::default().install_default(); + } +} + +#[cfg(test)] +mod tests { + use rustls::NamedGroup; + + use super::*; + + fn kx_group_names(kind: CryptoProviderKind) -> Vec { + kind.provider().kx_groups.iter().map(|g| g.name()).collect() + } + + #[test] + fn parses_provider_names() { + assert_eq!( + "ring".parse::().unwrap(), + CryptoProviderKind::Ring + ); + assert_eq!( + "aws-lc-rs".parse::().unwrap(), + CryptoProviderKind::AwsLcRs + ); + assert_eq!( + "AWS_LC_RS".parse::().unwrap(), + CryptoProviderKind::AwsLcRs + ); + assert!("openssl".parse::().is_err()); + } + + #[test] + fn ring_offers_only_classical_groups() { + assert_eq!( + kx_group_names(CryptoProviderKind::Ring), + [ + NamedGroup::X25519, + NamedGroup::secp256r1, + NamedGroup::secp384r1 + ] + ); + } + + #[test] + fn aws_lc_rs_prefers_hybrid_post_quantum() { + // The client only sends a key share for the first group (plus X25519 when + // that group is a hybrid), so X25519MLKEM768 has to come first or servers + // will settle on classical X25519. + assert_eq!( + kx_group_names(CryptoProviderKind::AwsLcRs), + [ + NamedGroup::X25519MLKEM768, + NamedGroup::X25519, + NamedGroup::secp256r1, + NamedGroup::secp384r1, + ] + ); + } +} diff --git a/crates/base/test_cases/tls-key-exchange/index.ts b/crates/base/test_cases/tls-key-exchange/index.ts new file mode 100644 index 00000000..f92cb0ef --- /dev/null +++ b/crates/base/test_cases/tls-key-exchange/index.ts @@ -0,0 +1,17 @@ +// Fetches https://localhost:, trusting the CA certificate sent as the +// request body, and relays the response text (or the error with a 500). +export default { + async fetch(req: Request) { + const port = req.headers.get("x-port"); + const client = Deno.createHttpClient({ caCerts: [await req.text()] }); + + try { + const resp = await fetch(`https://localhost:${port}`, { client }); + return new Response(await resp.text(), { status: resp.status }); + } catch (err) { + return new Response(String(err), { status: 500 }); + } finally { + client.close(); + } + }, +}; diff --git a/crates/base/tests/tls_crypto_provider_tests.rs b/crates/base/tests/tls_crypto_provider_tests.rs new file mode 100644 index 00000000..6462577b --- /dev/null +++ b/crates/base/tests/tls_crypto_provider_tests.rs @@ -0,0 +1,162 @@ +//! The rustls crypto provider is process-wide and can only be installed once, +//! so these tests live in their own binary, apart from `integration_tests` +//! (which runs with the default, ring). + +use std::io::BufReader; +use std::io::Read; +use std::io::Write; +use std::net::TcpListener; +use std::net::TcpStream; +use std::sync::Arc; +use std::time::Duration; + +use anyhow::Context; +use base::utils::test_utils::TestBedBuilder; +use base::utils::tls::CryptoProviderKind; +use deno::deno_tls::rustls; +use http_v02::StatusCode; +use hyper_v014::body::to_bytes; +use hyper_v014::Body; +use rustls::crypto::aws_lc_rs::kx_group::X25519MLKEM768; +use rustls::crypto::CryptoProvider; +use rustls::pki_types::ServerName; +use rustls::ClientConfig; +use rustls::ClientConnection; +use rustls::RootCertStore; +use rustls::ServerConfig; +use rustls::ServerConnection; +use rustls::StreamOwned; + +const TLS_LOCALHOST_ROOT_CA: &[u8] = + include_bytes!("./fixture/tls/root-ca.pem"); +const TLS_LOCALHOST_CERT: &[u8] = include_bytes!("./fixture/tls/localhost.pem"); +const TLS_LOCALHOST_KEY: &[u8] = + include_bytes!("./fixture/tls/localhost-key.pem"); + +/// Starts a TLS 1.3 server on a background thread that only accepts hybrid +/// post-quantum key exchange and answers each request with the name of the +/// negotiated group. Returns its port. +fn start_post_quantum_only_server() -> u16 { + let certs = rustls_pemfile::certs(&mut BufReader::new(TLS_LOCALHOST_CERT)) + .collect::, _>>() + .unwrap(); + let key = rustls_pemfile::private_key(&mut BufReader::new(TLS_LOCALHOST_KEY)) + .unwrap() + .unwrap(); + let provider = CryptoProvider { + kx_groups: vec![X25519MLKEM768], + ..CryptoProviderKind::AwsLcRs.provider() + }; + let config = Arc::new( + ServerConfig::builder_with_provider(Arc::new(provider)) + .with_protocol_versions(&[&rustls::version::TLS13]) + .unwrap() + .with_no_client_auth() + .with_single_cert(certs, key) + .unwrap(), + ); + + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + + std::thread::spawn(move || { + for sock in listener.incoming().flatten() { + let conn = ServerConnection::new(config.clone()).unwrap(); + let mut tls = StreamOwned::new(conn, sock); + // Clients that can't do X25519MLKEM768 fail the handshake here. + let _ = respond_with_key_exchange_group(&mut tls); + } + }); + + port +} + +fn respond_with_key_exchange_group( + tls: &mut StreamOwned, +) -> std::io::Result<()> { + let mut req = Vec::new(); + let mut buf = [0; 1024]; + while !req.windows(4).any(|w| w == b"\r\n\r\n") { + let n = tls.read(&mut buf)?; + if n == 0 { + return Ok(()); + } + req.extend_from_slice(&buf[..n]); + } + + let group = format!( + "{:?}", + tls.conn.negotiated_key_exchange_group().unwrap().name() + ); + write!( + tls, + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + group.len(), + group + )?; + tls.conn.send_close_notify(); + tls.flush() +} + +#[tokio::test] +async fn fetch_negotiates_hybrid_post_quantum_key_exchange_with_aws_lc_rs() { + CryptoProviderKind::AwsLcRs + .install_default() + .expect("no other test in this binary installs a provider"); + + let port = start_post_quantum_only_server(); + let tb = TestBedBuilder::new("./test_cases/main").build().await; + + let mut res = tb + .request(|b| { + b.uri("/tls-key-exchange") + .method("POST") + .header("x-port", port) + .body(Body::from(TLS_LOCALHOST_ROOT_CA)) + .context("can't make request") + }) + .await + .unwrap(); + + let status = res.status(); + let body = to_bytes(res.body_mut()).await.unwrap(); + assert_eq!(status, StatusCode::OK, "{}", String::from_utf8_lossy(&body)); + assert_eq!(body, "X25519MLKEM768"); + + tb.exit(Duration::from_secs(10)).await; +} + +#[test] +fn ring_cannot_negotiate_with_post_quantum_only_server() { + let port = start_post_quantum_only_server(); + + let mut roots = RootCertStore::empty(); + for cert in rustls_pemfile::certs(&mut BufReader::new(TLS_LOCALHOST_ROOT_CA)) + { + roots.add(cert.unwrap()).unwrap(); + } + let config = ClientConfig::builder_with_provider(Arc::new( + CryptoProviderKind::Ring.provider(), + )) + .with_safe_default_protocol_versions() + .unwrap() + .with_root_certificates(roots) + .with_no_client_auth(); + + let conn = ClientConnection::new( + Arc::new(config), + ServerName::try_from("localhost").unwrap(), + ) + .unwrap(); + let sock = TcpStream::connect(("127.0.0.1", port)).unwrap(); + let mut tls = StreamOwned::new(conn, sock); + + let err = tls + .write_all(b"GET / HTTP/1.1\r\nHost: localhost\r\n\r\n") + .and_then(|_| tls.read_to_end(&mut Vec::new())) + .unwrap_err(); + assert!( + err.to_string().contains("HandshakeFailure"), + "unexpected error: {err}" + ); +}