Files
tsunagi/vendor/iroh/src/tls.rs
T
Aleksandr Bogomiakov 2b0c938487 Bound iroh path retries to prevent multi-connection OOM
A long-running rc.33 daemon reached OOM with roughly 22 GiB resident and
24 GiB swapped. Live inspection found 40 GiB and 10/20 GiB anonymous
container mappings; the active worker stack and tracing metadata identified
iroh's scheduled path-open retry loop. In iroh 1.2.0 every failed connection
requeues the same path, while each retry visits every connection again.
Separate control and data connections multiply the queue geometrically.

Vendor the published iroh 1.2.0 source and select it with a workspace Cargo
patch. Deduplicate retry admission and cap distinct pending paths at 64,
evicting the oldest before inserting a new candidate. Keep the current and
next retry batches bounded without combining control/data connections or
changing wire protocols, identity derivation, authentication or state.
Document source provenance, the live evidence and removal conditions.
Upstream PR 4551 merged on October 6, but inspection of the official 1.3.0
crate still shows the unconditional enqueue, so that upgrade alone is not
a fix. No version bump, release tag or installed-service change.

The default workspace suite includes the exact vendored admission module.
Three regressions failed with the original enqueue and pass with the fix:
repeated failures across connections, duplicate admission at capacity, and
10,000 distinct candidates with bounded length/capacity and FIFO eviction.
Transport integration tests continue using real endpoints and encryption.

Checks on Linux in nix develop:
- cargo fmt --all -- --check
- cargo clippy --locked --workspace --all-targets -- -D warnings
- cargo test --locked --workspace --all-targets, with only the inherited
  TSUNAGI_CONTROL_SOCKET removed from the test environment
- git diff --cached --check

Initial full-suite runs failed six DNS readiness checks because the inherited
system socket path overrode their temporary state directories. Clearing that
environment variable resolves those failures without changing application code.
Root/network-dependent ignored tests and other operating systems were not run.
2026-10-14 23:28:53 +01:00

148 lines
5.6 KiB
Rust

