iroh_live_node/crypto.rs
1//! The rustls crypto provider that iroh and moq share, see [`crypto_provider`].
2
3use std::sync::{Arc, OnceLock};
4
5use iroh::endpoint::{Builder, presets::Preset};
6use rustls::{
7 Side, SupportedCipherSuite,
8 crypto::CryptoProvider,
9 quic::{Keys, Version},
10};
11use tracing::{info, warn};
12
13/// The crypto backends, in the order the selection prefers them.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15enum Backend {
16 Ring,
17 AwsLcRs,
18 Rind,
19}
20
21impl Backend {
22 /// Returns the backend the enabled features select.
23 ///
24 /// ring wins over aws-lc-rs, as in iroh's own presets, so an endpoint
25 /// bound with iroh's `presets::N0` runs on the same backend.
26 const fn selected() -> Self {
27 if cfg!(feature = "crypto-ring") {
28 Self::Ring
29 } else if cfg!(feature = "crypto-aws-lc-rs") {
30 Self::AwsLcRs
31 } else {
32 Self::Rind
33 }
34 }
35
36 /// Returns the backend a provider runs on, if it is one of the three.
37 ///
38 /// Each backend's random source is a unit struct that debug-prints as the
39 /// backend's name.
40 fn of(provider: &CryptoProvider) -> Option<Self> {
41 match format!("{:?}", provider.secure_random).as_str() {
42 "Ring" => Some(Self::Ring),
43 "AwsLcRs" => Some(Self::AwsLcRs),
44 "Rind" => Some(Self::Rind),
45 _ => None,
46 }
47 }
48
49 /// Returns the backend's name, as its feature names it.
50 const fn name(self) -> &'static str {
51 match self {
52 Self::Ring => "ring",
53 Self::AwsLcRs => "aws-lc-rs",
54 Self::Rind => "rind",
55 }
56 }
57
58 /// Installs the backend as the process default, unless one is installed.
59 ///
60 /// Returns whether this call installed it.
61 fn install(self) -> bool {
62 match self {
63 #[cfg(feature = "crypto-ring")]
64 Self::Ring => rustls::crypto::ring::default_provider()
65 .install_default()
66 .is_ok(),
67 #[cfg(feature = "crypto-aws-lc-rs")]
68 Self::AwsLcRs => rustls::crypto::aws_lc_rs::default_provider()
69 .install_default()
70 .is_ok(),
71 // rind, which moq installs by itself if nothing is installed, with
72 // a suite first that iroh's token key can use.
73 _ => {
74 let mut provider = rind_rustls::default_provider();
75 token_key_suite_first(&mut provider);
76 provider.install_default().is_ok()
77 }
78 }
79 }
80}
81
82/// The key length iroh hands the AEAD that seals its QUIC tokens.
83const TOKEN_KEY_LEN: usize = 32;
84
85/// Moves a TLS 1.3 suite with a 32-byte key to the front, unless one is first.
86///
87/// iroh seals and opens its QUIC Retry and address-validation tokens with the
88/// AEAD of the provider's first TLS 1.3 suite, under a 32-byte key. With a
89/// shorter key, as AES-128-GCM has, the AEAD panics on the first token an
90/// endpoint seals or opens. rind lists AES-128-GCM first on CPUs with AES
91/// instructions, ring and aws-lc-rs list AES-256-GCM first. The other suites
92/// keep their order, so AES-128-GCM stays for QUIC's Initial packets.
93///
94/// Returns whether the order changed.
95fn token_key_suite_first(provider: &mut CryptoProvider) -> bool {
96 let key_len =
97 |suite: &SupportedCipherSuite| suite.tls13().map(|tls13| tls13.aead_alg.key_len());
98 let first = provider.cipher_suites.iter().find_map(key_len);
99 if first.is_none_or(|len| len == TOKEN_KEY_LEN) {
100 return false;
101 }
102 let Some(index) = provider
103 .cipher_suites
104 .iter()
105 .position(|suite| key_len(suite) == Some(TOKEN_KEY_LEN))
106 else {
107 return false;
108 };
109 let suite = provider.cipher_suites.remove(index);
110 provider.cipher_suites.insert(0, suite);
111 true
112}
113
114/// Returns whether every QUIC suite of the provider seals packets per path.
115///
116/// iroh's multipath QUIC seals and opens every packet with
117/// `encrypt_in_place_for_path` and `decrypt_in_place_for_path`, which rustls
118/// leaves failing by default. rind-rustls up to 0.23.4 keeps that default.
119fn seals_per_path(provider: &CryptoProvider) -> bool {
120 provider
121 .cipher_suites
122 .iter()
123 .filter_map(|suite| suite.tls13())
124 .filter_map(|suite| suite.quic.map(|quic| (suite, quic)))
125 .all(|(suite, quic)| {
126 let keys = Keys::initial(Version::V1, suite, quic, &[0; 8], Side::Client);
127 let mut payload = [0u8; 16];
128 keys.local
129 .packet
130 .encrypt_in_place_for_path(1, 0, &[0], &mut payload)
131 .is_ok()
132 })
133}
134
135/// Returns the rustls crypto provider for iroh's and moq's TLS.
136///
137/// A cargo feature picks the backend: `crypto-ring`, `crypto-aws-lc-rs`, the
138/// default, or `crypto-rind`. Features are additive, so more than one can be
139/// on in a build. The first of ring, aws-lc-rs and rind that is on wins, in
140/// that order, which is the order iroh's own presets prefer, so `crypto-rind`
141/// takes effect only with default features off. rind is also what a build
142/// gets with none of them on, since moq compiles it in either way. The
143/// default moves to `crypto-rind` once rind-rustls releases per-path QUIC
144/// keys (kixel-ai/rind#1278).
145///
146/// The first call installs the backend as rustls's process default. If the
147/// process installed a provider before, that one stays and is returned
148/// instead, so an application that installs its own provider first runs
149/// iroh-live on it. Every call returns the same `Arc`. Two installs happen
150/// without the application asking for them: moq code that runs first, such
151/// as a hand-built `moq_tokio::client::Config`, installs rind, and rustls's
152/// `ClientConfig::builder()` installs ring when rustls has only its `ring`
153/// feature on, as through reqwest's `rustls-tls`. The first call logs a
154/// warning when the provider it finds is not the selected backend.
155///
156/// iroh seals its QUIC tokens with the first TLS 1.3 suite under a 32-byte
157/// key, so the provider lists such a suite first: rind's AES-256-GCM goes
158/// before its AES-128-GCM. When the provider installed first lists a suite
159/// with a shorter key first, as rind's default does on CPUs with AES
160/// instructions, this returns a reordered copy instead of the process
161/// default, and moq keeps the process default.
162///
163/// [`MoqPreset`](crate::MoqPreset), [`MinimalPreset`] and
164/// [`EndpointConfig`](crate::EndpointConfig) hand it to iroh. moq's QUIC,
165/// WebTransport and media relay configs read the process default when they are
166/// built, and moq installs rind there if nothing is installed yet. Call this
167/// before building a moq config by hand, so the selected backend is
168/// installed before moq installs its fallback. Relay links do so before
169/// they build a moq client.
170///
171/// # Panics
172///
173/// Panics if a QUIC suite of the provider cannot seal packets per path,
174/// which iroh's multipath QUIC needs on every packet. rind-rustls 0.23.4 from
175/// crates.io cannot; the message names the `[patch.crates-io]` block that
176/// fixes it.
177///
178/// # Examples
179///
180/// An application that installs its own provider first runs on it:
181///
182/// ```no_run
183/// # #[cfg(feature = "crypto-ring")]
184/// # {
185/// let _ = rustls::crypto::ring::default_provider().install_default();
186/// let provider = iroh_live_node::crypto_provider();
187/// assert!(std::sync::Arc::ptr_eq(
188/// &provider,
189/// rustls::crypto::CryptoProvider::get_default().unwrap()
190/// ));
191/// # }
192/// ```
193pub fn crypto_provider() -> Arc<CryptoProvider> {
194 static PROVIDER: OnceLock<Arc<CryptoProvider>> = OnceLock::new();
195 PROVIDER
196 .get_or_init(|| {
197 let selected = Backend::selected();
198 let installed = selected.install();
199 let provider = CryptoProvider::get_default()
200 .expect("a crypto provider is installed")
201 .clone();
202 let backend = Backend::of(&provider);
203 if installed {
204 info!(
205 backend = selected.name(),
206 "installed the rustls crypto provider"
207 );
208 } else if backend != Some(selected) {
209 warn!(
210 selected = selected.name(),
211 installed = backend.map_or("unknown", Backend::name),
212 "another rustls crypto provider was installed first, \
213 iroh and moq run on it instead of the selected backend"
214 );
215 }
216 assert!(
217 seals_per_path(&provider),
218 "the rustls crypto provider ({}) cannot seal QUIC packets per \
219 path, which iroh needs. rind-rustls gains this in \
220 kixel-ai/rind#1278: copy the [patch.crates-io] block for rind \
221 and rind-rustls from iroh-live's root Cargo.toml into your \
222 workspace, or turn on crypto-ring or crypto-aws-lc-rs",
223 backend.map_or("unknown", Backend::name),
224 );
225 // A provider installed first, such as rind's default that moq
226 // installs, may list a suite first that iroh's token key cannot
227 // use. rustls keeps the installed one, so iroh gets a copy.
228 let mut reordered = CryptoProvider::clone(&provider);
229 if token_key_suite_first(&mut reordered) {
230 warn!(
231 installed = backend.map_or("unknown", Backend::name),
232 "the installed rustls crypto provider lists a TLS 1.3 suite \
233 with a short key first, iroh runs on a copy that lists one \
234 with a 32-byte key first for its QUIC tokens"
235 );
236 return Arc::new(reordered);
237 }
238 provider
239 })
240 .clone()
241}
242
243/// An iroh preset that sets only the crypto provider.
244///
245/// It stands in for iroh's `presets::Minimal`, which exists only with one of
246/// iroh's `tls-*` features and picks its provider by those, not by this
247/// crate's. Use it for an endpoint without iroh relays or address lookups, as in
248/// tests. It sets [`crypto_provider`].
249///
250/// ```no_run
251/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
252/// let endpoint = iroh::Endpoint::bind(iroh_live_node::MinimalPreset).await?;
253/// # drop(endpoint);
254/// # Ok(())
255/// # }
256/// ```
257#[derive(Debug, Clone, Copy, Default)]
258pub struct MinimalPreset;
259
260impl Preset for MinimalPreset {
261 fn apply(self, builder: Builder) -> Builder {
262 builder.crypto_provider(crypto_provider())
263 }
264}
265
266#[cfg(test)]
267mod tests {
268 use super::*;
269
270 #[test]
271 fn the_provider_is_the_process_default() {
272 let provider = crypto_provider();
273 assert!(Arc::ptr_eq(&provider, &crypto_provider()));
274 let installed = CryptoProvider::get_default().expect("installed");
275 assert!(Arc::ptr_eq(&provider, installed));
276 assert!(Arc::ptr_eq(&provider, &moq_tokio::crypto::provider()));
277 }
278
279 /// The installed provider is the backend the features select.
280 #[test]
281 fn the_provider_is_the_selected_backend() {
282 let provider = crypto_provider();
283 assert_eq!(Backend::of(&provider), Some(Backend::selected()));
284 }
285
286 /// Every QUIC suite of the provider seals packets per path.
287 ///
288 /// This fails on rind-rustls 0.23.4 from crates.io, which lacks the
289 /// workspace's patch.
290 #[test]
291 fn the_provider_seals_per_path() {
292 assert!(seals_per_path(&crypto_provider()));
293 }
294
295 /// Returns the provider's first TLS 1.3 suite, whose AEAD iroh's token
296 /// key uses.
297 fn first_tls13(provider: &CryptoProvider) -> &'static rustls::Tls13CipherSuite {
298 provider
299 .cipher_suites
300 .iter()
301 .find_map(|suite| suite.tls13())
302 .expect("a TLS 1.3 suite")
303 }
304
305 /// The provider's first TLS 1.3 suite takes the 32-byte key iroh seals
306 /// its QUIC tokens with, and AES-128-GCM stays for Initial packets.
307 #[test]
308 fn the_first_tls13_suite_takes_a_32_byte_key() {
309 let provider = crypto_provider();
310 assert_eq!(first_tls13(&provider).aead_alg.key_len(), TOKEN_KEY_LEN);
311 assert!(
312 provider
313 .cipher_suites
314 .iter()
315 .any(|suite| suite.suite() == rustls::CipherSuite::TLS13_AES_128_GCM_SHA256)
316 );
317 }
318
319 /// rind's AES-first order gains AES-256-GCM in front and keeps every suite.
320 #[test]
321 fn rind_lists_aes_256_gcm_first() {
322 let mut provider = CryptoProvider {
323 cipher_suites: rind_rustls::ALL_CIPHER_SUITES.to_vec(),
324 ..rind_rustls::default_provider()
325 };
326 assert_eq!(first_tls13(&provider).aead_alg.key_len(), 16);
327 assert!(token_key_suite_first(&mut provider));
328 assert_eq!(
329 provider.cipher_suites[0],
330 rind_rustls::cipher_suite::TLS13_AES_256_GCM_SHA384
331 );
332 let mut rest = rind_rustls::ALL_CIPHER_SUITES.to_vec();
333 rest.retain(|suite| *suite != rind_rustls::cipher_suite::TLS13_AES_256_GCM_SHA384);
334 assert_eq!(provider.cipher_suites[1..], rest);
335 // A second pass leaves the order as it is.
336 assert!(!token_key_suite_first(&mut provider));
337 }
338
339 /// An endpoint on the provider seals a QUIC Retry token and opens it when
340 /// the client retries.
341 #[tokio::test]
342 async fn an_endpoint_retries_a_connection() {
343 const ALPN: &[u8] = b"iroh-live-node/test/retry";
344 let server = iroh::Endpoint::builder(MinimalPreset)
345 .alpns(vec![ALPN.to_vec()])
346 .bind()
347 .await
348 .expect("bind server");
349 let client = iroh::Endpoint::bind(MinimalPreset)
350 .await
351 .expect("bind client");
352 let accept = async {
353 let incoming = server.accept().await.expect("an incoming connection");
354 assert!(!incoming.remote_addr_validated());
355 incoming.retry().expect("a Retry");
356 let incoming = server.accept().await.expect("the retried connection");
357 assert!(incoming.remote_addr_validated());
358 incoming.accept().expect("accept").await.expect("handshake")
359 };
360 let connect = client.connect(server.addr(), ALPN);
361 let (accepted, connected) =
362 tokio::time::timeout(std::time::Duration::from_secs(10), async {
363 tokio::join!(accept, connect)
364 })
365 .await
366 .expect("the handshake finishes in time");
367 connected.expect("connect");
368 drop(accepted);
369 tokio::join!(client.close(), server.close());
370 }
371}