Files
EasyDNS/crates/dns-server/src/tls.rs
T
2026-11-22 14:21:54 +01:00

340 lines
15 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! DNS-over-TLS (RFC 7858) and DNS-over-HTTPS (RFC 8484; HTTP/2 and HTTP/1.1) listeners,
//! with TLS certificates that are reloaded when the files change.
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, SystemTime};
use bytes::Bytes;
use data_encoding::BASE64URL_NOPAD;
use http_body_util::{BodyExt, Full, Limited};
use hyper::service::service_fn;
use hyper_util::rt::{TokioExecutor, TokioIo, TokioTimer};
use hyper_util::server::conn::auto::Builder as AutoBuilder;
use rustls::ServerConfig;
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, PrivateKeyDer};
use rustls::server::{ClientHello, ResolvesServerCert};
use rustls::sign::CertifiedKey;
use tokio::net::TcpListener;
use tokio::sync::{Semaphore, watch};
use tokio_rustls::TlsAcceptor;
use crate::handler::{Reply, Transport, handle};
use crate::listener::serve_stream;
use crate::runtime::Shared;
const MAX_HTTP_HEADER: usize = 8 * 1024;
const MAX_HTTP_BODY: usize = 65_535;
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(5);
/// Time allowed to receive a DoH request body.
const BODY_TIMEOUT: Duration = Duration::from_secs(10);
/// Concurrent HTTP/2 streams (queries in flight) per DoH connection.
const MAX_H2_STREAMS: u32 = 100;
/// Certificate and key, re-read from disk when the files change (e.g. after a Let's
/// Encrypt renewal), without restarting the server. A broken new pair is rejected and the
/// previous certificate stays in use.
pub struct CertStore {
cert: PathBuf,
key: PathBuf,
current: RwLock<Arc<CertifiedKey>>,
stamp: Mutex<(Option<SystemTime>, Option<SystemTime>)>,
}
impl std::fmt::Debug for CertStore {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CertStore").field("cert", &self.cert).field("key", &self.key).finish()
}
}
fn mtime(p: &Path) -> Option<SystemTime> {
std::fs::metadata(p).and_then(|m| m.modified()).ok()
}
fn load_certified_key(cert: &Path, key: &Path) -> Result<CertifiedKey, String> {
let certs: Vec<CertificateDer<'static>> = CertificateDer::pem_file_iter(cert)
.map_err(|e| format!("{}: {e}", cert.display()))?
.collect::<Result<_, _>>()
.map_err(|e| format!("{}: {e}", cert.display()))?;
if certs.is_empty() {
return Err(format!("{}: no certificates found", cert.display()));
}
let key_der = PrivateKeyDer::from_pem_file(key).map_err(|e| format!("{}: {e}", key.display()))?;
let signing = rustls::crypto::ring::default_provider()
.key_provider
.load_private_key(key_der)
.map_err(|e| format!("{}: unsupported private key: {e}", key.display()))?;
let ck = CertifiedKey::new(certs, signing);
ck.keys_match().map_err(|e| format!("certificate/key mismatch: {e}"))?;
Ok(ck)
}
impl CertStore {
pub fn load(cert: &Path, key: &Path) -> Result<Arc<Self>, String> {
let ck = load_certified_key(cert, key)?;
Ok(Arc::new(Self {
cert: cert.to_path_buf(),
key: key.to_path_buf(),
current: RwLock::new(Arc::new(ck)),
stamp: Mutex::new((mtime(cert), mtime(key))),
}))
}
/// Reload when either file's modification time changed. `Ok(true)` = new certificate.
pub fn reload_if_changed(&self) -> Result<bool, String> {
let now = (mtime(&self.cert), mtime(&self.key));
{
let st = self.stamp.lock().unwrap_or_else(|e| e.into_inner());
if *st == now {
return Ok(false);
}
}
let ck = load_certified_key(&self.cert, &self.key)?;
*self.current.write().unwrap_or_else(|e| e.into_inner()) = Arc::new(ck);
*self.stamp.lock().unwrap_or_else(|e| e.into_inner()) = now;
Ok(true)
}
/// Check the files every `every` and swap in a renewed certificate.
pub async fn watch(self: Arc<Self>, every: Duration, mut shutdown: watch::Receiver<bool>) {
let mut tick = tokio::time::interval(every);
tick.tick().await;
loop {
tokio::select! {
_ = tick.tick() => {}
_ = shutdown.changed() => break,
}
match self.reload_if_changed() {
Ok(true) => tracing::info!(cert = %self.cert.display(), "TLS certificate reloaded"),
Ok(false) => {}
Err(e) => tracing::error!(error = %e, "new TLS certificate rejected; keeping the previous one"),
}
}
}
}
impl ResolvesServerCert for CertStore {
fn resolve(&self, _hello: ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
Some(Arc::clone(&self.current.read().unwrap_or_else(|e| e.into_inner())))
}
}
/// rustls server config using a (reloadable) certificate store.
pub fn server_config_with(store: Arc<CertStore>, alpn: &[&[u8]]) -> Result<Arc<ServerConfig>, String> {
let provider = Arc::new(rustls::crypto::ring::default_provider());
let mut cfg = ServerConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.map_err(|e| e.to_string())?
.with_no_client_auth()
.with_cert_resolver(store);
cfg.alpn_protocols = alpn.iter().map(|a| a.to_vec()).collect();
Ok(Arc::new(cfg))
}
/// Load certificate chain and key into a rustls server config (not reloaded).
pub fn server_config(cert: &Path, key: &Path, alpn: &[&[u8]]) -> Result<Arc<ServerConfig>, String> {
server_config_with(CertStore::load(cert, key)?, alpn)
}
/// ALPN offered by the DoH listener: HTTP/2 first (browsers, Android, Firefox), then HTTP/1.1.
pub const DOH_ALPN: &[&[u8]] = &[b"h2", b"http/1.1"];
/// Serve DoT until shutdown.
pub async fn serve_dot(shared: Arc<Shared>, listener: TcpListener, tls: Arc<ServerConfig>, mut shutdown: watch::Receiver<bool>) {
let acceptor = TlsAcceptor::from(tls);
let cfg = shared.rt().cfg.clone();
let conns = Arc::new(Semaphore::new(cfg.server.max_tcp_connections));
let idle = cfg.server.tcp_idle_timeout;
loop {
let (stream, peer) = tokio::select! {
r = listener.accept() => match r { Ok(v) => v, Err(_) => continue },
_ = shutdown.changed() => break,
};
// without this, the TLS handshake waits ~40 ms on delayed ACKs (Nagle)
let _ = stream.set_nodelay(true);
let Ok(permit) = Arc::clone(&conns).try_acquire_owned() else { continue };
let acceptor = acceptor.clone();
let shared = Arc::clone(&shared);
tokio::spawn(async move {
match tokio::time::timeout(HANDSHAKE_TIMEOUT, acceptor.accept(stream)).await {
Ok(Ok(tls)) => serve_stream(shared, tls, peer, Transport::Dot, idle).await,
Ok(Err(e)) => tracing::debug!(%peer, error = %e, "DoT handshake failed"),
Err(_) => tracing::debug!(%peer, "DoT handshake timeout"),
}
drop(permit);
});
}
}
type DohResponse = hyper::Response<Full<Bytes>>;
fn reply(status: u16, ctype: &str, body: impl Into<Bytes>) -> DohResponse {
let mut r = hyper::Response::new(Full::new(body.into()));
*r.status_mut() = hyper::StatusCode::from_u16(status).unwrap_or(hyper::StatusCode::INTERNAL_SERVER_ERROR);
if let Ok(v) = hyper::header::HeaderValue::from_str(ctype) {
r.headers_mut().insert(hyper::header::CONTENT_TYPE, v);
}
r
}
fn min_ttl(b: &[u8]) -> u32 {
dns_core::proto::op::Message::from_vec(b)
.ok()
.and_then(|m| m.answers.iter().chain(m.authorities.iter()).map(|r| r.ttl).min())
.unwrap_or(0)
}
/// One DoH request (RFC 8484): GET `?dns=` or POST `application/dns-message`.
async fn doh_request(shared: &Shared, req: hyper::Request<hyper::body::Incoming>, peer: SocketAddr) -> DohResponse {
if req.uri().path() != "/dns-query" {
return reply(404, "text/plain", "not found\n");
}
let msg: Vec<u8> = match *req.method() {
hyper::Method::GET => {
let q = req.uri().query().unwrap_or("");
let Some(v) = q.split('&').find_map(|kv| kv.strip_prefix("dns=")) else {
return reply(400, "text/plain", "missing dns parameter\n");
};
match BASE64URL_NOPAD.decode(v.trim_end_matches('=').as_bytes()) {
Ok(b) if b.len() <= MAX_HTTP_BODY => b,
_ => return reply(400, "text/plain", "invalid base64url\n"),
}
}
hyper::Method::POST => {
let ct = req.headers().get(hyper::header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).unwrap_or("");
if !ct.trim().eq_ignore_ascii_case("application/dns-message") {
return reply(415, "text/plain", "use application/dns-message\n");
}
let http1 = req.version() < hyper::Version::HTTP_2;
let declared =
req.headers().get(hyper::header::CONTENT_LENGTH).and_then(|v| v.to_str().ok()).and_then(|v| v.parse::<u64>().ok());
let body = if declared.is_some_and(|n| n > MAX_HTTP_BODY as u64) {
None
} else {
// bounded size and time (no slow-body attacks)
tokio::time::timeout(BODY_TIMEOUT, Limited::new(req.into_body(), MAX_HTTP_BODY).collect()).await.ok().and_then(Result::ok)
};
match body {
Some(b) => b.to_bytes().to_vec(),
None => {
let mut r = reply(413, "text/plain", "payload too large or too slow\n");
if http1 {
// the unread body makes the connection unusable: close it instead of waiting
r.headers_mut().insert(hyper::header::CONNECTION, hyper::header::HeaderValue::from_static("close"));
}
return r;
}
}
}
_ => {
let mut r = reply(405, "text/plain", "use GET or POST\n");
r.headers_mut().insert(hyper::header::ALLOW, hyper::header::HeaderValue::from_static("GET, POST"));
return r;
}
};
if msg.len() < 12 {
return reply(400, "text/plain", "DNS message too short\n");
}
match handle(shared, &msg, peer, Transport::Doh).await {
Reply::One(b) => {
let ttl = min_ttl(&b);
let mut r = reply(200, "application/dns-message", b);
if let Ok(v) = hyper::header::HeaderValue::from_str(&format!("max-age={ttl}")) {
r.headers_mut().insert(hyper::header::CACHE_CONTROL, v);
}
r
}
Reply::Many(_) => reply(400, "text/plain", "zone transfers are not available over DoH\n"),
Reply::None => reply(429, "text/plain", "request dropped\n"),
}
}
/// Serve one DoH connection: HTTP/1.1 (keep-alive) or HTTP/2 (multiplexed; selected by
/// ALPN, or by the HTTP/2 preface on plaintext connections behind a proxy).
pub async fn serve_http<S>(shared: Arc<Shared>, s: S, peer: SocketAddr, idle: Duration)
where
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static,
{
let svc = service_fn(move |req| {
let shared = Arc::clone(&shared);
async move { Ok::<_, std::convert::Infallible>(doh_request(&shared, req, peer).await) }
});
let mut b = AutoBuilder::new(TokioExecutor::new());
b.http1().timer(TokioTimer::new()).header_read_timeout(idle).keep_alive(true).max_buf_size(MAX_HTTP_HEADER + MAX_HTTP_BODY);
b.http2()
.timer(TokioTimer::new())
.max_concurrent_streams(MAX_H2_STREAMS)
.keep_alive_interval(Some(idle))
.keep_alive_timeout(idle)
.max_header_list_size(MAX_HTTP_HEADER as u32);
if let Err(e) = b.serve_connection(TokioIo::new(s), svc).await {
tracing::debug!(%peer, error = %e, "DoH connection ended");
}
}
/// Serve DoH (TLS, or plaintext when `tls` is `None` – only behind a reverse proxy).
pub async fn serve_doh(shared: Arc<Shared>, listener: TcpListener, tls: Option<Arc<ServerConfig>>, mut shutdown: watch::Receiver<bool>) {
let acceptor = tls.map(TlsAcceptor::from);
let cfg = shared.rt().cfg.clone();
let conns = Arc::new(Semaphore::new(cfg.server.max_tcp_connections));
let idle = cfg.server.tcp_idle_timeout.max(Duration::from_secs(30));
loop {
let (stream, peer) = tokio::select! {
r = listener.accept() => match r { Ok(v) => v, Err(_) => continue },
_ = shutdown.changed() => break,
};
let _ = stream.set_nodelay(true);
let Ok(permit) = Arc::clone(&conns).try_acquire_owned() else { continue };
let acceptor = acceptor.clone();
let shared = Arc::clone(&shared);
tokio::spawn(async move {
shared.metrics.tcp_connections.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
match acceptor {
Some(a) => match tokio::time::timeout(HANDSHAKE_TIMEOUT, a.accept(stream)).await {
Ok(Ok(tls)) => serve_http(Arc::clone(&shared), tls, peer, idle).await,
Ok(Err(e)) => tracing::debug!(%peer, error = %e, "DoH handshake failed"),
Err(_) => tracing::debug!(%peer, "DoH handshake timeout"),
},
None => serve_http(Arc::clone(&shared), stream, peer, idle).await,
}
shared.metrics.tcp_connections.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
drop(permit);
});
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
fn pair(dir: &Path, name: &str) -> Vec<u8> {
let ck = rcgen::generate_simple_self_signed(vec![name.to_string()]).unwrap();
std::fs::write(dir.join("c.pem"), ck.cert.pem()).unwrap();
std::fs::write(dir.join("k.pem"), ck.signing_key.serialize_pem()).unwrap();
ck.cert.der().to_vec()
}
#[test]
fn certificate_is_reloaded_when_files_change() {
let d = std::env::temp_dir().join(format!("edns-cert-{}", std::process::id()));
std::fs::create_dir_all(&d).unwrap();
let first = pair(&d, "one.test");
let store = CertStore::load(&d.join("c.pem"), &d.join("k.pem")).unwrap();
let current = |s: &CertStore| s.current.read().unwrap().cert[0].to_vec();
assert_eq!(current(&store), first);
assert!(!store.reload_if_changed().unwrap());
std::thread::sleep(Duration::from_millis(20));
let second = pair(&d, "two.test");
assert!(store.reload_if_changed().unwrap());
assert_eq!(current(&store), second);
// a broken renewal is rejected and the working certificate stays
std::thread::sleep(Duration::from_millis(20));
std::fs::write(d.join("k.pem"), "garbage").unwrap();
assert!(store.reload_if_changed().is_err());
assert_eq!(current(&store), second);
let _ = std::fs::remove_dir_all(&d);
}
}