iroh_dns_server/http/
tls.rs

1use std::{
2    borrow::Cow,
3    io,
4    path::{Path, PathBuf},
5    sync::{Arc, OnceLock},
6    time::Duration,
7};
8
9use axum_server::accept::Accept;
10use n0_error::{Result, StackResultExt, StdResultExt, bail_any};
11use n0_future::{FutureExt, future::Boxed as BoxFuture};
12use rustls::{
13    ServerConfig,
14    pki_types::{CertificateDer, PrivateKeyDer, pem::PemObject},
15};
16use serde::{Deserialize, Serialize};
17use tokio::io::{AsyncRead, AsyncWrite};
18use tokio_rustls_acme::{AcmeConfig, axum::AxumAcceptor, caches::DirCache};
19use tokio_stream::StreamExt;
20use tracing::{Instrument, debug, error, info_span};
21
22/// Strategy used to obtain TLS certificates for the HTTPS server.
23#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, strum::Display)]
24#[serde(rename_all = "snake_case")]
25#[non_exhaustive]
26pub enum CertMode {
27    /// Load pre-existing certificates from the `cert_cache` directory.
28    Manual,
29    /// Obtain certificates from Let's Encrypt via the ACME protocol.
30    LetsEncrypt,
31    /// Generate self-signed certificates and cache them in `cert_cache`.
32    SelfSigned,
33}
34
35impl CertMode {
36    /// Build the [`TlsAcceptor`] for this mode.
37    pub(crate) async fn build(
38        &self,
39        domains: Vec<String>,
40        cert_cache: PathBuf,
41        letsencrypt_contact: Option<String>,
42        letsencrypt_prod: bool,
43    ) -> Result<TlsAcceptor> {
44        Ok(match self {
45            CertMode::Manual => TlsAcceptor::manual(domains, cert_cache).await?,
46            CertMode::SelfSigned => TlsAcceptor::self_signed(domains)?,
47            CertMode::LetsEncrypt => {
48                let contact =
49                    letsencrypt_contact.context("contact is required for letsencrypt cert mode")?;
50                TlsAcceptor::letsencrypt(domains, &contact, letsencrypt_prod, cert_cache)?
51            }
52        })
53    }
54}
55
56/// How long a client may take to complete the TLS handshake.
57///
58/// Generous, so that clients on lossy high-latency links still get through.
59const TLS_HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(30);
60
61/// TLS Certificate Authority acceptor.
62#[derive(Clone)]
63pub(crate) enum TlsAcceptor {
64    LetsEncrypt(AxumAcceptor),
65    Manual(tokio_rustls::TlsAcceptor),
66}
67
68impl<I: AsyncRead + AsyncWrite + Unpin + Send + 'static, S: Send + 'static> Accept<I, S>
69    for TlsAcceptor
70{
71    type Stream = tokio_rustls::server::TlsStream<I>;
72    type Service = S;
73    type Future = BoxFuture<io::Result<(Self::Stream, Self::Service)>>;
74
75    fn accept(&self, stream: I, service: S) -> Self::Future {
76        let accept = match self {
77            Self::LetsEncrypt(a) => a.accept(stream, service).boxed(),
78            Self::Manual(a) => {
79                let accept = a.accept(stream);
80                async move { Ok((accept.await?, service)) }.boxed()
81            }
82        };
83        // Neither acceptor enforces our handshake timeout on its own.
84        async move {
85            tokio::time::timeout(TLS_HANDSHAKE_TIMEOUT, accept)
86                .await
87                .unwrap_or_else(|_| {
88                    Err(io::Error::new(
89                        io::ErrorKind::TimedOut,
90                        "TLS handshake timed out",
91                    ))
92                })
93        }
94        .boxed()
95    }
96}
97
98impl TlsAcceptor {
99    fn self_signed(domains: Vec<String>) -> Result<Self> {
100        let rcgen::CertifiedKey { cert, signing_key } =
101            rcgen::generate_simple_self_signed(domains).anyerr()?;
102        let key = PrivateKeyDer::try_from(signing_key.serialize_der())?;
103
104        let mut config =
105            ServerConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
106                .with_safe_default_protocol_versions()
107                .anyerr()?
108                .with_no_client_auth()
109                .with_single_cert(vec![cert.der().clone()], key)
110                .anyerr()?;
111
112        config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
113        let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(config));
114        Ok(Self::Manual(acceptor))
115    }
116
117    async fn manual(domains: Vec<String>, dir: PathBuf) -> Result<Self> {
118        let config = rustls::ServerConfig::builder_with_provider(Arc::new(
119            rustls::crypto::ring::default_provider(),
120        ))
121        .with_safe_default_protocol_versions()
122        .anyerr()?
123        .with_no_client_auth();
124
125        if domains.len() != 1 {
126            bail_any!("Multiple domains in manual mode are not supported");
127        }
128
129        let keyname = escape_hostname(&domains[0]);
130        let cert_path = dir.join(format!("{keyname}.crt"));
131        let key_path = dir.join(format!("{keyname}.key"));
132
133        let certs = load_certs(cert_path).await?;
134        let secret_key = load_secret_key(key_path).await?;
135
136        let config = config.with_single_cert(certs, secret_key).anyerr()?;
137        let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(config));
138        Ok(Self::Manual(acceptor))
139    }
140
141    fn letsencrypt(
142        domains: Vec<String>,
143        contact: &str,
144        is_production: bool,
145        dir: PathBuf,
146    ) -> Result<Self> {
147        let config = rustls::ServerConfig::builder().with_no_client_auth();
148        let mut state = AcmeConfig::new(domains)
149            .contact([format!("mailto:{contact}")])
150            .cache_option(Some(DirCache::new(dir)))
151            .directory_lets_encrypt(is_production)
152            .state();
153
154        let config = config.with_cert_resolver(state.resolver());
155        let acceptor = state.acceptor();
156
157        tokio::spawn(
158            async move {
159                loop {
160                    match state.next().await.unwrap() {
161                        Ok(ok) => debug!("acme event: {:?}", ok),
162                        Err(err) => error!("error: {:?}", err),
163                    }
164                }
165            }
166            .instrument(info_span!("acme")),
167        );
168        let config = Arc::new(config);
169        let acceptor = AxumAcceptor::new(acceptor, config);
170        Ok(Self::LetsEncrypt(acceptor))
171    }
172}
173
174async fn load_certs(filename: impl AsRef<Path>) -> Result<Vec<CertificateDer<'static>>> {
175    let filename = filename.as_ref();
176    let certfile = tokio::fs::read(filename)
177        .await
178        .with_std_context(|_| format!("cannot open certificate file at {}", filename.display()))?;
179    CertificateDer::pem_slice_iter(&certfile)
180        .collect::<Result<Vec<_>, _>>()
181        .with_std_context(|_| format!("cannot parse certificates from {}", filename.display()))
182}
183
184async fn load_secret_key(filename: impl AsRef<Path>) -> Result<PrivateKeyDer<'static>> {
185    let filename = filename.as_ref();
186    let keyfile = tokio::fs::read(filename)
187        .await
188        .with_std_context(|_| format!("cannot open secret key file at {}", filename.display()))?;
189    PrivateKeyDer::from_pem_slice(&keyfile)
190        .with_std_context(|_| format!("cannot parse secret key from {}", filename.display()))
191}
192
193static UNSAFE_HOSTNAME_CHARACTERS: OnceLock<regex::Regex> = OnceLock::new();
194
195fn escape_hostname(hostname: &str) -> Cow<'_, str> {
196    let regex = UNSAFE_HOSTNAME_CHARACTERS
197        .get_or_init(|| regex::Regex::new(r"[^a-zA-Z0-9-\.]").expect("valid regex"));
198    regex.replace_all(hostname, "")
199}
200
201#[cfg(test)]
202mod tests {
203    use std::time::Duration;
204
205    use axum_server::accept::Accept;
206    use tokio::time::Instant;
207
208    use super::{TLS_HANDSHAKE_TIMEOUT, TlsAcceptor};
209
210    #[tokio::test(start_paused = true)]
211    async fn test_handshake_timeout() {
212        let acceptor = TlsAcceptor::self_signed(vec!["localhost".to_string()]).unwrap();
213        let (_client, server_io) = tokio::io::duplex(1024);
214
215        let start = Instant::now();
216        let accept = acceptor.accept(server_io, ());
217        let err = tokio::time::timeout(TLS_HANDSHAKE_TIMEOUT + Duration::from_secs(1), accept)
218            .await
219            .expect("handshake timeout did not fire")
220            .expect_err("handshake cannot succeed without a client");
221        assert_eq!(err.kind(), std::io::ErrorKind::TimedOut);
222        assert!(start.elapsed() >= TLS_HANDSHAKE_TIMEOUT);
223    }
224}