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

No files matched your search

+50
View File
@@ -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()
}
}
+81
View File
@@ -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
}
+183
View File
@@ -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);
}
}
+688
View File
@@ -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(&note));
}
// 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(&note));
}
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))
}
+27
View File
@@ -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};
+309
View File
@@ -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);
});
}
}
+480
View File
@@ -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(&notify).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());
}
}
+203
View File
@@ -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
}
}
+148
View File
@@ -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();
}
}
+224
View File
@@ -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()
}
}
+339
View File
@@ -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);
}
}