iroh/
tls.rs

1//! TLS configuration for iroh.
2//!
3//! Currently there is one mechanism available:
4//! - Raw Public Keys, using the TLS extension described in [RFC 7250]
5//!
6//! [RFC 7250]: https://datatracker.ietf.org/doc/html/rfc7250
7
8use std::sync::Arc;
9
10use iroh_base::SecretKey;
11use noq::crypto::rustls::{QuicClientConfig, QuicServerConfig};
12use tracing::warn;
13
14use self::resolver::ResolveRawPublicKeyCert;
15
16pub(crate) mod misc;
17pub(crate) mod name;
18mod resolver;
19mod verifier;
20
21#[allow(deprecated)] // Re-export of backwards-compatibility item
22pub use iroh_relay::tls::CaRootsConfig;
23pub use iroh_relay::tls::CaTlsConfig;
24#[cfg(with_crypto_provider)]
25pub use iroh_relay::tls::default_provider;
26
27/// Maximum amount of TLS tickets we will cache (by default) for 0-RTT connection
28/// establishment.
29///
30/// 8 tickets per remote endpoint, 32 different endpoints would max out the required storage:
31/// ~200 bytes per session + certificates (which are ~387 bytes)
32/// So 8 * 32 * (200 + 387) = 150.272 bytes, assuming pointers to certificates
33/// are never aliased pointers (they're Arc'ed).
34/// I think 150KB is an acceptable default upper limit for such a cache.
35pub(crate) const DEFAULT_MAX_TLS_TICKETS: usize = 8 * 32;
36
37/// Configuration for TLS.
38///
39/// The main point of this struct is to keep state that should be kept the same
40/// over multiple TLS sessions the same.
41/// E.g. the `server_verifier` and `client_verifier` Arc pointers are checked to be
42/// the same between different TLS session calls with 0-RTT data in rustls.
43/// This makes sure that's the case.
44#[derive(Debug)]
45pub(crate) struct TlsConfig {
46    pub(crate) secret_key: SecretKey,
47    cert_resolver: Arc<ResolveRawPublicKeyCert>,
48    server_verifier: Arc<verifier::ServerCertificateVerifier>,
49    client_verifier: Arc<verifier::ClientCertificateVerifier>,
50    session_store: Arc<dyn rustls::client::ClientSessionStore>,
51    crypto_provider: Arc<rustls::crypto::CryptoProvider>,
52}
53
54impl TlsConfig {
55    pub(crate) fn new(
56        secret_key: SecretKey,
57        max_tls_tickets: usize,
58        crypto_provider: Arc<rustls::crypto::CryptoProvider>,
59    ) -> Self {
60        Self {
61            cert_resolver: Arc::new(ResolveRawPublicKeyCert::new(&secret_key)),
62            server_verifier: Arc::new(verifier::ServerCertificateVerifier),
63            client_verifier: Arc::new(verifier::ClientCertificateVerifier),
64            session_store: Arc::new(rustls::client::ClientSessionMemoryCache::new(
65                max_tls_tickets,
66            )),
67            crypto_provider,
68            secret_key,
69        }
70    }
71
72    /// Create a TLS client configuration.
73    ///
74    /// If *keylog* is `true` this will enable logging of the pre-master key to the file in the
75    /// `SSLKEYLOGFILE` environment variable.  This can be used to inspect the traffic for
76    /// debugging purposes.
77    pub(crate) fn make_client_config(
78        &self,
79        keylog: bool,
80    ) -> Result<QuicClientConfig, TlsConfigError> {
81        let mut crypto = rustls::ClientConfig::builder_with_provider(self.crypto_provider.clone())
82            .with_protocol_versions(verifier::PROTOCOL_VERSIONS)?
83            .dangerous()
84            .with_custom_certificate_verifier(self.server_verifier.clone())
85            .with_client_cert_resolver(self.cert_resolver.clone());
86
87        // TODO: enable/disable 0-RTT/storing tickets
88        crypto.resumption = rustls::client::Resumption::store(self.session_store.clone());
89        crypto.enable_early_data = true;
90
91        // The synthetic server name is used locally to select the expected endpoint ID
92        // and to partition the session cache. Iroh servers do not use SNI, so do not
93        // disclose the endpoint ID in the ClientHello.
94        crypto.enable_sni = false;
95
96        if keylog {
97            warn!("enabling SSLKEYLOGFILE for TLS pre-master keys");
98            crypto.key_log = Arc::new(rustls::KeyLogFile::new());
99        }
100
101        let quic = QuicClientConfig::try_from(crypto)?;
102        Ok(quic)
103    }
104
105    /// Create a TLS server configuration.
106    ///
107    /// If *keylog* is `true` this will enable logging of the pre-master key to the file in the
108    /// `SSLKEYLOGFILE` environment variable.  This can be used to inspect the traffic for
109    /// debugging purposes.
110    pub(crate) fn make_server_config(
111        &self,
112        keylog: bool,
113    ) -> Result<QuicServerConfig, TlsConfigError> {
114        let mut crypto = rustls::ServerConfig::builder_with_provider(self.crypto_provider.clone())
115            .with_protocol_versions(verifier::PROTOCOL_VERSIONS)?
116            .with_client_cert_verifier(self.client_verifier.clone())
117            .with_cert_resolver(self.cert_resolver.clone());
118        if keylog {
119            warn!("enabling SSLKEYLOGFILE for TLS pre-master keys");
120            crypto.key_log = Arc::new(rustls::KeyLogFile::new());
121        }
122
123        // must be u32::MAX or 0 (the default). Any other value panics with QUIC
124        // This is specified in RFC 9001: https://www.rfc-editor.org/rfc/rfc9001#section-4.6.1
125        crypto.max_early_data_size = u32::MAX;
126        let quic = QuicServerConfig::try_from(crypto)?;
127        Ok(quic)
128    }
129}
130
131#[allow(missing_docs)]
132#[n0_error::stack_error(derive, add_meta, from_sources)]
133#[non_exhaustive]
134pub enum TlsConfigError {
135    #[error(
136        "The configured crypto provider is missing support for TLS13_AES_128_GCM_SHA256, which is required for QUIC initial packets."
137    )]
138    CryptoProviderNoInitialCipherSuite {
139        #[error(std_err)]
140        source: noq::crypto::rustls::NoInitialCipherSuite,
141    },
142    #[error("The configured crypto provider is incompatible with iroh and QUIC encryption")]
143    CryptoProviderIncompatible {
144        #[error(std_err)]
145        source: rustls::Error,
146    },
147}