v0.1.0
This commit is contained in:
commit
fa432bebda
189 files changed
+26219
No files matched your search
@@ -0,0 +1,38 @@
|
||||
[package]
|
||||
name = "dns-server"
|
||||
description = "EasyDNS server: listeners (UDP/TCP/DoT/DoH), dispatcher and hybrid routing"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
dns-core.workspace = true
|
||||
dns-config.workspace = true
|
||||
dns-authoritative.workspace = true
|
||||
dns-cache.workspace = true
|
||||
dns-recursive.workspace = true
|
||||
dns-forwarder.workspace = true
|
||||
dns-policy.workspace = true
|
||||
dns-metrics.workspace = true
|
||||
tokio.workspace = true
|
||||
hyper.workspace = true
|
||||
hyper-util.workspace = true
|
||||
http-body-util.workspace = true
|
||||
bytes.workspace = true
|
||||
socket2.workspace = true
|
||||
lru.workspace = true
|
||||
tracing.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
rustls.workspace = true
|
||||
tokio-rustls.workspace = true
|
||||
data-encoding.workspace = true
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
nix = { version = "0.30", default-features = false, features = ["socket", "uio", "net"] }
|
||||
|
||||
[dev-dependencies]
|
||||
rcgen.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,50 @@
|
||||
//! Append-only audit log of administrative actions (JSON lines).
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct AuditEvent<'a> {
|
||||
pub time_unix: u64,
|
||||
pub actor: &'a str,
|
||||
pub action: &'a str,
|
||||
pub target: &'a str,
|
||||
pub result: &'a str,
|
||||
pub detail: &'a str,
|
||||
}
|
||||
|
||||
pub struct AuditLog {
|
||||
path: Option<PathBuf>,
|
||||
lock: Mutex<()>,
|
||||
}
|
||||
|
||||
impl AuditLog {
|
||||
pub fn new(path: Option<PathBuf>) -> Self {
|
||||
Self { path, lock: Mutex::new(()) }
|
||||
}
|
||||
|
||||
pub fn record(&self, actor: &str, action: &str, target: &str, result: &str, detail: &str) {
|
||||
let ev = AuditEvent { time_unix: dns_core::tsig::now(), actor, action, target, result, detail };
|
||||
tracing::info!(target: "audit", actor, action, target, result, detail, "audit");
|
||||
let Some(p) = &self.path else { return };
|
||||
let _g = self.lock.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(d) = p.parent() {
|
||||
let _ = std::fs::create_dir_all(d);
|
||||
}
|
||||
if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(p)
|
||||
&& let Ok(line) = serde_json::to_string(&ev)
|
||||
{
|
||||
let _ = writeln!(f, "{line}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Last `n` audit entries (raw JSON lines).
|
||||
pub fn tail(&self, n: usize) -> Vec<serde_json::Value> {
|
||||
let Some(p) = &self.path else { return Vec::new() };
|
||||
let text = std::fs::read_to_string(p).unwrap_or_default();
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
lines[lines.len().saturating_sub(n)..].iter().filter_map(|l| serde_json::from_str(l).ok()).collect()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
//! Offline configuration + zone validation (`easydns check-config`, `econf`, `ezone`).
|
||||
use dns_config::{Config, ZoneType};
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Finding {
|
||||
pub severity: &'static str,
|
||||
pub location: String,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Finding {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}: {}: {}", self.severity, self.location, self.message)
|
||||
}
|
||||
}
|
||||
|
||||
/// Check one zone file: syntax, SOA/NS, CNAME conflicts, out-of-zone data, lint warnings.
|
||||
pub fn check_zone_file(path: &std::path::Path, origin: &str) -> Vec<Finding> {
|
||||
let mut out = Vec::new();
|
||||
let loc = format!("{} ({origin})", path.display());
|
||||
let name = match dns_core::names::parse_name(origin) {
|
||||
Ok(n) => n,
|
||||
Err(e) => {
|
||||
out.push(Finding { severity: "error", location: loc, message: e.to_string() });
|
||||
return out;
|
||||
}
|
||||
};
|
||||
let records = match dns_core::zonefile::parse_file(path, &name) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
out.push(Finding { severity: "error", location: loc, message: e.to_string() });
|
||||
return out;
|
||||
}
|
||||
};
|
||||
match dns_authoritative::Zone::from_records(&name, records) {
|
||||
Ok(z) => {
|
||||
for w in dns_authoritative::zone::lint(&z) {
|
||||
out.push(Finding { severity: "warning", location: loc.clone(), message: w });
|
||||
}
|
||||
out.push(Finding {
|
||||
severity: "info",
|
||||
location: loc,
|
||||
message: format!("zone {} loaded: serial {}, {} records", z.origin(), z.serial(), z.record_count()),
|
||||
});
|
||||
}
|
||||
Err(e) => out.push(Finding { severity: "error", location: loc, message: e.to_string() }),
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Validate a configuration and all primary zone files it references.
|
||||
pub fn check_config(cfg: &Config) -> Vec<Finding> {
|
||||
let mut out: Vec<Finding> = cfg
|
||||
.validate()
|
||||
.into_iter()
|
||||
.map(|i| Finding { severity: if i.is_error() { "error" } else { "warning" }, location: i.path, message: i.message })
|
||||
.collect();
|
||||
for z in &cfg.zones {
|
||||
if z.zone_type == ZoneType::Primary
|
||||
&& let Some(f) = &z.file
|
||||
{
|
||||
let p = cfg.zone_file_path(f);
|
||||
if p.is_file() {
|
||||
out.extend(check_zone_file(&p, &z.name));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Err(e) = cfg.key_ring()
|
||||
&& !out.iter().any(|f| f.location.starts_with("keys"))
|
||||
{
|
||||
out.push(Finding { severity: "warning", location: "keys".into(), message: e });
|
||||
}
|
||||
if cfg.recursion.enabled
|
||||
&& let Err(e) = dns_recursive::hints::load(cfg.recursion.root_hints.as_ref().map(|p| cfg.resolve_path(p)).as_deref())
|
||||
.and_then(|h| dns_recursive::hints::root_servers(&h).map(|_| ()))
|
||||
{
|
||||
out.push(Finding { severity: "error", location: "recursion.root_hints".into(), message: e });
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
//! Coalescing of identical in-flight resolutions.
|
||||
//!
|
||||
//! When many clients ask for the same name/type at the same time and the answer is not
|
||||
//! cached, only the first query (the *leader*) goes out to upstreams or the Internet;
|
||||
//! the others wait for the leader's answer. This cuts outgoing traffic during bursts
|
||||
//! and cache-miss storms, and narrows the window for cache-poisoning attempts that rely
|
||||
//! on many parallel outstanding queries for the same name (the "birthday" attack).
|
||||
//!
|
||||
//! If the leader's future is dropped before it finishes, waiters are released and each
|
||||
//! resolves on its own, so a cancelled request never leaves others hanging.
|
||||
use std::collections::HashMap;
|
||||
use std::future::Future;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use dns_core::answer::Answer;
|
||||
use dns_core::proto::rr::{LowerName, RecordType};
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
/// What makes two resolutions interchangeable.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct FlightKey {
|
||||
/// Route (cache namespace): recursion and each forwarder pool are separate.
|
||||
pub ns: u16,
|
||||
pub name: LowerName,
|
||||
pub rtype: RecordType,
|
||||
pub dnssec_ok: bool,
|
||||
pub cd: bool,
|
||||
}
|
||||
|
||||
/// Waiters per in-flight key; beyond this, queries resolve independently (bounds memory).
|
||||
const MAX_WAITERS: usize = 1024;
|
||||
|
||||
type Waiters = Vec<oneshot::Sender<Answer>>;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Coalescer {
|
||||
inflight: Mutex<HashMap<FlightKey, Waiters>>,
|
||||
}
|
||||
|
||||
/// Removes the leader's entry on completion or cancellation.
|
||||
struct Leader<'a> {
|
||||
c: &'a Coalescer,
|
||||
key: Option<FlightKey>,
|
||||
}
|
||||
|
||||
impl Leader<'_> {
|
||||
fn finish(mut self, answer: &Answer) {
|
||||
if let Some(key) = self.key.take() {
|
||||
let waiters = self.c.lock().remove(&key).unwrap_or_default();
|
||||
for w in waiters {
|
||||
let _ = w.send(answer.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Leader<'_> {
|
||||
fn drop(&mut self) {
|
||||
// cancelled: dropping the senders wakes the waiters, which then resolve themselves
|
||||
if let Some(key) = self.key.take() {
|
||||
self.c.lock().remove(&key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum Role {
|
||||
Leader,
|
||||
Waiter(oneshot::Receiver<Answer>),
|
||||
Alone,
|
||||
}
|
||||
|
||||
impl Coalescer {
|
||||
fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<FlightKey, Waiters>> {
|
||||
self.inflight.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// Number of distinct resolutions currently in flight.
|
||||
pub fn in_flight(&self) -> usize {
|
||||
self.lock().len()
|
||||
}
|
||||
|
||||
/// Run `resolve` for `key`, or share the result of an identical call already running.
|
||||
pub async fn run<F, Fut>(&self, key: FlightKey, resolve: F) -> Answer
|
||||
where
|
||||
F: FnOnce() -> Fut,
|
||||
Fut: Future<Output = Answer>,
|
||||
{
|
||||
let role = {
|
||||
let mut map = self.lock();
|
||||
match map.get_mut(&key) {
|
||||
Some(w) if w.len() < MAX_WAITERS => {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
w.push(tx);
|
||||
Role::Waiter(rx)
|
||||
}
|
||||
Some(_) => Role::Alone,
|
||||
None => {
|
||||
map.insert(key.clone(), Vec::new());
|
||||
Role::Leader
|
||||
}
|
||||
}
|
||||
};
|
||||
match role {
|
||||
Role::Waiter(rx) => match rx.await {
|
||||
Ok(a) => a,
|
||||
Err(_) => resolve().await, // leader was cancelled
|
||||
},
|
||||
Role::Alone => resolve().await,
|
||||
Role::Leader => {
|
||||
let guard = Leader { c: self, key: Some(key) };
|
||||
let a = resolve().await;
|
||||
guard.finish(&a);
|
||||
a
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use dns_core::answer::Source;
|
||||
use dns_core::proto::op::ResponseCode;
|
||||
use dns_core::proto::rr::Name;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
fn key(n: &str) -> FlightKey {
|
||||
FlightKey { ns: 0, name: LowerName::new(&Name::from_ascii(n).unwrap()), rtype: RecordType::A, dnssec_ok: false, cd: false }
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn identical_queries_resolve_once() {
|
||||
let c = Arc::new(Coalescer::default());
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let mut hs = Vec::new();
|
||||
for _ in 0..50 {
|
||||
let (c, calls) = (Arc::clone(&c), Arc::clone(&calls));
|
||||
hs.push(tokio::spawn(async move {
|
||||
c.run(key("a.example."), || async {
|
||||
calls.fetch_add(1, Ordering::SeqCst);
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
Answer::new(ResponseCode::NoError, Source::Recursive)
|
||||
})
|
||||
.await
|
||||
}));
|
||||
}
|
||||
for h in hs {
|
||||
assert_eq!(h.await.unwrap().rcode, ResponseCode::NoError);
|
||||
}
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(c.in_flight(), 0);
|
||||
// different keys are not merged
|
||||
let a = c.run(key("b.example."), || async { Answer::new(ResponseCode::NXDomain, Source::Recursive) }).await;
|
||||
assert_eq!(a.rcode, ResponseCode::NXDomain);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelled_leader_releases_waiters() {
|
||||
let c = Arc::new(Coalescer::default());
|
||||
let c1 = Arc::clone(&c);
|
||||
let leader = tokio::spawn(async move {
|
||||
c1.run(key("c.example."), || async {
|
||||
tokio::time::sleep(Duration::from_secs(60)).await;
|
||||
Answer::new(ResponseCode::NoError, Source::Recursive)
|
||||
})
|
||||
.await
|
||||
});
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
let c2 = Arc::clone(&c);
|
||||
let waiter =
|
||||
tokio::spawn(
|
||||
async move { c2.run(key("c.example."), || async { Answer::new(ResponseCode::ServFail, Source::Recursive) }).await },
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
leader.abort();
|
||||
let a = tokio::time::timeout(Duration::from_secs(2), waiter).await.unwrap().unwrap();
|
||||
assert_eq!(a.rcode, ResponseCode::ServFail); // resolved on its own
|
||||
assert_eq!(c.in_flight(), 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,688 @@
|
||||
//! Message dispatcher: one request in, zero or more encoded responses out.
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
use dns_authoritative::store::TransferEvent;
|
||||
use dns_authoritative::{Lookup, ZoneKind};
|
||||
use dns_config::BlockAction;
|
||||
use dns_core::answer::{Answer, Source};
|
||||
use dns_core::proto::op::{Message, OpCode, ResponseCode};
|
||||
use dns_core::proto::rr::rdata::{A, AAAA, TXT};
|
||||
use dns_core::proto::rr::{DNSClass, LowerName, Name, RData, Record, RecordType};
|
||||
use dns_core::tsig::{ResponseSigner, TsigStatus, verify_request};
|
||||
use dns_core::wire;
|
||||
use dns_policy::RateDecision;
|
||||
|
||||
use crate::runtime::{Runtime, Shared};
|
||||
|
||||
/// Transport a request arrived on.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Transport {
|
||||
Udp,
|
||||
Tcp,
|
||||
Dot,
|
||||
Doh,
|
||||
}
|
||||
|
||||
impl Transport {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Transport::Udp => "udp",
|
||||
Transport::Tcp => "tcp",
|
||||
Transport::Dot => "dot",
|
||||
Transport::Doh => "doh",
|
||||
}
|
||||
}
|
||||
fn stream(self) -> bool {
|
||||
self != Transport::Udp
|
||||
}
|
||||
}
|
||||
|
||||
/// Encoded reply.
|
||||
#[derive(Debug)]
|
||||
pub enum Reply {
|
||||
None,
|
||||
One(Vec<u8>),
|
||||
Many(Vec<Vec<u8>>),
|
||||
}
|
||||
|
||||
/// Max CNAME hops when a local answer continues into resolution.
|
||||
const MAX_CROSS_CNAME: usize = 8;
|
||||
|
||||
fn anonymize(ip: IpAddr) -> String {
|
||||
match dns_policy::canonical_ip(ip) {
|
||||
IpAddr::V4(v4) => {
|
||||
let o = v4.octets();
|
||||
format!("{}.{}.{}.0/24", o[0], o[1], o[2])
|
||||
}
|
||||
IpAddr::V6(v6) => {
|
||||
let s = v6.segments();
|
||||
format!("{:x}:{:x}:{:x}::/48", s[0], s[1], s[2])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the slow path learnt about cacheability of its response.
|
||||
#[derive(Default)]
|
||||
struct CacheSlot {
|
||||
/// Set by `Ctx::finish` for responses that may be stored in the packet cache.
|
||||
info: std::sync::OnceLock<(Source, &'static str)>,
|
||||
/// Data from resolution was mixed into an authoritative answer (CNAME leaving a zone).
|
||||
resolved: std::sync::atomic::AtomicBool,
|
||||
}
|
||||
|
||||
struct Ctx<'a> {
|
||||
shared: &'a Shared,
|
||||
rt: Arc<Runtime>,
|
||||
client: SocketAddr,
|
||||
transport: Transport,
|
||||
tsig: TsigStatus,
|
||||
start: Instant,
|
||||
slot: &'a CacheSlot,
|
||||
}
|
||||
|
||||
impl Ctx<'_> {
|
||||
fn ip(&self) -> IpAddr {
|
||||
dns_policy::canonical_ip(self.client.ip())
|
||||
}
|
||||
|
||||
fn encode(&self, req: &Message, mut resp: Message) -> Reply {
|
||||
if let TsigStatus::Valid { key, mac } = &self.tsig {
|
||||
let mut signer = ResponseSigner::new(key.clone(), mac.clone());
|
||||
return match signer.sign(&mut resp) {
|
||||
Ok(b) if !self.transport.stream() && b.len() > wire::client_udp_limit(req, self.rt.cfg.server.max_udp_payload) => {
|
||||
let mut t = resp.clone();
|
||||
t.answers.clear();
|
||||
t.authorities.clear();
|
||||
t.additionals.clear();
|
||||
t.metadata.truncation = true;
|
||||
signer = ResponseSigner::new(key.clone(), mac.clone());
|
||||
signer.sign(&mut t).map(Reply::One).unwrap_or(Reply::None)
|
||||
}
|
||||
Ok(b) => Reply::One(b),
|
||||
Err(e) => {
|
||||
tracing::error!(error = %e, "failed to sign response");
|
||||
Reply::None
|
||||
}
|
||||
};
|
||||
}
|
||||
let bytes = if self.transport.stream() {
|
||||
wire::encode_tcp(&resp)
|
||||
} else {
|
||||
wire::encode_udp(&resp, wire::client_udp_limit(req, self.rt.cfg.server.max_udp_payload))
|
||||
};
|
||||
bytes.map(Reply::One).unwrap_or(Reply::None)
|
||||
}
|
||||
|
||||
fn finish(&self, req: &Message, resp: Message, source: Source, note: Option<&str>) -> Reply {
|
||||
let rcode = resp.metadata.response_code;
|
||||
let rcs = match rcode {
|
||||
ResponseCode::NoError => "NOERROR",
|
||||
ResponseCode::FormErr => "FORMERR",
|
||||
ResponseCode::ServFail => "SERVFAIL",
|
||||
ResponseCode::NXDomain => "NXDOMAIN",
|
||||
ResponseCode::NotImp => "NOTIMP",
|
||||
ResponseCode::Refused => "REFUSED",
|
||||
_ => "OTHER",
|
||||
};
|
||||
self.shared.metrics.response(rcs, source.as_str(), self.start.elapsed());
|
||||
if matches!(self.tsig, TsigStatus::Unsigned)
|
||||
&& matches!(rcode, ResponseCode::NoError | ResponseCode::NXDomain)
|
||||
&& matches!(
|
||||
source,
|
||||
Source::Authoritative | Source::Cache | Source::Recursive | Source::Forward | Source::Blocked | Source::Local
|
||||
)
|
||||
{
|
||||
let _ = self.slot.info.set((source, rcs));
|
||||
}
|
||||
if self.rt.cfg.logging.query_log {
|
||||
let client = if self.rt.cfg.logging.anonymize_clients { anonymize(self.client.ip()) } else { self.client.ip().to_string() };
|
||||
let (qn, qt) = req.queries.first().map(|q| (q.name.to_string(), q.query_type.to_string())).unwrap_or_default();
|
||||
tracing::info!(target: "query", client, qname = %qn, qtype = %qt, rcode = rcs, source = source.as_str(),
|
||||
transport = self.transport.as_str(), latency_us = self.start.elapsed().as_micros() as u64, note = note.unwrap_or(""), "query");
|
||||
}
|
||||
self.encode(req, resp)
|
||||
}
|
||||
}
|
||||
|
||||
/// Outcome of the UDP fast path in the listener.
|
||||
pub enum FastPath {
|
||||
/// Answered from the packet cache: send these bytes.
|
||||
Hit(Vec<u8>),
|
||||
/// Not answered; pass the rate-limit decision (if one was taken) to [`handle_with`].
|
||||
Miss(Option<RateDecision>),
|
||||
}
|
||||
|
||||
fn cache_hit(shared: &Shared, raw: &[u8], profile: u64, transport: Transport, start: Instant) -> Option<Vec<u8>> {
|
||||
let hit = shared.packet_cache.lookup(raw, profile)?;
|
||||
let qtype: &'static str = RecordType::from(hit.qtype).into();
|
||||
shared.metrics.query(transport.as_str(), qtype);
|
||||
shared.metrics.response(hit.rcode, hit.source, start.elapsed());
|
||||
Some(hit.bytes)
|
||||
}
|
||||
|
||||
/// UDP fast path, run inline in the receive loop: rate limit + packet cache, no task,
|
||||
/// no parsing. Anything else goes to [`handle_with`].
|
||||
pub fn udp_fast_path(shared: &Shared, raw: &[u8], client: SocketAddr) -> FastPath {
|
||||
let rt = shared.rt();
|
||||
if !shared.packet_cache.enabled() || rt.cfg.logging.query_log {
|
||||
return FastPath::Miss(None);
|
||||
}
|
||||
let decision = rt.ratelimit.check(client.ip());
|
||||
if decision == RateDecision::Allow {
|
||||
let profile = rt.client_profile(client.ip(), false);
|
||||
if let Some(b) = cache_hit(shared, raw, profile, Transport::Udp, Instant::now()) {
|
||||
return FastPath::Hit(b);
|
||||
}
|
||||
}
|
||||
FastPath::Miss(Some(decision))
|
||||
}
|
||||
|
||||
/// Handle one raw request.
|
||||
pub async fn handle(shared: &Shared, raw: &[u8], client: SocketAddr, transport: Transport) -> Reply {
|
||||
handle_with(shared, raw, client, transport, None).await
|
||||
}
|
||||
|
||||
/// Handle one raw request. `rl` is a rate-limit decision already taken by the caller,
|
||||
/// who then also already missed the packet cache ([`udp_fast_path`]).
|
||||
pub async fn handle_with(shared: &Shared, raw: &[u8], client: SocketAddr, transport: Transport, rl: Option<RateDecision>) -> Reply {
|
||||
let rt = shared.rt();
|
||||
let start = Instant::now();
|
||||
let pc = &shared.packet_cache;
|
||||
let use_pc = pc.enabled() && !rt.cfg.logging.query_log;
|
||||
let mut rl = rl;
|
||||
let mut profile = 0;
|
||||
if use_pc {
|
||||
profile = rt.client_profile(client.ip(), transport != Transport::Udp);
|
||||
if rl.is_none() {
|
||||
let decision = if transport == Transport::Udp { rt.ratelimit.check(client.ip()) } else { RateDecision::Allow };
|
||||
if decision == RateDecision::Allow {
|
||||
if let Some(b) = cache_hit(shared, raw, profile, transport, start) {
|
||||
return Reply::One(b);
|
||||
}
|
||||
}
|
||||
rl = Some(decision);
|
||||
}
|
||||
}
|
||||
// read before computing: a zone change during the computation makes the entry stale
|
||||
let generation = pc.current_generation();
|
||||
let slot = CacheSlot::default();
|
||||
let reply = handle_inner(shared, Arc::clone(&rt), raw, client, transport, rl, &slot, start).await;
|
||||
if use_pc && let (Reply::One(bytes), Some((source, rcode))) = (&reply, slot.info.get()) {
|
||||
let kind = match source {
|
||||
Source::Authoritative | Source::Local if !slot.resolved.load(std::sync::atomic::Ordering::Relaxed) => {
|
||||
crate::packet_cache::Kind::Authoritative
|
||||
}
|
||||
_ => crate::packet_cache::Kind::Resolved,
|
||||
};
|
||||
// resolved data only when caching is enabled at all
|
||||
if kind == crate::packet_cache::Kind::Authoritative || rt.cfg.cache.enabled {
|
||||
pc.store(raw, profile, bytes, crate::packet_cache::StoreMeta { kind, generation, rcode, source: source.as_str() });
|
||||
}
|
||||
}
|
||||
reply
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn handle_inner(
|
||||
shared: &Shared,
|
||||
rt: Arc<Runtime>,
|
||||
raw: &[u8],
|
||||
client: SocketAddr,
|
||||
transport: Transport,
|
||||
rl: Option<RateDecision>,
|
||||
slot: &CacheSlot,
|
||||
start: Instant,
|
||||
) -> Reply {
|
||||
let req = match Message::from_vec(raw) {
|
||||
Ok(m) => m,
|
||||
Err(_) => {
|
||||
shared.metrics.malformed.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
return wire::formerr_from_raw(raw).map(Reply::One).unwrap_or(Reply::None);
|
||||
}
|
||||
};
|
||||
if req.metadata.message_type == dns_core::proto::op::MessageType::Response {
|
||||
return Reply::None;
|
||||
}
|
||||
if transport == Transport::Udp {
|
||||
match rl.unwrap_or_else(|| rt.ratelimit.check(client.ip())) {
|
||||
RateDecision::Allow => {}
|
||||
RateDecision::Slip => {
|
||||
shared.metrics.rate_limited.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let mut r = wire::response_for(&req);
|
||||
r.metadata.truncation = true;
|
||||
return r.to_vec().map(Reply::One).unwrap_or(Reply::None);
|
||||
}
|
||||
RateDecision::Drop => {
|
||||
shared.metrics.rate_limited.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
return Reply::None;
|
||||
}
|
||||
}
|
||||
}
|
||||
let tsig = verify_request(raw, &req, &rt.ring);
|
||||
let ctx = Ctx { shared, rt: Arc::clone(&rt), client, transport, tsig, start, slot };
|
||||
// static name: no allocation per query
|
||||
let qtype_s: &'static str = req.queries.first().map_or("OTHER", |q| q.query_type.into());
|
||||
shared.metrics.query(transport.as_str(), qtype_s);
|
||||
|
||||
let mut resp = wire::response_for(&req);
|
||||
if let TsigStatus::Invalid(e) = &ctx.tsig {
|
||||
shared.metrics.tsig_failures.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
tracing::warn!(client = %client, error = %e, "TSIG verification failed");
|
||||
resp.metadata.response_code = ResponseCode::NotAuth;
|
||||
return ctx.finish(&req, resp, Source::Refused, Some(e));
|
||||
}
|
||||
if req.edns.as_ref().is_some_and(|e| e.version() > 0) {
|
||||
resp.metadata.response_code = ResponseCode::BADVERS;
|
||||
return ctx.finish(&req, resp, Source::Local, None);
|
||||
}
|
||||
if req.queries.len() != 1 {
|
||||
resp.metadata.response_code = ResponseCode::FormErr;
|
||||
return ctx.finish(&req, resp, Source::Local, None);
|
||||
}
|
||||
match req.metadata.op_code {
|
||||
OpCode::Query => handle_query(&ctx, &req, resp).await,
|
||||
OpCode::Notify => handle_notify(&ctx, &req, resp),
|
||||
OpCode::Update => handle_update(&ctx, &req, resp),
|
||||
_ => {
|
||||
resp.metadata.response_code = ResponseCode::NotImp;
|
||||
ctx.finish(&req, resp, Source::Local, None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn chaos(ctx: &Ctx<'_>, req: &Message, mut resp: Message) -> Reply {
|
||||
let q = &req.queries[0];
|
||||
let name = q.name.to_lowercase().to_string();
|
||||
let txt = match (&ctx.rt.cfg.server.identity, name.as_str(), q.query_type) {
|
||||
(Some(id), "id.server." | "hostname.bind.", RecordType::TXT) => Some(id.clone()),
|
||||
(Some(_), "version.bind." | "version.server.", RecordType::TXT) => Some(format!("EasyDNS {}", ctx.shared.version)),
|
||||
_ => None,
|
||||
};
|
||||
match txt {
|
||||
Some(t) => {
|
||||
let mut r = Record::from_rdata(q.name.clone(), 0, RData::TXT(TXT::new(vec![t])));
|
||||
r.dns_class = DNSClass::CH;
|
||||
resp.metadata.authoritative = true;
|
||||
resp.add_answer(r);
|
||||
}
|
||||
None => resp.metadata.response_code = ResponseCode::Refused,
|
||||
}
|
||||
ctx.finish(req, resp, Source::Local, None)
|
||||
}
|
||||
|
||||
async fn handle_query(ctx: &Ctx<'_>, req: &Message, mut resp: Message) -> Reply {
|
||||
let q = req.queries[0].clone();
|
||||
if q.query_class == DNSClass::CH {
|
||||
return chaos(ctx, req, resp);
|
||||
}
|
||||
if q.query_class != DNSClass::IN && q.query_class != DNSClass::ANY {
|
||||
resp.metadata.response_code = ResponseCode::Refused;
|
||||
return ctx.finish(req, resp, Source::Refused, None);
|
||||
}
|
||||
if matches!(q.query_type, RecordType::AXFR | RecordType::IXFR) {
|
||||
return handle_xfr(ctx, req, resp);
|
||||
}
|
||||
if matches!(q.query_type, RecordType::OPT | RecordType::TSIG) {
|
||||
resp.metadata.response_code = ResponseCode::FormErr;
|
||||
return ctx.finish(req, resp, Source::Local, None);
|
||||
}
|
||||
let ip = ctx.ip();
|
||||
let rt = &ctx.rt;
|
||||
let dnssec_ok = req.edns.as_ref().is_some_and(|e| e.flags().dnssec_ok);
|
||||
let may_resolve = rt.router.can_resolve() && rt.recursion_acl.contains(ip);
|
||||
resp.metadata.recursion_available = may_resolve;
|
||||
let view = rt.views.classify(ip);
|
||||
let qname = q.name.clone();
|
||||
|
||||
// 1. Local authoritative data.
|
||||
if let Some(entry) = rt.zones.find(&LowerName::new(&qname), view) {
|
||||
let Some(zone) = entry.current() else {
|
||||
resp.metadata.response_code = ResponseCode::ServFail;
|
||||
return ctx.finish(req, resp, Source::Authoritative, Some("zone not loaded or expired"));
|
||||
};
|
||||
match zone.lookup(&qname, q.query_type, dnssec_ok) {
|
||||
Lookup::Answer { answers, additional, authority, .. } => {
|
||||
resp.metadata.authoritative = true;
|
||||
resp.answers = answers;
|
||||
resp.authorities = authority;
|
||||
resp.additionals = additional;
|
||||
}
|
||||
Lookup::NoData { soa, proof } => {
|
||||
resp.metadata.authoritative = true;
|
||||
resp.authorities.push(soa);
|
||||
resp.authorities.extend(proof);
|
||||
}
|
||||
Lookup::NxDomain { soa, answers, proof } => {
|
||||
resp.metadata.authoritative = true;
|
||||
resp.metadata.response_code = ResponseCode::NXDomain;
|
||||
resp.answers = answers;
|
||||
resp.authorities.push(soa);
|
||||
resp.authorities.extend(proof);
|
||||
}
|
||||
Lookup::Referral { ns, glue, ds } => {
|
||||
if may_resolve && req.metadata.recursion_desired {
|
||||
let a = rt.router.resolve(&qname, q.query_type, ip, dnssec_ok, req.metadata.checking_disabled).await;
|
||||
return finish_answer(ctx, req, resp, a);
|
||||
}
|
||||
resp.authorities = ns;
|
||||
resp.authorities.extend(ds);
|
||||
resp.additionals = glue;
|
||||
}
|
||||
Lookup::CnameOut { answers, target } => {
|
||||
resp.metadata.authoritative = true;
|
||||
resp.answers = answers;
|
||||
if may_resolve && req.metadata.recursion_desired {
|
||||
ctx.slot.resolved.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
let a = resolve_target(ctx, &target, q.query_type, ip, dnssec_ok, req.metadata.checking_disabled, view).await;
|
||||
let negative = a.answers_empty_negative();
|
||||
resp.answers.extend(a.answers);
|
||||
resp.metadata.response_code = a.rcode;
|
||||
if negative {
|
||||
resp.authorities = a.authority;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return ctx.finish(req, resp, Source::Authoritative, None);
|
||||
}
|
||||
|
||||
// 2. Resolution is only for permitted clients.
|
||||
if !may_resolve || !req.metadata.recursion_desired {
|
||||
resp.metadata.response_code = ResponseCode::Refused;
|
||||
return ctx.finish(req, resp, Source::Refused, None);
|
||||
}
|
||||
// 3. Local-only names never leave the host.
|
||||
if rt.local_only.matches(&qname) {
|
||||
resp.metadata.response_code = ResponseCode::NXDomain;
|
||||
return ctx.finish(req, resp, Source::Local, Some("local-only name"));
|
||||
}
|
||||
// 4. Policy.
|
||||
if let Some(m) = rt.policy.check(&qname, ip) {
|
||||
ctx.shared.metrics.blocked.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
if rt.policy.log {
|
||||
tracing::info!(target: "policy", qname = %qname, list = %m.list, rule = %m.rule, category = m.category.as_deref().unwrap_or(""), "blocked");
|
||||
}
|
||||
apply_block(rt, &q.name, q.query_type, &mut resp);
|
||||
let note = format!("blocked by {} ({})", m.list, m.rule);
|
||||
return ctx.finish(req, resp, Source::Blocked, Some(¬e));
|
||||
}
|
||||
// 5. Forwarding / recursion.
|
||||
let a = rt.router.resolve(&qname, q.query_type, ip, dnssec_ok, req.metadata.checking_disabled).await;
|
||||
finish_answer(ctx, req, resp, a)
|
||||
}
|
||||
|
||||
trait NegExt {
|
||||
fn answers_empty_negative(&self) -> bool;
|
||||
}
|
||||
impl NegExt for Answer {
|
||||
fn answers_empty_negative(&self) -> bool {
|
||||
self.answers.is_empty() && matches!(self.rcode, ResponseCode::NXDomain | ResponseCode::NoError)
|
||||
}
|
||||
}
|
||||
|
||||
/// Continue a CNAME chain that left a local zone: other local zones first, then resolution.
|
||||
async fn resolve_target(
|
||||
ctx: &Ctx<'_>,
|
||||
target: &Name,
|
||||
qtype: RecordType,
|
||||
ip: IpAddr,
|
||||
dnssec_ok: bool,
|
||||
cd: bool,
|
||||
view: Option<&str>,
|
||||
) -> Answer {
|
||||
let mut out = Answer::new(ResponseCode::NoError, Source::Authoritative);
|
||||
let mut cur = target.clone();
|
||||
for _ in 0..MAX_CROSS_CNAME {
|
||||
if let Some(entry) = ctx.rt.zones.find(&LowerName::new(&cur), view) {
|
||||
let Some(zone) = entry.current() else { return Answer::servfail(Source::Authoritative, "zone unavailable") };
|
||||
match zone.lookup(&cur, qtype, dnssec_ok) {
|
||||
Lookup::Answer { answers, .. } => {
|
||||
out.answers.extend(answers);
|
||||
return out;
|
||||
}
|
||||
Lookup::CnameOut { answers, target } => {
|
||||
out.answers.extend(answers);
|
||||
cur = target;
|
||||
continue;
|
||||
}
|
||||
Lookup::NoData { soa, .. } => {
|
||||
out.authority.push(soa);
|
||||
return out;
|
||||
}
|
||||
Lookup::NxDomain { soa, answers, .. } => {
|
||||
out.answers.extend(answers);
|
||||
out.authority.push(soa);
|
||||
out.rcode = ResponseCode::NXDomain;
|
||||
return out;
|
||||
}
|
||||
Lookup::Referral { .. } => break,
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ctx.rt.local_only.matches(&cur) || ctx.rt.policy.check(&cur, ip).is_some() {
|
||||
out.rcode = ResponseCode::NXDomain;
|
||||
return out;
|
||||
}
|
||||
let mut a = ctx.rt.router.resolve(&cur, qtype, ip, dnssec_ok, cd).await;
|
||||
out.answers.append(&mut a.answers);
|
||||
out.authority = a.authority;
|
||||
out.rcode = a.rcode;
|
||||
out
|
||||
}
|
||||
|
||||
fn apply_block(rt: &Runtime, name: &Name, qtype: RecordType, resp: &mut Message) {
|
||||
let ttl = rt.policy.ttl;
|
||||
match rt.policy.action {
|
||||
BlockAction::Nxdomain => resp.metadata.response_code = ResponseCode::NXDomain,
|
||||
BlockAction::Refused => resp.metadata.response_code = ResponseCode::Refused,
|
||||
BlockAction::Null | BlockAction::Address => {
|
||||
let (v4, v6) = if rt.policy.action == BlockAction::Null {
|
||||
(std::net::Ipv4Addr::UNSPECIFIED, std::net::Ipv6Addr::UNSPECIFIED)
|
||||
} else {
|
||||
(rt.policy.v4.unwrap_or(std::net::Ipv4Addr::UNSPECIFIED), rt.policy.v6.unwrap_or(std::net::Ipv6Addr::UNSPECIFIED))
|
||||
};
|
||||
match qtype {
|
||||
RecordType::A => resp.add_answer(Record::from_rdata(name.clone(), ttl, RData::A(A::from(v4)))),
|
||||
RecordType::AAAA => resp.add_answer(Record::from_rdata(name.clone(), ttl, RData::AAAA(AAAA::from(v6)))),
|
||||
_ => resp, // NODATA
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn finish_answer(ctx: &Ctx<'_>, req: &Message, mut resp: Message, mut a: Answer) -> Reply {
|
||||
if a.security == dns_core::answer::Security::Bogus && !req.metadata.checking_disabled {
|
||||
// RFC 4035 §5.5: bogus data is not returned unless the client disabled checking.
|
||||
ctx.shared.metrics.dnssec_bogus.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
resp.metadata.response_code = ResponseCode::ServFail;
|
||||
resp.metadata.authoritative = false;
|
||||
let note = a.note.take().unwrap_or_else(|| "DNSSEC validation failed".into());
|
||||
return ctx.finish(req, resp, a.source, Some(¬e));
|
||||
}
|
||||
resp.metadata.response_code = a.rcode;
|
||||
resp.metadata.authoritative = false; // never AA for resolved data
|
||||
resp.answers = a.answers;
|
||||
resp.authorities = a.authority;
|
||||
resp.additionals = a.additional;
|
||||
let dnssec_ok = req.edns.as_ref().is_some_and(|e| e.flags().dnssec_ok);
|
||||
if !dnssec_ok {
|
||||
let strip =
|
||||
|v: &mut Vec<Record>| v.retain(|r| !matches!(r.record_type(), RecordType::RRSIG | RecordType::NSEC | RecordType::NSEC3));
|
||||
strip(&mut resp.answers);
|
||||
strip(&mut resp.authorities);
|
||||
}
|
||||
resp.metadata.authentic_data = a.security == dns_core::answer::Security::Secure && (dnssec_ok || req.metadata.authentic_data);
|
||||
match a.security {
|
||||
dns_core::answer::Security::Secure => ctx.shared.metrics.dnssec_secure.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
|
||||
dns_core::answer::Security::Insecure => ctx.shared.metrics.dnssec_insecure.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
|
||||
dns_core::answer::Security::Bogus => ctx.shared.metrics.dnssec_bogus.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
|
||||
dns_core::answer::Security::Indeterminate => 0,
|
||||
};
|
||||
if a.source == Source::Forward || a.source == Source::Recursive {
|
||||
if a.rcode == ResponseCode::ServFail {
|
||||
ctx.shared.metrics.upstream_errors.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
} else {
|
||||
ctx.shared.metrics.upstream_latency.observe(ctx.start.elapsed());
|
||||
}
|
||||
}
|
||||
let note = a.note.clone();
|
||||
ctx.finish(req, resp, a.source, note.as_deref())
|
||||
}
|
||||
|
||||
fn xfr_refuse(ctx: &Ctx<'_>, req: &Message, mut resp: Message, rcode: ResponseCode, why: &str) -> Reply {
|
||||
ctx.shared.metrics.xfr_out_refused.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
tracing::warn!(client = %ctx.client, zone = %req.queries[0].name, reason = why, "zone transfer refused");
|
||||
resp.metadata.response_code = rcode;
|
||||
ctx.finish(req, resp, Source::Refused, Some(why))
|
||||
}
|
||||
|
||||
fn handle_xfr(ctx: &Ctx<'_>, req: &Message, mut resp: Message) -> Reply {
|
||||
let q = &req.queries[0];
|
||||
let rt = &ctx.rt;
|
||||
let Some(entry) = rt.zones.get(&q.name) else {
|
||||
return xfr_refuse(ctx, req, resp, ResponseCode::NotAuth, "not authoritative for zone");
|
||||
};
|
||||
// Authorisation: ACL, plus TSIG with the configured key when one is set.
|
||||
let ip = ctx.ip();
|
||||
let acl_ok = entry.transfer_allowed_from(ip);
|
||||
let allowed = match (&entry.transfer_key, &ctx.tsig) {
|
||||
(Some(k), TsigStatus::Valid { key, .. }) => key.name == k.name && (entry.transfer_acl.is_empty() || acl_ok),
|
||||
(Some(_), _) => false,
|
||||
(None, _) => acl_ok,
|
||||
};
|
||||
if !allowed {
|
||||
return xfr_refuse(ctx, req, resp, ResponseCode::Refused, "client not authorised for transfer");
|
||||
}
|
||||
let Some(zone) = entry.current() else {
|
||||
return xfr_refuse(ctx, req, resp, ResponseCode::ServFail, "zone not loaded");
|
||||
};
|
||||
let start = Instant::now();
|
||||
let (records, kind) = if q.query_type == RecordType::AXFR {
|
||||
if ctx.transport == Transport::Udp {
|
||||
return xfr_refuse(ctx, req, resp, ResponseCode::Refused, "AXFR over UDP");
|
||||
}
|
||||
(dns_authoritative::xfr::axfr_records(&zone), "AXFR")
|
||||
} else {
|
||||
let client_serial = req.authorities.iter().find_map(|r| match &r.data {
|
||||
RData::SOA(s) => Some(s.serial),
|
||||
_ => None,
|
||||
});
|
||||
let Some(cs) = client_serial else {
|
||||
resp.metadata.response_code = ResponseCode::FormErr;
|
||||
return ctx.finish(req, resp, Source::Authoritative, Some("IXFR without SOA"));
|
||||
};
|
||||
let journal = entry.journal.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (recs, incremental) = dns_authoritative::xfr::ixfr_records(&zone, &journal, cs);
|
||||
drop(journal);
|
||||
if ctx.transport == Transport::Udp && recs.len() > 1 {
|
||||
// Too big for UDP: tell the client to retry over TCP (RFC 1995 §2).
|
||||
resp.metadata.authoritative = true;
|
||||
resp.answers.push(zone.soa().clone());
|
||||
return ctx.finish(req, resp, Source::Authoritative, Some("IXFR via TCP"));
|
||||
}
|
||||
(recs, if incremental { "IXFR" } else { "IXFR(AXFR-style)" })
|
||||
};
|
||||
let count = records.len();
|
||||
let messages = dns_authoritative::xfr::chunk(req, records);
|
||||
let mut out = Vec::with_capacity(messages.len());
|
||||
let mut signer = match &ctx.tsig {
|
||||
TsigStatus::Valid { key, mac } => Some(ResponseSigner::new(key.clone(), mac.clone())),
|
||||
_ => None,
|
||||
};
|
||||
for mut m in messages {
|
||||
let b = match signer.as_mut() {
|
||||
Some(s) => s.sign(&mut m).ok(),
|
||||
None => m.to_vec().ok(),
|
||||
};
|
||||
match b {
|
||||
Some(b) => out.push(b),
|
||||
None => return xfr_refuse(ctx, req, wire::response_for(req), ResponseCode::ServFail, "encoding failed"),
|
||||
}
|
||||
}
|
||||
ctx.shared.metrics.xfr_out_ok.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
ctx.shared.metrics.response("NOERROR", "authoritative", start.elapsed());
|
||||
tracing::info!(zone = %entry.name, client = %ctx.client, kind, records = count, serial = zone.serial(), "zone transfer served");
|
||||
entry.record_transfer(TransferEvent {
|
||||
time_unix: dns_core::tsig::now(),
|
||||
direction: "out",
|
||||
kind: kind.into(),
|
||||
peer: ctx.client.to_string(),
|
||||
serial: Some(zone.serial()),
|
||||
records: count,
|
||||
ok: true,
|
||||
error: None,
|
||||
duration_ms: start.elapsed().as_millis() as u64,
|
||||
});
|
||||
Reply::Many(out)
|
||||
}
|
||||
|
||||
fn handle_notify(ctx: &Ctx<'_>, req: &Message, mut resp: Message) -> Reply {
|
||||
let q = &req.queries[0];
|
||||
resp.metadata.authoritative = true;
|
||||
let entry = ctx.rt.zones.get(&q.name).filter(|e| e.kind == ZoneKind::Secondary);
|
||||
let Some(entry) = entry else {
|
||||
ctx.shared.metrics.notify_refused.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
resp.metadata.response_code = ResponseCode::NotAuth;
|
||||
return ctx.finish(req, resp, Source::Refused, Some("NOTIFY for unknown zone"));
|
||||
};
|
||||
let ip = ctx.ip();
|
||||
let key_required = entry.client_key.is_some();
|
||||
let key_ok = match (&entry.client_key, &ctx.tsig) {
|
||||
(Some(k), TsigStatus::Valid { key, .. }) => key.name == k.name,
|
||||
(Some(_), _) => false,
|
||||
(None, _) => true,
|
||||
};
|
||||
// Accept from allowed sources; with a TSIG key configured a correctly signed NOTIFY is also accepted.
|
||||
if !(entry.notify_allowed_from(ip) && (key_ok || !key_required) || key_required && key_ok) {
|
||||
ctx.shared.metrics.notify_refused.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
tracing::warn!(zone = %entry.name, client = %ctx.client, "NOTIFY refused");
|
||||
resp.metadata.response_code = ResponseCode::Refused;
|
||||
return ctx.finish(req, resp, Source::Refused, Some("NOTIFY not allowed"));
|
||||
}
|
||||
ctx.shared.metrics.notify_received.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
tracing::info!(zone = %entry.name, client = %ctx.client, "NOTIFY received; scheduling refresh");
|
||||
entry.refresh_trigger.notify_one();
|
||||
ctx.finish(req, resp, Source::Authoritative, None)
|
||||
}
|
||||
|
||||
fn handle_update(ctx: &Ctx<'_>, req: &Message, mut resp: Message) -> Reply {
|
||||
let q = &req.queries[0];
|
||||
resp.answers.clear();
|
||||
let Some(entry) = ctx.rt.zones.get(&q.name) else {
|
||||
resp.metadata.response_code = ResponseCode::NotAuth;
|
||||
ctx.shared.metrics.updates_refused.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
return ctx.finish(req, resp, Source::Refused, Some("UPDATE for unknown zone"));
|
||||
};
|
||||
let actor = match &ctx.tsig {
|
||||
TsigStatus::Valid { key, .. } => format!("tsig:{} from {}", key.name, ctx.client.ip()),
|
||||
_ => format!("unsigned from {}", ctx.client.ip()),
|
||||
};
|
||||
let signer = match &ctx.tsig {
|
||||
TsigStatus::Valid { key, .. } => Some(&key.name),
|
||||
_ => None,
|
||||
};
|
||||
let who = dns_authoritative::update::Requester { signer, addr_ok: entry.update_allowed_from(ctx.ip()) };
|
||||
let outcome = dns_authoritative::update::apply(&entry, req, who);
|
||||
resp.metadata.response_code = outcome.rcode;
|
||||
let ok = outcome.rcode == ResponseCode::NoError;
|
||||
ctx.shared.audit.record(
|
||||
&actor,
|
||||
"dns-update",
|
||||
&entry.name.to_string(),
|
||||
if ok { "ok" } else { "refused" },
|
||||
&format!("{} (+{} -{} serial {:?})", outcome.reason, outcome.added, outcome.removed, outcome.new_serial),
|
||||
);
|
||||
if ok {
|
||||
ctx.shared.metrics.updates_ok.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
if outcome.added + outcome.removed > 0 {
|
||||
entry.send_notifies();
|
||||
}
|
||||
} else {
|
||||
ctx.shared.metrics.updates_refused.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
ctx.finish(req, resp, Source::Authoritative, Some(&outcome.reason))
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
//! EasyDNS server: ties the roles together.
|
||||
//!
|
||||
//! Query processing order (see docs/hybrid.md):
|
||||
//! 1. parse / FORMERR, drop responses, rate limit (UDP),
|
||||
//! 2. TSIG verification, opcode dispatch (QUERY / NOTIFY / UPDATE),
|
||||
//! 3. zone transfers (AXFR/IXFR) with ACL + TSIG,
|
||||
//! 4. most specific local authoritative zone visible in the client's view → AA answer,
|
||||
//! 5. clients without recursion permission → REFUSED (no open resolver, no leaks),
|
||||
//! 6. local-only names (RFC 6761/6303) → NXDOMAIN without leaving the host,
|
||||
//! 7. allow/block policy,
|
||||
//! 8. conditional forwarding (longest suffix), then the default resolution
|
||||
//! (recursive / forward / forward-then-recursive), with a per-route cache namespace.
|
||||
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
|
||||
|
||||
pub mod audit;
|
||||
pub mod check;
|
||||
pub mod coalesce;
|
||||
pub mod handler;
|
||||
pub mod listener;
|
||||
pub mod packet_cache;
|
||||
pub mod router;
|
||||
pub mod runtime;
|
||||
pub mod server;
|
||||
pub mod tls;
|
||||
|
||||
pub use runtime::{Runtime, Shared};
|
||||
pub use server::{Server, ServerHandle};
|
||||
@@ -0,0 +1,309 @@
|
||||
//! UDP and TCP listeners with backpressure and graceful shutdown.
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
use tokio::net::{TcpListener, UdpSocket};
|
||||
use tokio::sync::{Semaphore, watch};
|
||||
|
||||
use crate::handler::{Reply, Transport, handle};
|
||||
use crate::runtime::Shared;
|
||||
|
||||
/// Max TCP queries pipelined on one connection before it is closed.
|
||||
const MAX_QUERIES_PER_CONN: usize = 10_000;
|
||||
|
||||
/// Kernel socket buffer requested per UDP socket. The kernel caps it at
|
||||
/// net.core.{r,w}mem_max; memory is only consumed while packets are queued.
|
||||
const UDP_SOCKET_BUFFER: usize = 1 << 20;
|
||||
|
||||
/// Upper bound for `server.udp_sockets`.
|
||||
const MAX_UDP_SOCKETS: usize = 64;
|
||||
|
||||
fn udp_socket(addr: SocketAddr, reuse_port: bool) -> std::io::Result<std::net::UdpSocket> {
|
||||
use socket2::{Domain, Protocol, Socket, Type};
|
||||
let s = Socket::new(Domain::for_address(addr), Type::DGRAM, Some(Protocol::UDP))?;
|
||||
if addr.is_ipv6() {
|
||||
// like BIND: `[::]` serves IPv6 only, so it can be listed next to `0.0.0.0`
|
||||
s.set_only_v6(true)?;
|
||||
}
|
||||
#[cfg(all(unix, not(any(target_os = "solaris", target_os = "illumos", target_os = "cygwin"))))]
|
||||
if reuse_port {
|
||||
s.set_reuse_port(true)?;
|
||||
}
|
||||
#[cfg(not(all(unix, not(any(target_os = "solaris", target_os = "illumos", target_os = "cygwin")))))]
|
||||
let _ = reuse_port;
|
||||
// best effort: a larger queue absorbs bursts instead of dropping them
|
||||
let _ = s.set_recv_buffer_size(UDP_SOCKET_BUFFER);
|
||||
let _ = s.set_send_buffer_size(UDP_SOCKET_BUFFER);
|
||||
s.set_nonblocking(true)?;
|
||||
s.bind(&addr.into())?;
|
||||
Ok(s.into())
|
||||
}
|
||||
|
||||
/// Bind a TCP listener (SO_REUSEADDR for quick restarts, IPv6-only for `[::]` addresses).
|
||||
pub fn bind_tcp(addr: SocketAddr) -> std::io::Result<tokio::net::TcpListener> {
|
||||
use socket2::{Domain, Protocol, Socket, Type};
|
||||
let s = Socket::new(Domain::for_address(addr), Type::STREAM, Some(Protocol::TCP))?;
|
||||
if addr.is_ipv6() {
|
||||
s.set_only_v6(true)?;
|
||||
}
|
||||
#[cfg(unix)]
|
||||
s.set_reuse_address(true)?;
|
||||
s.set_nonblocking(true)?;
|
||||
s.bind(&addr.into())?;
|
||||
s.listen(1024)?;
|
||||
tokio::net::TcpListener::from_std(s.into())
|
||||
}
|
||||
|
||||
/// Number of UDP sockets to open per address for `server.udp_sockets` (0 = auto).
|
||||
pub fn udp_socket_count(configured: usize) -> usize {
|
||||
if configured > 0 {
|
||||
return configured.min(MAX_UDP_SOCKETS);
|
||||
}
|
||||
std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1).clamp(1, 16)
|
||||
}
|
||||
|
||||
/// Bind `count` UDP sockets on `addr` sharing one port via SO_REUSEPORT, so the kernel
|
||||
/// load-balances queries across them and each socket gets its own receive loop.
|
||||
/// Falls back to fewer sockets (at least one) when SO_REUSEPORT is unavailable.
|
||||
pub fn bind_udp_group(addr: SocketAddr, count: usize) -> std::io::Result<Vec<UdpSocket>> {
|
||||
let count = count.clamp(1, MAX_UDP_SOCKETS);
|
||||
let first = match udp_socket(addr, count > 1) {
|
||||
Ok(s) => s,
|
||||
Err(e) if count > 1 => {
|
||||
tracing::warn!(%addr, error = %e, "SO_REUSEPORT unavailable, using a single UDP socket");
|
||||
return Ok(vec![UdpSocket::from_std(udp_socket(addr, false)?)?]);
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
// with port 0 the kernel picked a port: the rest of the group must join that one
|
||||
let actual = first.local_addr()?;
|
||||
let mut socks = vec![UdpSocket::from_std(first)?];
|
||||
for _ in 1..count {
|
||||
match udp_socket(actual, true).and_then(UdpSocket::from_std) {
|
||||
Ok(s) => socks.push(s),
|
||||
Err(e) => {
|
||||
tracing::warn!(%actual, error = %e, opened = socks.len(), "could not open more UDP sockets");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(socks)
|
||||
}
|
||||
|
||||
/// Serve one UDP socket until shutdown. `inflight` is shared by all UDP sockets so
|
||||
/// `server.max_inflight` stays a server-wide bound. On Linux packets are received and
|
||||
/// cached answers sent in batches (`recvmmsg`/`sendmmsg`): one system call for up to
|
||||
/// [`batch::BATCH`] packets instead of two per query.
|
||||
pub async fn serve_udp(shared: Arc<Shared>, sock: Arc<UdpSocket>, inflight: Arc<Semaphore>, shutdown: watch::Receiver<bool>) {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
batch::serve(shared, sock, inflight, shutdown).await
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
serve_udp_simple(shared, sock, inflight, shutdown).await
|
||||
}
|
||||
}
|
||||
|
||||
/// Hand one received packet to the fast path or a task. Returns a cached answer to send.
|
||||
fn dispatch(shared: &Arc<Shared>, sock: &Arc<UdpSocket>, inflight: &Arc<Semaphore>, pkt: &[u8], peer: SocketAddr) -> Option<Vec<u8>> {
|
||||
if pkt.len() < 12 {
|
||||
return None;
|
||||
}
|
||||
let pre = match crate::handler::udp_fast_path(shared, pkt, peer) {
|
||||
crate::handler::FastPath::Hit(b) => return Some(b),
|
||||
crate::handler::FastPath::Miss(d) => d,
|
||||
};
|
||||
let Ok(permit) = Arc::clone(inflight).try_acquire_owned() else {
|
||||
// overloaded: shed load rather than queueing unboundedly
|
||||
shared.metrics.rate_limited.fetch_add(1, Ordering::Relaxed);
|
||||
return None;
|
||||
};
|
||||
let pkt = pkt.to_vec();
|
||||
let shared = Arc::clone(shared);
|
||||
let sock = Arc::clone(sock);
|
||||
tokio::spawn(async move {
|
||||
shared.metrics.inflight.fetch_add(1, Ordering::Relaxed);
|
||||
if let Reply::One(b) = crate::handler::handle_with(&shared, &pkt, peer, Transport::Udp, pre).await {
|
||||
let _ = sock.send_to(&b, peer).await;
|
||||
}
|
||||
shared.metrics.inflight.fetch_sub(1, Ordering::Relaxed);
|
||||
drop(permit);
|
||||
});
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod batch {
|
||||
use std::io::{IoSlice, IoSliceMut};
|
||||
use std::net::SocketAddr;
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::sync::Arc;
|
||||
|
||||
use nix::sys::socket::{MsgFlags, MultiHeaders, SockaddrStorage, recvmmsg, sendmmsg};
|
||||
use tokio::io::Interest;
|
||||
use tokio::net::UdpSocket;
|
||||
use tokio::sync::{Semaphore, watch};
|
||||
|
||||
use crate::runtime::Shared;
|
||||
|
||||
/// Packets per system call.
|
||||
pub const BATCH: usize = 32;
|
||||
const BUF: usize = 4096;
|
||||
|
||||
fn to_std(a: &SockaddrStorage) -> Option<SocketAddr> {
|
||||
if let Some(v4) = a.as_sockaddr_in() {
|
||||
return Some(SocketAddr::V4((*v4).into()));
|
||||
}
|
||||
a.as_sockaddr_in6().map(|v6| SocketAddr::V6((*v6).into()))
|
||||
}
|
||||
|
||||
/// Receive up to BATCH packets without blocking: (length, sender) per packet.
|
||||
/// (Headers are built per call: they hold raw pointers and must not live across `await`.)
|
||||
fn recv_batch(fd: i32, bufs: &mut [Vec<u8>]) -> std::io::Result<Vec<(usize, Option<SocketAddr>)>> {
|
||||
let mut hdrs = MultiHeaders::<SockaddrStorage>::preallocate(bufs.len(), None);
|
||||
let mut iovs: Vec<[IoSliceMut<'_>; 1]> = bufs.iter_mut().map(|b| [IoSliceMut::new(&mut b[..])]).collect();
|
||||
let res = recvmmsg(fd, &mut hdrs, iovs.iter_mut(), MsgFlags::MSG_DONTWAIT, None).map_err(std::io::Error::from)?;
|
||||
Ok(res.map(|m| (m.bytes, m.address.as_ref().and_then(to_std))).collect())
|
||||
}
|
||||
|
||||
/// Send as many replies as possible in one call; returns how many were sent.
|
||||
fn send_batch(fd: i32, out: &[(Vec<u8>, SocketAddr)]) -> std::io::Result<usize> {
|
||||
let mut hdrs = MultiHeaders::<SockaddrStorage>::preallocate(out.len(), None);
|
||||
let iovs: Vec<[IoSlice<'_>; 1]> = out.iter().map(|(b, _)| [IoSlice::new(b)]).collect();
|
||||
let addrs: Vec<Option<SockaddrStorage>> = out.iter().map(|(_, a)| Some(SockaddrStorage::from(*a))).collect();
|
||||
let res = sendmmsg(fd, &mut hdrs, iovs.iter(), addrs, [], MsgFlags::MSG_DONTWAIT).map_err(std::io::Error::from)?;
|
||||
Ok(res.count())
|
||||
}
|
||||
|
||||
pub async fn serve(shared: Arc<Shared>, sock: Arc<UdpSocket>, inflight: Arc<Semaphore>, mut shutdown: watch::Receiver<bool>) {
|
||||
let fd = sock.as_raw_fd();
|
||||
let mut bufs: Vec<Vec<u8>> = (0..BATCH).map(|_| vec![0u8; BUF]).collect();
|
||||
let mut out: Vec<(Vec<u8>, SocketAddr)> = Vec::with_capacity(BATCH);
|
||||
loop {
|
||||
tokio::select! {
|
||||
r = sock.readable() => if r.is_err() { continue },
|
||||
_ = shutdown.changed() => break,
|
||||
}
|
||||
let got = match sock.try_io(Interest::READABLE, || recv_batch(fd, &mut bufs)) {
|
||||
Ok(v) => v,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => continue,
|
||||
Err(e) if e.raw_os_error() == Some(nix::libc::ENOSYS) => {
|
||||
tracing::warn!("recvmmsg unavailable; using one system call per packet");
|
||||
return super::serve_udp_simple(shared, sock, inflight, shutdown).await;
|
||||
}
|
||||
Err(e) => {
|
||||
// ICMP errors (e.g. connection refused) surface here on Linux; keep serving.
|
||||
tracing::debug!(error = %e, "UDP recv error");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
for (i, (n, peer)) in got.into_iter().enumerate() {
|
||||
let Some(peer) = peer else { continue };
|
||||
if let Some(reply) = super::dispatch(&shared, &sock, &inflight, &bufs[i][..n], peer) {
|
||||
out.push((reply, peer));
|
||||
}
|
||||
}
|
||||
// cached answers of this batch: one sendmmsg; whatever does not fit goes one by one
|
||||
let mut sent = 0;
|
||||
while sent < out.len() {
|
||||
match sock.try_io(Interest::WRITABLE, || send_batch(fd, &out[sent..])) {
|
||||
Ok(0) => break,
|
||||
Ok(k) => sent += k,
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
for (b, peer) in out.drain(..).skip(sent) {
|
||||
let _ = sock.send_to(&b, peer).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One `recv_from`/`send_to` per packet (non-Linux, or kernels without `recvmmsg`).
|
||||
async fn serve_udp_simple(shared: Arc<Shared>, sock: Arc<UdpSocket>, inflight: Arc<Semaphore>, mut shutdown: watch::Receiver<bool>) {
|
||||
let mut buf = vec![0u8; 4096];
|
||||
loop {
|
||||
let (n, peer) = tokio::select! {
|
||||
r = sock.recv_from(&mut buf) => match r {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
// ICMP errors (e.g. connection refused) surface here on Linux; keep serving.
|
||||
tracing::debug!(error = %e, "UDP recv error");
|
||||
continue;
|
||||
}
|
||||
},
|
||||
_ = shutdown.changed() => break,
|
||||
};
|
||||
// fast path: repeated queries are answered inline from the packet cache
|
||||
if let Some(reply) = dispatch(&shared, &sock, &inflight, &buf[..n], peer) {
|
||||
let _ = sock.send_to(&reply, peer).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle one stream connection (TCP or TLS): length-prefixed messages, idle timeout.
|
||||
pub async fn serve_stream<S>(shared: Arc<Shared>, mut stream: S, peer: SocketAddr, transport: Transport, idle: Duration)
|
||||
where
|
||||
S: AsyncRead + AsyncWrite + Unpin,
|
||||
{
|
||||
shared.metrics.tcp_connections.fetch_add(1, Ordering::Relaxed);
|
||||
for _ in 0..MAX_QUERIES_PER_CONN {
|
||||
let msg = match tokio::time::timeout(idle, dns_core::client::read_tcp_msg(&mut stream)).await {
|
||||
Ok(Ok(m)) => m,
|
||||
_ => break,
|
||||
};
|
||||
let reply = handle(&shared, &msg, peer, transport).await;
|
||||
let ok = match reply {
|
||||
Reply::None => true,
|
||||
Reply::One(b) => dns_core::client::write_tcp_msg(&mut stream, &b).await.is_ok(),
|
||||
Reply::Many(v) => {
|
||||
let mut ok = true;
|
||||
for b in v {
|
||||
if dns_core::client::write_tcp_msg(&mut stream, &b).await.is_err() {
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
ok
|
||||
}
|
||||
};
|
||||
if !ok {
|
||||
break;
|
||||
}
|
||||
}
|
||||
shared.metrics.tcp_connections.fetch_sub(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Serve TCP until shutdown.
|
||||
pub async fn serve_tcp(shared: Arc<Shared>, listener: TcpListener, mut shutdown: watch::Receiver<bool>) {
|
||||
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(e) => {
|
||||
tracing::warn!(error = %e, "TCP accept error");
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
continue;
|
||||
}
|
||||
},
|
||||
_ = shutdown.changed() => break,
|
||||
};
|
||||
let Ok(permit) = Arc::clone(&conns).try_acquire_owned() else {
|
||||
drop(stream); // connection limit reached
|
||||
continue;
|
||||
};
|
||||
let _ = stream.set_nodelay(true);
|
||||
let shared = Arc::clone(&shared);
|
||||
tokio::spawn(async move {
|
||||
serve_stream(shared, stream, peer, Transport::Tcp, idle).await;
|
||||
drop(permit);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,480 @@
|
||||
//! Cache of complete, encoded responses ("packet cache").
|
||||
//!
|
||||
//! A repeated query is answered by copying the stored response bytes and patching the
|
||||
//! message ID, the case of the question name (resolvers randomise it, "0x20") and – for
|
||||
//! data that did not come from a local zone – the TTLs, which are lowered by the time
|
||||
//! the response spent in the cache. No parsing, policy evaluation, zone lookup or
|
||||
//! encoding happens on a hit, and the UDP listener answers hits inline without spawning
|
||||
//! a task. This is the main per-core speed-up of the authoritative fast path.
|
||||
//!
|
||||
//! Correctness rules:
|
||||
//! * The key is the whole query after the ID (flags, question with a lower-cased name,
|
||||
//! EDNS record incl. DO bit, UDP size and options) plus a **client profile**: the view,
|
||||
//! whether the client may use recursion, whether it is exempt from block lists, which
|
||||
//! client-restricted forward rules match it, and whether the transport is UDP or a
|
||||
//! stream. Two clients with the same profile get byte-identical answers from the slow
|
||||
//! path, so sharing is safe.
|
||||
//! * Only plain queries are cached: opcode QUERY, one question, no answer/authority
|
||||
//! records and at most one additional record, which must be OPT – so TSIG-signed
|
||||
//! requests always take the slow path. Only NOERROR/NXDOMAIN responses are stored.
|
||||
//! * Entries are invalidated by a generation number that changes whenever a zone
|
||||
//! snapshot is published or a zone expires (`dns_authoritative::data_generation`) and
|
||||
//! when the configuration is reloaded or the cache is flushed.
|
||||
//! * Answers from local zones live at most `authoritative_max_age`; resolved and
|
||||
//! forwarded answers at most their smallest TTL (capped at 60 s), with TTLs counted down.
|
||||
//! * Memory is bounded by `max_entries` (LRU per shard).
|
||||
use std::hash::{BuildHasher, RandomState};
|
||||
use std::num::NonZeroUsize;
|
||||
use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use lru::LruCache;
|
||||
|
||||
const SHARDS: usize = 16;
|
||||
/// Upper bound for how long a resolved answer is reused (TTLs are counted down anyway).
|
||||
const MAX_RESOLVED_AGE: u32 = 60;
|
||||
/// Largest response kept.
|
||||
const MAX_RESPONSE: usize = 4096;
|
||||
|
||||
/// How a stored response may be reused.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Kind {
|
||||
/// From local zone data: TTLs are fixed; invalidated by zone changes.
|
||||
Authoritative,
|
||||
/// Resolved/forwarded/cached data: TTLs are decremented while cached.
|
||||
Resolved,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Entry {
|
||||
bytes: Box<[u8]>,
|
||||
/// Offsets of the 32-bit TTL fields of all non-OPT records.
|
||||
ttl_offsets: Box<[u16]>,
|
||||
/// End of the question section (the part copied from the query on a hit).
|
||||
question_end: u16,
|
||||
stored: Instant,
|
||||
max_age: u32,
|
||||
decrement: bool,
|
||||
generation: u64,
|
||||
rcode: &'static str,
|
||||
source: &'static str,
|
||||
}
|
||||
|
||||
type Shard = Mutex<LruCache<Box<[u8]>, Arc<Entry>>>;
|
||||
|
||||
/// Counters for metrics and status.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct PacketCacheStats {
|
||||
pub hits: AtomicU64,
|
||||
pub misses: AtomicU64,
|
||||
pub inserts: AtomicU64,
|
||||
}
|
||||
|
||||
/// How a response being stored may be reused, and its metric labels.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct StoreMeta {
|
||||
pub kind: Kind,
|
||||
/// From [`PacketCache::current_generation`], read before the answer was computed.
|
||||
pub generation: u64,
|
||||
pub rcode: &'static str,
|
||||
pub source: &'static str,
|
||||
}
|
||||
|
||||
/// A hit: response bytes ready to send, plus labels for metrics.
|
||||
#[derive(Debug)]
|
||||
pub struct Hit {
|
||||
pub bytes: Vec<u8>,
|
||||
pub qtype: u16,
|
||||
pub rcode: &'static str,
|
||||
pub source: &'static str,
|
||||
}
|
||||
|
||||
pub struct PacketCache {
|
||||
shards: Box<[Shard]>,
|
||||
hasher: RandomState,
|
||||
/// Local part of the generation (reloads, flushes); combined with the zone generation.
|
||||
local_generation: AtomicU64,
|
||||
authoritative_max_age: u32,
|
||||
pub stats: PacketCacheStats,
|
||||
}
|
||||
|
||||
/// Parsed facts about a cacheable query.
|
||||
struct QueryShape {
|
||||
/// End of the question section.
|
||||
question_end: usize,
|
||||
qtype: u16,
|
||||
}
|
||||
|
||||
/// Validate that `raw` is a plain, cacheable query and find its question.
|
||||
fn query_shape(raw: &[u8]) -> Option<QueryShape> {
|
||||
if raw.len() < 17 || raw.len() > 1024 {
|
||||
return None;
|
||||
}
|
||||
let flags = u16::from_be_bytes([raw[2], raw[3]]);
|
||||
// QR=0, opcode QUERY (0)
|
||||
if flags & 0x8000 != 0 || (flags >> 11) & 0xF != 0 {
|
||||
return None;
|
||||
}
|
||||
let count = |i: usize| u16::from_be_bytes([raw[i], raw[i + 1]]);
|
||||
if count(4) != 1 || count(6) != 0 || count(8) != 0 || count(10) > 1 {
|
||||
return None;
|
||||
}
|
||||
// question name: plain labels only (queries are not compressed)
|
||||
let mut i = 12;
|
||||
loop {
|
||||
let len = *raw.get(i)? as usize;
|
||||
if len == 0 {
|
||||
i += 1;
|
||||
break;
|
||||
}
|
||||
if len > 63 {
|
||||
return None;
|
||||
}
|
||||
i += 1 + len;
|
||||
}
|
||||
let qtype = u16::from_be_bytes([*raw.get(i)?, *raw.get(i + 1)?]);
|
||||
let qclass = u16::from_be_bytes([*raw.get(i + 2)?, *raw.get(i + 3)?]);
|
||||
let question_end = i + 4;
|
||||
// IN only; no zone transfers, OPT, TSIG or meta types
|
||||
if qclass != 1 || matches!(qtype, 251 | 252 | 41 | 250 | 249) {
|
||||
return None;
|
||||
}
|
||||
if count(10) == 1 {
|
||||
// the additional record must be OPT: root name, type 41
|
||||
if raw.get(question_end..question_end + 3)? != [0, 0, 41] {
|
||||
return None;
|
||||
}
|
||||
// …and must end exactly at the end of the packet
|
||||
let rdlen = u16::from_be_bytes([*raw.get(question_end + 9)?, *raw.get(question_end + 10)?]) as usize;
|
||||
if question_end + 11 + rdlen != raw.len() {
|
||||
return None;
|
||||
}
|
||||
} else if raw.len() != question_end {
|
||||
return None;
|
||||
}
|
||||
Some(QueryShape { question_end, qtype })
|
||||
}
|
||||
|
||||
/// Skip a (possibly compressed) name in a message; returns the offset after it.
|
||||
fn skip_name(m: &[u8], mut i: usize) -> Option<usize> {
|
||||
loop {
|
||||
let b = *m.get(i)?;
|
||||
match b & 0xC0 {
|
||||
0x00 if b == 0 => return Some(i + 1),
|
||||
0x00 => i += 1 + b as usize,
|
||||
0xC0 => return Some(i + 2),
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Offsets of TTL fields (except OPT) and the smallest TTL in a response.
|
||||
fn ttl_layout(m: &[u8], question_end: usize) -> Option<(Vec<u16>, u32)> {
|
||||
let count = |i: usize| -> Option<usize> { Some(u16::from_be_bytes([*m.get(i)?, *m.get(i + 1)?]) as usize) };
|
||||
let total = count(6)? + count(8)? + count(10)?;
|
||||
let mut i = question_end;
|
||||
let mut offsets = Vec::with_capacity(total);
|
||||
let mut min_ttl = u32::MAX;
|
||||
for _ in 0..total {
|
||||
i = skip_name(m, i)?;
|
||||
let rtype = u16::from_be_bytes([*m.get(i)?, *m.get(i + 1)?]);
|
||||
let ttl_at = i + 4;
|
||||
let ttl = u32::from_be_bytes(m.get(ttl_at..ttl_at + 4)?.try_into().ok()?);
|
||||
let rdlen = u16::from_be_bytes([*m.get(i + 8)?, *m.get(i + 9)?]) as usize;
|
||||
if rtype != 41 {
|
||||
offsets.push(u16::try_from(ttl_at).ok()?);
|
||||
min_ttl = min_ttl.min(ttl);
|
||||
}
|
||||
i += 10 + rdlen;
|
||||
if i > m.len() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
(i == m.len()).then_some((offsets, min_ttl))
|
||||
}
|
||||
|
||||
impl PacketCache {
|
||||
/// `max_entries == 0` disables the cache.
|
||||
pub fn new(max_entries: usize, authoritative_max_age: Duration) -> Self {
|
||||
let n = if max_entries == 0 { 0 } else { (max_entries / 64).clamp(1, SHARDS).next_power_of_two().min(SHARDS) };
|
||||
let shards = (0..n)
|
||||
.map(|i| {
|
||||
let cap = max_entries / n + usize::from(i < max_entries % n);
|
||||
Mutex::new(LruCache::new(NonZeroUsize::new(cap).unwrap_or(NonZeroUsize::MIN)))
|
||||
})
|
||||
.collect();
|
||||
Self {
|
||||
shards,
|
||||
hasher: RandomState::new(),
|
||||
local_generation: AtomicU64::new(0),
|
||||
authoritative_max_age: authoritative_max_age.as_secs().min(u64::from(u32::MAX)) as u32,
|
||||
stats: PacketCacheStats::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn enabled(&self) -> bool {
|
||||
!self.shards.is_empty()
|
||||
}
|
||||
|
||||
fn generation(&self) -> u64 {
|
||||
// the two counters only ever grow; any change of either invalidates
|
||||
self.local_generation.load(Relaxed).wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ dns_authoritative::data_generation()
|
||||
}
|
||||
|
||||
/// Drop everything (configuration reload, cache flush).
|
||||
pub fn invalidate(&self) {
|
||||
self.local_generation.fetch_add(1, Relaxed);
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.shards.iter().map(|s| s.lock().unwrap_or_else(|e| e.into_inner()).len()).sum()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.len() == 0
|
||||
}
|
||||
|
||||
fn key(raw: &[u8], shape: &QueryShape, profile: u64) -> Box<[u8]> {
|
||||
let mut k = Vec::with_capacity(8 + raw.len() - 2);
|
||||
k.extend_from_slice(&profile.to_be_bytes());
|
||||
k.extend_from_slice(&raw[2..12]);
|
||||
k.extend(raw[12..shape.question_end].iter().map(u8::to_ascii_lowercase));
|
||||
k.extend_from_slice(&raw[shape.question_end..]);
|
||||
k.into_boxed_slice()
|
||||
}
|
||||
|
||||
fn shard(&self, key: &[u8]) -> std::sync::MutexGuard<'_, LruCache<Box<[u8]>, Arc<Entry>>> {
|
||||
let i = (self.hasher.hash_one(key) as usize) & (self.shards.len() - 1);
|
||||
self.shards[i].lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// Answer `raw` from the cache, if possible.
|
||||
pub fn lookup(&self, raw: &[u8], profile: u64) -> Option<Hit> {
|
||||
if !self.enabled() {
|
||||
return None;
|
||||
}
|
||||
let shape = query_shape(raw)?;
|
||||
let key = Self::key(raw, &shape, profile);
|
||||
let generation = self.generation();
|
||||
let entry = {
|
||||
let mut s = self.shard(&key);
|
||||
let fresh = match s.get(&key) {
|
||||
Some(e) => e.generation == generation && e.stored.elapsed().as_secs() < u64::from(e.max_age),
|
||||
None => {
|
||||
drop(s);
|
||||
self.stats.misses.fetch_add(1, Relaxed);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if !fresh {
|
||||
s.pop(&key);
|
||||
drop(s);
|
||||
self.stats.misses.fetch_add(1, Relaxed);
|
||||
return None;
|
||||
}
|
||||
s.get(&key).map(Arc::clone)?
|
||||
};
|
||||
let mut out = entry.bytes.to_vec();
|
||||
out[0] = raw[0];
|
||||
out[1] = raw[1];
|
||||
// the question as the client sent it (same length; only letter case can differ)
|
||||
let qe = usize::from(entry.question_end);
|
||||
if qe == shape.question_end {
|
||||
out[12..qe].copy_from_slice(&raw[12..qe]);
|
||||
}
|
||||
if entry.decrement {
|
||||
let age = entry.stored.elapsed().as_secs() as u32;
|
||||
for &o in &*entry.ttl_offsets {
|
||||
let o = usize::from(o);
|
||||
let ttl = u32::from_be_bytes([out[o], out[o + 1], out[o + 2], out[o + 3]]);
|
||||
out[o..o + 4].copy_from_slice(&ttl.saturating_sub(age).to_be_bytes());
|
||||
}
|
||||
}
|
||||
self.stats.hits.fetch_add(1, Relaxed);
|
||||
Some(Hit { bytes: out, qtype: shape.qtype, rcode: entry.rcode, source: entry.source })
|
||||
}
|
||||
|
||||
/// Remember the response to `raw`. `meta.generation` must be taken *before* the response
|
||||
/// was computed, so a zone change during the computation is never cached as current.
|
||||
pub fn store(&self, raw: &[u8], profile: u64, response: &[u8], meta: StoreMeta) {
|
||||
let StoreMeta { kind, generation, rcode, source } = meta;
|
||||
if !self.enabled() || response.len() > MAX_RESPONSE || response.len() < 12 {
|
||||
return;
|
||||
}
|
||||
let Some(shape) = query_shape(raw) else { return };
|
||||
// response question must mirror the query (it always does for our encoder)
|
||||
if response.get(12..shape.question_end).map(|q| q.eq_ignore_ascii_case(&raw[12..shape.question_end])) != Some(true) {
|
||||
return;
|
||||
}
|
||||
let Some((offsets, min_ttl)) = ttl_layout(response, shape.question_end) else { return };
|
||||
let max_age = match kind {
|
||||
Kind::Authoritative => self.authoritative_max_age,
|
||||
Kind::Resolved if offsets.is_empty() => 5, // negative answer without SOA: keep briefly
|
||||
Kind::Resolved => min_ttl.min(MAX_RESOLVED_AGE),
|
||||
};
|
||||
if max_age == 0 {
|
||||
return;
|
||||
}
|
||||
let entry = Arc::new(Entry {
|
||||
bytes: response.into(),
|
||||
ttl_offsets: offsets.into_iter().collect(),
|
||||
question_end: shape.question_end as u16,
|
||||
stored: Instant::now(),
|
||||
max_age,
|
||||
decrement: kind == Kind::Resolved,
|
||||
generation,
|
||||
rcode,
|
||||
source,
|
||||
});
|
||||
let key = Self::key(raw, &shape, profile);
|
||||
self.shard(&key).put(key, entry);
|
||||
self.stats.inserts.fetch_add(1, Relaxed);
|
||||
}
|
||||
|
||||
/// Prometheus text for the packet cache.
|
||||
pub fn render_metrics(&self) -> String {
|
||||
let mut s = String::new();
|
||||
for (name, help, v) in [
|
||||
("dns_answer_cache_hits_total", "Queries answered from the encoded-answer cache", &self.stats.hits),
|
||||
("dns_answer_cache_misses_total", "Cacheable queries not found in the encoded-answer cache", &self.stats.misses),
|
||||
("dns_answer_cache_inserts_total", "Answers stored in the encoded-answer cache", &self.stats.inserts),
|
||||
] {
|
||||
s.push_str(&format!("# HELP {name} {help}\n# TYPE {name} counter\n{name} {}\n", v.load(Relaxed)));
|
||||
}
|
||||
s.push_str(&format!(
|
||||
"# HELP dns_answer_cache_entries Entries in the encoded-answer cache\n# TYPE dns_answer_cache_entries gauge\ndns_answer_cache_entries {}\n",
|
||||
self.len()
|
||||
));
|
||||
s
|
||||
}
|
||||
|
||||
/// Generation to pass to [`PacketCache::store`] (read before computing an answer).
|
||||
pub fn current_generation(&self) -> u64 {
|
||||
self.generation()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use dns_core::client::{QueryOptions, build_query};
|
||||
use dns_core::proto::op::{Message, ResponseCode};
|
||||
use dns_core::proto::rr::rdata::A;
|
||||
use dns_core::proto::rr::{Name, RData, Record, RecordType};
|
||||
|
||||
fn query(name: &str, dnssec: bool) -> Vec<u8> {
|
||||
let o = QueryOptions { dnssec_ok: dnssec, ..Default::default() };
|
||||
build_query(&Name::from_ascii(name).unwrap(), RecordType::A, &o).to_vec().unwrap()
|
||||
}
|
||||
|
||||
fn response(q: &[u8], ttl: u32) -> Vec<u8> {
|
||||
let m = Message::from_vec(q).unwrap();
|
||||
let mut r = dns_core::wire::response_for(&m);
|
||||
r.metadata.response_code = ResponseCode::NoError;
|
||||
r.answers.push(Record::from_rdata(m.queries[0].name.clone(), ttl, RData::A(A::new(192, 0, 2, 1))));
|
||||
r.to_vec().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hit_patches_id_case_and_ttl() {
|
||||
let c = PacketCache::new(1000, Duration::from_secs(30));
|
||||
let q = query("www.example.com.", false);
|
||||
let g = c.current_generation();
|
||||
c.store(&q, 1, &response(&q, 300), StoreMeta { kind: Kind::Resolved, generation: g, rcode: "NOERROR", source: "recursive" });
|
||||
// same question, other ID and 0x20 case
|
||||
let mut q2 = query("WwW.ExAmPlE.CoM.", false);
|
||||
q2[0] = 0xAB;
|
||||
q2[1] = 0xCD;
|
||||
let hit = c.lookup(&q2, 1).unwrap();
|
||||
let m = Message::from_vec(&hit.bytes).unwrap();
|
||||
assert_eq!(m.metadata.id, 0xABCD);
|
||||
assert_eq!(m.queries[0].name.to_ascii(), "WwW.ExAmPlE.CoM.");
|
||||
assert!(m.answers[0].ttl <= 300 && m.answers[0].ttl >= 299);
|
||||
assert_eq!(hit.qtype, 1);
|
||||
// other profile, DO bit or name: miss
|
||||
assert!(c.lookup(&q2, 2).is_none());
|
||||
assert!(c.lookup(&query("www.example.com.", true), 1).is_none());
|
||||
assert!(c.lookup(&query("mail.example.com.", false), 1).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generation_and_age_invalidate() {
|
||||
let c = PacketCache::new(1000, Duration::from_secs(30));
|
||||
let q = query("a.example.", false);
|
||||
c.store(
|
||||
&q,
|
||||
0,
|
||||
&response(&q, 300),
|
||||
StoreMeta { kind: Kind::Authoritative, generation: c.current_generation(), rcode: "NOERROR", source: "authoritative" },
|
||||
);
|
||||
assert!(c.lookup(&q, 0).is_some());
|
||||
c.invalidate();
|
||||
assert!(c.lookup(&q, 0).is_none());
|
||||
// stored with a stale generation (zone changed while computing): never served
|
||||
let g = c.current_generation();
|
||||
c.invalidate();
|
||||
c.store(
|
||||
&q,
|
||||
0,
|
||||
&response(&q, 300),
|
||||
StoreMeta { kind: Kind::Authoritative, generation: g, rcode: "NOERROR", source: "authoritative" },
|
||||
);
|
||||
assert!(c.lookup(&q, 0).is_none());
|
||||
// TTL 0 is not cached
|
||||
c.store(
|
||||
&q,
|
||||
0,
|
||||
&response(&q, 0),
|
||||
StoreMeta { kind: Kind::Resolved, generation: c.current_generation(), rcode: "NOERROR", source: "recursive" },
|
||||
);
|
||||
assert!(c.lookup(&q, 0).is_none());
|
||||
// authoritative TTLs are not changed
|
||||
c.store(
|
||||
&q,
|
||||
0,
|
||||
&response(&q, 300),
|
||||
StoreMeta { kind: Kind::Authoritative, generation: c.current_generation(), rcode: "NOERROR", source: "authoritative" },
|
||||
);
|
||||
assert_eq!(Message::from_vec(&c.lookup(&q, 0).unwrap().bytes).unwrap().answers[0].ttl, 300);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_plain_queries_are_cacheable() {
|
||||
let q = query("x.example.", false);
|
||||
assert!(query_shape(&q).is_some());
|
||||
let mut resp_flag = q.clone();
|
||||
resp_flag[2] |= 0x80; // QR=1
|
||||
assert!(query_shape(&resp_flag).is_none());
|
||||
let mut notify = q.clone();
|
||||
notify[2] |= 4 << 3; // opcode NOTIFY
|
||||
assert!(query_shape(¬ify).is_none());
|
||||
let mut trailing = query("x.example.", false);
|
||||
trailing.extend_from_slice(&[1, 2, 3]); // garbage, no additional record declared
|
||||
assert!(query_shape(&trailing).is_none());
|
||||
// a TSIG-signed query has an additional record that is not OPT
|
||||
let key = dns_core::tsig::TsigKey::new("k", "hmac-sha256", "c2VjcmV0c2VjcmV0c2VjcmV0c2VjcmV0").unwrap();
|
||||
let mut m = Message::from_vec(&query("x.example.", false)).unwrap();
|
||||
m.edns = None;
|
||||
let signed = key.sign_request(&mut m).unwrap();
|
||||
assert!(query_shape(&signed).is_none());
|
||||
let c = PacketCache::new(0, Duration::from_secs(1));
|
||||
assert!(!c.enabled() && c.lookup(&q, 0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounded_memory() {
|
||||
let c = PacketCache::new(256, Duration::from_secs(30));
|
||||
for i in 0..5000 {
|
||||
let q = query(&format!("h{i}.example."), false);
|
||||
c.store(
|
||||
&q,
|
||||
0,
|
||||
&response(&q, 300),
|
||||
StoreMeta { kind: Kind::Resolved, generation: c.current_generation(), rcode: "NOERROR", source: "recursive" },
|
||||
);
|
||||
}
|
||||
assert!(c.len() <= 256, "{}", c.len());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
//! Resolution routing for names that are not served from local zones.
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::net::IpAddr;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use dns_cache::{Cache, Key};
|
||||
use dns_config::{Config, DefaultResolution};
|
||||
use dns_core::answer::{Answer, Source};
|
||||
use dns_core::proto::op::ResponseCode;
|
||||
use dns_core::proto::rr::{LowerName, Name, RecordType};
|
||||
use dns_forwarder::Pool;
|
||||
use dns_policy::Acl;
|
||||
use dns_recursive::Resolver;
|
||||
|
||||
use crate::coalesce::{Coalescer, FlightKey};
|
||||
|
||||
/// A conditional forwarding rule.
|
||||
pub struct ForwardRule {
|
||||
pub suffix: LowerName,
|
||||
pub clients: Acl,
|
||||
pub pool: Arc<Pool>,
|
||||
pub cache_ns: u16,
|
||||
pub fallback_recursion: bool,
|
||||
}
|
||||
|
||||
pub struct Router {
|
||||
pub rules: Vec<ForwardRule>,
|
||||
pub default: DefaultResolution,
|
||||
pub default_pool: Option<Arc<Pool>>,
|
||||
pub default_ns: u16,
|
||||
pub resolver: Option<Arc<Resolver>>,
|
||||
pub cache: Arc<Cache>,
|
||||
/// Identical concurrent cache misses share one upstream/recursive resolution.
|
||||
pub flights: Coalescer,
|
||||
}
|
||||
|
||||
/// Cache namespace derived from the route definition (stable across reloads).
|
||||
fn ns_for(parts: &[&str]) -> u16 {
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
parts.hash(&mut h);
|
||||
(h.finish() as u16) | 0x8000 // never collides with the recursion namespace 0
|
||||
}
|
||||
|
||||
/// Recursion cache namespace.
|
||||
pub const RECURSION_NS: u16 = 0;
|
||||
|
||||
impl Router {
|
||||
pub fn build(cfg: &Config, cache: Arc<Cache>, resolver: Option<Arc<Resolver>>) -> Result<Self, String> {
|
||||
let timeout = cfg.upstreams.timeout.unwrap_or(Duration::from_secs(2));
|
||||
let ca = match &cfg.upstreams.tls_ca_file {
|
||||
Some(p) => {
|
||||
let p = cfg.resolve_path(p);
|
||||
Some(std::fs::read(&p).map_err(|e| format!("upstreams.tls_ca_file {}: {e}", p.display()))?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let mut rules = Vec::new();
|
||||
for f in &cfg.forward_zones {
|
||||
let suffix = dns_core::names::parse_lower(&f.domain).map_err(|e| e.to_string())?;
|
||||
let pool = Arc::new(Pool::with_tls_roots(&f.domain, &f.upstreams, f.strategy, timeout, ca.as_deref())?);
|
||||
let mut parts: Vec<&str> = vec![f.domain.as_str()];
|
||||
parts.extend(f.upstreams.iter().map(String::as_str));
|
||||
rules.push(ForwardRule {
|
||||
suffix,
|
||||
clients: Acl(cfg.expand_acl(&f.clients)?),
|
||||
pool,
|
||||
cache_ns: ns_for(&parts),
|
||||
fallback_recursion: f.fallback_recursion,
|
||||
});
|
||||
}
|
||||
// Most specific suffix first.
|
||||
rules.sort_by_key(|r| std::cmp::Reverse(r.suffix.num_labels()));
|
||||
let default_pool = if cfg.upstreams.servers.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(Arc::new(Pool::with_tls_roots("default", &cfg.upstreams.servers, cfg.upstreams.strategy, timeout, ca.as_deref())?))
|
||||
};
|
||||
let parts: Vec<&str> = cfg.upstreams.servers.iter().map(String::as_str).collect();
|
||||
Ok(Self {
|
||||
rules,
|
||||
default: cfg.resolution.default,
|
||||
default_pool,
|
||||
default_ns: ns_for(&parts),
|
||||
resolver,
|
||||
cache,
|
||||
flights: Coalescer::default(),
|
||||
})
|
||||
}
|
||||
|
||||
fn rule_for(&self, name: &Name, client: IpAddr) -> Option<&ForwardRule> {
|
||||
let l = LowerName::new(name);
|
||||
self.rules.iter().find(|r| r.suffix.zone_of(&l) && (r.clients.is_empty() || r.clients.contains(client)))
|
||||
}
|
||||
|
||||
async fn forward(&self, pool: &Arc<Pool>, ns: u16, name: &Name, qtype: RecordType, dnssec_ok: bool, cd: bool) -> Answer {
|
||||
let key = Key { ns, name: LowerName::new(name), rtype: qtype, dnssec: dnssec_ok };
|
||||
if let Some(a) = self.cache.get(&key) {
|
||||
if self.cache.prefetch_due(&key) {
|
||||
// popular entry about to expire: refresh it in the background
|
||||
let (pool, cache, name) = (Arc::clone(pool), Arc::clone(&self.cache), name.clone());
|
||||
tokio::spawn(async move {
|
||||
let _ = forward_fetch(&pool, &cache, key, &name, qtype, dnssec_ok, cd, false).await;
|
||||
});
|
||||
}
|
||||
return a;
|
||||
}
|
||||
let flight = FlightKey { ns, name: key.name.clone(), rtype: qtype, dnssec_ok, cd };
|
||||
self.flights.run(flight, || forward_fetch(pool, &self.cache, key, name, qtype, dnssec_ok, cd, true)).await
|
||||
}
|
||||
|
||||
async fn recurse(&self, name: &Name, qtype: RecordType) -> Answer {
|
||||
match &self.resolver {
|
||||
Some(r) => {
|
||||
let flight = FlightKey { ns: RECURSION_NS, name: LowerName::new(name), rtype: qtype, dnssec_ok: false, cd: false };
|
||||
let a = self.flights.run(flight, || r.resolve(name, qtype)).await;
|
||||
if a.source == Source::Cache && r.prefetch_due(name, qtype) {
|
||||
let (r, name) = (Arc::clone(r), name.clone());
|
||||
tokio::spawn(async move { r.refresh(&name, qtype).await });
|
||||
}
|
||||
if a.rcode == ResponseCode::ServFail {
|
||||
let key = Key { ns: RECURSION_NS, name: LowerName::new(name), rtype: qtype, dnssec: false };
|
||||
if let Some(s) = self.cache.get_stale(&key) {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
a
|
||||
}
|
||||
None => Answer::servfail(Source::Recursive, "recursion is not enabled"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Query a forwarder pool and cache the answer. `stale_on_error`: answer from stale
|
||||
/// cache data (or SERVFAIL) when the pool fails; a background prefetch passes `false`
|
||||
/// and simply keeps the existing entry.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn forward_fetch(
|
||||
pool: &Pool,
|
||||
cache: &Cache,
|
||||
key: Key,
|
||||
name: &Name,
|
||||
qtype: RecordType,
|
||||
dnssec_ok: bool,
|
||||
cd: bool,
|
||||
stale_on_error: bool,
|
||||
) -> Answer {
|
||||
{
|
||||
match pool.query(name, qtype, dnssec_ok, cd).await {
|
||||
Ok(f) => {
|
||||
let m = f.message;
|
||||
let mut a = Answer::new(m.metadata.response_code, Source::Forward);
|
||||
a.answers = m.answers;
|
||||
a.authority = m
|
||||
.authorities
|
||||
.into_iter()
|
||||
.filter(|r| r.record_type() == RecordType::SOA || (dnssec_ok && r.record_type() != RecordType::NS))
|
||||
.collect();
|
||||
if m.metadata.authentic_data {
|
||||
a.security = dns_core::answer::Security::Secure;
|
||||
}
|
||||
a.note = Some(format!("upstream {} ({}, {} ms)", f.upstream, f.reason, f.elapsed.as_millis()));
|
||||
cache.insert_answer(key, &a);
|
||||
a
|
||||
}
|
||||
Err(e) if stale_on_error => cache.get_stale(&key).unwrap_or_else(|| Answer::servfail(Source::Forward, e)),
|
||||
Err(e) => Answer::servfail(Source::Forward, e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Router {
|
||||
/// Resolve a name for a client that is allowed to use resolution.
|
||||
pub async fn resolve(&self, name: &Name, qtype: RecordType, client: IpAddr, dnssec_ok: bool, cd: bool) -> Answer {
|
||||
if let Some(rule) = self.rule_for(name, client) {
|
||||
let a = self.forward(&rule.pool, rule.cache_ns, name, qtype, dnssec_ok, cd).await;
|
||||
if a.rcode == ResponseCode::ServFail && rule.fallback_recursion && self.resolver.is_some() {
|
||||
return self.recurse(name, qtype).await;
|
||||
}
|
||||
return a;
|
||||
}
|
||||
match self.default {
|
||||
DefaultResolution::Recursive => self.recurse(name, qtype).await,
|
||||
DefaultResolution::Forward => match &self.default_pool {
|
||||
Some(p) => self.forward(p, self.default_ns, name, qtype, dnssec_ok, cd).await,
|
||||
None => Answer::servfail(Source::Forward, "no upstreams configured"),
|
||||
},
|
||||
DefaultResolution::ForwardThenRecursive => {
|
||||
let a = match &self.default_pool {
|
||||
Some(p) => self.forward(p, self.default_ns, name, qtype, dnssec_ok, cd).await,
|
||||
None => Answer::servfail(Source::Forward, "no upstreams configured"),
|
||||
};
|
||||
if a.rcode == ResponseCode::ServFail { self.recurse(name, qtype).await } else { a }
|
||||
}
|
||||
DefaultResolution::Refuse => Answer::new(ResponseCode::Refused, Source::Refused),
|
||||
}
|
||||
}
|
||||
|
||||
/// `true` when any resolution path exists.
|
||||
pub fn can_resolve(&self) -> bool {
|
||||
!self.rules.is_empty() || self.default != DefaultResolution::Refuse
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
//! Process-wide shared state and the hot-reloadable runtime snapshot.
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, RwLock};
|
||||
use std::time::Instant;
|
||||
|
||||
use dns_authoritative::{ZoneEntry, ZoneStore};
|
||||
use dns_cache::Cache;
|
||||
use dns_config::{Config, Overrides};
|
||||
use dns_core::tsig::KeyRing;
|
||||
use dns_metrics::Metrics;
|
||||
use dns_policy::{Acl, BlockPolicy, RateLimiter, SuffixSet, Views};
|
||||
|
||||
use crate::audit::AuditLog;
|
||||
use crate::router::{RECURSION_NS, Router};
|
||||
|
||||
/// Everything derived from one configuration version. Swapped atomically on reload;
|
||||
/// in-flight queries keep using the snapshot they started with.
|
||||
pub struct Runtime {
|
||||
pub cfg: Arc<Config>,
|
||||
pub zones: Arc<ZoneStore>,
|
||||
pub ring: KeyRing,
|
||||
pub recursion_acl: Acl,
|
||||
pub views: Views,
|
||||
pub ratelimit: RateLimiter,
|
||||
pub policy: BlockPolicy,
|
||||
pub local_only: SuffixSet,
|
||||
pub router: Router,
|
||||
pub resolver: Option<Arc<dns_recursive::Resolver>>,
|
||||
}
|
||||
|
||||
impl Runtime {
|
||||
/// Build a runtime. Returns it together with newly created zone entries
|
||||
/// (secondary tasks must be spawned for them).
|
||||
pub fn build(cfg: Config, cache: Arc<Cache>, previous: Option<&Runtime>) -> Result<(Self, Vec<Arc<ZoneEntry>>), String> {
|
||||
let errors: Vec<String> = cfg.validate().into_iter().filter(|i| i.is_error()).map(|i| i.to_string()).collect();
|
||||
if !errors.is_empty() {
|
||||
return Err(errors.join("\n"));
|
||||
}
|
||||
let ring = cfg.key_ring()?;
|
||||
let resolver = if cfg.recursion.enabled {
|
||||
let hints = dns_recursive::hints::load(cfg.recursion.root_hints.as_ref().map(|p| cfg.resolve_path(p)).as_deref())?;
|
||||
let mut r = dns_recursive::Resolver::new(
|
||||
dns_recursive::Settings::from_config(&cfg.recursion),
|
||||
hints,
|
||||
Arc::clone(&cache),
|
||||
RECURSION_NS,
|
||||
)?;
|
||||
if let (true, Some(p)) = (cfg.recursion.dnssec_validation, &cfg.recursion.trust_anchors) {
|
||||
let path = cfg.resolve_path(p);
|
||||
let recs =
|
||||
dns_core::zonefile::parse_file(&path, &dns_core::proto::rr::Name::root()).map_err(|e| format!("trust anchors: {e}"))?;
|
||||
r.set_trust_anchors(&recs)?;
|
||||
}
|
||||
Some(Arc::new(r))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut local = dns_policy::default_local_only();
|
||||
for s in &cfg.recursion.local_only_suffixes {
|
||||
local.push(dns_core::names::parse_lower(s).map_err(|e| e.to_string())?);
|
||||
}
|
||||
// Names served by forward rules are explicitly routed, never "local-only".
|
||||
let fwd: Vec<_> = cfg.forward_zones.iter().filter_map(|f| dns_core::names::parse_lower(&f.domain).ok()).collect();
|
||||
local.retain(|l| !fwd.iter().any(|f| l.zone_of(f) || f.zone_of(l)));
|
||||
let router = Router::build(&cfg, Arc::clone(&cache), resolver.clone())?;
|
||||
let views = Views::from_config(&cfg)?;
|
||||
let ratelimit = RateLimiter::from_config(&cfg)?;
|
||||
let policy = BlockPolicy::from_config(&cfg)?;
|
||||
let recursion_acl = Acl(cfg.expand_acl(&cfg.recursion.allowed_clients)?);
|
||||
// Zones last: building the store has side effects (stopping removed secondaries).
|
||||
let (zones, fresh) = ZoneStore::build(&cfg, &ring, previous.map(|p| p.zones.as_ref()))?;
|
||||
let rt = Runtime {
|
||||
recursion_acl,
|
||||
views,
|
||||
ratelimit,
|
||||
policy,
|
||||
local_only: SuffixSet::new(local),
|
||||
router,
|
||||
resolver,
|
||||
zones: Arc::new(zones),
|
||||
ring,
|
||||
cfg: Arc::new(cfg),
|
||||
};
|
||||
Ok((rt, fresh))
|
||||
}
|
||||
}
|
||||
|
||||
impl Runtime {
|
||||
/// Everything about a client that can change the answer to the same query:
|
||||
/// view, recursion permission, block-list exemption, client-restricted forward rules
|
||||
/// and stream vs UDP transport. Clients with equal profiles get identical answers.
|
||||
pub fn client_profile(&self, ip: std::net::IpAddr, stream: bool) -> u64 {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let ip = dns_policy::canonical_ip(ip);
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
self.views.classify(ip).hash(&mut h);
|
||||
self.recursion_acl.contains(ip).hash(&mut h);
|
||||
self.policy.exempt.contains(ip).hash(&mut h);
|
||||
for r in self.router.rules.iter().filter(|r| !r.clients.is_empty()) {
|
||||
r.clients.contains(ip).hash(&mut h);
|
||||
}
|
||||
stream.hash(&mut h);
|
||||
h.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// State shared for the lifetime of the process.
|
||||
pub struct Shared {
|
||||
pub metrics: Arc<Metrics>,
|
||||
pub cache: Arc<Cache>,
|
||||
runtime: RwLock<Arc<Runtime>>,
|
||||
pub config_path: Option<PathBuf>,
|
||||
pub overrides: Overrides,
|
||||
pub started: Instant,
|
||||
pub audit: AuditLog,
|
||||
pub version: &'static str,
|
||||
/// Encoded answers for repeated queries (see `packet_cache`).
|
||||
pub packet_cache: crate::packet_cache::PacketCache,
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
pub fn new(rt: Runtime, cache: Arc<Cache>, metrics: Arc<Metrics>, config_path: Option<PathBuf>, overrides: Overrides) -> Self {
|
||||
let audit = AuditLog::new(Some(rt.cfg.data_dir().join("audit.log")));
|
||||
let packet_cache = crate::packet_cache::PacketCache::new(rt.cfg.cache.answer_entries, rt.cfg.cache.answer_max_age);
|
||||
Self {
|
||||
packet_cache,
|
||||
metrics,
|
||||
cache,
|
||||
runtime: RwLock::new(Arc::new(rt)),
|
||||
config_path,
|
||||
overrides,
|
||||
started: Instant::now(),
|
||||
audit,
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Current runtime snapshot.
|
||||
pub fn rt(&self) -> Arc<Runtime> {
|
||||
self.runtime.read().unwrap_or_else(|e| e.into_inner()).clone()
|
||||
}
|
||||
|
||||
pub(crate) fn swap(&self, rt: Runtime) {
|
||||
*self.runtime.write().unwrap_or_else(|e| e.into_inner()) = Arc::new(rt);
|
||||
// policies, views, ACLs or forwarders may have changed
|
||||
self.packet_cache.invalidate();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
//! Server lifecycle: start, hot reload, graceful shutdown.
|
||||
use std::net::SocketAddr;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use dns_authoritative::{ZoneEntry, ZoneKind};
|
||||
use dns_cache::Cache;
|
||||
use dns_config::{Config, Overrides};
|
||||
use dns_metrics::Metrics;
|
||||
use serde::Serialize;
|
||||
use tokio::sync::watch;
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
use crate::runtime::{Runtime, Shared};
|
||||
|
||||
/// Entry point.
|
||||
pub struct Server;
|
||||
|
||||
/// Bound addresses (useful when binding port 0 in tests).
|
||||
#[derive(Debug, Clone, Default, Serialize)]
|
||||
pub struct Bound {
|
||||
pub dns: Vec<SocketAddr>,
|
||||
pub dot: Vec<SocketAddr>,
|
||||
pub doh: Vec<SocketAddr>,
|
||||
}
|
||||
|
||||
/// Running server.
|
||||
pub struct ServerHandle {
|
||||
pub shared: Arc<Shared>,
|
||||
pub bound: Bound,
|
||||
shutdown_tx: watch::Sender<bool>,
|
||||
tasks: std::sync::Mutex<Vec<JoinHandle<()>>>,
|
||||
}
|
||||
|
||||
/// What a reload changed.
|
||||
#[derive(Debug, Clone, Serialize, Default)]
|
||||
pub struct ReloadReport {
|
||||
pub zones: usize,
|
||||
pub new_zones: Vec<String>,
|
||||
pub restart_required: Vec<String>,
|
||||
}
|
||||
|
||||
fn spawn_secondary(e: Arc<ZoneEntry>) {
|
||||
if e.kind == ZoneKind::Secondary {
|
||||
tokio::spawn(dns_authoritative::secondary::run(e, |z| z.send_notifies()));
|
||||
}
|
||||
}
|
||||
|
||||
impl Server {
|
||||
/// Validate, build and start all listeners and background tasks.
|
||||
pub async fn start(cfg: Config, config_path: Option<PathBuf>, overrides: Overrides) -> Result<ServerHandle, String> {
|
||||
let cache = Arc::new(Cache::new(&cfg.cache));
|
||||
let metrics = Arc::new(Metrics::default());
|
||||
let (rt, fresh) = Runtime::build(cfg, Arc::clone(&cache), None)?;
|
||||
let cfg = rt.cfg.clone();
|
||||
let shared = Arc::new(Shared::new(rt, cache, metrics, config_path, overrides));
|
||||
let (tx, rx) = watch::channel(false);
|
||||
let mut tasks = Vec::new();
|
||||
let mut bound = Bound::default();
|
||||
|
||||
let udp_sockets = crate::listener::udp_socket_count(cfg.server.udp_sockets);
|
||||
let udp_inflight = Arc::new(tokio::sync::Semaphore::new(cfg.server.max_inflight));
|
||||
tracing::info!(udp_sockets, "UDP sockets per listen address");
|
||||
for addr in &cfg.server.listen {
|
||||
let mut port_addr = *addr;
|
||||
if cfg.server.udp {
|
||||
let socks = crate::listener::bind_udp_group(*addr, udp_sockets).map_err(|e| format!("bind UDP {addr}: {e}"))?;
|
||||
for sock in socks {
|
||||
port_addr = sock.local_addr().map_err(|e| e.to_string())?;
|
||||
let (sh, inf) = (Arc::clone(&shared), Arc::clone(&udp_inflight));
|
||||
tasks.push(tokio::spawn(crate::listener::serve_udp(sh, Arc::new(sock), inf, rx.clone())));
|
||||
}
|
||||
}
|
||||
if cfg.server.tcp {
|
||||
let l = crate::listener::bind_tcp(port_addr).map_err(|e| format!("bind TCP {port_addr}: {e}"))?;
|
||||
port_addr = l.local_addr().map_err(|e| e.to_string())?;
|
||||
tasks.push(tokio::spawn(crate::listener::serve_tcp(Arc::clone(&shared), l, rx.clone())));
|
||||
}
|
||||
bound.dns.push(port_addr);
|
||||
tracing::info!(%port_addr, "DNS listener started");
|
||||
}
|
||||
if !cfg.tls.dot_listen.is_empty() || (!cfg.tls.doh_listen.is_empty() && !cfg.tls.doh_plaintext_behind_proxy) {
|
||||
let (Some(c), Some(k)) = (&cfg.tls.cert_file, &cfg.tls.key_file) else {
|
||||
return Err("tls.cert_file and tls.key_file are required for DoT/DoH".into());
|
||||
};
|
||||
let (c, k) = (cfg.resolve_path(c), cfg.resolve_path(k));
|
||||
let certs = crate::tls::CertStore::load(&c, &k)?;
|
||||
tasks.push(tokio::spawn(Arc::clone(&certs).watch(Duration::from_secs(60), rx.clone())));
|
||||
for addr in &cfg.tls.dot_listen {
|
||||
let tls = crate::tls::server_config_with(Arc::clone(&certs), &[b"dot"])?;
|
||||
let l = crate::listener::bind_tcp(*addr).map_err(|e| format!("bind DoT {addr}: {e}"))?;
|
||||
bound.dot.push(l.local_addr().map_err(|e| e.to_string())?);
|
||||
tasks.push(tokio::spawn(crate::tls::serve_dot(Arc::clone(&shared), l, tls, rx.clone())));
|
||||
}
|
||||
for addr in &cfg.tls.doh_listen {
|
||||
let tls = crate::tls::server_config_with(Arc::clone(&certs), crate::tls::DOH_ALPN)?;
|
||||
let l = crate::listener::bind_tcp(*addr).map_err(|e| format!("bind DoH {addr}: {e}"))?;
|
||||
bound.doh.push(l.local_addr().map_err(|e| e.to_string())?);
|
||||
tasks.push(tokio::spawn(crate::tls::serve_doh(Arc::clone(&shared), l, Some(tls), rx.clone())));
|
||||
}
|
||||
} else {
|
||||
for addr in &cfg.tls.doh_listen {
|
||||
let l = crate::listener::bind_tcp(*addr).map_err(|e| format!("bind DoH {addr}: {e}"))?;
|
||||
bound.doh.push(l.local_addr().map_err(|e| e.to_string())?);
|
||||
tracing::warn!(%addr, "DoH served WITHOUT TLS (doh_plaintext_behind_proxy)");
|
||||
tasks.push(tokio::spawn(crate::tls::serve_doh(Arc::clone(&shared), l, None, rx.clone())));
|
||||
}
|
||||
}
|
||||
for e in fresh {
|
||||
spawn_secondary(e);
|
||||
}
|
||||
// DNSSEC re-signing (hourly check).
|
||||
{
|
||||
let shared = Arc::clone(&shared);
|
||||
let mut rx = rx.clone();
|
||||
tasks.push(tokio::spawn(async move {
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = tokio::time::sleep(Duration::from_secs(3600)) => {}
|
||||
_ = rx.changed() => return,
|
||||
}
|
||||
for z in shared.rt().zones.all() {
|
||||
match z.resign_if_needed() {
|
||||
Ok(true) => z.send_notifies(),
|
||||
Ok(false) => {}
|
||||
Err(e) => tracing::error!(zone = %z.name, error = %e, "re-signing failed"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
// Upstream health checks.
|
||||
{
|
||||
let shared = Arc::clone(&shared);
|
||||
let mut rx = rx.clone();
|
||||
tasks.push(tokio::spawn(async move {
|
||||
loop {
|
||||
let interval = shared.rt().cfg.upstreams.health_check_interval.unwrap_or(Duration::from_secs(30));
|
||||
tokio::select! {
|
||||
_ = tokio::time::sleep(interval) => {}
|
||||
_ = rx.changed() => return,
|
||||
}
|
||||
let rt = shared.rt();
|
||||
if let Some(p) = &rt.router.default_pool {
|
||||
p.health_check().await;
|
||||
}
|
||||
for r in &rt.router.rules {
|
||||
r.pool.health_check().await;
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
Ok(ServerHandle { shared, bound, shutdown_tx: tx, tasks: std::sync::Mutex::new(tasks) })
|
||||
}
|
||||
}
|
||||
|
||||
impl ServerHandle {
|
||||
/// Re-read the configuration file and atomically switch to it. On error the
|
||||
/// running configuration stays active (rollback).
|
||||
pub fn reload(&self) -> Result<ReloadReport, String> {
|
||||
let path = self.shared.config_path.clone().ok_or("server was started without a config file")?;
|
||||
let cfg = Config::load_with(&path, &self.shared.overrides).map_err(|e| e.to_string())?;
|
||||
self.reload_with(cfg)
|
||||
}
|
||||
|
||||
/// Apply an already-loaded configuration.
|
||||
pub fn reload_with(&self, cfg: Config) -> Result<ReloadReport, String> {
|
||||
let old = self.shared.rt();
|
||||
let mut report = ReloadReport::default();
|
||||
if cfg.server.listen != old.cfg.server.listen || cfg.server.udp != old.cfg.server.udp || cfg.server.tcp != old.cfg.server.tcp {
|
||||
report.restart_required.push("server.listen/udp/tcp".into());
|
||||
}
|
||||
if cfg.server.udp_sockets != old.cfg.server.udp_sockets || cfg.server.max_inflight != old.cfg.server.max_inflight {
|
||||
report.restart_required.push("server.udp_sockets/max_inflight".into());
|
||||
}
|
||||
if serde_json::to_string(&cfg.tls).ok() != serde_json::to_string(&old.cfg.tls).ok() {
|
||||
report.restart_required.push("tls".into());
|
||||
}
|
||||
if cfg.api.listen != old.cfg.api.listen || cfg.metrics.listen != old.cfg.metrics.listen {
|
||||
report.restart_required.push("api.listen/metrics.listen".into());
|
||||
}
|
||||
if cfg.cache.max_entries != old.cfg.cache.max_entries
|
||||
|| cfg.cache.answer_entries != old.cfg.cache.answer_entries
|
||||
|| cfg.cache.answer_max_age != old.cfg.cache.answer_max_age
|
||||
{
|
||||
report.restart_required.push("cache.max_entries/answer_entries/answer_max_age".into());
|
||||
}
|
||||
let (rt, fresh) = Runtime::build(cfg, Arc::clone(&self.shared.cache), Some(&old))?;
|
||||
report.zones = rt.zones.all().len();
|
||||
report.new_zones = fresh.iter().map(|e| e.name.to_string()).collect();
|
||||
for e in fresh {
|
||||
spawn_secondary(e);
|
||||
}
|
||||
self.shared.swap(rt);
|
||||
for r in &report.restart_required {
|
||||
tracing::warn!(setting = %r, "changed setting requires a restart to take effect");
|
||||
}
|
||||
tracing::info!(zones = report.zones, "configuration reloaded");
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// Stop listeners, wait for in-flight work (bounded), stop secondary tasks.
|
||||
pub async fn shutdown(&self) {
|
||||
let _ = self.shutdown_tx.send(true);
|
||||
for z in self.shared.rt().zones.all() {
|
||||
z.shutdown.store(true, std::sync::atomic::Ordering::Release);
|
||||
z.refresh_trigger.notify_one();
|
||||
}
|
||||
let tasks: Vec<JoinHandle<()>> = std::mem::take(&mut *self.tasks.lock().unwrap_or_else(|e| e.into_inner()));
|
||||
for t in tasks {
|
||||
let _ = tokio::time::timeout(Duration::from_secs(5), t).await;
|
||||
}
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
|
||||
while self.shared.metrics.inflight.load(std::sync::atomic::Ordering::Relaxed) > 0 && tokio::time::Instant::now() < deadline {
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Shutdown signal receiver (for auxiliary services such as the API).
|
||||
pub fn shutdown_signal(&self) -> watch::Receiver<bool> {
|
||||
self.shutdown_tx.subscribe()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
//! 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
//! Authoritative behaviour, Primary↔Secondary synchronisation, TSIG/ACL, DDNS.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used)]
|
||||
mod common;
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use common::*;
|
||||
use dns_core::client::{QueryOptions, TransferKind, TransferLimits, exchange, transfer};
|
||||
use dns_core::proto::op::ResponseCode;
|
||||
use dns_core::proto::rr::rdata::{A, TXT};
|
||||
use dns_core::proto::rr::{DNSClass, RData, Record, RecordType};
|
||||
use dns_core::tsig::TsigKey;
|
||||
|
||||
const ZONE: &str = r#"$TTL 300
|
||||
@ IN SOA ns1 hostmaster 2024010101 3600 5 1209600 60
|
||||
IN NS ns1
|
||||
IN MX 10 mail
|
||||
ns1 IN A 127.0.0.1
|
||||
mail IN A 192.0.2.25
|
||||
www IN A 192.0.2.10
|
||||
www IN AAAA 2001:db8::10
|
||||
alias IN CNAME www
|
||||
*.wild IN TXT "wild"
|
||||
sub IN NS ns.sub
|
||||
ns.sub IN A 192.0.2.53
|
||||
"#;
|
||||
|
||||
fn primary_yaml(dir: &std::path::Path, extra_zone: &str) -> String {
|
||||
write(dir, "example.com.zone", ZONE);
|
||||
format!(
|
||||
r#"
|
||||
server: {{ mode: primary, listen: ["127.0.0.1:0"], data_dir: data }}
|
||||
keys:
|
||||
- {{ name: xfr-key, algorithm: hmac-sha256, secret: "base64:{KEY_B64}" }}
|
||||
- {{ name: ddns-key, algorithm: hmac-sha256, secret: "base64:{KEY_B64}" }}
|
||||
api: {{ enabled: false }}
|
||||
rate_limit: {{ enabled: false }}
|
||||
zones:
|
||||
- name: example.com
|
||||
type: primary
|
||||
file: example.com.zone
|
||||
transfer_tsig_key: xfr-key
|
||||
update_keys: [ddns-key]
|
||||
update_acl: ["127.0.0.0/8"]
|
||||
{extra_zone}
|
||||
"#
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn authoritative_answers() {
|
||||
let dir = tmpdir("auth");
|
||||
let h = start(&dir, &primary_yaml(&dir, "")).await;
|
||||
let s = h.bound.dns[0];
|
||||
|
||||
let m = q(s, "www.example.com.", RecordType::A).await;
|
||||
assert!(m.metadata.authoritative);
|
||||
assert!(!m.metadata.recursion_available);
|
||||
assert_eq!(answers(&m), vec!["A 192.0.2.10"]);
|
||||
|
||||
let m = q(s, "alias.example.com.", RecordType::AAAA).await;
|
||||
assert_eq!(answers(&m), vec!["AAAA 2001:db8::10", "CNAME www.example.com."]);
|
||||
|
||||
let m = q(s, "nope.example.com.", RecordType::A).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NXDomain);
|
||||
assert!(m.metadata.authoritative);
|
||||
assert_eq!(m.authorities[0].record_type(), RecordType::SOA);
|
||||
|
||||
let m = q(s, "www.example.com.", RecordType::MX).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NoError);
|
||||
assert!(m.answers.is_empty());
|
||||
assert_eq!(m.authorities[0].ttl, 60, "negative TTL = min(SOA TTL, MINIMUM)");
|
||||
|
||||
let m = q(s, "x.wild.example.com.", RecordType::TXT).await;
|
||||
assert_eq!(answers(&m), vec!["TXT wild"]);
|
||||
|
||||
let m = q(s, "host.sub.example.com.", RecordType::A).await;
|
||||
assert!(!m.metadata.authoritative, "referral is not authoritative");
|
||||
assert_eq!(m.authorities[0].record_type(), RecordType::NS);
|
||||
assert_eq!(m.additionals.len(), 1);
|
||||
|
||||
let m = q(s, "example.com.", RecordType::MX).await;
|
||||
assert_eq!(m.additionals.len(), 1, "MX target address in additional section");
|
||||
|
||||
// Not our zone + no recursion configured -> REFUSED (no open resolver).
|
||||
let m = q(s, "www.example.org.", RecordType::A).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::Refused);
|
||||
|
||||
// TCP works too.
|
||||
let m = q_opts(s, "www.example.com.", RecordType::A, QueryOptions { tcp_only: true, ..Default::default() }).await;
|
||||
assert_eq!(answers(&m), vec!["A 192.0.2.10"]);
|
||||
|
||||
// Malformed packet -> FORMERR, response packets are ignored.
|
||||
let sock = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
sock.send_to(&[0x12, 0x34, 0x01, 0x00, 0, 1, 0, 0, 0, 0, 0, 0, 0xff, 0xff], s).await.unwrap();
|
||||
let mut buf = [0u8; 512];
|
||||
let (n, _) = tokio::time::timeout(Duration::from_secs(2), sock.recv_from(&mut buf)).await.unwrap().unwrap();
|
||||
let r = dns_core::proto::op::Message::from_vec(&buf[..n]).unwrap();
|
||||
assert_eq!((r.metadata.id, r.metadata.response_code), (0x1234, ResponseCode::FormErr));
|
||||
|
||||
h.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn transfers_require_tsig_and_acl() {
|
||||
let dir = tmpdir("xfr");
|
||||
let h = start(&dir, &primary_yaml(&dir, "")).await;
|
||||
let s = h.bound.dns[0];
|
||||
let zone = n("example.com.");
|
||||
let lim = TransferLimits { timeout: Duration::from_secs(5), ..Default::default() };
|
||||
|
||||
// No TSIG -> refused.
|
||||
let e = transfer(s, &zone, &TransferKind::Axfr, None, lim).await.unwrap_err();
|
||||
assert!(e.to_string().contains("REFUSED") || e.to_string().contains("Refused"), "{e}");
|
||||
// Wrong key secret -> NOTAUTH, and response cannot be verified.
|
||||
let bad = TsigKey::new("xfr-key", "hmac-sha256", "d3JvbmdzZWNyZXR3cm9uZ3NlY3JldA==").unwrap();
|
||||
assert!(transfer(s, &zone, &TransferKind::Axfr, Some(&bad), lim).await.is_err());
|
||||
// Right key -> full zone, every message verified.
|
||||
let key = TsigKey::new("xfr-key", "hmac-sha256", KEY_B64).unwrap();
|
||||
let st = transfer(s, &zone, &TransferKind::Axfr, Some(&key), lim).await.unwrap();
|
||||
assert!(st.tsig_verified);
|
||||
assert_eq!(st.records.first().unwrap().record_type(), RecordType::SOA);
|
||||
assert_eq!(st.records.last().unwrap().record_type(), RecordType::SOA);
|
||||
assert_eq!(st.records.len(), 12);
|
||||
let m = &h.shared.metrics;
|
||||
assert_eq!(m.xfr_out_refused.load(std::sync::atomic::Ordering::Relaxed), 1, "unsigned AXFR refused");
|
||||
assert_eq!(m.tsig_failures.load(std::sync::atomic::Ordering::Relaxed), 1, "bad MAC -> NOTAUTH");
|
||||
// AXFR over UDP is refused
|
||||
let mut am = dns_core::proto::op::Message::query();
|
||||
am.add_query(dns_core::proto::op::Query::query(zone.clone(), RecordType::AXFR));
|
||||
let mut opts = dns_core::client::QueryOptions { tsig: Some(key.clone()), ignore_tc: true, ..Default::default() };
|
||||
opts.retries = 0;
|
||||
let ex = exchange(s, am, &opts).await.unwrap();
|
||||
assert_eq!(ex.message.metadata.response_code, ResponseCode::Refused);
|
||||
h.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn primary_secondary_sync_notify_ixfr_restart() {
|
||||
// --- primary
|
||||
let pdir = tmpdir("pri");
|
||||
// the secondary listens on a fixed free port so the primary can NOTIFY it
|
||||
let sport = free_port();
|
||||
let secondary_addr = format!("127.0.0.1:{sport}");
|
||||
let p_yaml = primary_yaml(&pdir, "").replace(
|
||||
" update_keys: [ddns-key]",
|
||||
&format!(" notify: [\"{secondary_addr}\"]\n notify_tsig_key: xfr-key\n update_keys: [ddns-key]"),
|
||||
);
|
||||
let p = start(&pdir, &p_yaml).await;
|
||||
let paddr = p.bound.dns[0];
|
||||
|
||||
// --- secondary
|
||||
let sdir = tmpdir("sec");
|
||||
let s_yaml = format!(
|
||||
r#"
|
||||
server: {{ mode: secondary, listen: ["{secondary_addr}"], data_dir: data }}
|
||||
keys:
|
||||
- {{ name: xfr-key, algorithm: hmac-sha256, secret: "base64:{KEY_B64}" }}
|
||||
api: {{ enabled: false }}
|
||||
rate_limit: {{ enabled: false }}
|
||||
zones:
|
||||
- name: example.com
|
||||
type: secondary
|
||||
primaries: ["{paddr}"]
|
||||
transfer: {{ prefer: ixfr, fallback_axfr: true, tsig_key: xfr-key }}
|
||||
"#
|
||||
);
|
||||
let s = start(&sdir, &s_yaml).await;
|
||||
let saddr = s.bound.dns[0];
|
||||
|
||||
// initial AXFR
|
||||
eventually("secondary loads zone", || async { q(saddr, "www.example.com.", RecordType::A).await.answers.len() == 1 }).await;
|
||||
let m = q(saddr, "www.example.com.", RecordType::A).await;
|
||||
assert!(m.metadata.authoritative, "secondary answers authoritatively from its own copy");
|
||||
let entry = s.shared.rt().zones.get(&n("example.com.")).unwrap();
|
||||
assert_eq!(entry.transfers().last().unwrap().kind, "AXFR");
|
||||
|
||||
// change on the primary (same path the API uses) -> NOTIFY -> IXFR
|
||||
let pentry = p.shared.rt().zones.get(&n("example.com.")).unwrap();
|
||||
let new = Record::from_rdata(n("new.example.com."), 300, RData::A(A::new(192, 0, 2, 77)));
|
||||
let serial = pentry.modify(&[], &[new]).unwrap();
|
||||
pentry.send_notifies();
|
||||
eventually("secondary receives IXFR", || async { q(saddr, "new.example.com.", RecordType::A).await.answers.len() == 1 }).await;
|
||||
assert_eq!(entry.current().unwrap().serial(), serial);
|
||||
assert_eq!(entry.transfers().last().unwrap().kind, "IXFR");
|
||||
assert!(s.shared.metrics.notify_received.load(std::sync::atomic::Ordering::Relaxed) >= 1);
|
||||
// the primary's zone file was rewritten atomically with the new serial
|
||||
let text = std::fs::read_to_string(pdir.join("example.com.zone")).unwrap();
|
||||
assert!(text.contains("192.0.2.77"));
|
||||
|
||||
// NOTIFY from an unauthorised source is refused
|
||||
let mut nm = dns_core::proto::op::Message::new(7, dns_core::proto::op::MessageType::Query, dns_core::proto::op::OpCode::Notify);
|
||||
nm.add_query(dns_core::proto::op::Query::query(n("example.com."), RecordType::SOA));
|
||||
let sock = tokio::net::UdpSocket::bind("127.0.0.9:0").await.unwrap();
|
||||
sock.send_to(&nm.to_vec().unwrap(), saddr).await.unwrap();
|
||||
let mut buf = [0u8; 512];
|
||||
let (len, _) = tokio::time::timeout(Duration::from_secs(2), sock.recv_from(&mut buf)).await.unwrap().unwrap();
|
||||
assert_eq!(dns_core::proto::op::Message::from_vec(&buf[..len]).unwrap().metadata.response_code, ResponseCode::Refused);
|
||||
|
||||
// restart the secondary while the primary is down: the persisted copy is served
|
||||
s.shutdown().await;
|
||||
p.shutdown().await;
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
let s2 = start(&sdir, &s_yaml).await;
|
||||
let m = q(s2.bound.dns[0], "new.example.com.", RecordType::A).await;
|
||||
assert_eq!(answers(&m), vec!["A 192.0.2.77"]);
|
||||
assert!(m.metadata.authoritative);
|
||||
s2.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn secondary_expires_when_primary_unreachable() {
|
||||
let sdir = tmpdir("exp");
|
||||
std::fs::create_dir_all(sdir.join("data/secondary")).unwrap();
|
||||
// snapshot with tiny EXPIRE whose last success is long ago
|
||||
let z = ZONE.replace("3600 5 1209600 60", "5 5 10 60");
|
||||
write(&sdir.join("data/secondary"), "example.com.zone", &z);
|
||||
write(
|
||||
&sdir.join("data/secondary"),
|
||||
"example.com.zone.meta.json",
|
||||
r#"{"last_success_unix": 1000, "serial": 2024010101, "primary": "x"}"#,
|
||||
);
|
||||
let yaml = r#"
|
||||
server: { listen: ["127.0.0.1:0"], data_dir: data }
|
||||
api: { enabled: false }
|
||||
zones:
|
||||
- { name: example.com, type: secondary, primaries: ["127.0.0.1:9"] }
|
||||
"#;
|
||||
let s = start(&sdir, yaml).await;
|
||||
let m = q(s.bound.dns[0], "www.example.com.", RecordType::A).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::ServFail, "expired zone must not be served as authoritative");
|
||||
s.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn dynamic_update_authorised_and_refused() {
|
||||
let dir = tmpdir("ddns");
|
||||
let h = start(&dir, &primary_yaml(&dir, "")).await;
|
||||
let s = h.bound.dns[0];
|
||||
let zone = n("example.com.");
|
||||
let rec = Record::from_rdata(n("dyn.example.com."), 120, RData::A(A::new(192, 0, 2, 200)));
|
||||
|
||||
// unsigned -> REFUSED
|
||||
let m = dns_authoritative::update::build_update(&zone, vec![], vec![rec.clone()]);
|
||||
let ex = exchange(s, m, &QueryOptions::default()).await.unwrap();
|
||||
assert_eq!(ex.message.metadata.response_code, ResponseCode::Refused);
|
||||
|
||||
// signed with the update key -> applied
|
||||
let key = TsigKey::new("ddns-key", "hmac-sha256", KEY_B64).unwrap();
|
||||
let opts = QueryOptions { tsig: Some(key.clone()), ..Default::default() };
|
||||
let m = dns_authoritative::update::build_update(&zone, vec![], vec![rec.clone()]);
|
||||
let ex = exchange(s, m, &opts).await.unwrap();
|
||||
assert_eq!(ex.message.metadata.response_code, ResponseCode::NoError);
|
||||
assert!(ex.tsig_verified);
|
||||
assert_eq!(answers(&q(s, "dyn.example.com.", RecordType::A).await), vec!["A 192.0.2.200"]);
|
||||
|
||||
// prerequisite "name not in use" fails -> YXDOMAIN
|
||||
let mut pre = Record::update0(n("dyn.example.com."), 0, RecordType::ANY);
|
||||
pre.dns_class = DNSClass::NONE;
|
||||
let m = dns_authoritative::update::build_update(&zone, vec![pre], vec![rec.clone()]);
|
||||
let ex = exchange(s, m, &opts).await.unwrap();
|
||||
assert_eq!(ex.message.metadata.response_code, ResponseCode::YXDomain);
|
||||
|
||||
// delete the RRset
|
||||
let mut del = Record::update0(n("dyn.example.com."), 0, RecordType::A);
|
||||
del.dns_class = DNSClass::ANY;
|
||||
let m = dns_authoritative::update::build_update(&zone, vec![], vec![del]);
|
||||
assert_eq!(exchange(s, m, &opts).await.unwrap().message.metadata.response_code, ResponseCode::NoError);
|
||||
assert_eq!(q(s, "dyn.example.com.", RecordType::A).await.metadata.response_code, ResponseCode::NXDomain);
|
||||
|
||||
// the audit log captured both
|
||||
let audit = h.shared.audit.tail(10);
|
||||
assert!(audit.len() >= 3);
|
||||
h.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn update_policy_with_bind_key_file_and_ip_only_updates() {
|
||||
let dir = tmpdir("ddns-policy");
|
||||
write(&dir, "example.com.zone", ZONE);
|
||||
write(&dir, "example.net.zone", "$TTL 60\n@ SOA ns hostmaster 1 60 60 600 60\n@ NS ns\nns A 192.0.2.1\n");
|
||||
// key file copied from BIND, included unchanged
|
||||
write(
|
||||
&dir,
|
||||
"keys.conf",
|
||||
&format!(
|
||||
"key \"acme-key.\" {{\n\talgorithm hmac-sha256;\n\tsecret \"{KEY_B64}\";\n}};\nkey \"other-key\" {{ algorithm hmac-sha256; secret \"{KEY_B64}\"; }};\n"
|
||||
),
|
||||
);
|
||||
let yaml = r#"
|
||||
include: [keys.conf]
|
||||
server: { mode: primary, listen: ["127.0.0.1:0"], data_dir: data }
|
||||
api: { enabled: false }
|
||||
rate_limit: { enabled: false }
|
||||
zones:
|
||||
- name: example.com
|
||||
type: primary
|
||||
file: example.com.zone
|
||||
update_policy:
|
||||
- "grant acme-key. name _acme-challenge.example.com. TXT"
|
||||
- "grant acme-key. wildcard *.dyn.example.com. A"
|
||||
- { deny: other-key, match: zonesub }
|
||||
- name: example.net
|
||||
type: primary
|
||||
file: example.net.zone
|
||||
allow_update: ["127.0.0.1"] # IP only, no key (BIND allow-update { 127.0.0.1; })
|
||||
"#;
|
||||
let h = start(&dir, yaml).await;
|
||||
let s = h.bound.dns[0];
|
||||
let zone = n("example.com.");
|
||||
let txt = |owner: &str| Record::from_rdata(n(owner), 60, RData::TXT(TXT::new(vec!["token".into()])));
|
||||
let a = |owner: &str| Record::from_rdata(n(owner), 60, RData::A(A::new(192, 0, 2, 7)));
|
||||
let acme = QueryOptions { tsig: Some(TsigKey::new("acme-key.", "hmac-sha256", KEY_B64).unwrap()), ..Default::default() };
|
||||
let other = QueryOptions { tsig: Some(TsigKey::new("other-key", "hmac-sha256", KEY_B64).unwrap()), ..Default::default() };
|
||||
let rc = |ex: dns_core::client::Exchange| ex.message.metadata.response_code;
|
||||
let up = |r: Record| dns_authoritative::update::build_update(&zone, vec![], vec![r]);
|
||||
|
||||
// granted: exact name + type
|
||||
assert_eq!(rc(exchange(s, up(txt("_acme-challenge.example.com.")), &acme).await.unwrap()), ResponseCode::NoError);
|
||||
assert_eq!(answers(&q(s, "_acme-challenge.example.com.", RecordType::TXT).await), vec!["TXT token"]);
|
||||
// wrong type / wrong name / unsigned / other key -> refused
|
||||
assert_eq!(rc(exchange(s, up(a("_acme-challenge.example.com.")), &acme).await.unwrap()), ResponseCode::Refused);
|
||||
assert_eq!(rc(exchange(s, up(txt("www.example.com.")), &acme).await.unwrap()), ResponseCode::Refused);
|
||||
assert_eq!(rc(exchange(s, up(txt("_acme-challenge.example.com.")), &QueryOptions::default()).await.unwrap()), ResponseCode::Refused);
|
||||
assert_eq!(rc(exchange(s, up(txt("_acme-challenge.example.com.")), &other).await.unwrap()), ResponseCode::Refused);
|
||||
// wildcard: strictly below dyn.example.com
|
||||
assert_eq!(rc(exchange(s, up(a("h1.dyn.example.com.")), &acme).await.unwrap()), ResponseCode::NoError);
|
||||
assert_eq!(rc(exchange(s, up(a("dyn.example.com.")), &acme).await.unwrap()), ResponseCode::Refused);
|
||||
|
||||
// IP-only zone: unsigned update from 127.0.0.1 is accepted
|
||||
let net = n("example.net.");
|
||||
let m = dns_authoritative::update::build_update(&net, vec![], vec![a("host.example.net.")]);
|
||||
assert_eq!(rc(exchange(s, m, &QueryOptions::default()).await.unwrap()), ResponseCode::NoError);
|
||||
assert_eq!(answers(&q(s, "host.example.net.", RecordType::A).await), vec!["A 192.0.2.7"]);
|
||||
h.shutdown().await;
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
#![allow(dead_code, clippy::unwrap_used, clippy::expect_used)]
|
||||
use std::net::SocketAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use dns_config::{Config, Overrides};
|
||||
use dns_core::client::{QueryOptions, query};
|
||||
use dns_core::proto::op::Message;
|
||||
use dns_core::proto::rr::{Name, RecordType};
|
||||
use dns_server::{Server, ServerHandle};
|
||||
|
||||
pub fn tmpdir(tag: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("easydns-it-{tag}-{}-{}", std::process::id(), rand_u32()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
pub fn rand_u32() -> u32 {
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
let n = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().subsec_nanos();
|
||||
n ^ (std::process::id() << 16)
|
||||
}
|
||||
|
||||
pub fn write(dir: &Path, name: &str, text: &str) -> PathBuf {
|
||||
let p = dir.join(name);
|
||||
std::fs::write(&p, text).unwrap();
|
||||
p
|
||||
}
|
||||
|
||||
pub async fn start(dir: &Path, yaml: &str) -> ServerHandle {
|
||||
let path = write(dir, "config.yaml", yaml);
|
||||
let cfg = Config::load(&path).unwrap();
|
||||
Server::start(cfg, Some(path), Overrides::default()).await.unwrap()
|
||||
}
|
||||
|
||||
pub fn n(s: &str) -> Name {
|
||||
Name::from_ascii(s).unwrap()
|
||||
}
|
||||
|
||||
pub async fn q(server: SocketAddr, name: &str, t: RecordType) -> Message {
|
||||
q_opts(server, name, t, QueryOptions { timeout: Duration::from_secs(3), retries: 1, ..Default::default() }).await
|
||||
}
|
||||
|
||||
pub async fn q_opts(server: SocketAddr, name: &str, t: RecordType, o: QueryOptions) -> Message {
|
||||
query(server, &n(name), t, &o).await.unwrap_or_else(|e| panic!("query {name} {t} @{server}: {e}")).message
|
||||
}
|
||||
|
||||
pub fn answers(m: &Message) -> Vec<String> {
|
||||
let mut v: Vec<String> = m.answers.iter().map(|r| format!("{} {}", r.record_type(), r.data)).collect();
|
||||
v.sort();
|
||||
v
|
||||
}
|
||||
|
||||
/// Poll until `f` returns true (max ~10 s).
|
||||
pub async fn eventually<F, Fut>(what: &str, mut f: F)
|
||||
where
|
||||
F: FnMut() -> Fut,
|
||||
Fut: std::future::Future<Output = bool>,
|
||||
{
|
||||
for _ in 0..200 {
|
||||
if f().await {
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
panic!("timed out waiting for: {what}");
|
||||
}
|
||||
|
||||
/// A random free port usable on several 127.0.0.x addresses.
|
||||
pub fn free_port() -> u16 {
|
||||
for _ in 0..50 {
|
||||
let p = 20000 + (rand_u32() % 30000) as u16;
|
||||
let ok = ["127.0.0.2", "127.0.0.3", "127.0.0.4", "127.0.0.5", "127.0.0.6"].iter().all(|ip| {
|
||||
let a: SocketAddr = format!("{ip}:{p}").parse().unwrap();
|
||||
std::net::UdpSocket::bind(a).is_ok() && std::net::TcpListener::bind(a).is_ok()
|
||||
});
|
||||
if ok {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
panic!("no free port");
|
||||
}
|
||||
|
||||
pub const KEY_B64: &str = "c2VjcmV0c2VjcmV0c2VjcmV0c2VjcmV0c2VjcmV0MTI=";
|
||||
@@ -0,0 +1,182 @@
|
||||
//! DNSSEC end-to-end: online signing on primaries + validating recursive resolver.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used)]
|
||||
mod common;
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use common::*;
|
||||
use dns_core::client::QueryOptions;
|
||||
use dns_core::dnssec::{KeyAlgorithm, ZoneKey, key_file_contents};
|
||||
use dns_core::proto::op::ResponseCode;
|
||||
use dns_core::proto::rr::RecordType;
|
||||
use dns_server::ServerHandle;
|
||||
|
||||
/// Generate a CSK for `zone` into `dir`; returns (DS line, DNSKEY line).
|
||||
fn keygen(dir: &Path, zone: &str) -> (String, String) {
|
||||
let z = n(zone);
|
||||
let (pk, key) = ZoneKey::generate(KeyAlgorithm::Ed25519, true).unwrap();
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
let prefix = if zone == "." { "root.".to_string() } else { zone.to_string() };
|
||||
std::fs::write(dir.join(format!("{prefix}{}.csk.key", key.tag)), key_file_contents(KeyAlgorithm::Ed25519, true, &pk)).unwrap();
|
||||
let ds = key.ds_record(&z, 3600).unwrap();
|
||||
let dk = key.dnskey_record(&z, 3600);
|
||||
(format!("{} 3600 IN DS {}", ds.name, ds.data), format!("{} 3600 IN DNSKEY {}", dk.name, dk.data))
|
||||
}
|
||||
|
||||
async fn server(dir: &Path, tag: &str, ip: &str, port: u16, zones: &[(&str, String, bool)]) -> ServerHandle {
|
||||
let d = dir.join(tag);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let mut zl = String::new();
|
||||
for (name, text, signed) in zones {
|
||||
let f = format!("{}.zone", if *name == "." { "root" } else { name.trim_end_matches('.') });
|
||||
write(&d, &f, text);
|
||||
let dnssec = if *signed {
|
||||
format!(
|
||||
", dnssec: {{ keys_dir: \"{}\", auto_generate: false }}",
|
||||
dir.join("keys").join(name.trim_end_matches('.').replace('.', "_")).display()
|
||||
)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
zl.push_str(&format!(" - {{ name: \"{name}\", type: primary, file: \"{f}\"{dnssec} }}\n"));
|
||||
}
|
||||
let yaml = format!(
|
||||
"server: {{ listen: [\"{ip}:{port}\"], data_dir: data }}\napi: {{ enabled: false }}\nrate_limit: {{ enabled: false }}\nzones:\n{zl}"
|
||||
);
|
||||
start(&d, &yaml).await
|
||||
}
|
||||
|
||||
fn kdir(dir: &Path, zone: &str) -> std::path::PathBuf {
|
||||
dir.join("keys").join(zone.trim_end_matches('.').replace('.', "_"))
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn validating_resolver_secure_insecure_bogus() {
|
||||
let dir = tmpdir("dnssec");
|
||||
let port = free_port();
|
||||
let (_, root_key) = keygen(&kdir(&dir, "."), ".");
|
||||
let (zz_ds, _) = keygen(&kdir(&dir, "zz."), "zz.");
|
||||
let (ex_ds, _) = keygen(&kdir(&dir, "example.zz."), "example.zz.");
|
||||
// bogus.zz: the parent publishes a DS for a key the child does not use
|
||||
let (bogus_ds, _) = keygen(&dir.join("unused"), "bogus.zz.");
|
||||
let _ = keygen(&kdir(&dir, "bogus.zz."), "bogus.zz.");
|
||||
|
||||
let root = server(&dir, "root", "127.0.0.2", port, &[(".", format!(
|
||||
"$TTL 3600\n@ IN SOA a.root. hm.root. 1 3600 600 86400 300\n@ IN NS a.root.\na.root. IN A 127.0.0.2\nzz. IN NS ns.zz.\nns.zz. IN A 127.0.0.3\n{zz_ds}\n"), true)]).await;
|
||||
let tld = server(&dir, "tld", "127.0.0.3", port, &[("zz.", format!(
|
||||
"$TTL 3600\n@ IN SOA ns hm 1 3600 600 86400 300\n@ IN NS ns\nns IN A 127.0.0.3\nexample IN NS ns1.example\nns1.example IN A 127.0.0.4\n{ex_ds}\ninsecure IN NS ns1.example\nbogus IN NS ns1.example\n{bogus_ds}\n"), true)]).await;
|
||||
let auth = server(&dir, "auth", "127.0.0.4", port, &[
|
||||
("example.zz.", "$TTL 300\n@ IN SOA ns1 hm 1 3600 600 86400 120\n@ IN NS ns1\nns1 IN A 127.0.0.4\nwww IN A 192.0.2.1\n*.w IN A 192.0.2.7\nalias IN CNAME www\n".into(), true),
|
||||
("insecure.zz.", "$TTL 300\n@ IN SOA ns1.example.zz. hm 1 3600 600 86400 120\n@ IN NS ns1.example.zz.\nwww IN A 192.0.2.2\n".into(), false),
|
||||
("bogus.zz.", "$TTL 300\n@ IN SOA ns1.example.zz. hm 1 3600 600 86400 120\n@ IN NS ns1.example.zz.\nwww IN A 192.0.2.3\n".into(), true),
|
||||
]).await;
|
||||
|
||||
// authoritative side: signed answers and NSEC proofs with DO=1
|
||||
let do_opts = QueryOptions { dnssec_ok: true, recursion_desired: false, ..Default::default() };
|
||||
let m = q_opts(auth.bound.dns[0], "www.example.zz.", RecordType::A, do_opts.clone()).await;
|
||||
assert!(m.answers.iter().any(|r| r.record_type() == RecordType::RRSIG));
|
||||
let m = q_opts(auth.bound.dns[0], "nope.example.zz.", RecordType::A, do_opts.clone()).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NXDomain);
|
||||
assert!(m.authorities.iter().any(|r| r.record_type() == RecordType::NSEC));
|
||||
let m = q(auth.bound.dns[0], "www.example.zz.", RecordType::A).await;
|
||||
assert!(m.answers.iter().all(|r| r.record_type() != RecordType::RRSIG), "no RRSIG without DO");
|
||||
|
||||
// validating resolver anchored at the fixture root key
|
||||
let rdir = tmpdir("validator");
|
||||
write(&rdir, "root.hints", ". 3600000 NS a.root.\na.root. 3600000 A 127.0.0.2\n");
|
||||
write(&rdir, "anchors", &format!("{root_key}\n"));
|
||||
let yaml = format!(
|
||||
r#"
|
||||
server: {{ listen: ["127.0.0.1:0"], data_dir: data }}
|
||||
api: {{ enabled: false }}
|
||||
rate_limit: {{ enabled: false }}
|
||||
recursion: {{ enabled: true, root_hints: root.hints, trust_anchors: anchors, dnssec_validation: true, allowed_clients: ["127.0.0.1/32"], authority_port: {port}, query_timeout: 800ms }}
|
||||
resolution: {{ default: recursive }}
|
||||
"#
|
||||
);
|
||||
let r = start(&rdir, &yaml).await;
|
||||
let s = r.bound.dns[0];
|
||||
let ad = QueryOptions { dnssec_ok: true, ..Default::default() };
|
||||
|
||||
let m = q_opts(s, "www.example.zz.", RecordType::A, ad.clone()).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NoError, "{m:?}");
|
||||
assert!(m.metadata.authentic_data, "secure answer must have AD");
|
||||
assert_eq!(answers(&m).iter().filter(|a| a.starts_with("A ")).count(), 1);
|
||||
|
||||
let m = q_opts(s, "alias.example.zz.", RecordType::A, ad.clone()).await;
|
||||
assert!(m.metadata.authentic_data, "secure CNAME chain");
|
||||
|
||||
let m = q_opts(s, "nope.example.zz.", RecordType::A, ad.clone()).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NXDomain);
|
||||
assert!(m.metadata.authentic_data, "validated NXDOMAIN");
|
||||
|
||||
let m = q_opts(s, "www.example.zz.", RecordType::MX, ad.clone()).await;
|
||||
assert_eq!((m.metadata.response_code, m.answers.len()), (ResponseCode::NoError, 0));
|
||||
assert!(m.metadata.authentic_data, "validated NODATA");
|
||||
|
||||
let m = q_opts(s, "x.w.example.zz.", RecordType::A, ad.clone()).await;
|
||||
assert!(m.metadata.authentic_data, "validated wildcard expansion");
|
||||
|
||||
let m = q_opts(s, "www.insecure.zz.", RecordType::A, ad.clone()).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NoError);
|
||||
assert!(!m.metadata.authentic_data, "provably insecure delegation: no AD");
|
||||
assert_eq!(answers(&m), vec!["A 192.0.2.2"]);
|
||||
|
||||
let m = q_opts(s, "www.bogus.zz.", RecordType::A, ad.clone()).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::ServFail, "bogus data is not returned");
|
||||
assert!(m.answers.is_empty());
|
||||
let cd = QueryOptions { dnssec_ok: true, checking_disabled: true, ..Default::default() };
|
||||
let m = q_opts(s, "www.bogus.zz.", RecordType::A, cd).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NoError, "CD=1 returns unvalidated data");
|
||||
assert!(!m.metadata.authentic_data);
|
||||
|
||||
// clients without DO still get validated (AD only when requested)
|
||||
let m = q(s, "www.example.zz.", RecordType::A).await;
|
||||
assert!(m.answers.iter().all(|r| r.record_type() != RecordType::RRSIG));
|
||||
assert!(r.shared.metrics.dnssec_bogus.load(std::sync::atomic::Ordering::Relaxed) >= 1);
|
||||
|
||||
for h in [r, root, tld, auth] {
|
||||
h.shutdown().await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn signed_zone_changes_are_resigned_and_persisted() {
|
||||
let dir = tmpdir("sign-persist");
|
||||
keygen(&kdir(&dir, "example.com."), "example.com.");
|
||||
let port = free_port();
|
||||
let zone = "$TTL 300\n@ IN SOA ns hm 10 3600 600 86400 60\n@ IN NS ns\nns IN A 127.0.0.1\nwww IN A 192.0.2.1\n".to_string();
|
||||
let h = server(&dir, "p", "127.0.0.2", port, &[("example.com.", zone.clone(), true)]).await;
|
||||
let e = h.shared.rt().zones.get(&n("example.com.")).unwrap();
|
||||
let s1 = e.current().unwrap().serial();
|
||||
assert_eq!(s1, 10);
|
||||
let rec = dns_core::proto::rr::Record::from_rdata(
|
||||
n("new.example.com."),
|
||||
300,
|
||||
dns_core::proto::rr::RData::A(dns_core::proto::rr::rdata::A::new(192, 0, 2, 9)),
|
||||
);
|
||||
let s2 = e.modify(&[], &[rec]).unwrap();
|
||||
assert!(dns_core::serial::is_newer(s2, s1));
|
||||
let z = e.current().unwrap();
|
||||
assert!(z.all_records().iter().any(|r| r.name == n("new.example.com.") && r.record_type() == RecordType::RRSIG));
|
||||
assert!(z.all_records().iter().any(|r| r.name == n("new.example.com.") && r.record_type() == RecordType::NSEC));
|
||||
// the source file stays unsigned
|
||||
let src = std::fs::read_to_string(dir.join("p").join("example.com.zone")).unwrap();
|
||||
assert!(!src.contains("RRSIG") && src.contains("192.0.2.9"));
|
||||
let sigs_before: Vec<String> =
|
||||
z.all_records().iter().filter(|r| r.record_type() == RecordType::RRSIG).map(|r| r.data.to_string()).collect();
|
||||
h.shutdown().await;
|
||||
// restart: the persisted signed zone is reused (same serial, same signatures),
|
||||
// so secondaries never see different signatures under an unchanged serial.
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
let yaml = std::fs::read_to_string(dir.join("p").join("config.yaml")).unwrap();
|
||||
let h2 = start(&dir.join("p"), &yaml).await;
|
||||
let z2 = h2.shared.rt().zones.get(&n("example.com.")).unwrap().current().unwrap();
|
||||
assert_eq!(z2.serial(), s2);
|
||||
let sigs_after: Vec<String> =
|
||||
z2.all_records().iter().filter(|r| r.record_type() == RecordType::RRSIG).map(|r| r.data.to_string()).collect();
|
||||
assert_eq!(sigs_before, sigs_after);
|
||||
// DS for the parent is available
|
||||
assert_eq!(h2.shared.rt().zones.get(&n("example.com.")).unwrap().ds_records().len(), 1);
|
||||
h2.shutdown().await;
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
//! Performance-related behaviour: query coalescing and the SO_REUSEPORT socket group.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used)]
|
||||
mod common;
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use common::*;
|
||||
use dns_core::proto::op::Message;
|
||||
use dns_core::proto::rr::rdata::A;
|
||||
use dns_core::proto::rr::{RData, Record, RecordType};
|
||||
use tokio::net::UdpSocket;
|
||||
|
||||
/// Fake upstream: counts queries and answers each after `delay` with A 192.0.2.53.
|
||||
async fn slow_upstream(delay: Duration) -> (std::net::SocketAddr, Arc<AtomicUsize>) {
|
||||
let sock = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap());
|
||||
let addr = sock.local_addr().unwrap();
|
||||
let count = Arc::new(AtomicUsize::new(0));
|
||||
let c = Arc::clone(&count);
|
||||
tokio::spawn(async move {
|
||||
let mut buf = [0u8; 2048];
|
||||
loop {
|
||||
let Ok((n, peer)) = sock.recv_from(&mut buf).await else { return };
|
||||
let Ok(req) = Message::from_vec(&buf[..n]) else { continue };
|
||||
c.fetch_add(1, Ordering::SeqCst);
|
||||
let sock = Arc::clone(&sock);
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(delay).await;
|
||||
let mut resp = dns_core::wire::response_for(&req);
|
||||
let qn = req.queries[0].name.clone();
|
||||
resp.answers.push(Record::from_rdata(qn, 60, RData::A(A::new(192, 0, 2, 53))));
|
||||
let _ = sock.send_to(&resp.to_vec().unwrap(), peer).await;
|
||||
});
|
||||
}
|
||||
});
|
||||
(addr, count)
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn identical_concurrent_misses_reach_upstream_once() {
|
||||
let (up, count) = slow_upstream(Duration::from_millis(300)).await;
|
||||
let dir = tmpdir("coalesce");
|
||||
let yaml = format!(
|
||||
r#"
|
||||
server: {{ mode: forwarder, listen: ["127.0.0.1:0"], data_dir: data, udp_sockets: 4 }}
|
||||
api: {{ enabled: false }}
|
||||
rate_limit: {{ enabled: false }}
|
||||
upstreams: {{ strategy: failover, timeout: 2s, servers: ["{up}"] }}
|
||||
resolution: {{ default: forward }}
|
||||
"#
|
||||
);
|
||||
let h = start(&dir, &yaml).await;
|
||||
let s = h.bound.dns[0];
|
||||
let qs: Vec<_> = (0..40).map(|_| tokio::spawn(async move { q(s, "burst.example.", RecordType::A).await })).collect();
|
||||
for t in qs {
|
||||
assert_eq!(answers(&t.await.unwrap()), vec!["A 192.0.2.53"]);
|
||||
}
|
||||
assert_eq!(count.load(Ordering::SeqCst), 1, "40 identical misses must cost one upstream query");
|
||||
// a different name is its own resolution
|
||||
q(s, "other.example.", RecordType::A).await;
|
||||
assert_eq!(count.load(Ordering::SeqCst), 2);
|
||||
assert_eq!(h.shared.rt().router.flights.in_flight(), 0);
|
||||
h.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn reuseport_group_shares_one_port_and_answers() {
|
||||
let socks = dns_server::listener::bind_udp_group("127.0.0.1:0".parse().unwrap(), 4).unwrap();
|
||||
let ports: Vec<u16> = socks.iter().map(|s| s.local_addr().unwrap().port()).collect();
|
||||
assert!(!ports.is_empty() && ports.iter().all(|p| *p == ports[0]), "{ports:?}");
|
||||
#[cfg(target_os = "linux")]
|
||||
assert_eq!(socks.len(), 4);
|
||||
drop(socks);
|
||||
|
||||
// the server answers through every socket of the group: many distinct client ports
|
||||
// are hashed by the kernel onto different sockets
|
||||
let dir = tmpdir("reuseport");
|
||||
write(&dir, "z.zone", "$TTL 60\n@ SOA ns hostmaster 1 60 60 600 60\n@ NS ns\nns A 192.0.2.1\nwww A 192.0.2.80\n");
|
||||
let yaml = r#"
|
||||
server: { mode: primary, listen: ["127.0.0.1:0"], data_dir: data, udp_sockets: 4 }
|
||||
api: { enabled: false }
|
||||
rate_limit: { enabled: false }
|
||||
zones: [ { name: example.test, type: primary, file: z.zone } ]
|
||||
"#;
|
||||
let h = start(&dir, yaml).await;
|
||||
let s = h.bound.dns[0];
|
||||
let qs: Vec<_> = (0..64).map(|_| tokio::spawn(async move { q(s, "www.example.test.", RecordType::A).await })).collect();
|
||||
for t in qs {
|
||||
assert_eq!(answers(&t.await.unwrap()), vec!["A 192.0.2.80"]);
|
||||
}
|
||||
h.shutdown().await;
|
||||
}
|
||||
|
||||
/// The encoded-answer cache must never serve stale or wrong-transport data.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn answer_cache_is_invalidated_and_transport_aware() {
|
||||
use dns_core::client::{QueryOptions, exchange};
|
||||
use dns_core::proto::op::ResponseCode;
|
||||
use dns_core::proto::rr::rdata::A;
|
||||
use dns_core::proto::rr::{RData, Record};
|
||||
let dir = tmpdir("answer-cache");
|
||||
let mut zone = String::from("$TTL 60\n@ SOA ns hostmaster 1 60 60 600 60\n@ NS ns\nns A 192.0.2.1\nwww A 192.0.2.80\n");
|
||||
for i in 0..60 {
|
||||
zone.push_str(&format!("big TXT \"padding-record-number-{i:03}-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n"));
|
||||
}
|
||||
write(&dir, "z.zone", &zone);
|
||||
let yaml = r#"
|
||||
server: { mode: primary, listen: ["127.0.0.1:0"], data_dir: data }
|
||||
api: { enabled: false }
|
||||
rate_limit: { enabled: false }
|
||||
zones: [ { name: example.net, type: primary, file: z.zone, update_acl: ["127.0.0.1"] } ]
|
||||
"#;
|
||||
let h = start(&dir, yaml).await;
|
||||
let s = h.bound.dns[0];
|
||||
let hits = || h.shared.packet_cache.stats.hits.load(Ordering::Relaxed);
|
||||
|
||||
// second identical query is a cache hit, also with different letter case
|
||||
assert_eq!(answers(&q(s, "www.example.net.", RecordType::A).await), vec!["A 192.0.2.80"]);
|
||||
let before = hits();
|
||||
let m = q(s, "WWW.Example.NET.", RecordType::A).await;
|
||||
assert_eq!(answers(&m), vec!["A 192.0.2.80"]);
|
||||
assert_eq!(m.queries[0].name.to_ascii(), "WWW.Example.NET.", "0x20 case must be echoed");
|
||||
assert!(hits() > before, "expected a cache hit");
|
||||
|
||||
// a dynamic update is visible immediately (no stale cached answer)
|
||||
let zone_name = n("example.net.");
|
||||
let mut del = Record::update0(n("www.example.net."), 0, RecordType::A);
|
||||
del.dns_class = dns_core::proto::rr::DNSClass::ANY;
|
||||
let add = Record::from_rdata(n("www.example.net."), 60, RData::A(A::new(192, 0, 2, 99)));
|
||||
let m = dns_authoritative::update::build_update(&zone_name, vec![], vec![del, add]);
|
||||
assert_eq!(exchange(s, m, &QueryOptions::default()).await.unwrap().message.metadata.response_code, ResponseCode::NoError);
|
||||
assert_eq!(answers(&q(s, "www.example.net.", RecordType::A).await), vec!["A 192.0.2.99"]);
|
||||
|
||||
// UDP answer is truncated, TCP answer is complete – never mixed up by the cache
|
||||
for _ in 0..2 {
|
||||
let udp = q_opts(s, "big.example.net.", RecordType::TXT, QueryOptions { ignore_tc: true, ..Default::default() }).await;
|
||||
let tcp = q_opts(s, "big.example.net.", RecordType::TXT, QueryOptions { tcp_only: true, ..Default::default() }).await;
|
||||
assert_eq!(tcp.answers.len(), 60);
|
||||
assert!(udp.metadata.truncation && udp.answers.len() < 60, "UDP answer must stay truncated");
|
||||
assert!(!tcp.metadata.truncation);
|
||||
}
|
||||
|
||||
// reload invalidates
|
||||
let before_entries = h.shared.packet_cache.len();
|
||||
assert!(before_entries > 0);
|
||||
h.reload().unwrap();
|
||||
let before = hits();
|
||||
q(s, "www.example.net.", RecordType::A).await;
|
||||
assert_eq!(hits(), before, "no hit right after a reload");
|
||||
h.shutdown().await;
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
//! Recursive resolver, forwarder and hybrid routing against a local root→TLD→authoritative fixture.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used)]
|
||||
mod common;
|
||||
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use common::*;
|
||||
use dns_core::proto::op::ResponseCode;
|
||||
use dns_core::proto::rr::RecordType;
|
||||
use dns_server::ServerHandle;
|
||||
|
||||
struct Fixture {
|
||||
port: u16,
|
||||
servers: Vec<ServerHandle>,
|
||||
_dir: std::path::PathBuf,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn total_queries(&self, i: usize) -> u64 {
|
||||
self.servers[i].shared.metrics.total_queries()
|
||||
}
|
||||
}
|
||||
|
||||
async fn auth_server(dir: &std::path::Path, tag: &str, ip: &str, port: u16, zones: &[(&str, &str)], extra: &str) -> ServerHandle {
|
||||
let d = dir.join(tag);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let mut zl = String::new();
|
||||
for (name, text) in zones {
|
||||
let f = format!("{}.zone", name.trim_end_matches('.').replace('.', "_"));
|
||||
write(&d, if f == ".zone" { "root.zone" } else { &f }, text);
|
||||
let f = if f == ".zone" { "root.zone".to_string() } else { f };
|
||||
zl.push_str(&format!(" - {{ name: \"{name}\", type: primary, file: {f}, transfer_acl: [\"127.0.0.0/8\"] }}\n"));
|
||||
}
|
||||
let yaml = format!(
|
||||
"server: {{ listen: [\"{ip}:{port}\"], data_dir: data }}\napi: {{ enabled: false }}\nrate_limit: {{ enabled: false }}\n{extra}zones:\n{zl}"
|
||||
);
|
||||
start(&d, &yaml).await
|
||||
}
|
||||
|
||||
async fn fixture() -> Fixture {
|
||||
let dir = tmpdir("fixture");
|
||||
let port = free_port();
|
||||
let root = auth_server(
|
||||
&dir,
|
||||
"root",
|
||||
"127.0.0.2",
|
||||
port,
|
||||
&[(
|
||||
".",
|
||||
r#"$TTL 3600
|
||||
@ IN SOA a.root. hm.root. 1 3600 600 86400 300
|
||||
@ IN NS a.root.
|
||||
a.root. IN A 127.0.0.2
|
||||
zz. IN NS ns.zz.
|
||||
ns.zz. IN A 127.0.0.3
|
||||
"#,
|
||||
)],
|
||||
"",
|
||||
)
|
||||
.await;
|
||||
let tld = auth_server(
|
||||
&dir,
|
||||
"tld",
|
||||
"127.0.0.3",
|
||||
port,
|
||||
&[(
|
||||
"zz.",
|
||||
r#"$TTL 3600
|
||||
@ IN SOA ns hm 1 3600 600 86400 300
|
||||
@ IN NS ns
|
||||
ns IN A 127.0.0.3
|
||||
example IN NS ns1.example
|
||||
ns1.example IN A 127.0.0.4
|
||||
other IN NS ns1.example
|
||||
nogl IN NS ns.other
|
||||
"#,
|
||||
)],
|
||||
"",
|
||||
)
|
||||
.await;
|
||||
let auth = auth_server(
|
||||
&dir,
|
||||
"auth",
|
||||
"127.0.0.4",
|
||||
port,
|
||||
&[
|
||||
(
|
||||
"example.zz.",
|
||||
r#"$TTL 300
|
||||
@ IN SOA ns1 hm 1 3600 600 86400 120
|
||||
@ IN NS ns1
|
||||
ns1 IN A 127.0.0.4
|
||||
www IN A 192.0.2.1
|
||||
alias IN CNAME www.other.zz.
|
||||
deep.a.b IN A 192.0.2.9
|
||||
ads IN A 192.0.2.66
|
||||
"#,
|
||||
),
|
||||
(
|
||||
"other.zz.",
|
||||
"$TTL 300\n@ IN SOA ns hm 1 3600 600 86400 120\n@ IN NS ns1.example.zz.\nns IN A 127.0.0.4\nwww IN A 192.0.2.2\n",
|
||||
),
|
||||
("nogl.zz.", "$TTL 300\n@ IN SOA ns.other.zz. hm 1 3600 600 86400 120\n@ IN NS ns.other.zz.\nhost IN A 192.0.2.3\n"),
|
||||
],
|
||||
"",
|
||||
)
|
||||
.await;
|
||||
let corp = auth_server(
|
||||
&dir,
|
||||
"corp",
|
||||
"127.0.0.5",
|
||||
port,
|
||||
&[("corp.internal.", "$TTL 300\n@ IN SOA ns hm 1 3600 600 86400 120\n@ IN NS ns\nns IN A 127.0.0.5\nsecret IN A 10.1.2.3\n")],
|
||||
"",
|
||||
)
|
||||
.await;
|
||||
let net = auth_server(
|
||||
&dir,
|
||||
"net",
|
||||
"127.0.0.6",
|
||||
port,
|
||||
&[("example.net.", "$TTL 300\n@ IN SOA ns hm 7 3600 600 86400 120\n@ IN NS ns\nns IN A 127.0.0.6\nwww IN A 198.51.100.1\n")],
|
||||
"",
|
||||
)
|
||||
.await;
|
||||
Fixture { port, servers: vec![root, tld, auth, corp, net], _dir: dir }
|
||||
}
|
||||
|
||||
fn resolver_yaml(dir: &std::path::Path, port: u16, extra: &str) -> String {
|
||||
write(dir, "root.hints", ". 3600000 NS a.root.\na.root. 3600000 A 127.0.0.2\n");
|
||||
format!(
|
||||
r#"
|
||||
server: {{ listen: ["127.0.0.1:0"], data_dir: data }}
|
||||
api: {{ enabled: false }}
|
||||
rate_limit: {{ enabled: false }}
|
||||
recursion:
|
||||
enabled: true
|
||||
root_hints: root.hints
|
||||
allowed_clients: ["127.0.0.1/32"]
|
||||
authority_port: {port}
|
||||
query_timeout: 500ms
|
||||
resolution: {{ default: recursive }}
|
||||
{extra}
|
||||
"#
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn iterative_resolution_from_root() {
|
||||
let fx = fixture().await;
|
||||
let dir = tmpdir("resolver");
|
||||
let r = start(&dir, &resolver_yaml(&dir, fx.port, "")).await;
|
||||
let s = r.bound.dns[0];
|
||||
|
||||
let m = q(s, "www.example.zz.", RecordType::A).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NoError);
|
||||
assert_eq!(answers(&m), vec!["A 192.0.2.1"]);
|
||||
assert!(m.metadata.recursion_available);
|
||||
assert!(!m.metadata.authoritative, "recursive answers never carry AA");
|
||||
assert!(fx.total_queries(0) >= 1 && fx.total_queries(1) >= 1 && fx.total_queries(2) >= 1, "walked root → TLD → auth");
|
||||
|
||||
// CNAME into another zone
|
||||
let m = q(s, "alias.example.zz.", RecordType::A).await;
|
||||
assert_eq!(answers(&m), vec!["A 192.0.2.2", "CNAME www.other.zz."]);
|
||||
|
||||
// glueless delegation (NS name must be resolved first)
|
||||
let m = q(s, "host.nogl.zz.", RecordType::A).await;
|
||||
assert_eq!(answers(&m), vec!["A 192.0.2.3"]);
|
||||
|
||||
// QNAME minimisation across empty non-terminals
|
||||
let m = q(s, "deep.a.b.example.zz.", RecordType::A).await;
|
||||
assert_eq!(answers(&m), vec!["A 192.0.2.9"]);
|
||||
|
||||
// negative answers with SOA
|
||||
let m = q(s, "missing.example.zz.", RecordType::A).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NXDomain);
|
||||
assert_eq!(m.authorities[0].record_type(), RecordType::SOA);
|
||||
let m = q(s, "www.example.zz.", RecordType::MX).await;
|
||||
assert_eq!((m.metadata.response_code, m.answers.len()), (ResponseCode::NoError, 0));
|
||||
let m = q(s, "nosuchtld.", RecordType::A).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NXDomain);
|
||||
|
||||
// cache: second query does not touch the authorities
|
||||
let before = fx.total_queries(2);
|
||||
let hits = r.shared.cache.stats().hits;
|
||||
let pc_hits = r.shared.packet_cache.stats.hits.load(std::sync::atomic::Ordering::Relaxed);
|
||||
let m = q(s, "www.example.zz.", RecordType::A).await;
|
||||
assert_eq!(answers(&m), vec!["A 192.0.2.1"]);
|
||||
assert!(m.answers[0].ttl <= 300);
|
||||
assert_eq!(fx.total_queries(2), before);
|
||||
// answered by the record cache or the encoded-answer cache
|
||||
assert!(r.shared.cache.stats().hits > hits || r.shared.packet_cache.stats.hits.load(std::sync::atomic::Ordering::Relaxed) > pc_hits);
|
||||
|
||||
// TCP to the resolver
|
||||
let m = q_opts(s, "www.other.zz.", RecordType::A, dns_core::client::QueryOptions { tcp_only: true, ..Default::default() }).await;
|
||||
assert_eq!(answers(&m), vec!["A 192.0.2.2"]);
|
||||
|
||||
// client outside allowed_clients -> REFUSED, nothing sent upstream
|
||||
let root_before = fx.total_queries(0);
|
||||
let sock = tokio::net::UdpSocket::bind("127.0.0.9:0").await.unwrap();
|
||||
let qm = dns_core::client::build_query(&n("fresh.example.zz."), RecordType::A, &Default::default());
|
||||
sock.send_to(&qm.to_vec().unwrap(), s).await.unwrap();
|
||||
let mut buf = [0u8; 1500];
|
||||
let (len, _) = tokio::time::timeout(std::time::Duration::from_secs(2), sock.recv_from(&mut buf)).await.unwrap().unwrap();
|
||||
let resp = dns_core::proto::op::Message::from_vec(&buf[..len]).unwrap();
|
||||
assert_eq!(resp.metadata.response_code, ResponseCode::Refused);
|
||||
assert!(!resp.metadata.recursion_available);
|
||||
assert_eq!(fx.total_queries(0), root_before);
|
||||
|
||||
// local-only names never leave the host
|
||||
let m = q(s, "printer.local.", RecordType::A).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NXDomain);
|
||||
let m = q(s, "1.1.168.192.in-addr.arpa.", RecordType::PTR).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NXDomain);
|
||||
assert_eq!(fx.total_queries(0), root_before);
|
||||
|
||||
// resolver protects itself: server answering garbage is handled (dead port)
|
||||
r.shutdown().await;
|
||||
for h in fx.servers {
|
||||
h.shutdown().await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn hybrid_node_routes_without_leaks() {
|
||||
let fx = fixture().await;
|
||||
let dir = tmpdir("hybrid");
|
||||
write(&dir, "example.com.zone", "$TTL 300\n@ IN SOA ns hm 1 3600 600 86400 60\n@ IN NS ns\nns IN A 127.0.0.1\nwww IN A 203.0.113.80\n");
|
||||
write(&dir, "block.txt", "ads.example.zz\n");
|
||||
let extra = format!(
|
||||
r#"
|
||||
zones:
|
||||
- {{ name: example.com, type: primary, file: example.com.zone }}
|
||||
- {{ name: example.net, type: secondary, primaries: ["127.0.0.6:{p}"] }}
|
||||
forward_zones:
|
||||
- {{ domain: corp.internal, upstreams: ["127.0.0.5:{p}"] }}
|
||||
policy:
|
||||
blocklists: [ {{ name: ads, file: block.txt, category: ads }} ]
|
||||
"#,
|
||||
p = fx.port
|
||||
);
|
||||
let h = start(&dir, &resolver_yaml(&dir, fx.port, &extra)).await;
|
||||
let s = h.bound.dns[0];
|
||||
|
||||
// Primary
|
||||
let m = q(s, "www.example.com.", RecordType::A).await;
|
||||
assert!(m.metadata.authoritative);
|
||||
assert_eq!(answers(&m), vec!["A 203.0.113.80"]);
|
||||
// Secondary (synchronised from 127.0.0.6)
|
||||
eventually("hybrid secondary sync", || async { q(s, "www.example.net.", RecordType::A).await.answers.len() == 1 }).await;
|
||||
assert!(q(s, "www.example.net.", RecordType::A).await.metadata.authoritative);
|
||||
// Conditional forwarding to the private DNS; the root never sees the private name
|
||||
let root_before = fx.total_queries(0);
|
||||
let m = q(s, "secret.corp.internal.", RecordType::A).await;
|
||||
assert_eq!(answers(&m), vec!["A 10.1.2.3"]);
|
||||
assert!(!m.metadata.authoritative);
|
||||
let m = q(s, "nothere.corp.internal.", RecordType::A).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NXDomain);
|
||||
// names under the local zones are never sent upstream either
|
||||
let m = q(s, "missing.example.com.", RecordType::A).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NXDomain);
|
||||
assert!(m.metadata.authoritative);
|
||||
assert_eq!(fx.total_queries(0), root_before, "no leak of private/local names to the root");
|
||||
// Recursion for everything else
|
||||
let m = q(s, "www.example.zz.", RecordType::A).await;
|
||||
assert_eq!(answers(&m), vec!["A 192.0.2.1"]);
|
||||
// Blocklist
|
||||
let before = fx.total_queries(2);
|
||||
let m = q(s, "ads.example.zz.", RecordType::A).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NXDomain);
|
||||
assert_eq!(fx.total_queries(2), before, "blocked names are not resolved");
|
||||
assert_eq!(h.shared.metrics.blocked.load(Ordering::Relaxed), 1);
|
||||
// cache namespaces: the forward route and recursion do not share entries
|
||||
assert!(h.shared.cache.stats().entries > 0);
|
||||
|
||||
h.shutdown().await;
|
||||
for x in fx.servers {
|
||||
x.shutdown().await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn forwarder_failover_and_reload() {
|
||||
let fx = fixture().await;
|
||||
let dir = tmpdir("fwd");
|
||||
let yaml = format!(
|
||||
r#"
|
||||
server: {{ mode: forwarder, listen: ["127.0.0.1:0"], data_dir: data }}
|
||||
api: {{ enabled: false }}
|
||||
rate_limit: {{ enabled: false }}
|
||||
upstreams:
|
||||
strategy: failover
|
||||
timeout: 300ms
|
||||
servers: ["127.0.0.1:9", "127.0.0.5:{p}"]
|
||||
resolution: {{ default: forward }}
|
||||
"#,
|
||||
p = fx.port
|
||||
);
|
||||
let h = start(&dir, &yaml).await;
|
||||
let s = h.bound.dns[0];
|
||||
let m = q(s, "secret.corp.internal.", RecordType::A).await;
|
||||
assert_eq!(answers(&m), vec!["A 10.1.2.3"], "dead first upstream is skipped");
|
||||
let stats = h.shared.rt().router.default_pool.as_ref().unwrap().stats();
|
||||
assert!(stats[0].1.failures >= 1);
|
||||
|
||||
// hot reload: switch the default to refuse; the change applies atomically
|
||||
let new_yaml = yaml.replace("default: forward", "default: refuse").replace("mode: forwarder", "mode: hybrid");
|
||||
write(&dir, "config.yaml", &new_yaml);
|
||||
let rep = h.reload().unwrap();
|
||||
assert!(rep.restart_required.is_empty());
|
||||
let m = q(s, "other.corp.internal.", RecordType::A).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::Refused);
|
||||
// invalid config is rejected and the old one stays active
|
||||
write(&dir, "config.yaml", "server: { bogus: 1 }");
|
||||
assert!(h.reload().is_err());
|
||||
let m = q(s, "other.corp.internal.", RecordType::A).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::Refused);
|
||||
h.shutdown().await;
|
||||
for x in fx.servers {
|
||||
x.shutdown().await;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//! Malformed / hostile input must never panic or hang the server (stable-Rust fuzzing).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used)]
|
||||
mod common;
|
||||
|
||||
use common::*;
|
||||
use dns_core::client::{QueryOptions, build_query};
|
||||
use dns_core::proto::rr::RecordType;
|
||||
|
||||
/// xorshift PRNG (deterministic, no extra deps)
|
||||
struct Rng(u64);
|
||||
impl Rng {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn random_and_mutated_packets_do_not_panic() {
|
||||
let dir = tmpdir("fuzz");
|
||||
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.1\n*.w IN TXT \"x\"\n",
|
||||
);
|
||||
let yaml = "server: { listen: [\"127.0.0.1:0\"], data_dir: data }\napi: { enabled: false }\nrate_limit: { enabled: false }\nzones: [ { name: example.test, type: primary, file: z.zone, transfer_acl: [\"127.0.0.1/32\"] } ]\n";
|
||||
let h = start(&dir, yaml).await;
|
||||
let shared = &h.shared;
|
||||
let peer: std::net::SocketAddr = "127.0.0.1:5555".parse().unwrap();
|
||||
let mut rng = Rng(0x9E37_79B9_7F4A_7C15);
|
||||
let seeds: Vec<Vec<u8>> = ["www.example.test.", "x.w.example.test.", "example.test."]
|
||||
.iter()
|
||||
.flat_map(|n| {
|
||||
[RecordType::A, RecordType::AXFR, RecordType::IXFR, RecordType::ANY]
|
||||
.map(|t| build_query(&n.parse().unwrap(), t, &QueryOptions::default()).to_vec().unwrap())
|
||||
})
|
||||
.collect();
|
||||
for i in 0..30_000u32 {
|
||||
let pkt: Vec<u8> = if i % 3 == 0 {
|
||||
let len = (rng.next() % 600) as usize;
|
||||
(0..len).map(|_| rng.next() as u8).collect()
|
||||
} else {
|
||||
let mut p = seeds[(rng.next() as usize) % seeds.len()].clone();
|
||||
for _ in 0..(1 + rng.next() % 6) {
|
||||
let idx = (rng.next() as usize) % p.len();
|
||||
p[idx] = rng.next() as u8;
|
||||
}
|
||||
if rng.next().is_multiple_of(5) {
|
||||
p.truncate((rng.next() as usize) % p.len());
|
||||
}
|
||||
p
|
||||
};
|
||||
let _ = dns_core::proto::op::Message::from_vec(&pkt);
|
||||
for t in [dns_server::handler::Transport::Udp, dns_server::handler::Transport::Tcp] {
|
||||
let _ = tokio::time::timeout(std::time::Duration::from_secs(2), dns_server::handler::handle(shared, &pkt, peer, t))
|
||||
.await
|
||||
.expect("handler hung");
|
||||
}
|
||||
}
|
||||
// zone file parser and config parser with garbage
|
||||
for _ in 0..2000 {
|
||||
let len = (rng.next() % 300) as usize;
|
||||
let s: String = (0..len).map(|_| (32 + (rng.next() % 95) as u8) as char).collect();
|
||||
let _ = dns_core::zonefile::parse_str(&s, &"example.test.".parse().unwrap(), None);
|
||||
let _ = dns_config::Config::from_str_any(&s, "fuzz");
|
||||
}
|
||||
// server still answers
|
||||
let m = q(h.bound.dns[0], "www.example.test.", RecordType::A).await;
|
||||
assert_eq!(answers(&m), vec!["A 192.0.2.1"]);
|
||||
h.shutdown().await;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
Reference in new issue
Block a user