v0.1.0
This commit is contained in:
commit
fa432bebda
189 files changed
+26219
No files matched your search
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
name = "dns-recursive"
|
||||
description = "EasyDNS iterative recursive resolver (root hints → TLD → authoritative)"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
dns-core.workspace = true
|
||||
dns-config.workspace = true
|
||||
dns-cache.workspace = true
|
||||
tokio.workspace = true
|
||||
tracing.workspace = true
|
||||
serde.workspace = true
|
||||
rand.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
dns-authoritative.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,58 @@
|
||||
//! Root hints: built-in copy and file loading.
|
||||
use std::net::IpAddr;
|
||||
use std::path::Path;
|
||||
|
||||
use dns_core::proto::rr::{Name, RData, Record};
|
||||
|
||||
/// Built-in root hints (same content as `config/root.hints`).
|
||||
pub const BUILTIN: &str = include_str!("../../../config/root.hints");
|
||||
|
||||
/// Parse root hints text.
|
||||
pub fn parse(text: &str) -> Result<Vec<Record>, String> {
|
||||
dns_core::zonefile::parse_str(text, &Name::root(), None).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Load root hints from a file, or the built-in copy.
|
||||
pub fn load(path: Option<&Path>) -> Result<Vec<Record>, String> {
|
||||
match path {
|
||||
Some(p) => {
|
||||
let text = std::fs::read_to_string(p).map_err(|e| format!("{}: {e}", p.display()))?;
|
||||
parse(&text)
|
||||
}
|
||||
None => parse(BUILTIN),
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract (NS name, addresses) for the root zone.
|
||||
pub fn root_servers(hints: &[Record]) -> Result<Vec<(Name, Vec<IpAddr>)>, String> {
|
||||
let mut out: Vec<(Name, Vec<IpAddr>)> = Vec::new();
|
||||
for r in hints {
|
||||
if let RData::NS(ns) = &r.data {
|
||||
if r.name.is_root() {
|
||||
out.push((ns.0.clone(), Vec::new()));
|
||||
}
|
||||
}
|
||||
}
|
||||
for r in hints {
|
||||
if let Some(ip) = r.data.ip_addr() {
|
||||
if let Some(e) = out.iter_mut().find(|(n, _)| n.eq_ignore_root_case(&r.name)) {
|
||||
e.1.push(ip);
|
||||
}
|
||||
}
|
||||
}
|
||||
out.retain(|(_, a)| !a.is_empty());
|
||||
if out.is_empty() {
|
||||
return Err("root hints contain no usable root server addresses".into());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn builtin_hints() {
|
||||
let r = super::root_servers(&super::load(None).unwrap()).unwrap();
|
||||
assert_eq!(r.len(), 13);
|
||||
assert!(r.iter().all(|(_, a)| a.len() == 2));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,810 @@
|
||||
//! Iterative recursive resolver.
|
||||
//!
|
||||
//! Starts at the closest cached delegation (or the root hints) and follows
|
||||
//! referrals down to the authoritative servers, without any upstream resolver.
|
||||
//!
|
||||
//! Protections:
|
||||
//! * bailiwick checks: only data within the zone of the queried server is accepted;
|
||||
//! glue is only accepted for names inside the delegating zone,
|
||||
//! * random query IDs and source ports, question matching, mixed-case independent matching,
|
||||
//! * QNAME minimisation (RFC 9156) with automatic fallback,
|
||||
//! * per-resolution budgets: total upstream queries, referral depth, CNAME chain,
|
||||
//! sub-resolution depth (NS address lookups) and wall-clock deadline,
|
||||
//! * per-server RTT tracking and back-off of unresponsive / lame servers,
|
||||
//! * caching of final answers (positive and RFC 2308 negative) and of delegations.
|
||||
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
|
||||
|
||||
pub mod hints;
|
||||
pub mod validator;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::future::Future;
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use std::pin::Pin;
|
||||
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use dns_cache::{Cache, Key, Rank};
|
||||
use dns_core::answer::{Answer, Source};
|
||||
use dns_core::client::{QueryOptions, query};
|
||||
use dns_core::proto::op::{Message, ResponseCode};
|
||||
use dns_core::proto::rr::{LowerName, Name, RData, Record, RecordType};
|
||||
use serde::Serialize;
|
||||
|
||||
/// Resolver settings (derived from `recursion:` config).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Settings {
|
||||
pub max_depth: u32,
|
||||
pub max_queries: u32,
|
||||
pub max_cname: u32,
|
||||
pub query_timeout: Duration,
|
||||
pub total_timeout: Duration,
|
||||
pub port: u16,
|
||||
pub qname_minimization: bool,
|
||||
pub ipv6: bool,
|
||||
/// Maximum nesting of NS-address sub-resolutions.
|
||||
pub max_subqueries_depth: u32,
|
||||
/// Request DNSSEC records (DO bit) and validate answers.
|
||||
pub dnssec: bool,
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
pub fn from_config(c: &dns_config::RecursionConfig) -> Self {
|
||||
Self {
|
||||
max_depth: c.max_depth,
|
||||
max_queries: c.max_queries,
|
||||
max_cname: c.max_cname_chain,
|
||||
query_timeout: c.query_timeout,
|
||||
total_timeout: c.total_timeout,
|
||||
port: c.authority_port,
|
||||
qname_minimization: c.qname_minimization,
|
||||
ipv6: c.use_ipv6_transport,
|
||||
max_subqueries_depth: 4,
|
||||
dnssec: c.dnssec_validation,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One step of an iterative resolution (used by `etrace` and debug logging).
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct TraceStep {
|
||||
pub zone: String,
|
||||
pub server: String,
|
||||
pub server_name: Option<String>,
|
||||
pub qname: String,
|
||||
pub qtype: String,
|
||||
pub rcode: String,
|
||||
pub outcome: String,
|
||||
pub elapsed_ms: f64,
|
||||
pub depth: u32,
|
||||
}
|
||||
|
||||
struct Ctx {
|
||||
queries_left: AtomicU32,
|
||||
deadline: Instant,
|
||||
trace: Option<Mutex<Vec<TraceStep>>>,
|
||||
}
|
||||
|
||||
impl Ctx {
|
||||
fn take_query(&self) -> bool {
|
||||
self.queries_left.fetch_update(Ordering::AcqRel, Ordering::Acquire, |v| v.checked_sub(1)).is_ok()
|
||||
}
|
||||
fn expired(&self) -> bool {
|
||||
Instant::now() >= self.deadline
|
||||
}
|
||||
fn trace(&self, s: TraceStep) {
|
||||
if let Some(t) = &self.trace {
|
||||
t.lock().unwrap_or_else(|e| e.into_inner()).push(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
struct ServerInfo {
|
||||
rtt_ms: Option<f64>,
|
||||
fails: u32,
|
||||
dead_until: Option<Instant>,
|
||||
}
|
||||
|
||||
/// The iterative resolver.
|
||||
pub struct Resolver {
|
||||
settings: Settings,
|
||||
roots: Vec<(Name, Vec<IpAddr>)>,
|
||||
cache: Arc<Cache>,
|
||||
ns: u16,
|
||||
servers: Mutex<HashMap<IpAddr, ServerInfo>>,
|
||||
pub queries_sent: AtomicU64,
|
||||
validator: Option<validator::Validator>,
|
||||
}
|
||||
|
||||
/// What an authoritative server told us about the current question.
|
||||
enum Step {
|
||||
/// Records that answer (owner == qname, type or CNAME).
|
||||
Answer(Message),
|
||||
Referral {
|
||||
zone: Name,
|
||||
ns: Vec<Record>,
|
||||
glue: Vec<Record>,
|
||||
},
|
||||
NxDomain(Message),
|
||||
NoData(Message),
|
||||
/// Try another server.
|
||||
Lame(String),
|
||||
}
|
||||
|
||||
type BoxFut<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
|
||||
|
||||
fn rtype_matches(r: &Record, qtype: RecordType) -> bool {
|
||||
qtype == RecordType::ANY || r.record_type() == qtype || r.record_type() == RecordType::RRSIG
|
||||
}
|
||||
|
||||
fn ns_names(ns: &[Record]) -> Vec<Name> {
|
||||
ns.iter()
|
||||
.filter_map(|r| match &r.data {
|
||||
RData::NS(n) => Some(n.0.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl Resolver {
|
||||
pub fn new(settings: Settings, hints: Vec<Record>, cache: Arc<Cache>, cache_namespace: u16) -> Result<Self, String> {
|
||||
let roots = hints::root_servers(&hints)?;
|
||||
let validator = settings.dnssec.then(validator::Validator::with_root_anchors);
|
||||
Ok(Self {
|
||||
settings,
|
||||
roots,
|
||||
cache,
|
||||
ns: cache_namespace,
|
||||
servers: Mutex::new(HashMap::new()),
|
||||
queries_sent: AtomicU64::new(0),
|
||||
validator,
|
||||
})
|
||||
}
|
||||
|
||||
/// Replace the trust anchors (from a DS/DNSKEY file).
|
||||
pub fn set_trust_anchors(&mut self, records: &[Record]) -> Result<(), String> {
|
||||
self.validator = Some(validator::Validator::from_records(records)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn settings(&self) -> &Settings {
|
||||
&self.settings
|
||||
}
|
||||
|
||||
fn new_ctx(&self, trace: bool) -> Ctx {
|
||||
Ctx {
|
||||
queries_left: AtomicU32::new(self.settings.max_queries),
|
||||
deadline: Instant::now() + self.settings.total_timeout,
|
||||
trace: trace.then(|| Mutex::new(Vec::new())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve `name`/`qtype` iteratively (and validate when DNSSEC is enabled).
|
||||
pub async fn resolve(&self, name: &Name, qtype: RecordType) -> Answer {
|
||||
let ctx = self.new_ctx(false);
|
||||
if self.validator.is_none() {
|
||||
return self.resolve_inner(name.clone(), qtype, 0, &ctx).await;
|
||||
}
|
||||
let key = Key { ns: self.ns, name: LowerName::new(name), rtype: qtype, dnssec: true };
|
||||
if let Some(a) = self.cache.get(&key) {
|
||||
return a;
|
||||
}
|
||||
let mut a = self.resolve_inner(name.clone(), qtype, 0, &ctx).await;
|
||||
if a.rcode == ResponseCode::ServFail {
|
||||
return a;
|
||||
}
|
||||
let vctx = self.validation_ctx();
|
||||
let (sec, note) = self.validate_answer(name, qtype, &a, &vctx).await;
|
||||
a.security = sec;
|
||||
if sec == dns_core::answer::Security::Bogus {
|
||||
tracing::warn!(qname = %name, qtype = %qtype, reason = note.as_deref().unwrap_or(""), "DNSSEC validation failed (bogus)");
|
||||
a.note = note;
|
||||
return a; // not cached (Cache::insert_answer refuses bogus data)
|
||||
}
|
||||
self.cache.insert_answer(key, &a);
|
||||
a
|
||||
}
|
||||
|
||||
/// Whether the cached answer for `name`/`qtype` should be refreshed now (prefetch).
|
||||
pub fn prefetch_due(&self, name: &Name, qtype: RecordType) -> bool {
|
||||
let key = Key { ns: self.ns, name: LowerName::new(name), rtype: qtype, dnssec: self.validator.is_some() };
|
||||
self.cache.prefetch_due(&key)
|
||||
}
|
||||
|
||||
/// Resolve again without reading the top-level cache entry and store the fresh
|
||||
/// answer (prefetch). On failure the existing entry is left as it is.
|
||||
pub async fn refresh(&self, name: &Name, qtype: RecordType) {
|
||||
let ctx = self.new_ctx(false);
|
||||
let a = self.resolve_chain(name.clone(), qtype, 0, &ctx).await;
|
||||
if !matches!(a.rcode, ResponseCode::NoError | ResponseCode::NXDomain) {
|
||||
return;
|
||||
}
|
||||
self.cache.insert_answer(Key { ns: self.ns, name: LowerName::new(name), rtype: qtype, dnssec: false }, &a);
|
||||
if self.validator.is_some() {
|
||||
let mut a = a;
|
||||
let (sec, _) = self.validate_answer(name, qtype, &a, &self.validation_ctx()).await;
|
||||
if sec != dns_core::answer::Security::Bogus {
|
||||
a.security = sec;
|
||||
self.cache.insert_answer(Key { ns: self.ns, name: LowerName::new(name), rtype: qtype, dnssec: true }, &a);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validation_ctx(&self) -> Ctx {
|
||||
Ctx {
|
||||
queries_left: AtomicU32::new(self.settings.max_queries * 3),
|
||||
deadline: Instant::now() + self.settings.total_timeout * 2,
|
||||
trace: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate an answer for `qname`/`qtype` (public entry used by `ednssec`).
|
||||
pub async fn validate(&self, qname: &Name, qtype: RecordType, a: &Answer) -> (dns_core::answer::Security, Option<String>) {
|
||||
let vctx = self.validation_ctx();
|
||||
self.validate_answer(qname, qtype, a, &vctx).await
|
||||
}
|
||||
|
||||
/// Key state of a zone (public for diagnostics).
|
||||
pub async fn zone_key_state(&self, zone: &Name) -> validator::KeyState {
|
||||
let vctx = self.validation_ctx();
|
||||
self.key_state(zone.clone(), &vctx, 0).await
|
||||
}
|
||||
|
||||
fn key_state<'a>(&'a self, zone: Name, ctx: &'a Ctx, depth: u32) -> BoxFut<'a, validator::KeyState> {
|
||||
use validator::KeyState;
|
||||
Box::pin(async move {
|
||||
let Some(v) = &self.validator else { return KeyState::Insecure };
|
||||
if let Some(s) = v.cached(&zone) {
|
||||
return s;
|
||||
}
|
||||
if depth > 64 {
|
||||
return KeyState::Bogus("chain of trust too deep".into());
|
||||
}
|
||||
let st = if v.is_anchor(&zone) {
|
||||
let ans = self.resolve_inner(zone.clone(), RecordType::DNSKEY, 1, ctx).await;
|
||||
if ans.rcode != ResponseCode::NoError {
|
||||
KeyState::Bogus(format!("cannot fetch DNSKEY for anchor {zone}: {}", ans.note.unwrap_or_default()))
|
||||
} else {
|
||||
v.validate_anchor_keys(&zone, &ans.answers)
|
||||
}
|
||||
} else if v.closest_anchor(&zone).is_none() {
|
||||
KeyState::Insecure
|
||||
} else {
|
||||
let ds = self.resolve_inner(zone.clone(), RecordType::DS, 1, ctx).await;
|
||||
if ds.rcode == ResponseCode::ServFail {
|
||||
KeyState::Bogus(format!("cannot fetch DS for {zone}"))
|
||||
} else {
|
||||
let signer = ds
|
||||
.answers
|
||||
.iter()
|
||||
.chain(ds.authority.iter())
|
||||
.filter_map(dns_core::dnssec::rrsig_info)
|
||||
.map(|(s, _, _)| s)
|
||||
.find(|s| s.zone_of(&zone) && !s.eq_ignore_root_case(&zone));
|
||||
let soa_owner = ds.authority.iter().find(|r| r.record_type() == RecordType::SOA).map(|r| r.name.clone());
|
||||
let parent = signer
|
||||
.or(soa_owner.filter(|o| o.zone_of(&zone) && !o.eq_ignore_root_case(&zone)))
|
||||
.unwrap_or_else(|| zone.base_name());
|
||||
match self.key_state(parent.clone(), ctx, depth + 1).await {
|
||||
KeyState::Secure(pk) => {
|
||||
let has_ds = ds.answers.iter().any(|r| r.record_type() == RecordType::DS);
|
||||
let dk = if has_ds { Some(self.resolve_inner(zone.clone(), RecordType::DNSKEY, 1, ctx).await) } else { None };
|
||||
v.child_state(&zone, &parent, &pk, &ds, dk.as_ref())
|
||||
}
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
};
|
||||
v.store(&zone, &st);
|
||||
st
|
||||
})
|
||||
}
|
||||
|
||||
/// Zone apex enclosing `name`, learned from an SOA query.
|
||||
async fn apex_of(&self, name: &Name, ctx: &Ctx) -> Name {
|
||||
let a = self.resolve_inner(name.clone(), RecordType::SOA, 1, ctx).await;
|
||||
a.answers
|
||||
.iter()
|
||||
.chain(a.authority.iter())
|
||||
.find(|r| r.record_type() == RecordType::SOA)
|
||||
.map(|r| r.name.clone())
|
||||
.unwrap_or_else(Name::root)
|
||||
}
|
||||
|
||||
async fn validate_answer(
|
||||
&self,
|
||||
qname: &Name,
|
||||
qtype: RecordType,
|
||||
a: &Answer,
|
||||
ctx: &Ctx,
|
||||
) -> (dns_core::answer::Security, Option<String>) {
|
||||
use dns_core::answer::Security;
|
||||
use validator::KeyState;
|
||||
let Some(v) = &self.validator else { return (Security::Indeterminate, None) };
|
||||
if v.closest_anchor(qname).is_none() {
|
||||
return (Security::Insecure, None);
|
||||
}
|
||||
// key states for every signer in the answer section
|
||||
let mut states: HashMap<Name, KeyState> = HashMap::new();
|
||||
for r in a.answers.iter().chain(a.authority.iter()) {
|
||||
if let Some((signer, _, _)) = dns_core::dnssec::rrsig_info(r) {
|
||||
if let std::collections::hash_map::Entry::Vacant(slot) = states.entry(signer.clone()) {
|
||||
let st = self.key_state(signer, ctx, 0).await;
|
||||
slot.insert(st);
|
||||
}
|
||||
}
|
||||
}
|
||||
// unsigned RRsets are only acceptable inside insecure zones
|
||||
let mut unsigned_owners: Vec<(Name, RecordType)> = Vec::new();
|
||||
for r in a.answers.iter().filter(|r| r.record_type() != RecordType::RRSIG) {
|
||||
let covered = a.answers.iter().filter_map(dns_core::dnssec::rrsig_info).any(|(_, t, _)| t == r.record_type());
|
||||
if !covered && !unsigned_owners.iter().any(|(n, t)| n.eq_ignore_root_case(&r.name) && *t == r.record_type()) {
|
||||
unsigned_owners.push((r.name.clone(), r.record_type()));
|
||||
}
|
||||
}
|
||||
for (owner, t) in &unsigned_owners {
|
||||
let apex = self.apex_of(owner, ctx).await;
|
||||
match self.key_state(apex.clone(), ctx, 0).await {
|
||||
KeyState::Secure(_) => return (Security::Bogus, Some(format!("{owner} {t} is unsigned in signed zone {apex}"))),
|
||||
KeyState::Bogus(e) => return (Security::Bogus, Some(e)),
|
||||
KeyState::Insecure => {}
|
||||
}
|
||||
}
|
||||
let (mut sec, note) = validator::Validator::check_rrsets(a, &|s| states.get(s).cloned());
|
||||
if sec == Security::Bogus || sec == Security::Indeterminate {
|
||||
return (sec, note);
|
||||
}
|
||||
// wildcard expansions need a proof that no closer match exists
|
||||
for r in a.answers.iter() {
|
||||
if let RData::DNSSEC(dns_core::proto::dnssec::rdata::DNSSECRData::RRSIG(sig)) = &r.data {
|
||||
if (sig.input().num_labels as usize) < r.name.num_labels() as usize {
|
||||
let signer = sig.input().signer_name.clone();
|
||||
if let Some(KeyState::Secure(keys)) = states.get(&signer) {
|
||||
match v.verify_denial(&signer, keys, &a.authority, &r.name, sig.input().type_covered) {
|
||||
Ok(dns_core::dnssec::Denial::NxDomain) => {}
|
||||
Ok(dns_core::dnssec::Denial::Unproven(m)) if m == "wildcard not denied" => {}
|
||||
Ok(other) => return (Security::Bogus, Some(format!("wildcard proof for {}: {other:?}", r.name))),
|
||||
Err(e) => return (Security::Bogus, Some(format!("wildcard proof for {}: {e}", r.name))),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !validator::is_negative(a) {
|
||||
return (sec, None);
|
||||
}
|
||||
// negative answer: SOA + NSEC/NSEC3 proof from the zone of the last name in the chain
|
||||
let last = a
|
||||
.answers
|
||||
.iter()
|
||||
.filter_map(|r| match &r.data {
|
||||
RData::CNAME(c) => Some(c.0.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.next_back()
|
||||
.unwrap_or_else(|| qname.clone());
|
||||
let zone = match a.authority.iter().filter_map(dns_core::dnssec::rrsig_info).find(|(_, t, _)| *t == RecordType::SOA) {
|
||||
Some((s, _, _)) => s,
|
||||
None => match a.authority.iter().find(|r| r.record_type() == RecordType::SOA) {
|
||||
Some(r) => r.name.clone(),
|
||||
None => self.apex_of(&last, ctx).await,
|
||||
},
|
||||
};
|
||||
let keys = match self.key_state(zone.clone(), ctx, 0).await {
|
||||
KeyState::Insecure => return (Security::Insecure, None),
|
||||
KeyState::Bogus(e) => return (Security::Bogus, Some(e)),
|
||||
KeyState::Secure(k) => k,
|
||||
};
|
||||
let soa: Vec<Record> = a.authority.iter().filter(|r| r.record_type() == RecordType::SOA).cloned().collect();
|
||||
let sigs: Vec<Record> = a.authority.iter().filter(|r| r.record_type() == RecordType::RRSIG).cloned().collect();
|
||||
if let Err(e) = dns_core::dnssec::verify_rrset(&zone, &soa, &sigs, &keys, &zone, dns_core::tsig::now() as u32) {
|
||||
return (Security::Bogus, Some(format!("negative answer SOA: {e}")));
|
||||
}
|
||||
let want_nx = a.rcode == ResponseCode::NXDomain;
|
||||
match v.verify_denial(&zone, &keys, &a.authority, &last, qtype) {
|
||||
Ok(dns_core::dnssec::Denial::NxDomain) if want_nx => {}
|
||||
Ok(dns_core::dnssec::Denial::NoData | dns_core::dnssec::Denial::InsecureDelegation) if !want_nx => {}
|
||||
Ok(other) => return (Security::Bogus, Some(format!("denial of existence does not match: {other:?}"))),
|
||||
Err(e) => return (Security::Bogus, Some(format!("denial of existence: {e}"))),
|
||||
}
|
||||
if sec == Security::Indeterminate {
|
||||
sec = Security::Secure;
|
||||
}
|
||||
(sec, None)
|
||||
}
|
||||
|
||||
/// Resolve without using the answer cache for the final question and return the trace.
|
||||
pub async fn resolve_traced(&self, name: &Name, qtype: RecordType) -> (Answer, Vec<TraceStep>) {
|
||||
let ctx = self.new_ctx(true);
|
||||
let a = self.resolve_chain(name.clone(), qtype, 0, &ctx).await;
|
||||
let steps = ctx.trace.map(|m| m.into_inner().unwrap_or_else(|e| e.into_inner())).unwrap_or_default();
|
||||
(a, steps)
|
||||
}
|
||||
|
||||
fn resolve_inner<'a>(&'a self, name: Name, qtype: RecordType, depth: u32, ctx: &'a Ctx) -> BoxFut<'a, Answer> {
|
||||
Box::pin(async move {
|
||||
let key = Key { ns: self.ns, name: LowerName::new(&name), rtype: qtype, dnssec: false };
|
||||
if let Some(a) = self.cache.get(&key) {
|
||||
return a;
|
||||
}
|
||||
let a = self.resolve_chain(name, qtype, depth, ctx).await;
|
||||
if matches!(a.rcode, ResponseCode::NoError | ResponseCode::NXDomain | ResponseCode::ServFail) {
|
||||
self.cache.insert_answer(key, &a);
|
||||
}
|
||||
a
|
||||
})
|
||||
}
|
||||
|
||||
/// Follow CNAMEs across zones, accumulating the chain.
|
||||
async fn resolve_chain(&self, name: Name, qtype: RecordType, depth: u32, ctx: &Ctx) -> Answer {
|
||||
let mut chain: Vec<Record> = Vec::new();
|
||||
let mut cur = name;
|
||||
for _ in 0..=self.settings.max_cname {
|
||||
// A cached answer for an intermediate CNAME target can finish the chain.
|
||||
if !chain.is_empty() {
|
||||
let key = Key { ns: self.ns, name: LowerName::new(&cur), rtype: qtype, dnssec: false };
|
||||
if let Some(mut a) = self.cache.get(&key) {
|
||||
chain.append(&mut a.answers);
|
||||
a.answers = chain;
|
||||
a.source = Source::Recursive;
|
||||
return a;
|
||||
}
|
||||
}
|
||||
let msg = match self.iterate(&cur, qtype, depth, ctx).await {
|
||||
Ok(s) => s,
|
||||
Err(e) => return Answer::servfail(Source::Recursive, e),
|
||||
};
|
||||
let rcode = msg.0;
|
||||
let m = msg.1;
|
||||
// Walk the answer section following CNAMEs from `cur`.
|
||||
let mut found_final = false;
|
||||
let mut target = cur.clone();
|
||||
for _ in 0..=self.settings.max_cname {
|
||||
let owned: Vec<&Record> = m.answers.iter().filter(|r| r.name.eq_ignore_root_case(&target)).collect();
|
||||
let finals: Vec<Record> = owned
|
||||
.iter()
|
||||
.filter(|r| match dns_core::dnssec::rrsig_info(r) {
|
||||
Some((_, ct, _)) => qtype == RecordType::ANY || ct == qtype,
|
||||
None => rtype_matches(r, qtype),
|
||||
})
|
||||
.map(|r| (*r).clone())
|
||||
.collect();
|
||||
if !finals.is_empty() && (qtype == RecordType::CNAME || finals.iter().any(|r| r.record_type() != RecordType::RRSIG)) {
|
||||
chain.extend(finals);
|
||||
found_final = true;
|
||||
break;
|
||||
}
|
||||
let cname = owned.iter().find_map(|r| match &r.data {
|
||||
RData::CNAME(c) => Some(((*r).clone(), c.0.clone())),
|
||||
_ => None,
|
||||
});
|
||||
match cname {
|
||||
Some((rec, t)) => {
|
||||
if chain.iter().any(|r| r.name.eq_ignore_root_case(&t)) || t.eq_ignore_root_case(&cur) {
|
||||
return Answer::servfail(Source::Recursive, "CNAME loop");
|
||||
}
|
||||
chain.push(rec);
|
||||
// keep the signatures over the CNAME for validation
|
||||
chain.extend(
|
||||
owned
|
||||
.iter()
|
||||
.filter(|r| dns_core::dnssec::rrsig_info(r).is_some_and(|(_, ct, _)| ct == RecordType::CNAME))
|
||||
.map(|r| (*r).clone()),
|
||||
);
|
||||
target = t;
|
||||
}
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
let dnssec_auth: Vec<Record> = if self.settings.dnssec {
|
||||
m.authorities
|
||||
.iter()
|
||||
.filter(|r| matches!(r.record_type(), RecordType::NSEC | RecordType::NSEC3 | RecordType::RRSIG))
|
||||
.cloned()
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
if found_final {
|
||||
let mut a = Answer::new(ResponseCode::NoError, Source::Recursive);
|
||||
a.answers = chain;
|
||||
a.authority = dnssec_auth;
|
||||
return a;
|
||||
}
|
||||
if target != cur
|
||||
&& !chain.is_empty()
|
||||
&& rcode == ResponseCode::NoError
|
||||
&& m.answers.iter().all(|r| !r.name.eq_ignore_root_case(&target))
|
||||
{
|
||||
// CNAME points elsewhere: continue from the target.
|
||||
cur = target;
|
||||
continue;
|
||||
}
|
||||
// Negative answer (for the last name in the chain).
|
||||
let mut a = Answer::new(rcode, Source::Recursive);
|
||||
a.answers = chain;
|
||||
a.authority = m.authorities.iter().filter(|r| r.record_type() == RecordType::SOA).cloned().collect();
|
||||
a.authority.extend(dnssec_auth);
|
||||
return a;
|
||||
}
|
||||
Answer::servfail(Source::Recursive, "CNAME chain too long")
|
||||
}
|
||||
|
||||
/// Find the closest enclosing delegation known to the cache.
|
||||
fn closest_delegation(&self, qname: &Name) -> (Name, Vec<Name>) {
|
||||
for anc in dns_core::names::ancestors(qname) {
|
||||
if anc.is_root() {
|
||||
break;
|
||||
}
|
||||
if let Some(ns) = self.cache.get_rrset(self.ns, &anc, RecordType::NS) {
|
||||
let names = ns_names(&ns);
|
||||
if !names.is_empty() {
|
||||
return (anc, names);
|
||||
}
|
||||
}
|
||||
}
|
||||
(Name::root(), self.roots.iter().map(|(n, _)| n.clone()).collect())
|
||||
}
|
||||
|
||||
fn known_addresses(&self, ns: &Name) -> Vec<IpAddr> {
|
||||
if let Some((_, a)) = self.roots.iter().find(|(n, _)| n.eq_ignore_root_case(ns)) {
|
||||
return a.iter().copied().filter(|ip| self.settings.ipv6 || ip.is_ipv4()).collect();
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let types: &[RecordType] = if self.settings.ipv6 { &[RecordType::A, RecordType::AAAA] } else { &[RecordType::A] };
|
||||
for t in types {
|
||||
if let Some(rs) = self.cache.get_rrset(self.ns, ns, *t) {
|
||||
out.extend(rs.iter().filter_map(|r| r.data.ip_addr()));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn order_servers(&self, addrs: &mut Vec<(IpAddr, Option<Name>)>) {
|
||||
let map = self.servers.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let now = Instant::now();
|
||||
addrs.retain(|(ip, _)| !map.get(ip).and_then(|s| s.dead_until).is_some_and(|t| t > now));
|
||||
addrs.sort_by(|a, b| {
|
||||
let ra = map.get(&a.0).and_then(|s| s.rtt_ms).unwrap_or(rand::random::<f64>() * 50.0);
|
||||
let rb = map.get(&b.0).and_then(|s| s.rtt_ms).unwrap_or(rand::random::<f64>() * 50.0);
|
||||
ra.total_cmp(&rb)
|
||||
});
|
||||
}
|
||||
|
||||
fn server_result(&self, ip: IpAddr, rtt: Option<Duration>) {
|
||||
let mut map = self.servers.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if map.len() > 50_000 {
|
||||
map.clear();
|
||||
}
|
||||
let s = map.entry(ip).or_default();
|
||||
match rtt {
|
||||
Some(d) => {
|
||||
let ms = d.as_secs_f64() * 1000.0;
|
||||
s.rtt_ms = Some(s.rtt_ms.map_or(ms, |o| o * 0.7 + ms * 0.3));
|
||||
s.fails = 0;
|
||||
s.dead_until = None;
|
||||
}
|
||||
None => {
|
||||
s.fails += 1;
|
||||
s.rtt_ms = Some(s.rtt_ms.unwrap_or(500.0) + 200.0);
|
||||
if s.fails >= 3 {
|
||||
s.dead_until = Some(Instant::now() + Duration::from_secs(60u64.min(5 << s.fails.min(4))));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Iterate from the closest delegation to an authoritative response for `qname`.
|
||||
/// Returns (rcode, message) where the answer section holds the data for `qname`.
|
||||
async fn iterate(&self, qname: &Name, qtype: RecordType, depth: u32, ctx: &Ctx) -> Result<(ResponseCode, Message), String> {
|
||||
// DS lives in the parent zone: start the search above the cut.
|
||||
let start = if qtype == RecordType::DS && !qname.is_root() { qname.base_name() } else { qname.clone() };
|
||||
let (mut zone, mut ns) = self.closest_delegation(&start);
|
||||
let mut minimise = self.settings.qname_minimization;
|
||||
let mut qmin_labels = zone.num_labels() + 1;
|
||||
for _ in 0..self.settings.max_depth {
|
||||
if ctx.expired() {
|
||||
return Err("resolution deadline exceeded".into());
|
||||
}
|
||||
let full = !minimise || qmin_labels >= qname.num_labels();
|
||||
let (ask_name, ask_type) = if full { (qname.clone(), qtype) } else { (qname.trim_to(qmin_labels as usize), RecordType::A) };
|
||||
let step = self.ask_zone(&zone, &ns, &ask_name, ask_type, depth, ctx).await?;
|
||||
match step {
|
||||
Step::Referral { zone: child, ns: nsrecs, glue } => {
|
||||
if qtype == RecordType::DS && child.eq_ignore_root_case(qname) {
|
||||
return Err(format!("parent {zone} referred the DS query for {qname} to the child"));
|
||||
}
|
||||
if !child.zone_of(qname) || child.num_labels() <= zone.num_labels() {
|
||||
return Err(format!("bad referral from {zone} to {child}"));
|
||||
}
|
||||
self.cache.insert_rrset(self.ns, &nsrecs, Rank::Authority);
|
||||
let mut by_name: HashMap<(LowerName, RecordType), Vec<Record>> = HashMap::new();
|
||||
for g in glue {
|
||||
by_name.entry((LowerName::new(&g.name), g.record_type())).or_default().push(g);
|
||||
}
|
||||
for (_, set) in by_name {
|
||||
self.cache.insert_rrset(self.ns, &set, Rank::Glue);
|
||||
}
|
||||
ns = ns_names(&nsrecs);
|
||||
zone = child;
|
||||
qmin_labels = zone.num_labels() + 1;
|
||||
}
|
||||
Step::Answer(m) => {
|
||||
if full {
|
||||
return Ok((ResponseCode::NoError, m));
|
||||
}
|
||||
// Minimised name exists and has data: no cut there, go one label deeper.
|
||||
if m.answers.iter().any(|r| r.record_type() == RecordType::CNAME) {
|
||||
minimise = false;
|
||||
}
|
||||
qmin_labels += 1;
|
||||
}
|
||||
Step::NoData(m) => {
|
||||
if full {
|
||||
return Ok((ResponseCode::NoError, m));
|
||||
}
|
||||
qmin_labels += 1;
|
||||
}
|
||||
Step::NxDomain(m) => {
|
||||
if full {
|
||||
return Ok((ResponseCode::NXDomain, m));
|
||||
}
|
||||
// RFC 8020 says nothing exists below; re-ask with the full name for robustness
|
||||
// against servers that mishandle empty non-terminals.
|
||||
minimise = false;
|
||||
}
|
||||
Step::Lame(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
Err("too many referrals".into())
|
||||
}
|
||||
|
||||
/// Ask the servers of `zone` (trying several) and classify the answer.
|
||||
async fn ask_zone(&self, zone: &Name, ns: &[Name], qname: &Name, qtype: RecordType, depth: u32, ctx: &Ctx) -> Result<Step, String> {
|
||||
let mut addrs: Vec<(IpAddr, Option<Name>)> = Vec::new();
|
||||
for n in ns {
|
||||
for ip in self.known_addresses(n) {
|
||||
addrs.push((ip, Some(n.clone())));
|
||||
}
|
||||
}
|
||||
if addrs.is_empty() {
|
||||
// Resolve NS addresses (no glue). Skip NS names inside the zone itself (would loop).
|
||||
if depth >= self.settings.max_subqueries_depth {
|
||||
return Err(format!("NS address resolution too deep for {zone}"));
|
||||
}
|
||||
for n in ns.iter().take(3) {
|
||||
if zone.zone_of(n) && !zone.is_root() {
|
||||
continue;
|
||||
}
|
||||
for t in if self.settings.ipv6 { vec![RecordType::A, RecordType::AAAA] } else { vec![RecordType::A] } {
|
||||
let a = self.resolve_inner(n.clone(), t, depth + 1, ctx).await;
|
||||
for r in &a.answers {
|
||||
if r.name.eq_ignore_root_case(n) {
|
||||
if let Some(ip) = r.data.ip_addr() {
|
||||
addrs.push((ip, Some(n.clone())));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !addrs.is_empty() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if addrs.is_empty() {
|
||||
return Err(format!("no usable name server addresses for {zone}"));
|
||||
}
|
||||
self.order_servers(&mut addrs);
|
||||
if addrs.is_empty() {
|
||||
return Err(format!("all name servers for {zone} are unresponsive"));
|
||||
}
|
||||
let mut errors = Vec::new();
|
||||
for (ip, nsname) in addrs.iter().take(6) {
|
||||
if ctx.expired() {
|
||||
break;
|
||||
}
|
||||
if !ctx.take_query() {
|
||||
return Err("query budget exhausted".into());
|
||||
}
|
||||
self.queries_sent.fetch_add(1, Ordering::Relaxed);
|
||||
let server = SocketAddr::new(*ip, self.settings.port);
|
||||
let opts = QueryOptions {
|
||||
timeout: self.settings.query_timeout,
|
||||
retries: 0,
|
||||
recursion_desired: false,
|
||||
dnssec_ok: self.settings.dnssec,
|
||||
..Default::default()
|
||||
};
|
||||
let start = Instant::now();
|
||||
let res = query(server, qname, qtype, &opts).await;
|
||||
let elapsed = start.elapsed();
|
||||
let mut trace = TraceStep {
|
||||
zone: zone.to_string(),
|
||||
server: server.to_string(),
|
||||
server_name: nsname.as_ref().map(|n| n.to_string()),
|
||||
qname: qname.to_string(),
|
||||
qtype: qtype.to_string(),
|
||||
rcode: String::new(),
|
||||
outcome: String::new(),
|
||||
elapsed_ms: elapsed.as_secs_f64() * 1000.0,
|
||||
depth,
|
||||
};
|
||||
let m = match res {
|
||||
Ok(ex) => ex.message,
|
||||
Err(e) => {
|
||||
self.server_result(*ip, None);
|
||||
trace.outcome = format!("error: {e}");
|
||||
ctx.trace(trace);
|
||||
errors.push(format!("{server}: {e}"));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
trace.rcode = m.metadata.response_code.to_string();
|
||||
let step = classify(zone, qname, qtype, m);
|
||||
match &step {
|
||||
Step::Lame(e) => {
|
||||
self.server_result(*ip, None);
|
||||
trace.outcome = format!("lame: {e}");
|
||||
ctx.trace(trace);
|
||||
errors.push(format!("{server}: {e}"));
|
||||
continue;
|
||||
}
|
||||
Step::Referral { zone: z, ns, .. } => {
|
||||
trace.outcome = format!("referral to {z} ({} NS)", ns.len());
|
||||
}
|
||||
Step::Answer(m) => trace.outcome = format!("answer ({} records)", m.answers.len()),
|
||||
Step::NoData(_) => trace.outcome = "NODATA".into(),
|
||||
Step::NxDomain(_) => trace.outcome = "NXDOMAIN".into(),
|
||||
}
|
||||
self.server_result(*ip, Some(elapsed));
|
||||
ctx.trace(trace);
|
||||
return Ok(step);
|
||||
}
|
||||
Err(format!("no server for {zone} answered: {}", errors.join("; ")))
|
||||
}
|
||||
}
|
||||
|
||||
/// Classify a response from a server authoritative for `zone`, applying bailiwick rules.
|
||||
fn classify(zone: &Name, qname: &Name, qtype: RecordType, mut m: Message) -> Step {
|
||||
let rcode = m.metadata.response_code;
|
||||
match rcode {
|
||||
ResponseCode::NoError | ResponseCode::NXDomain => {}
|
||||
other => return Step::Lame(format!("rcode {other}")),
|
||||
}
|
||||
// Bailiwick: drop anything outside the server's zone.
|
||||
m.answers.retain(|r| zone.zone_of(&r.name));
|
||||
m.authorities.retain(|r| zone.zone_of(&r.name));
|
||||
m.additionals.retain(|r| zone.zone_of(&r.name) && matches!(r.record_type(), RecordType::A | RecordType::AAAA));
|
||||
|
||||
let has_answer =
|
||||
m.answers.iter().any(|r| r.name.eq_ignore_root_case(qname) && (rtype_matches(r, qtype) || r.record_type() == RecordType::CNAME));
|
||||
if has_answer {
|
||||
return Step::Answer(m);
|
||||
}
|
||||
if rcode == ResponseCode::NXDomain {
|
||||
return Step::NxDomain(m);
|
||||
}
|
||||
// Referral: NS for a proper descendant of `zone` that encloses qname.
|
||||
let ns: Vec<Record> = m
|
||||
.authorities
|
||||
.iter()
|
||||
.filter(|r| r.record_type() == RecordType::NS && r.name.zone_of(qname) && r.name.num_labels() > zone.num_labels())
|
||||
.cloned()
|
||||
.collect();
|
||||
if let Some(first) = ns.first() {
|
||||
let child = first.name.clone();
|
||||
let ns: Vec<Record> = ns.into_iter().filter(|r| r.name.eq_ignore_root_case(&child)).collect();
|
||||
let targets = ns_names(&ns);
|
||||
let glue = m.additionals.iter().filter(|r| targets.iter().any(|t| t.eq_ignore_root_case(&r.name))).cloned().collect();
|
||||
return Step::Referral { zone: child, ns, glue };
|
||||
}
|
||||
if m.authorities.iter().any(|r| r.record_type() == RecordType::NS && r.name.eq_ignore_root_case(zone)) && !m.metadata.authoritative {
|
||||
return Step::Lame("upward/lame referral".into());
|
||||
}
|
||||
if !m.metadata.authoritative && m.authorities.iter().all(|r| r.record_type() != RecordType::SOA) {
|
||||
return Step::Lame("non-authoritative empty answer".into());
|
||||
}
|
||||
Step::NoData(m)
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
//! DNSSEC validation (RFC 4035 §5) for the iterative resolver.
|
||||
//!
|
||||
//! The chain of trust is built top-down from the trust anchors (by default the IANA root
|
||||
//! KSKs 20326 and 38696): DNSKEY(root) → DS(child) signed by parent → DNSKEY(child)
|
||||
//! matching a DS and self-signed → RRSIGs over answer RRsets. Missing DS proven by signed
|
||||
//! NSEC/NSEC3 → insecure. Anything else that fails → bogus (SERVFAIL unless CD=1).
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use dns_core::answer::{Answer, Security};
|
||||
use dns_core::dnssec::{Denial, algorithm_supported, check_nsec, check_nsec3, dnskey_of, ds_matches, ds_of, rrsig_info, verify_rrset};
|
||||
use dns_core::proto::dnssec::rdata::DNSKEY;
|
||||
use dns_core::proto::dnssec::{PublicKey, TrustAnchors, Verifier};
|
||||
use dns_core::proto::op::ResponseCode;
|
||||
use dns_core::proto::rr::{Name, Record, RecordType};
|
||||
|
||||
/// Key state of a zone.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum KeyState {
|
||||
Secure(Vec<DNSKEY>),
|
||||
Insecure,
|
||||
Bogus(String),
|
||||
}
|
||||
|
||||
/// A configured trust anchor.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Anchor {
|
||||
Key(DNSKEY),
|
||||
Ds(dns_core::proto::dnssec::rdata::DS),
|
||||
}
|
||||
|
||||
pub struct Validator {
|
||||
anchors: Vec<(Name, Anchor)>,
|
||||
cache: Mutex<HashMap<Name, (KeyState, Instant)>>,
|
||||
}
|
||||
|
||||
const KEY_CACHE_TTL: Duration = Duration::from_secs(300);
|
||||
|
||||
fn now32() -> u32 {
|
||||
dns_core::tsig::now() as u32
|
||||
}
|
||||
|
||||
impl Validator {
|
||||
/// Built-in IANA root anchors.
|
||||
pub fn with_root_anchors() -> Self {
|
||||
let ta = TrustAnchors::default();
|
||||
let mut anchors = Vec::new();
|
||||
let mut i = 0;
|
||||
while let Some(pk) = ta.get(i) {
|
||||
anchors.push((Name::root(), Anchor::Key(DNSKEY::new(true, true, false, pk.clone()))));
|
||||
i += 1;
|
||||
}
|
||||
Self { anchors, cache: Mutex::new(HashMap::new()) }
|
||||
}
|
||||
|
||||
/// Anchors from a zone-file formatted file with DS and/or DNSKEY records.
|
||||
pub fn from_records(records: &[Record]) -> Result<Self, String> {
|
||||
let mut anchors = Vec::new();
|
||||
for r in records {
|
||||
if let Some(k) = dnskey_of(r) {
|
||||
anchors.push((r.name.clone(), Anchor::Key(k.clone())));
|
||||
} else if let Some(d) = ds_of(r) {
|
||||
anchors.push((r.name.clone(), Anchor::Ds(d.clone())));
|
||||
}
|
||||
}
|
||||
if anchors.is_empty() {
|
||||
return Err("trust anchor file contains no DS or DNSKEY records".into());
|
||||
}
|
||||
Ok(Self { anchors, cache: Mutex::new(HashMap::new()) })
|
||||
}
|
||||
|
||||
pub fn anchor_names(&self) -> Vec<Name> {
|
||||
let mut v: Vec<Name> = self.anchors.iter().map(|(n, _)| n.clone()).collect();
|
||||
v.dedup();
|
||||
v
|
||||
}
|
||||
|
||||
pub(crate) fn cached(&self, zone: &Name) -> Option<KeyState> {
|
||||
let c = self.cache.lock().unwrap_or_else(|e| e.into_inner());
|
||||
c.get(zone).filter(|(_, t)| t.elapsed() < KEY_CACHE_TTL).map(|(s, _)| s.clone())
|
||||
}
|
||||
|
||||
pub(crate) fn store(&self, zone: &Name, st: &KeyState) {
|
||||
let mut c = self.cache.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if c.len() > 10_000 {
|
||||
c.clear();
|
||||
}
|
||||
c.insert(zone.clone(), (st.clone(), Instant::now()));
|
||||
}
|
||||
|
||||
/// Is `zone` a trust anchor point?
|
||||
pub fn is_anchor(&self, zone: &Name) -> bool {
|
||||
self.anchors.iter().any(|(n, _)| n.eq_ignore_root_case(zone))
|
||||
}
|
||||
|
||||
/// Closest anchor at or above `name`.
|
||||
pub fn closest_anchor(&self, name: &Name) -> Option<Name> {
|
||||
self.anchors.iter().filter(|(n, _)| n.zone_of(name)).map(|(n, _)| n.clone()).max_by_key(|n| n.num_labels())
|
||||
}
|
||||
|
||||
/// Validate a DNSKEY RRset for an anchored zone.
|
||||
pub fn validate_anchor_keys(&self, zone: &Name, answer: &[Record]) -> KeyState {
|
||||
let keys: Vec<Record> =
|
||||
answer.iter().filter(|r| r.record_type() == RecordType::DNSKEY && r.name.eq_ignore_root_case(zone)).cloned().collect();
|
||||
let sigs: Vec<Record> = answer.iter().filter(|r| r.record_type() == RecordType::RRSIG).cloned().collect();
|
||||
let dnskeys: Vec<DNSKEY> = keys.iter().filter_map(dnskey_of).cloned().collect();
|
||||
let trusted: Vec<DNSKEY> = dnskeys
|
||||
.iter()
|
||||
.filter(|k| {
|
||||
self.anchors.iter().any(|(n, a)| {
|
||||
n.eq_ignore_root_case(zone)
|
||||
&& match a {
|
||||
Anchor::Key(ak) => {
|
||||
ak.public_key().public_bytes() == k.public_key().public_bytes() && ak.algorithm() == k.algorithm()
|
||||
}
|
||||
Anchor::Ds(ds) => ds_matches(ds, zone, k),
|
||||
}
|
||||
})
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
if trusted.is_empty() {
|
||||
return KeyState::Bogus(format!("no DNSKEY of {zone} matches the trust anchor"));
|
||||
}
|
||||
match verify_rrset(zone, &keys, &sigs, &trusted, zone, now32()) {
|
||||
Ok(_) => KeyState::Secure(dnskeys),
|
||||
Err(e) => KeyState::Bogus(format!("DNSKEY RRset of {zone}: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Given the parent's key state and the DS answer, derive the child's key state.
|
||||
pub fn child_state(
|
||||
&self,
|
||||
zone: &Name,
|
||||
parent: &Name,
|
||||
parent_keys: &[DNSKEY],
|
||||
ds_answer: &Answer,
|
||||
dnskey_answer: Option<&Answer>,
|
||||
) -> KeyState {
|
||||
let ds: Vec<Record> =
|
||||
ds_answer.answers.iter().filter(|r| r.record_type() == RecordType::DS && r.name.eq_ignore_root_case(zone)).cloned().collect();
|
||||
let sigs: Vec<Record> =
|
||||
ds_answer.answers.iter().chain(ds_answer.authority.iter()).filter(|r| r.record_type() == RecordType::RRSIG).cloned().collect();
|
||||
if ds.is_empty() {
|
||||
// Need a signed denial from the parent.
|
||||
match self.verify_denial(parent, parent_keys, &ds_answer.authority, zone, RecordType::DS) {
|
||||
Ok(Denial::InsecureDelegation) | Ok(Denial::NoData) => return KeyState::Insecure,
|
||||
Ok(Denial::NxDomain) => return KeyState::Bogus(format!("{zone} does not exist (NXDOMAIN proven)")),
|
||||
Ok(Denial::Unproven(e)) | Err(e) => return KeyState::Bogus(format!("missing DS for {zone} not proven: {e}")),
|
||||
}
|
||||
}
|
||||
if let Err(e) = verify_rrset(zone, &ds, &sigs, parent_keys, parent, now32()) {
|
||||
return KeyState::Bogus(format!("DS RRset of {zone}: {e}"));
|
||||
}
|
||||
let ds_rd: Vec<_> =
|
||||
ds.iter().filter_map(ds_of).filter(|d| algorithm_supported(d.algorithm()) && d.digest_type().is_supported()).cloned().collect();
|
||||
if ds_rd.is_empty() {
|
||||
return KeyState::Insecure; // RFC 4035 §5.2: unsupported algorithms → insecure
|
||||
}
|
||||
let Some(ka) = dnskey_answer else { return KeyState::Bogus("no DNSKEY answer".into()) };
|
||||
let keys: Vec<Record> =
|
||||
ka.answers.iter().filter(|r| r.record_type() == RecordType::DNSKEY && r.name.eq_ignore_root_case(zone)).cloned().collect();
|
||||
let ksigs: Vec<Record> = ka.answers.iter().filter(|r| r.record_type() == RecordType::RRSIG).cloned().collect();
|
||||
let dnskeys: Vec<DNSKEY> = keys.iter().filter_map(dnskey_of).cloned().collect();
|
||||
let entry: Vec<DNSKEY> = dnskeys.iter().filter(|k| ds_rd.iter().any(|d| ds_matches(d, zone, k))).cloned().collect();
|
||||
if entry.is_empty() {
|
||||
return KeyState::Bogus(format!("no DNSKEY of {zone} matches its DS"));
|
||||
}
|
||||
match verify_rrset(zone, &keys, &ksigs, &entry, zone, now32()) {
|
||||
Ok(_) => KeyState::Secure(dnskeys),
|
||||
Err(e) => KeyState::Bogus(format!("DNSKEY RRset of {zone}: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Verify the signatures of NSEC/NSEC3 records in `authority` and evaluate the denial.
|
||||
pub fn verify_denial(
|
||||
&self,
|
||||
zone: &Name,
|
||||
keys: &[DNSKEY],
|
||||
authority: &[Record],
|
||||
qname: &Name,
|
||||
qtype: RecordType,
|
||||
) -> Result<Denial, String> {
|
||||
let sigs: Vec<Record> = authority.iter().filter(|r| r.record_type() == RecordType::RRSIG).cloned().collect();
|
||||
let mut verified = Vec::new();
|
||||
for t in [RecordType::NSEC, RecordType::NSEC3] {
|
||||
let mut owners: Vec<Name> = authority.iter().filter(|r| r.record_type() == t).map(|r| r.name.clone()).collect();
|
||||
owners.dedup();
|
||||
for o in owners {
|
||||
let set: Vec<Record> =
|
||||
authority.iter().filter(|r| r.record_type() == t && r.name.eq_ignore_root_case(&o)).cloned().collect();
|
||||
verify_rrset(&o, &set, &sigs, keys, zone, now32()).map_err(|e| format!("{o} {t}: {e}"))?;
|
||||
verified.extend(set);
|
||||
}
|
||||
}
|
||||
if verified.is_empty() {
|
||||
return Err("no NSEC/NSEC3 records in the response".into());
|
||||
}
|
||||
Ok(if verified.iter().any(|r| r.record_type() == RecordType::NSEC) {
|
||||
check_nsec(&verified, qname, qtype, zone)
|
||||
} else {
|
||||
check_nsec3(&verified, qname, qtype, zone)
|
||||
})
|
||||
}
|
||||
|
||||
/// Validate RRsets of a positive answer given a key-state lookup per signer.
|
||||
pub fn check_rrsets(answer: &Answer, state_of: &dyn Fn(&Name) -> Option<KeyState>) -> (Security, Option<String>) {
|
||||
let sigs: Vec<Record> = answer.answers.iter().filter(|r| r.record_type() == RecordType::RRSIG).cloned().collect();
|
||||
let mut groups: Vec<(Name, RecordType, Vec<Record>)> = Vec::new();
|
||||
for r in answer.answers.iter().filter(|r| r.record_type() != RecordType::RRSIG) {
|
||||
match groups.iter_mut().find(|(n, t, _)| n.eq_ignore_root_case(&r.name) && *t == r.record_type()) {
|
||||
Some(g) => g.2.push(r.clone()),
|
||||
None => groups.push((r.name.clone(), r.record_type(), vec![r.clone()])),
|
||||
}
|
||||
}
|
||||
let mut result = Security::Secure;
|
||||
for (owner, t, set) in &groups {
|
||||
let signer = sigs.iter().filter_map(rrsig_info).find(|(_, ct, _)| ct == t).map(|(s, _, _)| s);
|
||||
let signer = match signer {
|
||||
Some(s) => s,
|
||||
None => {
|
||||
// unsigned RRset: fine only if its zone is insecure (caller checked)
|
||||
result = Security::Insecure;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
match state_of(&signer) {
|
||||
Some(KeyState::Secure(keys)) => {
|
||||
if let Err(e) = verify_rrset(owner, set, &sigs, &keys, &signer, now32()) {
|
||||
return (Security::Bogus, Some(format!("{owner} {t}: {e}")));
|
||||
}
|
||||
}
|
||||
Some(KeyState::Insecure) => result = Security::Insecure,
|
||||
Some(KeyState::Bogus(e)) => return (Security::Bogus, Some(e)),
|
||||
None => return (Security::Indeterminate, Some(format!("no key state for {signer}"))),
|
||||
}
|
||||
}
|
||||
(result, None)
|
||||
}
|
||||
}
|
||||
|
||||
/// Is this response negative?
|
||||
pub fn is_negative(a: &Answer) -> bool {
|
||||
a.rcode == ResponseCode::NXDomain
|
||||
|| (a.rcode == ResponseCode::NoError
|
||||
&& a.answers.iter().all(|r| r.record_type() == RecordType::CNAME || r.record_type() == RecordType::RRSIG))
|
||||
}
|
||||
Reference in new issue
Block a user