v0.1.0
This commit is contained in:
commit
fa432bebda
189 files changed
+26219
No files matched your search
@@ -0,0 +1,688 @@
|
||||
//! Message dispatcher: one request in, zero or more encoded responses out.
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
use dns_authoritative::store::TransferEvent;
|
||||
use dns_authoritative::{Lookup, ZoneKind};
|
||||
use dns_config::BlockAction;
|
||||
use dns_core::answer::{Answer, Source};
|
||||
use dns_core::proto::op::{Message, OpCode, ResponseCode};
|
||||
use dns_core::proto::rr::rdata::{A, AAAA, TXT};
|
||||
use dns_core::proto::rr::{DNSClass, LowerName, Name, RData, Record, RecordType};
|
||||
use dns_core::tsig::{ResponseSigner, TsigStatus, verify_request};
|
||||
use dns_core::wire;
|
||||
use dns_policy::RateDecision;
|
||||
|
||||
use crate::runtime::{Runtime, Shared};
|
||||
|
||||
/// Transport a request arrived on.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Transport {
|
||||
Udp,
|
||||
Tcp,
|
||||
Dot,
|
||||
Doh,
|
||||
}
|
||||
|
||||
impl Transport {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Transport::Udp => "udp",
|
||||
Transport::Tcp => "tcp",
|
||||
Transport::Dot => "dot",
|
||||
Transport::Doh => "doh",
|
||||
}
|
||||
}
|
||||
fn stream(self) -> bool {
|
||||
self != Transport::Udp
|
||||
}
|
||||
}
|
||||
|
||||
/// Encoded reply.
|
||||
#[derive(Debug)]
|
||||
pub enum Reply {
|
||||
None,
|
||||
One(Vec<u8>),
|
||||
Many(Vec<Vec<u8>>),
|
||||
}
|
||||
|
||||
/// Max CNAME hops when a local answer continues into resolution.
|
||||
const MAX_CROSS_CNAME: usize = 8;
|
||||
|
||||
fn anonymize(ip: IpAddr) -> String {
|
||||
match dns_policy::canonical_ip(ip) {
|
||||
IpAddr::V4(v4) => {
|
||||
let o = v4.octets();
|
||||
format!("{}.{}.{}.0/24", o[0], o[1], o[2])
|
||||
}
|
||||
IpAddr::V6(v6) => {
|
||||
let s = v6.segments();
|
||||
format!("{:x}:{:x}:{:x}::/48", s[0], s[1], s[2])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the slow path learnt about cacheability of its response.
|
||||
#[derive(Default)]
|
||||
struct CacheSlot {
|
||||
/// Set by `Ctx::finish` for responses that may be stored in the packet cache.
|
||||
info: std::sync::OnceLock<(Source, &'static str)>,
|
||||
/// Data from resolution was mixed into an authoritative answer (CNAME leaving a zone).
|
||||
resolved: std::sync::atomic::AtomicBool,
|
||||
}
|
||||
|
||||
struct Ctx<'a> {
|
||||
shared: &'a Shared,
|
||||
rt: Arc<Runtime>,
|
||||
client: SocketAddr,
|
||||
transport: Transport,
|
||||
tsig: TsigStatus,
|
||||
start: Instant,
|
||||
slot: &'a CacheSlot,
|
||||
}
|
||||
|
||||
impl Ctx<'_> {
|
||||
fn ip(&self) -> IpAddr {
|
||||
dns_policy::canonical_ip(self.client.ip())
|
||||
}
|
||||
|
||||
fn encode(&self, req: &Message, mut resp: Message) -> Reply {
|
||||
if let TsigStatus::Valid { key, mac } = &self.tsig {
|
||||
let mut signer = ResponseSigner::new(key.clone(), mac.clone());
|
||||
return match signer.sign(&mut resp) {
|
||||
Ok(b) if !self.transport.stream() && b.len() > wire::client_udp_limit(req, self.rt.cfg.server.max_udp_payload) => {
|
||||
let mut t = resp.clone();
|
||||
t.answers.clear();
|
||||
t.authorities.clear();
|
||||
t.additionals.clear();
|
||||
t.metadata.truncation = true;
|
||||
signer = ResponseSigner::new(key.clone(), mac.clone());
|
||||
signer.sign(&mut t).map(Reply::One).unwrap_or(Reply::None)
|
||||
}
|
||||
Ok(b) => Reply::One(b),
|
||||
Err(e) => {
|
||||
tracing::error!(error = %e, "failed to sign response");
|
||||
Reply::None
|
||||
}
|
||||
};
|
||||
}
|
||||
let bytes = if self.transport.stream() {
|
||||
wire::encode_tcp(&resp)
|
||||
} else {
|
||||
wire::encode_udp(&resp, wire::client_udp_limit(req, self.rt.cfg.server.max_udp_payload))
|
||||
};
|
||||
bytes.map(Reply::One).unwrap_or(Reply::None)
|
||||
}
|
||||
|
||||
fn finish(&self, req: &Message, resp: Message, source: Source, note: Option<&str>) -> Reply {
|
||||
let rcode = resp.metadata.response_code;
|
||||
let rcs = match rcode {
|
||||
ResponseCode::NoError => "NOERROR",
|
||||
ResponseCode::FormErr => "FORMERR",
|
||||
ResponseCode::ServFail => "SERVFAIL",
|
||||
ResponseCode::NXDomain => "NXDOMAIN",
|
||||
ResponseCode::NotImp => "NOTIMP",
|
||||
ResponseCode::Refused => "REFUSED",
|
||||
_ => "OTHER",
|
||||
};
|
||||
self.shared.metrics.response(rcs, source.as_str(), self.start.elapsed());
|
||||
if matches!(self.tsig, TsigStatus::Unsigned)
|
||||
&& matches!(rcode, ResponseCode::NoError | ResponseCode::NXDomain)
|
||||
&& matches!(
|
||||
source,
|
||||
Source::Authoritative | Source::Cache | Source::Recursive | Source::Forward | Source::Blocked | Source::Local
|
||||
)
|
||||
{
|
||||
let _ = self.slot.info.set((source, rcs));
|
||||
}
|
||||
if self.rt.cfg.logging.query_log {
|
||||
let client = if self.rt.cfg.logging.anonymize_clients { anonymize(self.client.ip()) } else { self.client.ip().to_string() };
|
||||
let (qn, qt) = req.queries.first().map(|q| (q.name.to_string(), q.query_type.to_string())).unwrap_or_default();
|
||||
tracing::info!(target: "query", client, qname = %qn, qtype = %qt, rcode = rcs, source = source.as_str(),
|
||||
transport = self.transport.as_str(), latency_us = self.start.elapsed().as_micros() as u64, note = note.unwrap_or(""), "query");
|
||||
}
|
||||
self.encode(req, resp)
|
||||
}
|
||||
}
|
||||
|
||||
/// Outcome of the UDP fast path in the listener.
|
||||
pub enum FastPath {
|
||||
/// Answered from the packet cache: send these bytes.
|
||||
Hit(Vec<u8>),
|
||||
/// Not answered; pass the rate-limit decision (if one was taken) to [`handle_with`].
|
||||
Miss(Option<RateDecision>),
|
||||
}
|
||||
|
||||
fn cache_hit(shared: &Shared, raw: &[u8], profile: u64, transport: Transport, start: Instant) -> Option<Vec<u8>> {
|
||||
let hit = shared.packet_cache.lookup(raw, profile)?;
|
||||
let qtype: &'static str = RecordType::from(hit.qtype).into();
|
||||
shared.metrics.query(transport.as_str(), qtype);
|
||||
shared.metrics.response(hit.rcode, hit.source, start.elapsed());
|
||||
Some(hit.bytes)
|
||||
}
|
||||
|
||||
/// UDP fast path, run inline in the receive loop: rate limit + packet cache, no task,
|
||||
/// no parsing. Anything else goes to [`handle_with`].
|
||||
pub fn udp_fast_path(shared: &Shared, raw: &[u8], client: SocketAddr) -> FastPath {
|
||||
let rt = shared.rt();
|
||||
if !shared.packet_cache.enabled() || rt.cfg.logging.query_log {
|
||||
return FastPath::Miss(None);
|
||||
}
|
||||
let decision = rt.ratelimit.check(client.ip());
|
||||
if decision == RateDecision::Allow {
|
||||
let profile = rt.client_profile(client.ip(), false);
|
||||
if let Some(b) = cache_hit(shared, raw, profile, Transport::Udp, Instant::now()) {
|
||||
return FastPath::Hit(b);
|
||||
}
|
||||
}
|
||||
FastPath::Miss(Some(decision))
|
||||
}
|
||||
|
||||
/// Handle one raw request.
|
||||
pub async fn handle(shared: &Shared, raw: &[u8], client: SocketAddr, transport: Transport) -> Reply {
|
||||
handle_with(shared, raw, client, transport, None).await
|
||||
}
|
||||
|
||||
/// Handle one raw request. `rl` is a rate-limit decision already taken by the caller,
|
||||
/// who then also already missed the packet cache ([`udp_fast_path`]).
|
||||
pub async fn handle_with(shared: &Shared, raw: &[u8], client: SocketAddr, transport: Transport, rl: Option<RateDecision>) -> Reply {
|
||||
let rt = shared.rt();
|
||||
let start = Instant::now();
|
||||
let pc = &shared.packet_cache;
|
||||
let use_pc = pc.enabled() && !rt.cfg.logging.query_log;
|
||||
let mut rl = rl;
|
||||
let mut profile = 0;
|
||||
if use_pc {
|
||||
profile = rt.client_profile(client.ip(), transport != Transport::Udp);
|
||||
if rl.is_none() {
|
||||
let decision = if transport == Transport::Udp { rt.ratelimit.check(client.ip()) } else { RateDecision::Allow };
|
||||
if decision == RateDecision::Allow {
|
||||
if let Some(b) = cache_hit(shared, raw, profile, transport, start) {
|
||||
return Reply::One(b);
|
||||
}
|
||||
}
|
||||
rl = Some(decision);
|
||||
}
|
||||
}
|
||||
// read before computing: a zone change during the computation makes the entry stale
|
||||
let generation = pc.current_generation();
|
||||
let slot = CacheSlot::default();
|
||||
let reply = handle_inner(shared, Arc::clone(&rt), raw, client, transport, rl, &slot, start).await;
|
||||
if use_pc && let (Reply::One(bytes), Some((source, rcode))) = (&reply, slot.info.get()) {
|
||||
let kind = match source {
|
||||
Source::Authoritative | Source::Local if !slot.resolved.load(std::sync::atomic::Ordering::Relaxed) => {
|
||||
crate::packet_cache::Kind::Authoritative
|
||||
}
|
||||
_ => crate::packet_cache::Kind::Resolved,
|
||||
};
|
||||
// resolved data only when caching is enabled at all
|
||||
if kind == crate::packet_cache::Kind::Authoritative || rt.cfg.cache.enabled {
|
||||
pc.store(raw, profile, bytes, crate::packet_cache::StoreMeta { kind, generation, rcode, source: source.as_str() });
|
||||
}
|
||||
}
|
||||
reply
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn handle_inner(
|
||||
shared: &Shared,
|
||||
rt: Arc<Runtime>,
|
||||
raw: &[u8],
|
||||
client: SocketAddr,
|
||||
transport: Transport,
|
||||
rl: Option<RateDecision>,
|
||||
slot: &CacheSlot,
|
||||
start: Instant,
|
||||
) -> Reply {
|
||||
let req = match Message::from_vec(raw) {
|
||||
Ok(m) => m,
|
||||
Err(_) => {
|
||||
shared.metrics.malformed.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
return wire::formerr_from_raw(raw).map(Reply::One).unwrap_or(Reply::None);
|
||||
}
|
||||
};
|
||||
if req.metadata.message_type == dns_core::proto::op::MessageType::Response {
|
||||
return Reply::None;
|
||||
}
|
||||
if transport == Transport::Udp {
|
||||
match rl.unwrap_or_else(|| rt.ratelimit.check(client.ip())) {
|
||||
RateDecision::Allow => {}
|
||||
RateDecision::Slip => {
|
||||
shared.metrics.rate_limited.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let mut r = wire::response_for(&req);
|
||||
r.metadata.truncation = true;
|
||||
return r.to_vec().map(Reply::One).unwrap_or(Reply::None);
|
||||
}
|
||||
RateDecision::Drop => {
|
||||
shared.metrics.rate_limited.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
return Reply::None;
|
||||
}
|
||||
}
|
||||
}
|
||||
let tsig = verify_request(raw, &req, &rt.ring);
|
||||
let ctx = Ctx { shared, rt: Arc::clone(&rt), client, transport, tsig, start, slot };
|
||||
// static name: no allocation per query
|
||||
let qtype_s: &'static str = req.queries.first().map_or("OTHER", |q| q.query_type.into());
|
||||
shared.metrics.query(transport.as_str(), qtype_s);
|
||||
|
||||
let mut resp = wire::response_for(&req);
|
||||
if let TsigStatus::Invalid(e) = &ctx.tsig {
|
||||
shared.metrics.tsig_failures.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
tracing::warn!(client = %client, error = %e, "TSIG verification failed");
|
||||
resp.metadata.response_code = ResponseCode::NotAuth;
|
||||
return ctx.finish(&req, resp, Source::Refused, Some(e));
|
||||
}
|
||||
if req.edns.as_ref().is_some_and(|e| e.version() > 0) {
|
||||
resp.metadata.response_code = ResponseCode::BADVERS;
|
||||
return ctx.finish(&req, resp, Source::Local, None);
|
||||
}
|
||||
if req.queries.len() != 1 {
|
||||
resp.metadata.response_code = ResponseCode::FormErr;
|
||||
return ctx.finish(&req, resp, Source::Local, None);
|
||||
}
|
||||
match req.metadata.op_code {
|
||||
OpCode::Query => handle_query(&ctx, &req, resp).await,
|
||||
OpCode::Notify => handle_notify(&ctx, &req, resp),
|
||||
OpCode::Update => handle_update(&ctx, &req, resp),
|
||||
_ => {
|
||||
resp.metadata.response_code = ResponseCode::NotImp;
|
||||
ctx.finish(&req, resp, Source::Local, None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn chaos(ctx: &Ctx<'_>, req: &Message, mut resp: Message) -> Reply {
|
||||
let q = &req.queries[0];
|
||||
let name = q.name.to_lowercase().to_string();
|
||||
let txt = match (&ctx.rt.cfg.server.identity, name.as_str(), q.query_type) {
|
||||
(Some(id), "id.server." | "hostname.bind.", RecordType::TXT) => Some(id.clone()),
|
||||
(Some(_), "version.bind." | "version.server.", RecordType::TXT) => Some(format!("EasyDNS {}", ctx.shared.version)),
|
||||
_ => None,
|
||||
};
|
||||
match txt {
|
||||
Some(t) => {
|
||||
let mut r = Record::from_rdata(q.name.clone(), 0, RData::TXT(TXT::new(vec![t])));
|
||||
r.dns_class = DNSClass::CH;
|
||||
resp.metadata.authoritative = true;
|
||||
resp.add_answer(r);
|
||||
}
|
||||
None => resp.metadata.response_code = ResponseCode::Refused,
|
||||
}
|
||||
ctx.finish(req, resp, Source::Local, None)
|
||||
}
|
||||
|
||||
async fn handle_query(ctx: &Ctx<'_>, req: &Message, mut resp: Message) -> Reply {
|
||||
let q = req.queries[0].clone();
|
||||
if q.query_class == DNSClass::CH {
|
||||
return chaos(ctx, req, resp);
|
||||
}
|
||||
if q.query_class != DNSClass::IN && q.query_class != DNSClass::ANY {
|
||||
resp.metadata.response_code = ResponseCode::Refused;
|
||||
return ctx.finish(req, resp, Source::Refused, None);
|
||||
}
|
||||
if matches!(q.query_type, RecordType::AXFR | RecordType::IXFR) {
|
||||
return handle_xfr(ctx, req, resp);
|
||||
}
|
||||
if matches!(q.query_type, RecordType::OPT | RecordType::TSIG) {
|
||||
resp.metadata.response_code = ResponseCode::FormErr;
|
||||
return ctx.finish(req, resp, Source::Local, None);
|
||||
}
|
||||
let ip = ctx.ip();
|
||||
let rt = &ctx.rt;
|
||||
let dnssec_ok = req.edns.as_ref().is_some_and(|e| e.flags().dnssec_ok);
|
||||
let may_resolve = rt.router.can_resolve() && rt.recursion_acl.contains(ip);
|
||||
resp.metadata.recursion_available = may_resolve;
|
||||
let view = rt.views.classify(ip);
|
||||
let qname = q.name.clone();
|
||||
|
||||
// 1. Local authoritative data.
|
||||
if let Some(entry) = rt.zones.find(&LowerName::new(&qname), view) {
|
||||
let Some(zone) = entry.current() else {
|
||||
resp.metadata.response_code = ResponseCode::ServFail;
|
||||
return ctx.finish(req, resp, Source::Authoritative, Some("zone not loaded or expired"));
|
||||
};
|
||||
match zone.lookup(&qname, q.query_type, dnssec_ok) {
|
||||
Lookup::Answer { answers, additional, authority, .. } => {
|
||||
resp.metadata.authoritative = true;
|
||||
resp.answers = answers;
|
||||
resp.authorities = authority;
|
||||
resp.additionals = additional;
|
||||
}
|
||||
Lookup::NoData { soa, proof } => {
|
||||
resp.metadata.authoritative = true;
|
||||
resp.authorities.push(soa);
|
||||
resp.authorities.extend(proof);
|
||||
}
|
||||
Lookup::NxDomain { soa, answers, proof } => {
|
||||
resp.metadata.authoritative = true;
|
||||
resp.metadata.response_code = ResponseCode::NXDomain;
|
||||
resp.answers = answers;
|
||||
resp.authorities.push(soa);
|
||||
resp.authorities.extend(proof);
|
||||
}
|
||||
Lookup::Referral { ns, glue, ds } => {
|
||||
if may_resolve && req.metadata.recursion_desired {
|
||||
let a = rt.router.resolve(&qname, q.query_type, ip, dnssec_ok, req.metadata.checking_disabled).await;
|
||||
return finish_answer(ctx, req, resp, a);
|
||||
}
|
||||
resp.authorities = ns;
|
||||
resp.authorities.extend(ds);
|
||||
resp.additionals = glue;
|
||||
}
|
||||
Lookup::CnameOut { answers, target } => {
|
||||
resp.metadata.authoritative = true;
|
||||
resp.answers = answers;
|
||||
if may_resolve && req.metadata.recursion_desired {
|
||||
ctx.slot.resolved.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
let a = resolve_target(ctx, &target, q.query_type, ip, dnssec_ok, req.metadata.checking_disabled, view).await;
|
||||
let negative = a.answers_empty_negative();
|
||||
resp.answers.extend(a.answers);
|
||||
resp.metadata.response_code = a.rcode;
|
||||
if negative {
|
||||
resp.authorities = a.authority;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return ctx.finish(req, resp, Source::Authoritative, None);
|
||||
}
|
||||
|
||||
// 2. Resolution is only for permitted clients.
|
||||
if !may_resolve || !req.metadata.recursion_desired {
|
||||
resp.metadata.response_code = ResponseCode::Refused;
|
||||
return ctx.finish(req, resp, Source::Refused, None);
|
||||
}
|
||||
// 3. Local-only names never leave the host.
|
||||
if rt.local_only.matches(&qname) {
|
||||
resp.metadata.response_code = ResponseCode::NXDomain;
|
||||
return ctx.finish(req, resp, Source::Local, Some("local-only name"));
|
||||
}
|
||||
// 4. Policy.
|
||||
if let Some(m) = rt.policy.check(&qname, ip) {
|
||||
ctx.shared.metrics.blocked.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
if rt.policy.log {
|
||||
tracing::info!(target: "policy", qname = %qname, list = %m.list, rule = %m.rule, category = m.category.as_deref().unwrap_or(""), "blocked");
|
||||
}
|
||||
apply_block(rt, &q.name, q.query_type, &mut resp);
|
||||
let note = format!("blocked by {} ({})", m.list, m.rule);
|
||||
return ctx.finish(req, resp, Source::Blocked, Some(¬e));
|
||||
}
|
||||
// 5. Forwarding / recursion.
|
||||
let a = rt.router.resolve(&qname, q.query_type, ip, dnssec_ok, req.metadata.checking_disabled).await;
|
||||
finish_answer(ctx, req, resp, a)
|
||||
}
|
||||
|
||||
trait NegExt {
|
||||
fn answers_empty_negative(&self) -> bool;
|
||||
}
|
||||
impl NegExt for Answer {
|
||||
fn answers_empty_negative(&self) -> bool {
|
||||
self.answers.is_empty() && matches!(self.rcode, ResponseCode::NXDomain | ResponseCode::NoError)
|
||||
}
|
||||
}
|
||||
|
||||
/// Continue a CNAME chain that left a local zone: other local zones first, then resolution.
|
||||
async fn resolve_target(
|
||||
ctx: &Ctx<'_>,
|
||||
target: &Name,
|
||||
qtype: RecordType,
|
||||
ip: IpAddr,
|
||||
dnssec_ok: bool,
|
||||
cd: bool,
|
||||
view: Option<&str>,
|
||||
) -> Answer {
|
||||
let mut out = Answer::new(ResponseCode::NoError, Source::Authoritative);
|
||||
let mut cur = target.clone();
|
||||
for _ in 0..MAX_CROSS_CNAME {
|
||||
if let Some(entry) = ctx.rt.zones.find(&LowerName::new(&cur), view) {
|
||||
let Some(zone) = entry.current() else { return Answer::servfail(Source::Authoritative, "zone unavailable") };
|
||||
match zone.lookup(&cur, qtype, dnssec_ok) {
|
||||
Lookup::Answer { answers, .. } => {
|
||||
out.answers.extend(answers);
|
||||
return out;
|
||||
}
|
||||
Lookup::CnameOut { answers, target } => {
|
||||
out.answers.extend(answers);
|
||||
cur = target;
|
||||
continue;
|
||||
}
|
||||
Lookup::NoData { soa, .. } => {
|
||||
out.authority.push(soa);
|
||||
return out;
|
||||
}
|
||||
Lookup::NxDomain { soa, answers, .. } => {
|
||||
out.answers.extend(answers);
|
||||
out.authority.push(soa);
|
||||
out.rcode = ResponseCode::NXDomain;
|
||||
return out;
|
||||
}
|
||||
Lookup::Referral { .. } => break,
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ctx.rt.local_only.matches(&cur) || ctx.rt.policy.check(&cur, ip).is_some() {
|
||||
out.rcode = ResponseCode::NXDomain;
|
||||
return out;
|
||||
}
|
||||
let mut a = ctx.rt.router.resolve(&cur, qtype, ip, dnssec_ok, cd).await;
|
||||
out.answers.append(&mut a.answers);
|
||||
out.authority = a.authority;
|
||||
out.rcode = a.rcode;
|
||||
out
|
||||
}
|
||||
|
||||
fn apply_block(rt: &Runtime, name: &Name, qtype: RecordType, resp: &mut Message) {
|
||||
let ttl = rt.policy.ttl;
|
||||
match rt.policy.action {
|
||||
BlockAction::Nxdomain => resp.metadata.response_code = ResponseCode::NXDomain,
|
||||
BlockAction::Refused => resp.metadata.response_code = ResponseCode::Refused,
|
||||
BlockAction::Null | BlockAction::Address => {
|
||||
let (v4, v6) = if rt.policy.action == BlockAction::Null {
|
||||
(std::net::Ipv4Addr::UNSPECIFIED, std::net::Ipv6Addr::UNSPECIFIED)
|
||||
} else {
|
||||
(rt.policy.v4.unwrap_or(std::net::Ipv4Addr::UNSPECIFIED), rt.policy.v6.unwrap_or(std::net::Ipv6Addr::UNSPECIFIED))
|
||||
};
|
||||
match qtype {
|
||||
RecordType::A => resp.add_answer(Record::from_rdata(name.clone(), ttl, RData::A(A::from(v4)))),
|
||||
RecordType::AAAA => resp.add_answer(Record::from_rdata(name.clone(), ttl, RData::AAAA(AAAA::from(v6)))),
|
||||
_ => resp, // NODATA
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn finish_answer(ctx: &Ctx<'_>, req: &Message, mut resp: Message, mut a: Answer) -> Reply {
|
||||
if a.security == dns_core::answer::Security::Bogus && !req.metadata.checking_disabled {
|
||||
// RFC 4035 §5.5: bogus data is not returned unless the client disabled checking.
|
||||
ctx.shared.metrics.dnssec_bogus.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
resp.metadata.response_code = ResponseCode::ServFail;
|
||||
resp.metadata.authoritative = false;
|
||||
let note = a.note.take().unwrap_or_else(|| "DNSSEC validation failed".into());
|
||||
return ctx.finish(req, resp, a.source, Some(¬e));
|
||||
}
|
||||
resp.metadata.response_code = a.rcode;
|
||||
resp.metadata.authoritative = false; // never AA for resolved data
|
||||
resp.answers = a.answers;
|
||||
resp.authorities = a.authority;
|
||||
resp.additionals = a.additional;
|
||||
let dnssec_ok = req.edns.as_ref().is_some_and(|e| e.flags().dnssec_ok);
|
||||
if !dnssec_ok {
|
||||
let strip =
|
||||
|v: &mut Vec<Record>| v.retain(|r| !matches!(r.record_type(), RecordType::RRSIG | RecordType::NSEC | RecordType::NSEC3));
|
||||
strip(&mut resp.answers);
|
||||
strip(&mut resp.authorities);
|
||||
}
|
||||
resp.metadata.authentic_data = a.security == dns_core::answer::Security::Secure && (dnssec_ok || req.metadata.authentic_data);
|
||||
match a.security {
|
||||
dns_core::answer::Security::Secure => ctx.shared.metrics.dnssec_secure.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
|
||||
dns_core::answer::Security::Insecure => ctx.shared.metrics.dnssec_insecure.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
|
||||
dns_core::answer::Security::Bogus => ctx.shared.metrics.dnssec_bogus.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
|
||||
dns_core::answer::Security::Indeterminate => 0,
|
||||
};
|
||||
if a.source == Source::Forward || a.source == Source::Recursive {
|
||||
if a.rcode == ResponseCode::ServFail {
|
||||
ctx.shared.metrics.upstream_errors.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
} else {
|
||||
ctx.shared.metrics.upstream_latency.observe(ctx.start.elapsed());
|
||||
}
|
||||
}
|
||||
let note = a.note.clone();
|
||||
ctx.finish(req, resp, a.source, note.as_deref())
|
||||
}
|
||||
|
||||
fn xfr_refuse(ctx: &Ctx<'_>, req: &Message, mut resp: Message, rcode: ResponseCode, why: &str) -> Reply {
|
||||
ctx.shared.metrics.xfr_out_refused.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
tracing::warn!(client = %ctx.client, zone = %req.queries[0].name, reason = why, "zone transfer refused");
|
||||
resp.metadata.response_code = rcode;
|
||||
ctx.finish(req, resp, Source::Refused, Some(why))
|
||||
}
|
||||
|
||||
fn handle_xfr(ctx: &Ctx<'_>, req: &Message, mut resp: Message) -> Reply {
|
||||
let q = &req.queries[0];
|
||||
let rt = &ctx.rt;
|
||||
let Some(entry) = rt.zones.get(&q.name) else {
|
||||
return xfr_refuse(ctx, req, resp, ResponseCode::NotAuth, "not authoritative for zone");
|
||||
};
|
||||
// Authorisation: ACL, plus TSIG with the configured key when one is set.
|
||||
let ip = ctx.ip();
|
||||
let acl_ok = entry.transfer_allowed_from(ip);
|
||||
let allowed = match (&entry.transfer_key, &ctx.tsig) {
|
||||
(Some(k), TsigStatus::Valid { key, .. }) => key.name == k.name && (entry.transfer_acl.is_empty() || acl_ok),
|
||||
(Some(_), _) => false,
|
||||
(None, _) => acl_ok,
|
||||
};
|
||||
if !allowed {
|
||||
return xfr_refuse(ctx, req, resp, ResponseCode::Refused, "client not authorised for transfer");
|
||||
}
|
||||
let Some(zone) = entry.current() else {
|
||||
return xfr_refuse(ctx, req, resp, ResponseCode::ServFail, "zone not loaded");
|
||||
};
|
||||
let start = Instant::now();
|
||||
let (records, kind) = if q.query_type == RecordType::AXFR {
|
||||
if ctx.transport == Transport::Udp {
|
||||
return xfr_refuse(ctx, req, resp, ResponseCode::Refused, "AXFR over UDP");
|
||||
}
|
||||
(dns_authoritative::xfr::axfr_records(&zone), "AXFR")
|
||||
} else {
|
||||
let client_serial = req.authorities.iter().find_map(|r| match &r.data {
|
||||
RData::SOA(s) => Some(s.serial),
|
||||
_ => None,
|
||||
});
|
||||
let Some(cs) = client_serial else {
|
||||
resp.metadata.response_code = ResponseCode::FormErr;
|
||||
return ctx.finish(req, resp, Source::Authoritative, Some("IXFR without SOA"));
|
||||
};
|
||||
let journal = entry.journal.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (recs, incremental) = dns_authoritative::xfr::ixfr_records(&zone, &journal, cs);
|
||||
drop(journal);
|
||||
if ctx.transport == Transport::Udp && recs.len() > 1 {
|
||||
// Too big for UDP: tell the client to retry over TCP (RFC 1995 §2).
|
||||
resp.metadata.authoritative = true;
|
||||
resp.answers.push(zone.soa().clone());
|
||||
return ctx.finish(req, resp, Source::Authoritative, Some("IXFR via TCP"));
|
||||
}
|
||||
(recs, if incremental { "IXFR" } else { "IXFR(AXFR-style)" })
|
||||
};
|
||||
let count = records.len();
|
||||
let messages = dns_authoritative::xfr::chunk(req, records);
|
||||
let mut out = Vec::with_capacity(messages.len());
|
||||
let mut signer = match &ctx.tsig {
|
||||
TsigStatus::Valid { key, mac } => Some(ResponseSigner::new(key.clone(), mac.clone())),
|
||||
_ => None,
|
||||
};
|
||||
for mut m in messages {
|
||||
let b = match signer.as_mut() {
|
||||
Some(s) => s.sign(&mut m).ok(),
|
||||
None => m.to_vec().ok(),
|
||||
};
|
||||
match b {
|
||||
Some(b) => out.push(b),
|
||||
None => return xfr_refuse(ctx, req, wire::response_for(req), ResponseCode::ServFail, "encoding failed"),
|
||||
}
|
||||
}
|
||||
ctx.shared.metrics.xfr_out_ok.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
ctx.shared.metrics.response("NOERROR", "authoritative", start.elapsed());
|
||||
tracing::info!(zone = %entry.name, client = %ctx.client, kind, records = count, serial = zone.serial(), "zone transfer served");
|
||||
entry.record_transfer(TransferEvent {
|
||||
time_unix: dns_core::tsig::now(),
|
||||
direction: "out",
|
||||
kind: kind.into(),
|
||||
peer: ctx.client.to_string(),
|
||||
serial: Some(zone.serial()),
|
||||
records: count,
|
||||
ok: true,
|
||||
error: None,
|
||||
duration_ms: start.elapsed().as_millis() as u64,
|
||||
});
|
||||
Reply::Many(out)
|
||||
}
|
||||
|
||||
fn handle_notify(ctx: &Ctx<'_>, req: &Message, mut resp: Message) -> Reply {
|
||||
let q = &req.queries[0];
|
||||
resp.metadata.authoritative = true;
|
||||
let entry = ctx.rt.zones.get(&q.name).filter(|e| e.kind == ZoneKind::Secondary);
|
||||
let Some(entry) = entry else {
|
||||
ctx.shared.metrics.notify_refused.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
resp.metadata.response_code = ResponseCode::NotAuth;
|
||||
return ctx.finish(req, resp, Source::Refused, Some("NOTIFY for unknown zone"));
|
||||
};
|
||||
let ip = ctx.ip();
|
||||
let key_required = entry.client_key.is_some();
|
||||
let key_ok = match (&entry.client_key, &ctx.tsig) {
|
||||
(Some(k), TsigStatus::Valid { key, .. }) => key.name == k.name,
|
||||
(Some(_), _) => false,
|
||||
(None, _) => true,
|
||||
};
|
||||
// Accept from allowed sources; with a TSIG key configured a correctly signed NOTIFY is also accepted.
|
||||
if !(entry.notify_allowed_from(ip) && (key_ok || !key_required) || key_required && key_ok) {
|
||||
ctx.shared.metrics.notify_refused.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
tracing::warn!(zone = %entry.name, client = %ctx.client, "NOTIFY refused");
|
||||
resp.metadata.response_code = ResponseCode::Refused;
|
||||
return ctx.finish(req, resp, Source::Refused, Some("NOTIFY not allowed"));
|
||||
}
|
||||
ctx.shared.metrics.notify_received.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
tracing::info!(zone = %entry.name, client = %ctx.client, "NOTIFY received; scheduling refresh");
|
||||
entry.refresh_trigger.notify_one();
|
||||
ctx.finish(req, resp, Source::Authoritative, None)
|
||||
}
|
||||
|
||||
fn handle_update(ctx: &Ctx<'_>, req: &Message, mut resp: Message) -> Reply {
|
||||
let q = &req.queries[0];
|
||||
resp.answers.clear();
|
||||
let Some(entry) = ctx.rt.zones.get(&q.name) else {
|
||||
resp.metadata.response_code = ResponseCode::NotAuth;
|
||||
ctx.shared.metrics.updates_refused.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
return ctx.finish(req, resp, Source::Refused, Some("UPDATE for unknown zone"));
|
||||
};
|
||||
let actor = match &ctx.tsig {
|
||||
TsigStatus::Valid { key, .. } => format!("tsig:{} from {}", key.name, ctx.client.ip()),
|
||||
_ => format!("unsigned from {}", ctx.client.ip()),
|
||||
};
|
||||
let signer = match &ctx.tsig {
|
||||
TsigStatus::Valid { key, .. } => Some(&key.name),
|
||||
_ => None,
|
||||
};
|
||||
let who = dns_authoritative::update::Requester { signer, addr_ok: entry.update_allowed_from(ctx.ip()) };
|
||||
let outcome = dns_authoritative::update::apply(&entry, req, who);
|
||||
resp.metadata.response_code = outcome.rcode;
|
||||
let ok = outcome.rcode == ResponseCode::NoError;
|
||||
ctx.shared.audit.record(
|
||||
&actor,
|
||||
"dns-update",
|
||||
&entry.name.to_string(),
|
||||
if ok { "ok" } else { "refused" },
|
||||
&format!("{} (+{} -{} serial {:?})", outcome.reason, outcome.added, outcome.removed, outcome.new_serial),
|
||||
);
|
||||
if ok {
|
||||
ctx.shared.metrics.updates_ok.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
if outcome.added + outcome.removed > 0 {
|
||||
entry.send_notifies();
|
||||
}
|
||||
} else {
|
||||
ctx.shared.metrics.updates_refused.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
ctx.finish(req, resp, Source::Authoritative, Some(&outcome.reason))
|
||||
}
|
||||
Reference in new issue
Block a user