This commit is contained in:
Mateusz Gruszczyński committed 2026-11-22 14:21:54 +01:00
commit fa432bebda
189 files changed
+26219

No files matched your search

+245
View File
@@ -0,0 +1,245 @@
//! DNS-over-TLS and DNS-over-HTTPS listeners.
#![allow(clippy::unwrap_used, clippy::expect_used)]
mod common;
use std::time::Duration;
use common::*;
use dns_core::client::{QueryOptions, build_query};
use dns_core::proto::op::{Message, ResponseCode};
use dns_core::proto::rr::RecordType;
use dns_core::tls::{DohMethod, client_config, doh_exchange, dot_exchange};
use dns_core::tls_pool::{DohClient, DotPool};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
fn cert(dir: &std::path::Path) -> Vec<u8> {
let ck = rcgen::generate_simple_self_signed(vec!["dns.test".to_string(), "127.0.0.1".to_string()]).unwrap();
write(dir, "cert.pem", &ck.cert.pem());
write(dir, "key.pem", &ck.signing_key.serialize_pem());
ck.cert.pem().into_bytes()
}
#[tokio::test(flavor = "multi_thread")]
async fn dot_and_doh() {
let dir = tmpdir("tls");
let ca = cert(&dir);
write(&dir, "z.zone", "$TTL 60\n@ IN SOA ns hm 1 3600 600 86400 60\n@ IN NS ns\nns IN A 127.0.0.1\nwww IN A 192.0.2.80\n");
let yaml = r#"
server: { listen: ["127.0.0.1:0"], data_dir: data }
api: { enabled: false }
tls: { cert_file: cert.pem, key_file: key.pem, dot_listen: ["127.0.0.1:0"], doh_listen: ["127.0.0.1:0"] }
zones: [ { name: example.test, type: primary, file: z.zone } ]
"#;
let h = start(&dir, yaml).await;
let (dot, doh) = (h.bound.dot[0], h.bound.doh[0]);
let cfg = client_config(Some(&ca), false, &[b"dot"]).unwrap();
let q = build_query(&n("www.example.test."), RecordType::A, &QueryOptions::default()).to_vec().unwrap();
// DoT
let (raw, info) = dot_exchange(dot, "dns.test", &q, Duration::from_secs(3), cfg.clone()).await.unwrap();
let m = Message::from_vec(&raw).unwrap();
assert_eq!(answers(&m), vec!["A 192.0.2.80"]);
assert!(info.protocol.contains("TLS"));
// many concurrent DoT connections
let mut tasks = Vec::new();
for _ in 0..20 {
let (cfg, q) = (cfg.clone(), q.clone());
tasks.push(tokio::spawn(async move { dot_exchange(dot, "dns.test", &q, Duration::from_secs(5), cfg).await.is_ok() }));
}
for t in tasks {
assert!(t.await.unwrap());
}
// certificate not trusted -> handshake fails
let untrusted = client_config(None, false, &[]).unwrap();
assert!(dot_exchange(dot, "dns.test", &q, Duration::from_secs(3), untrusted).await.is_err());
// wrong name -> fails
assert!(dot_exchange(dot, "other.name", &q, Duration::from_secs(3), cfg.clone()).await.is_err());
// DoH POST and GET
let hcfg = client_config(Some(&ca), false, &[b"http/1.1"]).unwrap();
for method in [DohMethod::Post, DohMethod::Get] {
let (st, body, _) = doh_exchange(doh, "dns.test", "/dns-query", &q, method, Duration::from_secs(3), hcfg.clone()).await.unwrap();
assert_eq!(st, 200, "{method:?}");
let m = Message::from_vec(&body).unwrap();
assert_eq!(m.metadata.response_code, ResponseCode::NoError);
assert_eq!(answers(&m), vec!["A 192.0.2.80"]);
}
// wrong path
let (st, _, _) = doh_exchange(doh, "dns.test", "/nope", &q, DohMethod::Post, Duration::from_secs(3), hcfg.clone()).await.unwrap();
assert_eq!(st, 404);
// raw HTTP error cases over TLS
async fn raw_http(doh: std::net::SocketAddr, cfg: std::sync::Arc<rustls::ClientConfig>, req: &str) -> u16 {
let tcp = tokio::net::TcpStream::connect(doh).await.unwrap();
let name = rustls::pki_types::ServerName::try_from("dns.test").unwrap();
let mut s = tokio_rustls::TlsConnector::from(cfg).connect(name, tcp).await.unwrap();
s.write_all(req.as_bytes()).await.unwrap();
let mut buf = Vec::new();
// a server that keeps the connection open must not hang the test
tokio::time::timeout(Duration::from_secs(5), s.read_to_end(&mut buf)).await.expect("server did not close the connection").ok();
let text = String::from_utf8_lossy(&buf);
text.split_whitespace().nth(1).unwrap().parse().unwrap()
}
assert_eq!(
raw_http(doh, hcfg.clone(), "PUT /dns-query HTTP/1.1\r\nHost: x\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").await,
405
);
assert_eq!(raw_http(doh, hcfg.clone(), "GET /dns-query?dns=!!! HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n").await, 400);
assert_eq!(
raw_http(
doh,
hcfg.clone(),
"POST /dns-query HTTP/1.1\r\nHost: x\r\nContent-Type: text/plain\r\nContent-Length: 2\r\nConnection: close\r\n\r\nhi"
)
.await,
415
);
assert_eq!(raw_http(doh, hcfg.clone(), "POST /dns-query HTTP/1.1\r\nHost: x\r\nContent-Type: application/dns-message\r\nContent-Length: 999999\r\nConnection: close\r\n\r\n").await, 413);
assert_eq!(raw_http(doh, hcfg.clone(), "POST /dns-query HTTP/1.1\r\nHost: x\r\nContent-Type: application/dns-message\r\nContent-Length: 3\r\nConnection: close\r\n\r\nabc").await, 400);
assert!(h.shared.metrics.queries[2].load(std::sync::atomic::Ordering::Relaxed) >= 21);
assert!(h.shared.metrics.queries[3].load(std::sync::atomic::Ordering::Relaxed) >= 2);
h.shutdown().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn doh_http2_and_pooled_dot_clients() {
let dir = tmpdir("tls-h2");
let ca = cert(&dir);
write(&dir, "z.zone", "$TTL 60\n@ IN SOA ns hm 1 3600 600 86400 60\n@ IN NS ns\nns IN A 127.0.0.1\nwww IN A 192.0.2.80\n");
let yaml = r#"
server: { listen: ["127.0.0.1:0"], data_dir: data }
api: { enabled: false }
rate_limit: { enabled: false }
tls: { cert_file: cert.pem, key_file: key.pem, dot_listen: ["127.0.0.1:0"], doh_listen: ["127.0.0.1:0"] }
zones: [ { name: example.test, type: primary, file: z.zone } ]
"#;
let h = start(&dir, yaml).await;
let (dot, doh) = (h.bound.dot[0], h.bound.doh[0]);
let base = client_config(Some(&ca), false, &[]).unwrap();
let q = build_query(&n("www.example.test."), RecordType::A, &QueryOptions::default()).to_vec().unwrap();
// DoH over HTTP/2: 50 concurrent queries multiplexed on one connection, GET and POST
let c = std::sync::Arc::new(DohClient::new(doh, "dns.test", "/dns-query", &base));
let mut tasks = Vec::new();
for i in 0..50 {
let (c, q) = (std::sync::Arc::clone(&c), q.clone());
let method = if i % 2 == 0 { DohMethod::Post } else { DohMethod::Get };
tasks.push(tokio::spawn(async move { c.exchange(&q, method, Duration::from_secs(5)).await }));
}
for t in tasks {
let (st, body) = t.await.unwrap().unwrap();
assert_eq!(st, 200);
assert_eq!(answers(&Message::from_vec(&body).unwrap()), vec!["A 192.0.2.80"]);
}
assert!(c.uses_http2(), "server must negotiate h2");
// DoT pool: sequential queries reuse one connection
let pool = DotPool::new(dot, "dns.test", &base, 4);
for _ in 0..20 {
let raw = pool.exchange(&q, Duration::from_secs(5)).await.unwrap();
assert_eq!(answers(&Message::from_vec(&raw).unwrap()), vec!["A 192.0.2.80"]);
}
assert_eq!(pool.idle_connections().await, 1);
// a wrong name or untrusted CA is still rejected
assert!(DotPool::new(dot, "other.name", &base, 1).exchange(&q, Duration::from_secs(3)).await.is_err());
let untrusted = client_config(None, false, &[]).unwrap();
assert!(DohClient::new(doh, "dns.test", "/dns-query", &untrusted).exchange(&q, DohMethod::Post, Duration::from_secs(3)).await.is_err());
h.shutdown().await;
}
/// A forwarder whose upstreams are only reachable over DoT and DoH (private CA via
/// `upstreams.tls_ca_file`) answers its plain-DNS clients.
#[tokio::test(flavor = "multi_thread")]
async fn secure_forwarder_over_dot_and_doh() {
let dir = tmpdir("tls-fwd");
cert(&dir);
write(&dir, "z.zone", "$TTL 60\n@ IN SOA ns hm 1 3600 600 86400 60\n@ IN NS ns\nns IN A 127.0.0.1\nwww IN A 192.0.2.80\n");
let up = start(
&dir,
r#"
server: { listen: ["127.0.0.1:0"], data_dir: data-up }
api: { enabled: false }
rate_limit: { enabled: false }
tls: { cert_file: cert.pem, key_file: key.pem, dot_listen: ["127.0.0.1:0"], doh_listen: ["127.0.0.1:0"] }
zones: [ { name: example.net, type: primary, file: z.zone } ]
"#,
)
.await;
let (dot, doh) = (up.bound.dot[0], up.bound.doh[0]);
for (label, server) in [("dot", format!("tls://{dot}#dns.test")), ("doh", format!("https://{doh}/dns-query#dns.test"))] {
let fwd = start(
&dir,
&format!(
r#"
server: {{ mode: forwarder, listen: ["127.0.0.1:0"], data_dir: data-{label} }}
api: {{ enabled: false }}
rate_limit: {{ enabled: false }}
cache: {{ enabled: false }}
upstreams: {{ strategy: failover, timeout: 3s, servers: ["{server}"], tls_ca_file: cert.pem }}
resolution: {{ default: forward }}
"#
),
)
.await;
for _ in 0..5 {
let m = q(fwd.bound.dns[0], "www.example.net.", RecordType::A).await;
assert_eq!(
answers(&m),
vec!["A 192.0.2.80"],
"{label}: {:?} {:?}",
m.metadata.response_code,
fwd.shared.rt().router.default_pool.as_ref().map(|p| p.upstreams[0].stats())
);
}
fwd.shutdown().await;
}
up.shutdown().await;
}
/// Manual measurement: `cargo test -p dns-server --test transport -- --ignored --nocapture`
#[tokio::test(flavor = "multi_thread")]
#[ignore]
async fn measure_pooled_vs_one_shot() {
let dir = tmpdir("tls-bench");
let ca = cert(&dir);
write(&dir, "z.zone", "$TTL 60\n@ IN SOA ns hm 1 3600 600 86400 60\n@ IN NS ns\nns IN A 127.0.0.1\nwww IN A 192.0.2.80\n");
let yaml = r#"
server: { listen: ["127.0.0.1:0"], data_dir: data }
api: { enabled: false }
rate_limit: { enabled: false }
tls: { cert_file: cert.pem, key_file: key.pem, dot_listen: ["127.0.0.1:0"], doh_listen: ["127.0.0.1:0"] }
zones: [ { name: example.test, type: primary, file: z.zone } ]
"#;
let h = start(&dir, yaml).await;
let (dot, doh) = (h.bound.dot[0], h.bound.doh[0]);
let base = client_config(Some(&ca), false, &[]).unwrap();
let q = build_query(&n("www.example.test."), RecordType::A, &QueryOptions::default()).to_vec().unwrap();
let n_q = 300;
let dcfg = client_config(Some(&ca), false, &[b"dot"]).unwrap();
let t = std::time::Instant::now();
for _ in 0..n_q {
dot_exchange(dot, "dns.test", &q, Duration::from_secs(5), dcfg.clone()).await.unwrap();
}
let one_shot = t.elapsed() / n_q;
let pool = DotPool::new(dot, "dns.test", &base, 4);
let t = std::time::Instant::now();
for _ in 0..n_q {
pool.exchange(&q, Duration::from_secs(5)).await.unwrap();
}
let pooled = t.elapsed() / n_q;
let h1 = client_config(Some(&ca), false, &[b"http/1.1"]).unwrap();
let t = std::time::Instant::now();
for _ in 0..n_q {
doh_exchange(doh, "dns.test", "/dns-query", &q, DohMethod::Post, Duration::from_secs(5), h1.clone()).await.unwrap();
}
let doh_one = t.elapsed() / n_q;
let c = DohClient::new(doh, "dns.test", "/dns-query", &base);
let t = std::time::Instant::now();
for _ in 0..n_q {
c.exchange(&q, DohMethod::Post, Duration::from_secs(5)).await.unwrap();
}
let doh_h2 = t.elapsed() / n_q;
eprintln!(
"per query: DoT one-shot {one_shot:?}, DoT pooled {pooled:?}, DoH HTTP/1.1 one-shot {doh_one:?}, DoH HTTP/2 persistent {doh_h2:?}"
);
h.shutdown().await;
}