//! TLS configuration for iroh.
//!
//! Currently there is one mechanism available:
//! - Raw Public Keys, using the TLS extension described in [RFC 7250]
//!
//! [RFC 7250]: https://datatracker.ietf.org/doc/html/rfc7250
use std::sync::Arc;
use iroh_base::SecretKey;
use noq::crypto::rustls::{QuicClientConfig, QuicServerConfig};
use tracing::warn;
use self::resolver::ResolveRawPublicKeyCert;
pub(crate) mod misc;
pub(crate) mod name;
mod resolver;
mod verifier;
#[allow(deprecated)] // Re-export of backwards-compatibility item
pub use iroh_relay::tls::CaRootsConfig;
pub use iroh_relay::tls::CaTlsConfig;
#[cfg(with_crypto_provider)]
pub use iroh_relay::tls::default_provider;
/// Maximum amount of TLS tickets we will cache (by default) for 0-RTT connection
/// establishment.
///
/// 8 tickets per remote endpoint, 32 different endpoints would max out the required storage:
/// ~200 bytes per session + certificates (which are ~387 bytes)
/// So 8 * 32 * (200 + 387) = 150.272 bytes, assuming pointers to certificates
/// are never aliased pointers (they're Arc'ed).
/// I think 150KB is an acceptable default upper limit for such a cache.
pub(crate) const DEFAULT_MAX_TLS_TICKETS: usize = 8 * 32;
/// Configuration for TLS.
///
/// The main point of this struct is to keep state that should be kept the same
/// over multiple TLS sessions the same.
/// E.g. the `server_verifier` and `client_verifier` Arc pointers are checked to be
/// the same between different TLS session calls with 0-RTT data in rustls.
/// This makes sure that's the case.
#[derive(Debug)]
pub(crate) struct TlsConfig {
pub(crate) secret_key: SecretKey,
cert_resolver: Arc<ResolveRawPublicKeyCert>,
server_verifier: Arc<verifier::ServerCertificateVerifier>,
client_verifier: Arc<verifier::ClientCertificateVerifier>,
session_store: Arc<dyn rustls::client::ClientSessionStore>,
crypto_provider: Arc<rustls::crypto::CryptoProvider>,
}
impl TlsConfig {
pub(crate) fn new(
secret_key: SecretKey,
max_tls_tickets: usize,
crypto_provider: Arc<rustls::crypto::CryptoProvider>,
) -> Self {
Self {
cert_resolver: Arc::new(ResolveRawPublicKeyCert::new(&secret_key)),
server_verifier: Arc::new(verifier::ServerCertificateVerifier),
client_verifier: Arc::new(verifier::ClientCertificateVerifier),
session_store: Arc::new(rustls::client::ClientSessionMemoryCache::new(
max_tls_tickets,
)),
crypto_provider,
secret_key,
}
}
/// Create a TLS client configuration.
///
/// If *keylog* is `true` this will enable logging of the pre-master key to the file in the
/// `SSLKEYLOGFILE` environment variable. This can be used to inspect the traffic for
/// debugging purposes.
pub(crate) fn make_client_config(
&self,
keylog: bool,
) -> Result<QuicClientConfig, TlsConfigError> {
let mut crypto = rustls::ClientConfig::builder_with_provider(self.crypto_provider.clone())
.with_protocol_versions(verifier::PROTOCOL_VERSIONS)?
.dangerous()
.with_custom_certificate_verifier(self.server_verifier.clone())
.with_client_cert_resolver(self.cert_resolver.clone());
// TODO: enable/disable 0-RTT/storing tickets
crypto.resumption = rustls::client::Resumption::store(self.session_store.clone());
crypto.enable_early_data = true;
// The synthetic server name is used locally to select the expected endpoint ID
// and to partition the session cache. Iroh servers do not use SNI, so do not
// disclose the endpoint ID in the ClientHello.
crypto.enable_sni = false;
if keylog {
warn!("enabling SSLKEYLOGFILE for TLS pre-master keys");
crypto.key_log = Arc::new(rustls::KeyLogFile::new());
}
let quic = QuicClientConfig::try_from(crypto)?;
Ok(quic)
}
/// Create a TLS server configuration.
///
/// If *keylog* is `true` this will enable logging of the pre-master key to the file in the
/// `SSLKEYLOGFILE` environment variable. This can be used to inspect the traffic for
/// debugging purposes.
pub(crate) fn make_server_config(
&self,
keylog: bool,
) -> Result<QuicServerConfig, TlsConfigError> {
let mut crypto = rustls::ServerConfig::builder_with_provider(self.crypto_provider.clone())
.with_protocol_versions(verifier::PROTOCOL_VERSIONS)?
.with_client_cert_verifier(self.client_verifier.clone())
.with_cert_resolver(self.cert_resolver.clone());
if keylog {
warn!("enabling SSLKEYLOGFILE for TLS pre-master keys");
crypto.key_log = Arc::new(rustls::KeyLogFile::new());
}
// must be u32::MAX or 0 (the default). Any other value panics with QUIC
// This is specified in RFC 9001: https://www.rfc-editor.org/rfc/rfc9001#section-4.6.1
crypto.max_early_data_size = u32::MAX;
let quic = QuicServerConfig::try_from(crypto)?;
Ok(quic)
}
}
#[allow(missing_docs)]
#[n0_error::stack_error(derive, add_meta, from_sources)]
#[non_exhaustive]
pub enum TlsConfigError {
#[error(
"The configured crypto provider is missing support for TLS13_AES_128_GCM_SHA256, which is required for QUIC initial packets."
)]
CryptoProviderNoInitialCipherSuite {
#[error(std_err)]
source: noq::crypto::rustls::NoInitialCipherSuite,
},
#[error("The configured crypto provider is incompatible with iroh and QUIC encryption")]
CryptoProviderIncompatible {
#[error(std_err)]
source: rustls::Error,
},
}