v0.1.0
This commit is contained in:
commit
fa432bebda
189 files changed
+26219
No files matched your search
@@ -0,0 +1,26 @@
|
||||
[package]
|
||||
name = "dns-api"
|
||||
description = "EasyDNS REST API (/api/v1) and metrics endpoint"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
dns-core.workspace = true
|
||||
dns-config.workspace = true
|
||||
dns-authoritative.workspace = true
|
||||
dns-server.workspace = true
|
||||
dns-policy.workspace = true
|
||||
dns-metrics.workspace = true
|
||||
dns-cache.workspace = true
|
||||
axum.workspace = true
|
||||
tokio.workspace = true
|
||||
tracing.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
serde_norway.workspace = true
|
||||
data-encoding.workspace = true
|
||||
ring = "0.17"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,180 @@
|
||||
//! Token authentication, roles, client ACL and request rate limiting.
|
||||
use std::collections::HashMap;
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Instant;
|
||||
|
||||
use axum::extract::{ConnectInfo, Request, State};
|
||||
use axum::http::{Method, StatusCode};
|
||||
use axum::middleware::Next;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use dns_config::{ApiRole, Config};
|
||||
use dns_policy::Acl;
|
||||
|
||||
use crate::ApiState;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum Role {
|
||||
Admin,
|
||||
ReadOnly,
|
||||
}
|
||||
|
||||
/// Who made a request (inserted into request extensions).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Caller {
|
||||
pub name: String,
|
||||
pub role: Role,
|
||||
pub ip: IpAddr,
|
||||
}
|
||||
|
||||
struct Token {
|
||||
name: String,
|
||||
role: Role,
|
||||
hash: [u8; 32],
|
||||
}
|
||||
|
||||
pub struct Auth {
|
||||
required: bool,
|
||||
tokens: Vec<Token>,
|
||||
acl: Acl,
|
||||
rpm: u32,
|
||||
buckets: Mutex<HashMap<IpAddr, (f64, Instant)>>,
|
||||
}
|
||||
|
||||
/// SHA-256 of a token (hex), for `sha256:` token references.
|
||||
pub fn hash_token(t: &str) -> String {
|
||||
data_encoding::HEXLOWER.encode(ring::digest::digest(&ring::digest::SHA256, t.as_bytes()).as_ref())
|
||||
}
|
||||
|
||||
fn sha(t: &str) -> [u8; 32] {
|
||||
let mut out = [0u8; 32];
|
||||
out.copy_from_slice(ring::digest::digest(&ring::digest::SHA256, t.as_bytes()).as_ref());
|
||||
out
|
||||
}
|
||||
|
||||
impl Auth {
|
||||
pub fn from_config(cfg: &Config) -> Result<Self, String> {
|
||||
let mut tokens = Vec::new();
|
||||
for t in &cfg.api.tokens {
|
||||
let hash = if let Some(h) = t.token.strip_prefix("sha256:") {
|
||||
let b = data_encoding::HEXLOWER_PERMISSIVE.decode(h.as_bytes()).map_err(|_| format!("token {}: bad sha256 hex", t.name))?;
|
||||
<[u8; 32]>::try_from(b.as_slice()).map_err(|_| format!("token {}: sha256 must be 32 bytes", t.name))?
|
||||
} else {
|
||||
sha(&cfg.resolve_secret(&t.token).map_err(|e| format!("token {}: {e}", t.name))?)
|
||||
};
|
||||
let role = match t.role {
|
||||
ApiRole::Admin => Role::Admin,
|
||||
ApiRole::ReadOnly => Role::ReadOnly,
|
||||
};
|
||||
tokens.push(Token { name: t.name.clone(), role, hash });
|
||||
}
|
||||
if cfg.api.local_token {
|
||||
let tok = ensure_control_token(&cfg.control_token_path())?;
|
||||
tokens.push(Token { name: "local-control".into(), role: Role::Admin, hash: sha(&tok) });
|
||||
}
|
||||
Ok(Self {
|
||||
required: cfg.api.auth_required,
|
||||
tokens,
|
||||
acl: Acl(cfg.expand_acl(&cfg.api.allowed_clients)?),
|
||||
rpm: cfg.api.requests_per_minute.max(1),
|
||||
buckets: Mutex::new(HashMap::new()),
|
||||
})
|
||||
}
|
||||
|
||||
fn check_rate(&self, ip: IpAddr) -> bool {
|
||||
let mut m = self.buckets.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if m.len() > 10_000 {
|
||||
m.clear();
|
||||
}
|
||||
let cap = f64::from(self.rpm);
|
||||
let now = Instant::now();
|
||||
let e = m.entry(ip).or_insert((cap, now));
|
||||
e.0 = (e.0 + now.duration_since(e.1).as_secs_f64() * cap / 60.0).min(cap);
|
||||
e.1 = now;
|
||||
if e.0 >= 1.0 {
|
||||
e.0 -= 1.0;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn identify(&self, header: Option<&str>) -> Option<(String, Role)> {
|
||||
let tok = header?.strip_prefix("Bearer ")?.trim();
|
||||
let h = sha(tok);
|
||||
let mut found = None;
|
||||
for t in &self.tokens {
|
||||
// constant-time comparison over all tokens
|
||||
if ct_eq(&h, &t.hash) {
|
||||
found = Some((t.name.clone(), t.role));
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the local control token, creating it (random 256-bit, hex, mode 0640) if missing.
|
||||
pub fn ensure_control_token(path: &std::path::Path) -> Result<String, String> {
|
||||
if let Ok(t) = std::fs::read_to_string(path) {
|
||||
let t = t.trim().to_string();
|
||||
if t.len() >= 32 {
|
||||
return Ok(t);
|
||||
}
|
||||
}
|
||||
let mut raw = [0u8; 32];
|
||||
ring::rand::SecureRandom::fill(&ring::rand::SystemRandom::new(), &mut raw).map_err(|_| "random generator failed".to_string())?;
|
||||
let tok = data_encoding::HEXLOWER.encode(&raw);
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
}
|
||||
let tmp = path.with_extension("token.tmp");
|
||||
{
|
||||
use std::io::Write;
|
||||
let mut o = std::fs::OpenOptions::new();
|
||||
o.write(true).create(true).truncate(true);
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::OpenOptionsExt::mode(&mut o, 0o640);
|
||||
let mut f = o.open(&tmp).map_err(|e| format!("{}: {e}", tmp.display()))?;
|
||||
f.write_all(format!("{tok}\n").as_bytes()).map_err(|e| e.to_string())?;
|
||||
}
|
||||
std::fs::rename(&tmp, path).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
tracing::info!(path = %path.display(), "created local control token for the easydns CLI");
|
||||
Ok(tok)
|
||||
}
|
||||
|
||||
/// Constant-time equality for fixed-size digests.
|
||||
fn ct_eq(a: &[u8; 32], b: &[u8; 32]) -> bool {
|
||||
a.iter().zip(b.iter()).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
|
||||
}
|
||||
|
||||
pub fn error(status: StatusCode, msg: &str) -> Response {
|
||||
(status, axum::Json(serde_json::json!({ "error": { "status": status.as_u16(), "message": msg } }))).into_response()
|
||||
}
|
||||
|
||||
/// Middleware: ACL → rate limit → authentication → role check.
|
||||
pub async fn guard(State(st): State<Arc<ApiState>>, ConnectInfo(peer): ConnectInfo<SocketAddr>, mut req: Request, next: Next) -> Response {
|
||||
let ip = dns_policy::canonical_ip(peer.ip());
|
||||
let a = &st.auth;
|
||||
if !a.acl.contains(ip) {
|
||||
return error(StatusCode::FORBIDDEN, "client address not allowed");
|
||||
}
|
||||
if !a.check_rate(ip) {
|
||||
return error(StatusCode::TOO_MANY_REQUESTS, "rate limit exceeded");
|
||||
}
|
||||
let path = req.uri().path().to_string();
|
||||
let public = matches!(path.as_str(), "/healthz" | "/readyz" | "/api/v1/health");
|
||||
let caller = match a.identify(req.headers().get("authorization").and_then(|v| v.to_str().ok())) {
|
||||
Some((name, role)) => Caller { name, role, ip },
|
||||
None if public || !a.required => {
|
||||
Caller { name: "anonymous".into(), role: if a.required { Role::ReadOnly } else { Role::Admin }, ip }
|
||||
}
|
||||
None => return error(StatusCode::UNAUTHORIZED, "missing or invalid bearer token"),
|
||||
};
|
||||
let mutating = !matches!(*req.method(), Method::GET | Method::HEAD | Method::OPTIONS);
|
||||
if mutating && caller.role != Role::Admin {
|
||||
return error(StatusCode::FORBIDDEN, "admin role required");
|
||||
}
|
||||
req.extensions_mut().insert(caller);
|
||||
next.run(req).await
|
||||
}
|
||||
@@ -0,0 +1,798 @@
|
||||
//! Endpoint implementations.
|
||||
use std::collections::BTreeMap;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Extension, Path, Query, State};
|
||||
use axum::http::{HeaderMap, StatusCode, header};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use dns_authoritative::{ZoneEntry, ZoneKind};
|
||||
use dns_config::{ApiOverlay, Config, ZoneConfig, ZoneType};
|
||||
use dns_core::proto::rr::{Name, RData, Record, RecordType};
|
||||
use dns_server::Runtime;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::ApiState;
|
||||
use crate::auth::{Caller, error};
|
||||
|
||||
type St = State<Arc<ApiState>>;
|
||||
|
||||
fn ok(v: Value) -> Response {
|
||||
Json(v).into_response()
|
||||
}
|
||||
|
||||
fn zone_entry(st: &ApiState, zone: &str) -> Result<Arc<ZoneEntry>, Response> {
|
||||
let name = dns_core::names::parse_name(zone).map_err(|e| error(StatusCode::BAD_REQUEST, &e.to_string()))?;
|
||||
st.server.shared.rt().zones.get(&name).ok_or_else(|| error(StatusCode::NOT_FOUND, "zone not found"))
|
||||
}
|
||||
|
||||
fn audit(st: &ApiState, c: &Caller, action: &str, target: &str, result: &str, detail: &str) {
|
||||
st.server.shared.audit.record(&format!("api:{}@{}", c.name, c.ip), action, target, result, detail);
|
||||
}
|
||||
|
||||
fn record_id(r: &Record) -> String {
|
||||
let s = format!("{}|{}|{}", r.name.to_lowercase(), r.record_type(), r.data);
|
||||
crate::hash_token(&s)[..16].to_string()
|
||||
}
|
||||
|
||||
fn record_json(r: &Record) -> Value {
|
||||
json!({ "id": record_id(r), "name": r.name.to_string(), "type": r.record_type().to_string(), "ttl": r.ttl, "data": r.data.to_string() })
|
||||
}
|
||||
|
||||
fn etag(serial: u32) -> String {
|
||||
format!("\"{serial}\"")
|
||||
}
|
||||
|
||||
/// `If-Match` guard against lost updates.
|
||||
fn check_if_match(h: &HeaderMap, serial: u32) -> Result<(), Response> {
|
||||
match h.get(header::IF_MATCH).and_then(|v| v.to_str().ok()) {
|
||||
Some(v) if v.trim() != "*" && v.trim() != etag(serial) => {
|
||||
Err(error(StatusCode::PRECONDITION_FAILED, &format!("zone changed (current ETag {})", etag(serial))))
|
||||
}
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn zone_summary(e: &ZoneEntry) -> Value {
|
||||
let st = e.status();
|
||||
json!({
|
||||
"name": e.name.to_string(),
|
||||
"kind": e.kind,
|
||||
"views": e.views,
|
||||
"serial": st.serial,
|
||||
"loaded": st.loaded,
|
||||
"expired": st.expired,
|
||||
"records": st.records,
|
||||
"status": st,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn health(State(st): St) -> Response {
|
||||
let rt = st.server.shared.rt();
|
||||
let expired: Vec<String> = rt.zones.all().iter().filter(|z| z.is_expired()).map(|z| z.name.to_string()).collect();
|
||||
ok(json!({ "status": if expired.is_empty() { "ok" } else { "degraded" }, "expired_zones": expired }))
|
||||
}
|
||||
|
||||
pub async fn ready(State(st): St) -> Response {
|
||||
let rt = st.server.shared.rt();
|
||||
let not_loaded = rt.zones.all().iter().filter(|z| z.kind == ZoneKind::Primary && z.current().is_none()).count();
|
||||
if not_loaded == 0 {
|
||||
(StatusCode::OK, "ready\n").into_response()
|
||||
} else {
|
||||
(StatusCode::SERVICE_UNAVAILABLE, "zones not loaded\n").into_response()
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn status(State(st): St) -> Response {
|
||||
let s = &st.server.shared;
|
||||
let rt = s.rt();
|
||||
let roles = json!({
|
||||
"primary": rt.zones.all().iter().filter(|z| z.kind == ZoneKind::Primary).count(),
|
||||
"secondary": rt.zones.all().iter().filter(|z| z.kind == ZoneKind::Secondary).count(),
|
||||
"recursive": rt.resolver.is_some(),
|
||||
"forwarder": rt.router.default_pool.is_some() || !rt.router.rules.is_empty(),
|
||||
"forward_zones": rt.router.rules.len(),
|
||||
"default_resolution": rt.cfg.resolution.default,
|
||||
});
|
||||
ok(json!({
|
||||
"version": s.version,
|
||||
"mode": rt.cfg.server.mode,
|
||||
"uptime_seconds": s.started.elapsed().as_secs(),
|
||||
"listeners": st.server.bound,
|
||||
"roles": roles,
|
||||
"zones": rt.zones.all().iter().map(|z| zone_summary(z)).collect::<Vec<_>>(),
|
||||
"dnssec_validation": rt.cfg.recursion.dnssec_validation,
|
||||
}))
|
||||
}
|
||||
|
||||
pub async fn stats(State(st): St) -> Response {
|
||||
let s = &st.server.shared;
|
||||
let m = &s.metrics;
|
||||
let c = s.cache.stats();
|
||||
let total = c.hits + c.misses;
|
||||
ok(json!({
|
||||
"queries_total": m.total_queries(),
|
||||
"responses": { "noerror": m.rcode("NOERROR"), "nxdomain": m.rcode("NXDOMAIN"), "servfail": m.rcode("SERVFAIL"), "refused": m.rcode("REFUSED") },
|
||||
"sources": dns_metrics::SOURCES.iter().map(|x| (x.to_string(), m.source(x))).collect::<BTreeMap<_, _>>(),
|
||||
"latency_p50_s": m.latency.quantile(0.5), "latency_p95_s": m.latency.quantile(0.95), "latency_p99_s": m.latency.quantile(0.99),
|
||||
"cache": c,
|
||||
"cache_hit_rate": if total > 0 { c_hits(total, &s.cache) } else { 0.0 },
|
||||
"blocked": m.blocked.load(std::sync::atomic::Ordering::Relaxed),
|
||||
"rate_limited": m.rate_limited.load(std::sync::atomic::Ordering::Relaxed),
|
||||
"uptime_seconds": s.started.elapsed().as_secs(),
|
||||
}))
|
||||
}
|
||||
|
||||
fn c_hits(total: u64, c: &dns_cache::Cache) -> f64 {
|
||||
c.stats().hits as f64 / total as f64
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
pub struct Page {
|
||||
page: Option<usize>,
|
||||
per_page: Option<usize>,
|
||||
name: Option<String>,
|
||||
#[serde(rename = "type")]
|
||||
rtype: Option<String>,
|
||||
kind: Option<String>,
|
||||
}
|
||||
|
||||
fn paginate<T: Clone>(items: &[T], p: &Page) -> (Vec<T>, Value) {
|
||||
let per = p.per_page.unwrap_or(100).clamp(1, 1000);
|
||||
let page = p.page.unwrap_or(1).max(1);
|
||||
let start = (page - 1) * per;
|
||||
let slice = items.iter().skip(start).take(per).cloned().collect();
|
||||
(slice, json!({ "page": page, "per_page": per, "total": items.len() }))
|
||||
}
|
||||
|
||||
pub async fn zones_list(State(st): St, Query(p): Query<Page>) -> Response {
|
||||
let rt = st.server.shared.rt();
|
||||
let all: Vec<Value> = rt
|
||||
.zones
|
||||
.all()
|
||||
.iter()
|
||||
.filter(|z| p.kind.as_deref().is_none_or(|k| format!("{:?}", z.kind).eq_ignore_ascii_case(k)))
|
||||
.filter(|z| p.name.as_deref().is_none_or(|n| z.name.to_string().contains(&n.to_ascii_lowercase())))
|
||||
.map(|z| zone_summary(z))
|
||||
.collect();
|
||||
let (items, meta) = paginate(&all, &p);
|
||||
ok(json!({ "items": items, "pagination": meta }))
|
||||
}
|
||||
|
||||
pub async fn zone_show(State(st): St, Path(zone): Path<String>) -> Response {
|
||||
let e = match zone_entry(&st, &zone) {
|
||||
Ok(e) => e,
|
||||
Err(r) => return r,
|
||||
};
|
||||
let serial = e.current().map(|z| z.serial()).unwrap_or(0);
|
||||
let mut v = zone_summary(&e);
|
||||
v["config"] = serde_json::to_value(&e.config).unwrap_or(Value::Null);
|
||||
v["journal_entries"] = json!(e.journal.lock().map(|j| j.len()).unwrap_or(0));
|
||||
([(header::ETAG, etag(serial))], Json(v)).into_response()
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct NewZone {
|
||||
name: String,
|
||||
/// Full zone file text; alternatively give `ns` + `hostmaster` to generate a minimal zone.
|
||||
zone_file: Option<String>,
|
||||
#[serde(default)]
|
||||
ns: Vec<String>,
|
||||
hostmaster: Option<String>,
|
||||
#[serde(default)]
|
||||
transfer_acl: Vec<String>,
|
||||
#[serde(default)]
|
||||
notify: Vec<SocketAddr>,
|
||||
}
|
||||
|
||||
fn persist_overlay(cfg: &Config, o: &ApiOverlay) -> Result<(), Response> {
|
||||
let text = serde_norway::to_string(o).map_err(|e| error(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()))?;
|
||||
dns_core::zonefile::atomic_write(&cfg.overlay_path(), text.as_bytes())
|
||||
.map_err(|e| error(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()))
|
||||
}
|
||||
|
||||
fn reload(st: &ApiState) -> Result<dns_server::server::ReloadReport, Response> {
|
||||
st.server.reload().map_err(|e| error(StatusCode::UNPROCESSABLE_ENTITY, &format!("reload failed, previous configuration kept: {e}")))
|
||||
}
|
||||
|
||||
pub async fn zone_create(State(st): St, Extension(c): Extension<Caller>, Json(b): Json<NewZone>) -> Response {
|
||||
let rt = st.server.shared.rt();
|
||||
let name = match dns_core::names::parse_name(&b.name) {
|
||||
Ok(n) => n,
|
||||
Err(e) => return error(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
};
|
||||
if rt.zones.get(&name).is_some() {
|
||||
return error(StatusCode::CONFLICT, "zone already exists");
|
||||
}
|
||||
let text = match (&b.zone_file, b.ns.first()) {
|
||||
(Some(t), _) => t.clone(),
|
||||
(None, Some(_)) => {
|
||||
let hm = b.hostmaster.clone().unwrap_or_else(|| format!("hostmaster.{name}"));
|
||||
let mut t = format!("$TTL 3600\n@ IN SOA {} {} 1 3600 900 1209600 300\n", b.ns[0], hm);
|
||||
for ns in &b.ns {
|
||||
t.push_str(&format!("@ IN NS {ns}\n"));
|
||||
}
|
||||
t
|
||||
}
|
||||
_ => return error(StatusCode::BAD_REQUEST, "provide zone_file or ns"),
|
||||
};
|
||||
let records = match dns_core::zonefile::parse_str(&text, &name, None) {
|
||||
Ok(r) => r,
|
||||
Err(e) => return error(StatusCode::UNPROCESSABLE_ENTITY, &e.to_string()),
|
||||
};
|
||||
if let Err(e) = dns_authoritative::Zone::from_records(&name, records) {
|
||||
return error(StatusCode::UNPROCESSABLE_ENTITY, &e.to_string());
|
||||
}
|
||||
let file = rt.cfg.data_dir().join("zones").join(format!("{}zone", name.to_ascii()));
|
||||
if let Err(e) = dns_core::zonefile::atomic_write(&file, text.as_bytes()) {
|
||||
return error(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string());
|
||||
}
|
||||
let mut o = match rt.cfg.load_overlay() {
|
||||
Ok(o) => o,
|
||||
Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
|
||||
};
|
||||
o.zones.push(ZoneConfig {
|
||||
source: None,
|
||||
name: name.to_string(),
|
||||
zone_type: ZoneType::Primary,
|
||||
file: Some(file),
|
||||
transfer_acl: b.transfer_acl,
|
||||
transfer_tsig_key: None,
|
||||
notify: b.notify,
|
||||
notify_tsig_key: None,
|
||||
primaries: Vec::new(),
|
||||
transfer: Default::default(),
|
||||
allow_notify: Vec::new(),
|
||||
update_keys: Vec::new(),
|
||||
update_acl: Vec::new(),
|
||||
update_policy: Vec::new(),
|
||||
serial_strategy: Default::default(),
|
||||
views: Vec::new(),
|
||||
journal_size: 100,
|
||||
dnssec: None,
|
||||
});
|
||||
if let Err(r) = persist_overlay(&rt.cfg, &o) {
|
||||
return r;
|
||||
}
|
||||
match reload(&st) {
|
||||
Ok(_) => {
|
||||
audit(&st, &c, "zone-create", &name.to_string(), "ok", "");
|
||||
(StatusCode::CREATED, Json(json!({ "name": name.to_string() }))).into_response()
|
||||
}
|
||||
Err(r) => {
|
||||
o.zones.retain(|z| z.name != name.to_string());
|
||||
let _ = persist_overlay(&rt.cfg, &o);
|
||||
audit(&st, &c, "zone-create", &name.to_string(), "failed", "");
|
||||
r
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct ReplaceZone {
|
||||
zone_file: String,
|
||||
}
|
||||
|
||||
/// Replace the full contents of a primary zone (serial is bumped automatically).
|
||||
pub async fn zone_replace(
|
||||
State(st): St,
|
||||
Extension(c): Extension<Caller>,
|
||||
Path(zone): Path<String>,
|
||||
h: HeaderMap,
|
||||
Json(b): Json<ReplaceZone>,
|
||||
) -> Response {
|
||||
let e = match zone_entry(&st, &zone) {
|
||||
Ok(e) => e,
|
||||
Err(r) => return r,
|
||||
};
|
||||
let Some(cur) = e.current() else { return error(StatusCode::SERVICE_UNAVAILABLE, "zone not loaded") };
|
||||
if let Err(r) = check_if_match(&h, cur.serial()) {
|
||||
return r;
|
||||
}
|
||||
let recs = match dns_core::zonefile::parse_str(&b.zone_file, &e.name, None) {
|
||||
Ok(r) => r,
|
||||
Err(err) => return error(StatusCode::UNPROCESSABLE_ENTITY, &err.to_string()),
|
||||
};
|
||||
let new = match dns_authoritative::Zone::from_records(&e.name, recs) {
|
||||
Ok(z) => z,
|
||||
Err(err) => return error(StatusCode::UNPROCESSABLE_ENTITY, &err.to_string()),
|
||||
};
|
||||
let (rm, add) = cur.diff(&new);
|
||||
match e.modify(&rm, &add) {
|
||||
Ok(serial) => {
|
||||
e.send_notifies();
|
||||
audit(&st, &c, "zone-replace", &e.name.to_string(), "ok", &format!("+{} -{} serial {serial}", add.len(), rm.len()));
|
||||
([(header::ETAG, etag(serial))], Json(json!({ "serial": serial, "added": add.len(), "removed": rm.len() }))).into_response()
|
||||
}
|
||||
Err(err) => error(StatusCode::UNPROCESSABLE_ENTITY, &err),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn zone_delete(State(st): St, Extension(c): Extension<Caller>, Path(zone): Path<String>) -> Response {
|
||||
let e = match zone_entry(&st, &zone) {
|
||||
Ok(e) => e,
|
||||
Err(r) => return r,
|
||||
};
|
||||
let rt = st.server.shared.rt();
|
||||
let mut o = match rt.cfg.load_overlay() {
|
||||
Ok(o) => o,
|
||||
Err(err) => return error(StatusCode::INTERNAL_SERVER_ERROR, &err.to_string()),
|
||||
};
|
||||
let before = o.zones.len();
|
||||
o.zones.retain(|z| dns_core::names::parse_name(&z.name).ok().as_ref() != Some(&e.name));
|
||||
if o.zones.len() == before {
|
||||
return error(StatusCode::CONFLICT, "zone is defined in the configuration file; remove it there");
|
||||
}
|
||||
if let Err(r) = persist_overlay(&rt.cfg, &o) {
|
||||
return r;
|
||||
}
|
||||
match reload(&st) {
|
||||
Ok(_) => {
|
||||
audit(&st, &c, "zone-delete", &e.name.to_string(), "ok", "");
|
||||
StatusCode::NO_CONTENT.into_response()
|
||||
}
|
||||
Err(r) => r,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn records_list(State(st): St, Path(zone): Path<String>, Query(p): Query<Page>) -> Response {
|
||||
let e = match zone_entry(&st, &zone) {
|
||||
Ok(e) => e,
|
||||
Err(r) => return r,
|
||||
};
|
||||
let Some(z) = e.current() else { return error(StatusCode::SERVICE_UNAVAILABLE, "zone not loaded or expired") };
|
||||
let want_type = p.rtype.as_deref().map(|t| t.to_ascii_uppercase());
|
||||
let all: Vec<Value> = z
|
||||
.all_records()
|
||||
.iter()
|
||||
.filter(|r| p.name.as_deref().is_none_or(|n| r.name.to_string().to_ascii_lowercase().starts_with(&n.to_ascii_lowercase())))
|
||||
.filter(|r| want_type.as_deref().is_none_or(|t| r.record_type().to_string() == t))
|
||||
.map(record_json)
|
||||
.collect();
|
||||
let (items, meta) = paginate(&all, &p);
|
||||
([(header::ETAG, etag(z.serial()))], Json(json!({ "items": items, "pagination": meta, "serial": z.serial() }))).into_response()
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct RecordBody {
|
||||
name: String,
|
||||
#[serde(rename = "type")]
|
||||
rtype: String,
|
||||
#[serde(default = "default_ttl")]
|
||||
ttl: u32,
|
||||
data: String,
|
||||
}
|
||||
|
||||
fn default_ttl() -> u32 {
|
||||
3600
|
||||
}
|
||||
|
||||
fn build_record(zone: &Name, b: &RecordBody) -> Result<Record, Response> {
|
||||
let name = if b.name == "@" {
|
||||
zone.clone()
|
||||
} else if b.name.ends_with('.') {
|
||||
dns_core::names::parse_name(&b.name).map_err(|e| error(StatusCode::BAD_REQUEST, &e.to_string()))?
|
||||
} else {
|
||||
dns_core::names::parse_name(&format!("{}.{}", b.name, zone)).map_err(|e| error(StatusCode::BAD_REQUEST, &e.to_string()))?
|
||||
};
|
||||
if !zone.zone_of(&name) {
|
||||
return Err(error(StatusCode::BAD_REQUEST, "record name outside zone"));
|
||||
}
|
||||
let rtype: RecordType = b.rtype.to_ascii_uppercase().parse().map_err(|_| error(StatusCode::BAD_REQUEST, "unknown record type"))?;
|
||||
if matches!(rtype, RecordType::SOA) {
|
||||
return Err(error(StatusCode::BAD_REQUEST, "SOA is managed automatically; use PUT /zones/{zone}"));
|
||||
}
|
||||
let data = RData::try_from_str(rtype, &b.data).map_err(|e| error(StatusCode::BAD_REQUEST, &format!("invalid {rtype} data: {e}")))?;
|
||||
let data = match data {
|
||||
// relative names in RDATA are made absolute against the zone
|
||||
RData::CNAME(c) if !c.0.is_fqdn() => RData::CNAME(dns_core::proto::rr::rdata::CNAME(
|
||||
c.0.append_domain(zone).map_err(|e| error(StatusCode::BAD_REQUEST, &e.to_string()))?,
|
||||
)),
|
||||
other => other,
|
||||
};
|
||||
Ok(Record::from_rdata(name, b.ttl, data))
|
||||
}
|
||||
|
||||
fn find_record(e: &ZoneEntry, id: &str) -> Option<Record> {
|
||||
e.current()?.all_records().into_iter().find(|r| record_id(r) == id && r.record_type() != RecordType::SOA)
|
||||
}
|
||||
|
||||
async fn change(
|
||||
st: &ApiState,
|
||||
c: &Caller,
|
||||
e: &Arc<ZoneEntry>,
|
||||
h: &HeaderMap,
|
||||
removed: Vec<Record>,
|
||||
added: Vec<Record>,
|
||||
action: &str,
|
||||
) -> Response {
|
||||
let Some(cur) = e.current() else { return error(StatusCode::SERVICE_UNAVAILABLE, "zone not loaded") };
|
||||
if e.kind != ZoneKind::Primary {
|
||||
return error(StatusCode::CONFLICT, "records can only be changed on primary zones");
|
||||
}
|
||||
if let Err(r) = check_if_match(h, cur.serial()) {
|
||||
return r;
|
||||
}
|
||||
match e.modify(&removed, &added) {
|
||||
Ok(serial) => {
|
||||
e.send_notifies();
|
||||
audit(st, c, action, &e.name.to_string(), "ok", &format!("+{} -{} serial {serial}", added.len(), removed.len()));
|
||||
let body = json!({ "serial": serial, "records": added.iter().map(record_json).collect::<Vec<_>>() });
|
||||
let status = if action == "record-add" { StatusCode::CREATED } else { StatusCode::OK };
|
||||
(status, [(header::ETAG, etag(serial))], Json(body)).into_response()
|
||||
}
|
||||
Err(err) => {
|
||||
audit(st, c, action, &e.name.to_string(), "rejected", &err);
|
||||
error(StatusCode::UNPROCESSABLE_ENTITY, &err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn record_add(
|
||||
State(st): St,
|
||||
Extension(c): Extension<Caller>,
|
||||
Path(zone): Path<String>,
|
||||
h: HeaderMap,
|
||||
Json(b): Json<RecordBody>,
|
||||
) -> Response {
|
||||
let e = match zone_entry(&st, &zone) {
|
||||
Ok(e) => e,
|
||||
Err(r) => return r,
|
||||
};
|
||||
let rec = match build_record(&e.name, &b) {
|
||||
Ok(r) => r,
|
||||
Err(r) => return r,
|
||||
};
|
||||
change(&st, &c, &e, &h, vec![], vec![rec], "record-add").await
|
||||
}
|
||||
|
||||
pub async fn record_update(
|
||||
State(st): St,
|
||||
Extension(c): Extension<Caller>,
|
||||
Path((zone, id)): Path<(String, String)>,
|
||||
h: HeaderMap,
|
||||
Json(b): Json<RecordBody>,
|
||||
) -> Response {
|
||||
let e = match zone_entry(&st, &zone) {
|
||||
Ok(e) => e,
|
||||
Err(r) => return r,
|
||||
};
|
||||
let Some(old) = find_record(&e, &id) else { return error(StatusCode::NOT_FOUND, "record not found") };
|
||||
let rec = match build_record(&e.name, &b) {
|
||||
Ok(r) => r,
|
||||
Err(r) => return r,
|
||||
};
|
||||
change(&st, &c, &e, &h, vec![old], vec![rec], "record-update").await
|
||||
}
|
||||
|
||||
pub async fn record_delete(
|
||||
State(st): St,
|
||||
Extension(c): Extension<Caller>,
|
||||
Path((zone, id)): Path<(String, String)>,
|
||||
h: HeaderMap,
|
||||
) -> Response {
|
||||
let e = match zone_entry(&st, &zone) {
|
||||
Ok(e) => e,
|
||||
Err(r) => return r,
|
||||
};
|
||||
let Some(old) = find_record(&e, &id) else { return error(StatusCode::NOT_FOUND, "record not found") };
|
||||
change(&st, &c, &e, &h, vec![old], vec![], "record-delete").await
|
||||
}
|
||||
|
||||
pub async fn zone_notify(State(st): St, Extension(c): Extension<Caller>, Path(zone): Path<String>) -> Response {
|
||||
let e = match zone_entry(&st, &zone) {
|
||||
Ok(e) => e,
|
||||
Err(r) => return r,
|
||||
};
|
||||
if e.config.notify.is_empty() {
|
||||
return error(StatusCode::CONFLICT, "zone has no notify targets");
|
||||
}
|
||||
e.send_notifies();
|
||||
audit(&st, &c, "zone-notify", &e.name.to_string(), "ok", "");
|
||||
(StatusCode::ACCEPTED, Json(json!({ "targets": e.config.notify }))).into_response()
|
||||
}
|
||||
|
||||
pub async fn zone_sync(State(st): St, Extension(c): Extension<Caller>, Path(zone): Path<String>) -> Response {
|
||||
let e = match zone_entry(&st, &zone) {
|
||||
Ok(e) => e,
|
||||
Err(r) => return r,
|
||||
};
|
||||
if e.kind != ZoneKind::Secondary {
|
||||
return error(StatusCode::CONFLICT, "sync is only valid for secondary zones");
|
||||
}
|
||||
let res = dns_authoritative::secondary::refresh_once(&e).await;
|
||||
if res.is_ok() {
|
||||
e.set_expired(false);
|
||||
e.update_status(|s| {
|
||||
s.last_success_unix = Some(dns_core::tsig::now());
|
||||
s.last_error = None;
|
||||
});
|
||||
}
|
||||
audit(&st, &c, "zone-sync", &e.name.to_string(), if res.is_ok() { "ok" } else { "failed" }, "");
|
||||
match res {
|
||||
Ok(o) => ok(json!({ "result": format!("{o:?}"), "serial": e.current().map(|z| z.serial()) })),
|
||||
Err(err) => error(StatusCode::BAD_GATEWAY, &err),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn zone_transfers(State(st): St, Path(zone): Path<String>) -> Response {
|
||||
match zone_entry(&st, &zone) {
|
||||
Ok(e) => ok(json!({ "items": e.transfers() })),
|
||||
Err(r) => r,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn cache_stats(State(st): St) -> Response {
|
||||
ok(serde_json::to_value(st.server.shared.cache.stats()).unwrap_or(Value::Null))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct CacheClear {
|
||||
domain: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn cache_clear(State(st): St, Extension(c): Extension<Caller>, Query(q): Query<CacheClear>) -> Response {
|
||||
let cache = &st.server.shared.cache;
|
||||
let removed = match &q.domain {
|
||||
Some(d) => match dns_core::names::parse_name(d) {
|
||||
Ok(n) => cache.clear_domain(&n),
|
||||
Err(e) => return error(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
},
|
||||
None => cache.clear(),
|
||||
};
|
||||
// encoded answers may contain the flushed data
|
||||
st.server.shared.packet_cache.invalidate();
|
||||
audit(&st, &c, "cache-clear", q.domain.as_deref().unwrap_or("*"), "ok", &format!("{removed} entries"));
|
||||
ok(json!({ "removed": removed }))
|
||||
}
|
||||
|
||||
pub async fn upstreams_list(State(st): St) -> Response {
|
||||
let rt = st.server.shared.rt();
|
||||
let mut groups = Vec::new();
|
||||
if let Some(p) = &rt.router.default_pool {
|
||||
groups.push(json!({ "group": "default", "strategy": p.strategy, "servers": p.stats().into_iter().map(|(a, s)| json!({"address": a, "stats": s})).collect::<Vec<_>>() }));
|
||||
}
|
||||
for r in &rt.router.rules {
|
||||
groups.push(json!({ "group": r.suffix.to_string(), "strategy": r.pool.strategy, "servers": r.pool.stats().into_iter().map(|(a, s)| json!({"address": a, "stats": s})).collect::<Vec<_>>() }));
|
||||
}
|
||||
ok(json!({ "items": groups }))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct NewUpstream {
|
||||
address: String,
|
||||
}
|
||||
|
||||
pub async fn upstreams_add(State(st): St, Extension(c): Extension<Caller>, Json(b): Json<NewUpstream>) -> Response {
|
||||
if let Err(e) = dns_config::upstream::UpstreamAddr::parse(&b.address) {
|
||||
return error(StatusCode::BAD_REQUEST, &e);
|
||||
}
|
||||
let rt = st.server.shared.rt();
|
||||
let mut o = match rt.cfg.load_overlay() {
|
||||
Ok(o) => o,
|
||||
Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
|
||||
};
|
||||
if !o.upstreams.contains(&b.address) {
|
||||
o.upstreams.push(b.address.clone());
|
||||
}
|
||||
if let Err(r) = persist_overlay(&rt.cfg, &o) {
|
||||
return r;
|
||||
}
|
||||
match reload(&st) {
|
||||
Ok(_) => {
|
||||
audit(&st, &c, "upstream-add", &b.address, "ok", "");
|
||||
(StatusCode::CREATED, Json(json!({ "address": b.address }))).into_response()
|
||||
}
|
||||
Err(r) => r,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn policies_get(State(st): St) -> Response {
|
||||
let cfg = st.server.shared.rt().cfg.clone();
|
||||
ok(json!({
|
||||
"recursion_allowed_clients": cfg.recursion.allowed_clients,
|
||||
"acls": cfg.acls,
|
||||
"views": cfg.resolution.views,
|
||||
"rate_limit": cfg.rate_limit,
|
||||
"policy": cfg.policy,
|
||||
"api_allowed_clients": cfg.api.allowed_clients,
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct PolicyPut {
|
||||
allowlist: Option<Vec<String>>,
|
||||
block_action: Option<dns_config::BlockAction>,
|
||||
}
|
||||
|
||||
pub async fn policies_put(State(st): St, Extension(c): Extension<Caller>, Json(b): Json<PolicyPut>) -> Response {
|
||||
let rt = st.server.shared.rt();
|
||||
let mut o = match rt.cfg.load_overlay() {
|
||||
Ok(o) => o,
|
||||
Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
|
||||
};
|
||||
if b.allowlist.is_some() {
|
||||
o.allowlist = b.allowlist;
|
||||
}
|
||||
if b.block_action.is_some() {
|
||||
o.block_action = b.block_action;
|
||||
}
|
||||
if let Err(r) = persist_overlay(&rt.cfg, &o) {
|
||||
return r;
|
||||
}
|
||||
match reload(&st) {
|
||||
Ok(_) => {
|
||||
audit(&st, &c, "policy-update", "policy", "ok", "");
|
||||
policies_get(State(st)).await
|
||||
}
|
||||
Err(r) => r,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn blocklists_get(State(st): St) -> Response {
|
||||
let rt = st.server.shared.rt();
|
||||
ok(json!({ "lists": rt.cfg.policy.blocklists, "loaded": rt.policy.list_names(), "rules": rt.policy.rule_count() }))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct NewRule {
|
||||
rule: String,
|
||||
}
|
||||
|
||||
pub async fn blocklists_add(State(st): St, Extension(c): Extension<Caller>, Json(b): Json<NewRule>) -> Response {
|
||||
let rt = st.server.shared.rt();
|
||||
let rule = b.rule.trim().to_string();
|
||||
if rule.is_empty() || rule.contains('\n') {
|
||||
return error(StatusCode::BAD_REQUEST, "invalid rule");
|
||||
}
|
||||
let mut test = dns_policy::BlockPolicy::default();
|
||||
if let Err(e) = test.add_rule("api", &rule) {
|
||||
return error(StatusCode::BAD_REQUEST, &e);
|
||||
}
|
||||
let mut o = match rt.cfg.load_overlay() {
|
||||
Ok(o) => o,
|
||||
Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
|
||||
};
|
||||
if !o.block_rules.contains(&rule) {
|
||||
o.block_rules.push(rule.clone());
|
||||
}
|
||||
let file = rt.cfg.data_dir().join("blocklists").join("api.txt");
|
||||
if let Err(e) = dns_core::zonefile::atomic_write(&file, (o.block_rules.join("\n") + "\n").as_bytes()) {
|
||||
return error(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string());
|
||||
}
|
||||
if let Err(r) = persist_overlay(&rt.cfg, &o) {
|
||||
return r;
|
||||
}
|
||||
match reload(&st) {
|
||||
Ok(_) => {
|
||||
audit(&st, &c, "blocklist-add", &rule, "ok", "");
|
||||
(StatusCode::CREATED, Json(json!({ "rule": rule }))).into_response()
|
||||
}
|
||||
Err(r) => r,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn config_reload(State(st): St, Extension(c): Extension<Caller>) -> Response {
|
||||
match st.server.reload() {
|
||||
Ok(rep) => {
|
||||
audit(&st, &c, "config-reload", "config", "ok", &format!("{rep:?}"));
|
||||
ok(serde_json::to_value(rep).unwrap_or(Value::Null))
|
||||
}
|
||||
Err(e) => {
|
||||
audit(&st, &c, "config-reload", "config", "failed", &e);
|
||||
error(StatusCode::UNPROCESSABLE_ENTITY, &format!("reload failed, previous configuration kept: {e}"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct AuditQ {
|
||||
n: Option<usize>,
|
||||
}
|
||||
|
||||
pub async fn audit_tail(State(st): St, Query(q): Query<AuditQ>) -> Response {
|
||||
ok(json!({ "items": st.server.shared.audit.tail(q.n.unwrap_or(100).min(10_000)) }))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct DnsQ {
|
||||
name: String,
|
||||
#[serde(rename = "type")]
|
||||
rtype: Option<String>,
|
||||
}
|
||||
|
||||
/// Run a query through this server (convenience for `easydns query`).
|
||||
pub async fn api_query(State(st): St, Query(q): Query<DnsQ>) -> Response {
|
||||
let Some(mut addr) = st.server.bound.dns.first().copied() else { return error(StatusCode::SERVICE_UNAVAILABLE, "no DNS listener") };
|
||||
if addr.ip().is_unspecified() {
|
||||
addr.set_ip(if addr.is_ipv4() { [127, 0, 0, 1].into() } else { std::net::Ipv6Addr::LOCALHOST.into() });
|
||||
}
|
||||
let name = match dns_core::names::parse_name(&q.name) {
|
||||
Ok(n) => n,
|
||||
Err(e) => return error(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
};
|
||||
let t: RecordType = q.rtype.as_deref().unwrap_or("A").to_ascii_uppercase().parse().unwrap_or(RecordType::A);
|
||||
match dns_core::client::query(addr, &name, t, &Default::default()).await {
|
||||
Ok(ex) => ok(json!({
|
||||
"rcode": rcode_name(ex.message.metadata.response_code),
|
||||
"aa": ex.message.metadata.authoritative,
|
||||
"answers": ex.message.answers.iter().map(record_json).collect::<Vec<_>>(),
|
||||
"authority": ex.message.authorities.iter().map(record_json).collect::<Vec<_>>(),
|
||||
"elapsed_ms": ex.elapsed.as_secs_f64() * 1000.0,
|
||||
})),
|
||||
Err(e) => error(StatusCode::BAD_GATEWAY, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn rcode_name(r: dns_core::proto::op::ResponseCode) -> String {
|
||||
use dns_core::proto::op::ResponseCode as R;
|
||||
match r {
|
||||
R::NoError => "NOERROR".into(),
|
||||
R::NXDomain => "NXDOMAIN".into(),
|
||||
R::ServFail => "SERVFAIL".into(),
|
||||
R::Refused => "REFUSED".into(),
|
||||
R::FormErr => "FORMERR".into(),
|
||||
R::NotImp => "NOTIMP".into(),
|
||||
other => format!("RCODE{}", u16::from(other)),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn openapi() -> Response {
|
||||
let eps: &[(&str, &[&str], &str)] = &[
|
||||
("/status", &["get"], "Service and role status"),
|
||||
("/stats", &["get"], "Counters and statistics"),
|
||||
("/zones", &["get", "post"], "List / create zones"),
|
||||
("/zones/{zone}", &["get", "put", "delete"], "Zone details / replace contents / delete API-created zone"),
|
||||
("/zones/{zone}/records", &["get", "post"], "List (paginated, filter by name/type) / add records"),
|
||||
("/zones/{zone}/records/{id}", &["put", "delete"], "Replace / delete a record (If-Match supported)"),
|
||||
("/zones/{zone}/notify", &["post"], "Send NOTIFY to secondaries"),
|
||||
("/zones/{zone}/sync", &["post"], "Refresh a secondary zone now"),
|
||||
("/zones/{zone}/transfers", &["get"], "Transfer history"),
|
||||
("/cache", &["get", "delete"], "Cache statistics / flush (optionally ?domain=)"),
|
||||
("/upstreams", &["get", "post"], "Upstream status / add an upstream"),
|
||||
("/policies", &["get", "put"], "ACLs, views, rate limits, allowlist / block action"),
|
||||
("/blocklists", &["get", "post"], "Block lists / add a rule"),
|
||||
("/config/reload", &["post"], "Hot reload with rollback"),
|
||||
("/audit", &["get"], "Audit log tail"),
|
||||
("/query", &["get"], "Resolve through this server"),
|
||||
("/health", &["get"], "Health check (no auth)"),
|
||||
];
|
||||
let mut paths = serde_json::Map::new();
|
||||
for (p, methods, desc) in eps {
|
||||
let mut m = serde_json::Map::new();
|
||||
for meth in *methods {
|
||||
m.insert((*meth).into(), json!({ "summary": desc, "security": [{"bearer": []}],
|
||||
"responses": { "200": {"description": "OK"}, "401": {"description": "Unauthorized"}, "403": {"description": "Forbidden"} } }));
|
||||
}
|
||||
paths.insert(format!("/api/v1{p}"), Value::Object(m));
|
||||
}
|
||||
ok(json!({
|
||||
"openapi": "3.0.3",
|
||||
"info": { "title": "EasyDNS API", "version": env!("CARGO_PKG_VERSION") },
|
||||
"components": { "securitySchemes": { "bearer": { "type": "http", "scheme": "bearer" } } },
|
||||
"paths": paths,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Per-zone gauges (cardinality bounded by the number of configured zones).
|
||||
pub fn zone_metrics(rt: &Runtime) -> String {
|
||||
let mut s = String::from("# HELP dns_zone_serial Current SOA serial per zone\n# TYPE dns_zone_serial gauge\n");
|
||||
for z in rt.zones.all() {
|
||||
if let Some(cur) = z.snapshot_any() {
|
||||
s.push_str(&format!("dns_zone_serial{{zone=\"{}\",role=\"{:?}\"}} {}\n", z.name, z.kind, cur.serial()));
|
||||
}
|
||||
}
|
||||
s.push_str("# HELP dns_zone_expired Secondary zone expired (1) or not (0)\n# TYPE dns_zone_expired gauge\n");
|
||||
for z in rt.zones.all().iter().filter(|z| z.kind == ZoneKind::Secondary) {
|
||||
s.push_str(&format!("dns_zone_expired{{zone=\"{}\"}} {}\n", z.name, u8::from(z.is_expired())));
|
||||
}
|
||||
s.push_str("# HELP dns_zone_last_sync_timestamp_seconds Last successful refresh of a secondary zone\n# TYPE dns_zone_last_sync_timestamp_seconds gauge\n");
|
||||
for z in rt.zones.all().iter().filter(|z| z.kind == ZoneKind::Secondary) {
|
||||
if let Some(t) = z.status().last_success_unix {
|
||||
s.push_str(&format!("dns_zone_last_sync_timestamp_seconds{{zone=\"{}\"}} {t}\n", z.name));
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
//! REST API (`/api/v1`), health endpoints and the Prometheus `/metrics` listener.
|
||||
//!
|
||||
//! * Listens on loopback by default; `api.allowed_clients` is enforced per request.
|
||||
//! * Bearer tokens with roles `admin` / `read-only`; tokens are configured as references
|
||||
//! (`env:`, `file:`) or as `sha256:<hex>` hashes and compared in constant time.
|
||||
//! * Every state-changing call is audited; record changes support `If-Match` (zone serial ETag).
|
||||
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
|
||||
// Handlers return `Result<_, axum::Response>`; boxing the error would only add noise.
|
||||
#![allow(clippy::result_large_err)]
|
||||
|
||||
mod auth;
|
||||
mod handlers;
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::Router;
|
||||
use axum::routing::{get, post, put};
|
||||
use dns_server::ServerHandle;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::sync::watch;
|
||||
|
||||
pub use auth::{Auth, Role, hash_token};
|
||||
|
||||
/// Shared API state.
|
||||
pub struct ApiState {
|
||||
pub server: Arc<ServerHandle>,
|
||||
pub auth: auth::Auth,
|
||||
}
|
||||
|
||||
/// Build the API router.
|
||||
pub fn router(state: Arc<ApiState>) -> Router {
|
||||
use handlers::*;
|
||||
let v1 = Router::new()
|
||||
.route("/status", get(status))
|
||||
.route("/stats", get(stats))
|
||||
.route("/zones", get(zones_list).post(zone_create))
|
||||
.route("/zones/{zone}", get(zone_show).put(zone_replace).delete(zone_delete))
|
||||
.route("/zones/{zone}/records", get(records_list).post(record_add))
|
||||
.route("/zones/{zone}/records/{id}", put(record_update).delete(record_delete))
|
||||
.route("/zones/{zone}/notify", post(zone_notify))
|
||||
.route("/zones/{zone}/sync", post(zone_sync))
|
||||
.route("/zones/{zone}/transfers", get(zone_transfers))
|
||||
.route("/cache", get(cache_stats).delete(cache_clear))
|
||||
.route("/upstreams", get(upstreams_list).post(upstreams_add))
|
||||
.route("/policies", get(policies_get).put(policies_put))
|
||||
.route("/blocklists", get(blocklists_get).post(blocklists_add))
|
||||
.route("/config/reload", post(config_reload))
|
||||
.route("/audit", get(audit_tail))
|
||||
.route("/query", get(api_query))
|
||||
.route("/health", get(health))
|
||||
.route("/openapi.json", get(openapi));
|
||||
Router::new()
|
||||
.nest("/api/v1", v1)
|
||||
.route("/healthz", get(health))
|
||||
.route("/readyz", get(ready))
|
||||
.layer(axum::middleware::from_fn_with_state(Arc::clone(&state), auth::guard))
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
/// Serve the API until shutdown. Returns the bound address.
|
||||
pub async fn serve_api(state: Arc<ApiState>, addr: SocketAddr, mut shutdown: watch::Receiver<bool>) -> Result<SocketAddr, String> {
|
||||
let l = TcpListener::bind(addr).await.map_err(|e| format!("bind API {addr}: {e}"))?;
|
||||
let bound = l.local_addr().map_err(|e| e.to_string())?;
|
||||
let app = router(state).into_make_service_with_connect_info::<SocketAddr>();
|
||||
tokio::spawn(async move {
|
||||
let _ = axum::serve(l, app)
|
||||
.with_graceful_shutdown(async move {
|
||||
let _ = shutdown.changed().await;
|
||||
})
|
||||
.await;
|
||||
});
|
||||
tracing::info!(%bound, "REST API listening");
|
||||
Ok(bound)
|
||||
}
|
||||
|
||||
/// Serve `/metrics` (Prometheus text format) until shutdown.
|
||||
pub async fn serve_metrics(server: Arc<ServerHandle>, addr: SocketAddr, mut shutdown: watch::Receiver<bool>) -> Result<SocketAddr, String> {
|
||||
let l = TcpListener::bind(addr).await.map_err(|e| format!("bind metrics {addr}: {e}"))?;
|
||||
let bound = l.local_addr().map_err(|e| e.to_string())?;
|
||||
let app = Router::new()
|
||||
.route(
|
||||
"/metrics",
|
||||
get(move || {
|
||||
let s = Arc::clone(&server);
|
||||
async move {
|
||||
let shared = &s.shared;
|
||||
let mut extra = shared.cache.render_metrics();
|
||||
extra.push_str(&handlers::zone_metrics(&shared.rt()));
|
||||
extra.push_str(&shared.packet_cache.render_metrics());
|
||||
([(axum::http::header::CONTENT_TYPE, "text/plain; version=0.0.4")], shared.metrics.render(&extra))
|
||||
}
|
||||
}),
|
||||
)
|
||||
.route("/healthz", get(|| async { "ok\n" }));
|
||||
tokio::spawn(async move {
|
||||
let _ = axum::serve(l, app)
|
||||
.with_graceful_shutdown(async move {
|
||||
let _ = shutdown.changed().await;
|
||||
})
|
||||
.await;
|
||||
});
|
||||
tracing::info!(%bound, "metrics listening");
|
||||
Ok(bound)
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
//! REST API: authentication, roles, record management with ETags, zone lifecycle, reload.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used)]
|
||||
|
||||
use std::io::{Read, Write};
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn http(addr: SocketAddr, method: &str, path: &str, token: Option<&str>, body: Option<Value>, extra: &str) -> (u16, Value, String) {
|
||||
let mut s = std::net::TcpStream::connect(addr).unwrap();
|
||||
let body = body.map(|b| b.to_string()).unwrap_or_default();
|
||||
let mut req = format!("{method} {path} HTTP/1.1\r\nHost: x\r\nConnection: close\r\n{extra}");
|
||||
if let Some(t) = token {
|
||||
req.push_str(&format!("Authorization: Bearer {t}\r\n"));
|
||||
}
|
||||
req.push_str(&format!("Content-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}", body.len()));
|
||||
s.write_all(req.as_bytes()).unwrap();
|
||||
let mut buf = Vec::new();
|
||||
s.read_to_end(&mut buf).unwrap();
|
||||
let text = String::from_utf8_lossy(&buf).to_string();
|
||||
let status = text.split_whitespace().nth(1).unwrap().parse().unwrap();
|
||||
let (head, body) = text.split_once("\r\n\r\n").unwrap();
|
||||
// axum may use chunked encoding
|
||||
let body = if head.to_ascii_lowercase().contains("transfer-encoding: chunked") {
|
||||
let mut out = String::new();
|
||||
let mut rest = body;
|
||||
while let Some((size, tail)) = rest.split_once("\r\n") {
|
||||
let n = usize::from_str_radix(size.trim(), 16).unwrap_or(0);
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
out.push_str(&tail[..n]);
|
||||
rest = &tail[n + 2..];
|
||||
}
|
||||
out
|
||||
} else {
|
||||
body.to_string()
|
||||
};
|
||||
(status, serde_json::from_str(&body).unwrap_or(Value::Null), head.to_string())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn api_end_to_end() {
|
||||
let dir = std::env::temp_dir().join(format!("easydns-api-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("z.zone"), "$TTL 60\n@ IN SOA ns hm 1 3600 600 86400 60\n@ IN NS ns\nns IN A 127.0.0.1\n").unwrap();
|
||||
std::fs::write(dir.join("admin.token"), "admin-secret").unwrap();
|
||||
let ro_hash = dns_api::hash_token("reader-secret");
|
||||
let yaml = format!(
|
||||
r#"
|
||||
server: {{ listen: ["127.0.0.1:0"], data_dir: data }}
|
||||
api: {{ listen: "127.0.0.1:0", tokens: [ {{ name: admin, role: admin, token: "file:admin.token" }}, {{ name: ro, role: read-only, token: "sha256:{ro_hash}" }} ] }}
|
||||
zones: [ {{ name: example.test, type: primary, file: z.zone }} ]
|
||||
"#
|
||||
);
|
||||
std::fs::write(dir.join("config.yaml"), &yaml).unwrap();
|
||||
let cfg = dns_config::Config::load(&dir.join("config.yaml")).unwrap();
|
||||
let auth = dns_api::Auth::from_config(&cfg).unwrap();
|
||||
let server = Arc::new(dns_server::Server::start(cfg.clone(), Some(dir.join("config.yaml")), Default::default()).await.unwrap());
|
||||
let st = Arc::new(dns_api::ApiState { server: Arc::clone(&server), auth });
|
||||
let api = dns_api::serve_api(st, cfg.api.listen, server.shutdown_signal()).await.unwrap();
|
||||
let a = |m: &'static str, p: String, t: Option<&'static str>, b: Option<Value>, e: &'static str| {
|
||||
let p = p.clone();
|
||||
tokio::task::spawn_blocking(move || http(api, m, &p, t, b, e))
|
||||
};
|
||||
|
||||
// health is public, everything else needs a token
|
||||
assert_eq!(a("GET", "/healthz".into(), None, None, "").await.unwrap().0, 200);
|
||||
assert_eq!(a("GET", "/api/v1/zones".into(), None, None, "").await.unwrap().0, 401);
|
||||
assert_eq!(a("GET", "/api/v1/zones".into(), Some("wrong"), None, "").await.unwrap().0, 401);
|
||||
let (s, v, _) = a("GET", "/api/v1/zones".into(), Some("reader-secret"), None, "").await.unwrap();
|
||||
assert_eq!((s, v["pagination"]["total"].as_u64()), (200, Some(1)));
|
||||
// read-only cannot modify
|
||||
let rec = json!({"name": "www", "type": "A", "ttl": 120, "data": "192.0.2.5"});
|
||||
assert_eq!(a("POST", "/api/v1/zones/example.test/records".into(), Some("reader-secret"), Some(rec.clone()), "").await.unwrap().0, 403);
|
||||
// admin adds a record; ETag = serial
|
||||
let (s, v, head) = a("POST", "/api/v1/zones/example.test/records".into(), Some("admin-secret"), Some(rec), "").await.unwrap();
|
||||
assert_eq!(s, 201, "{v}");
|
||||
assert!(head.contains("etag: \"2\"") || head.contains("ETag: \"2\""), "{head}");
|
||||
let id = v["records"][0]["id"].as_str().unwrap().to_string();
|
||||
// the DNS listener serves it
|
||||
let m = dns_core::client::query(
|
||||
server.bound.dns[0],
|
||||
&"www.example.test.".parse().unwrap(),
|
||||
dns_core::proto::rr::RecordType::A,
|
||||
&Default::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(m.message.answers.len(), 1);
|
||||
// stale If-Match is rejected
|
||||
let upd = json!({"name": "www", "type": "A", "ttl": 120, "data": "192.0.2.6"});
|
||||
assert_eq!(
|
||||
a("PUT", format!("/api/v1/zones/example.test/records/{id}"), Some("admin-secret"), Some(upd.clone()), "If-Match: \"1\"\r\n")
|
||||
.await
|
||||
.unwrap()
|
||||
.0,
|
||||
412
|
||||
);
|
||||
let (s, v, _) =
|
||||
a("PUT", format!("/api/v1/zones/example.test/records/{id}"), Some("admin-secret"), Some(upd), "If-Match: \"2\"\r\n").await.unwrap();
|
||||
assert_eq!((s, v["serial"].as_u64()), (200, Some(3)));
|
||||
// invalid data
|
||||
let bad = json!({"name": "x", "type": "A", "data": "not-an-ip"});
|
||||
assert_eq!(a("POST", "/api/v1/zones/example.test/records".into(), Some("admin-secret"), Some(bad), "").await.unwrap().0, 400);
|
||||
// list with filter + pagination
|
||||
let (_, v, _) = a("GET", "/api/v1/zones/example.test/records?type=A&per_page=1".into(), Some("reader-secret"), None, "").await.unwrap();
|
||||
assert_eq!(v["items"].as_array().unwrap().len(), 1);
|
||||
// create + delete an API zone
|
||||
let (s, _, _) =
|
||||
a("POST", "/api/v1/zones".into(), Some("admin-secret"), Some(json!({"name": "new.test", "ns": ["ns1.example.test."]})), "")
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(s, 201);
|
||||
assert_eq!(a("GET", "/api/v1/zones/new.test".into(), Some("reader-secret"), None, "").await.unwrap().0, 200);
|
||||
assert_eq!(a("DELETE", "/api/v1/zones/example.test".into(), Some("admin-secret"), None, "").await.unwrap().0, 409);
|
||||
assert_eq!(a("DELETE", "/api/v1/zones/new.test".into(), Some("admin-secret"), None, "").await.unwrap().0, 204);
|
||||
assert_eq!(a("GET", "/api/v1/zones/new.test".into(), Some("reader-secret"), None, "").await.unwrap().0, 404);
|
||||
// reload, cache, stats, audit, openapi
|
||||
assert_eq!(a("POST", "/api/v1/config/reload".into(), Some("admin-secret"), None, "").await.unwrap().0, 200);
|
||||
assert_eq!(a("DELETE", "/api/v1/cache".into(), Some("admin-secret"), None, "").await.unwrap().0, 200);
|
||||
assert_eq!(a("GET", "/api/v1/stats".into(), Some("reader-secret"), None, "").await.unwrap().0, 200);
|
||||
let (_, v, _) = a("GET", "/api/v1/audit".into(), Some("reader-secret"), None, "").await.unwrap();
|
||||
assert!(v["items"].as_array().unwrap().len() >= 5);
|
||||
let (_, v, _) = a("GET", "/api/v1/openapi.json".into(), Some("reader-secret"), None, "").await.unwrap();
|
||||
assert_eq!(v["openapi"], "3.0.3");
|
||||
server.shutdown().await;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
name = "dns-authoritative"
|
||||
description = "EasyDNS authoritative engine: zones, lookup, Primary/Secondary, AXFR/IXFR, NOTIFY, DDNS"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
dns-core.workspace = true
|
||||
dns-config.workspace = true
|
||||
tokio.workspace = true
|
||||
tracing.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
thiserror.workspace = true
|
||||
ipnet.workspace = true
|
||||
data-encoding.workspace = true
|
||||
rand.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,212 @@
|
||||
//! Persistent IXFR journal (one JSON object per line, records in wire format, base64).
|
||||
use std::collections::VecDeque;
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use data_encoding::BASE64;
|
||||
use dns_core::proto::rr::Record;
|
||||
use dns_core::proto::serialize::binary::{BinDecodable, BinEncodable};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// One zone version change: `from` → `to`.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Diff {
|
||||
pub from_soa: Record,
|
||||
pub to_soa: Record,
|
||||
pub removed: Vec<Record>,
|
||||
pub added: Vec<Record>,
|
||||
}
|
||||
|
||||
impl Diff {
|
||||
pub fn from_serial(&self) -> u32 {
|
||||
soa_serial(&self.from_soa)
|
||||
}
|
||||
pub fn to_serial(&self) -> u32 {
|
||||
soa_serial(&self.to_soa)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn soa_serial(r: &Record) -> u32 {
|
||||
match &r.data {
|
||||
dns_core::proto::rr::RData::SOA(s) => s.serial,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Line {
|
||||
from: String,
|
||||
to: String,
|
||||
del: Vec<String>,
|
||||
add: Vec<String>,
|
||||
}
|
||||
|
||||
fn enc(r: &Record) -> Option<String> {
|
||||
r.to_bytes().ok().map(|b| BASE64.encode(&b))
|
||||
}
|
||||
|
||||
fn dec(s: &str) -> Option<Record> {
|
||||
let b = BASE64.decode(s.as_bytes()).ok()?;
|
||||
Record::from_bytes(&b).ok()
|
||||
}
|
||||
|
||||
/// Bounded journal of diffs, oldest first.
|
||||
#[derive(Debug)]
|
||||
pub struct Journal {
|
||||
entries: VecDeque<Diff>,
|
||||
max: usize,
|
||||
path: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl Journal {
|
||||
pub fn in_memory(max: usize) -> Self {
|
||||
Self { entries: VecDeque::new(), max: max.max(1), path: None }
|
||||
}
|
||||
|
||||
/// Load a journal; a corrupt or unreadable file is ignored (IXFR then falls back to AXFR).
|
||||
pub fn load(path: &Path, max: usize) -> Self {
|
||||
let mut j = Self { entries: VecDeque::new(), max: max.max(1), path: Some(path.to_path_buf()) };
|
||||
if let Ok(text) = std::fs::read_to_string(path) {
|
||||
for (i, line) in text.lines().enumerate() {
|
||||
match Self::parse_line(line) {
|
||||
Some(d) => j.entries.push_back(d),
|
||||
None => {
|
||||
tracing::warn!(file = %path.display(), line = i + 1, "corrupt journal entry; truncating journal");
|
||||
j.entries.clear();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
while j.entries.len() > j.max {
|
||||
j.entries.pop_front();
|
||||
}
|
||||
}
|
||||
j
|
||||
}
|
||||
|
||||
fn parse_line(line: &str) -> Option<Diff> {
|
||||
let l: Line = serde_json::from_str(line).ok()?;
|
||||
Some(Diff {
|
||||
from_soa: dec(&l.from)?,
|
||||
to_soa: dec(&l.to)?,
|
||||
removed: l.del.iter().map(|s| dec(s)).collect::<Option<_>>()?,
|
||||
added: l.add.iter().map(|s| dec(s)).collect::<Option<_>>()?,
|
||||
})
|
||||
}
|
||||
|
||||
fn line(d: &Diff) -> Option<String> {
|
||||
let l = Line {
|
||||
from: enc(&d.from_soa)?,
|
||||
to: enc(&d.to_soa)?,
|
||||
del: d.removed.iter().map(enc).collect::<Option<_>>()?,
|
||||
add: d.added.iter().map(enc).collect::<Option<_>>()?,
|
||||
};
|
||||
serde_json::to_string(&l).ok()
|
||||
}
|
||||
|
||||
/// Append a diff. If it does not continue the chain, the journal is reset.
|
||||
pub fn push(&mut self, d: Diff) {
|
||||
if let Some(last) = self.entries.back()
|
||||
&& last.to_serial() != d.from_serial()
|
||||
{
|
||||
self.entries.clear();
|
||||
}
|
||||
self.entries.push_back(d);
|
||||
let mut compact = false;
|
||||
while self.entries.len() > self.max {
|
||||
self.entries.pop_front();
|
||||
compact = true;
|
||||
}
|
||||
if let Err(e) = self.persist(compact) {
|
||||
tracing::error!(error = %e, "failed to persist IXFR journal");
|
||||
}
|
||||
}
|
||||
|
||||
fn persist(&self, rewrite: bool) -> std::io::Result<()> {
|
||||
let Some(path) = &self.path else { return Ok(()) };
|
||||
if rewrite || self.entries.len() == 1 {
|
||||
let mut s = String::new();
|
||||
for d in &self.entries {
|
||||
if let Some(l) = Self::line(d) {
|
||||
s.push_str(&l);
|
||||
s.push('\n');
|
||||
}
|
||||
}
|
||||
dns_core::zonefile::atomic_write(path, s.as_bytes()).map_err(std::io::Error::other)
|
||||
} else if let Some(d) = self.entries.back() {
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
let mut f = std::fs::OpenOptions::new().create(true).append(true).open(path)?;
|
||||
if let Some(l) = Self::line(d) {
|
||||
writeln!(f, "{l}")?;
|
||||
}
|
||||
f.sync_data()
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) {
|
||||
self.entries.clear();
|
||||
let _ = self.persist(true);
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.entries.len()
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.entries.is_empty()
|
||||
}
|
||||
|
||||
/// The chain of diffs from `serial` up to the newest version, if available.
|
||||
pub fn since(&self, serial: u32) -> Option<Vec<Diff>> {
|
||||
let start = self.entries.iter().position(|d| d.from_serial() == serial)?;
|
||||
let chain: Vec<Diff> = self.entries.iter().skip(start).cloned().collect();
|
||||
for w in chain.windows(2) {
|
||||
if w[0].to_serial() != w[1].from_serial() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(chain)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use dns_core::proto::rr::{
|
||||
Name, RData,
|
||||
rdata::{A, SOA},
|
||||
};
|
||||
|
||||
fn soa(serial: u32) -> Record {
|
||||
let n = Name::from_ascii("example.com.").unwrap();
|
||||
Record::from_rdata(n.clone(), 3600, RData::SOA(SOA::new(n.clone(), n, serial, 1, 1, 1, 1)))
|
||||
}
|
||||
fn a(last: u8) -> Record {
|
||||
Record::from_rdata(Name::from_ascii("www.example.com.").unwrap(), 60, RData::A(A::new(192, 0, 2, last)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chain_and_persistence() {
|
||||
let dir = std::env::temp_dir().join(format!("edns-jnl-{}", rand::random::<u32>()));
|
||||
let p = dir.join("example.com.jnl");
|
||||
let mut j = Journal::load(&p, 3);
|
||||
for s in 1..=4u32 {
|
||||
j.push(Diff { from_soa: soa(s), to_soa: soa(s + 1), removed: vec![a(s as u8)], added: vec![a(s as u8 + 1)] });
|
||||
}
|
||||
assert_eq!(j.len(), 3);
|
||||
assert!(j.since(1).is_none());
|
||||
assert_eq!(j.since(2).unwrap().len(), 3);
|
||||
assert_eq!(j.since(4).unwrap().len(), 1);
|
||||
let j2 = Journal::load(&p, 3);
|
||||
assert_eq!(j2.len(), 3);
|
||||
assert_eq!(j2.since(3).unwrap()[0].added[0].data, a(4).data);
|
||||
// a gap resets the journal
|
||||
let mut j3 = Journal::load(&p, 3);
|
||||
j3.push(Diff { from_soa: soa(100), to_soa: soa(101), removed: vec![], added: vec![] });
|
||||
assert_eq!(j3.len(), 1);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//! EasyDNS authoritative engine.
|
||||
//!
|
||||
//! * [`zone`] – validated immutable zone snapshots and the lookup algorithm.
|
||||
//! * [`journal`] – persistent IXFR journal.
|
||||
//! * [`xfr`] – AXFR/IXFR response generation (server side) and IXFR application.
|
||||
//! * [`store`] – the set of served zones (Primary/Secondary) with atomic swaps.
|
||||
//! * [`secondary`] – SOA-timer driven synchronisation.
|
||||
//! * [`update`] – RFC 2136 dynamic updates.
|
||||
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
|
||||
|
||||
pub mod journal;
|
||||
pub mod secondary;
|
||||
pub mod signing;
|
||||
pub mod store;
|
||||
pub mod update;
|
||||
pub mod xfr;
|
||||
pub mod zone;
|
||||
|
||||
pub use store::{ZoneEntry, ZoneKind, ZoneStore, data_generation};
|
||||
pub use zone::{Lookup, Zone, ZoneError, ZoneRef};
|
||||
@@ -0,0 +1,285 @@
|
||||
//! Secondary zone synchronisation driven by SOA timers (RFC 1034 §4.3.5, RFC 1996).
|
||||
//!
|
||||
//! * startup: load the last persisted snapshot (if still within EXPIRE),
|
||||
//! * refresh: SOA query to the primaries; IXFR (fallback AXFR) when the serial is newer,
|
||||
//! * NOTIFY / manual sync wakes the task immediately,
|
||||
//! * failure: retry after RETRY; after EXPIRE without success the zone stops being served
|
||||
//! (queries get SERVFAIL) until a refresh succeeds.
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use dns_config::TransferPreference;
|
||||
use dns_core::client::{QueryOptions, TransferKind, TransferLimits, query, transfer};
|
||||
use dns_core::proto::rr::{RData, RecordType};
|
||||
use dns_core::tsig::now;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::store::{TransferEvent, ZoneEntry};
|
||||
use crate::xfr::{Applied, apply_transfer};
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Meta {
|
||||
last_success_unix: u64,
|
||||
serial: u32,
|
||||
primary: String,
|
||||
}
|
||||
|
||||
fn meta_path(e: &ZoneEntry) -> std::path::PathBuf {
|
||||
let mut p = e.file.clone().into_os_string();
|
||||
p.push(".meta.json");
|
||||
p.into()
|
||||
}
|
||||
|
||||
/// Load the persisted snapshot at startup.
|
||||
pub fn load_snapshot(e: &ZoneEntry) {
|
||||
if !e.file.is_file() {
|
||||
return;
|
||||
}
|
||||
let records = match dns_core::zonefile::parse_file(&e.file, &e.name) {
|
||||
Ok(r) => r,
|
||||
Err(err) => {
|
||||
tracing::error!(zone = %e.name, error = %err, "cannot read secondary snapshot");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let zone = match crate::zone::Zone::from_records(&e.name, records) {
|
||||
Ok(z) => z,
|
||||
Err(err) => {
|
||||
tracing::error!(zone = %e.name, error = %err, "invalid secondary snapshot");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let (_, _, expire, _) = zone.soa_timers();
|
||||
let meta: Option<Meta> = std::fs::read_to_string(meta_path(e)).ok().and_then(|s| serde_json::from_str(&s).ok());
|
||||
let last = meta.as_ref().map(|m| m.last_success_unix).unwrap_or(0);
|
||||
let expired = now().saturating_sub(last) > u64::from(expire);
|
||||
tracing::info!(zone = %e.name, serial = zone.serial(), expired, "loaded secondary snapshot");
|
||||
e.install(zone, Vec::new());
|
||||
e.set_expired(expired);
|
||||
e.update_status(|s| {
|
||||
s.last_success_unix = (last > 0).then_some(last);
|
||||
s.expires_at_unix = (last > 0).then_some(last + u64::from(expire));
|
||||
s.source = meta.map(|m| m.primary);
|
||||
});
|
||||
}
|
||||
|
||||
fn persist(e: &ZoneEntry, primary: SocketAddr) {
|
||||
let Some(z) = e.snapshot_any() else { return };
|
||||
let text = dns_core::zonefile::emit(&e.name, &z.all_records());
|
||||
if let Err(err) = dns_core::zonefile::atomic_write(&e.file, text.as_bytes()) {
|
||||
tracing::error!(zone = %e.name, error = %err, "failed to persist snapshot");
|
||||
return;
|
||||
}
|
||||
let meta = Meta { last_success_unix: now(), serial: z.serial(), primary: primary.to_string() };
|
||||
if let Ok(s) = serde_json::to_string(&meta) {
|
||||
let _ = dns_core::zonefile::atomic_write(&meta_path(e), s.as_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
/// Outcome of one refresh attempt.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum RefreshOutcome {
|
||||
UpToDate(u32),
|
||||
Updated { serial: u32, kind: &'static str },
|
||||
}
|
||||
|
||||
async fn primary_serial(e: &ZoneEntry, primary: SocketAddr) -> Result<u32, String> {
|
||||
let opts = QueryOptions {
|
||||
timeout: Duration::from_secs(3),
|
||||
retries: 1,
|
||||
recursion_desired: false,
|
||||
tsig: e.client_key.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
let ex = query(primary, &e.name, RecordType::SOA, &opts).await.map_err(|err| err.to_string())?;
|
||||
if !ex.message.metadata.authoritative {
|
||||
return Err(format!("{primary} is not authoritative for {}", e.name));
|
||||
}
|
||||
ex.message
|
||||
.answers
|
||||
.iter()
|
||||
.find_map(|r| match &r.data {
|
||||
RData::SOA(s) if r.name.eq_ignore_root_case(&e.name) => Some(s.serial),
|
||||
_ => None,
|
||||
})
|
||||
.ok_or_else(|| format!("{primary}: no SOA in answer ({})", ex.message.metadata.response_code))
|
||||
}
|
||||
|
||||
async fn do_transfer(e: &ZoneEntry, primary: SocketAddr, ixfr: bool) -> Result<RefreshOutcome, String> {
|
||||
let current = e.snapshot_any();
|
||||
let kind = match (¤t, ixfr) {
|
||||
(Some(z), true) => TransferKind::Ixfr { current_soa: Box::new(z.soa().clone()) },
|
||||
_ => TransferKind::Axfr,
|
||||
};
|
||||
let label = if matches!(kind, TransferKind::Axfr) { "AXFR" } else { "IXFR" };
|
||||
let limits = TransferLimits { timeout: e.config.transfer.timeout, max_records: e.max_records, ..Default::default() };
|
||||
let started = Instant::now();
|
||||
let res = transfer(primary, &e.name, &kind, e.client_key.as_ref(), limits).await;
|
||||
let mut ev = TransferEvent {
|
||||
time_unix: now(),
|
||||
direction: "in",
|
||||
kind: label.to_string(),
|
||||
peer: primary.to_string(),
|
||||
serial: None,
|
||||
records: 0,
|
||||
ok: false,
|
||||
error: None,
|
||||
duration_ms: 0,
|
||||
};
|
||||
let outcome = match res {
|
||||
Err(err) => Err(err.to_string()),
|
||||
Ok(stream) => {
|
||||
ev.records = stream.records.len();
|
||||
match apply_transfer(&e.name, current.as_deref(), &stream.records, e.max_records) {
|
||||
Ok(Applied::UpToDate) => Ok(RefreshOutcome::UpToDate(current.map(|z| z.serial()).unwrap_or(0))),
|
||||
Ok(Applied::Full(z)) => {
|
||||
let serial = z.serial();
|
||||
let diffs = match ¤t {
|
||||
Some(old) if dns_core::serial::is_newer(serial, old.serial()) => {
|
||||
let (rm, add) = old.diff(&z);
|
||||
vec![crate::journal::Diff { from_soa: old.soa().clone(), to_soa: z.soa().clone(), removed: rm, added: add }]
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
e.install(z, diffs);
|
||||
let kind = if label == "IXFR" { "IXFR(AXFR-style)" } else { "AXFR" };
|
||||
ev.kind = kind.into();
|
||||
Ok(RefreshOutcome::Updated { serial, kind })
|
||||
}
|
||||
Ok(Applied::Incremental(z, diffs)) => {
|
||||
let serial = z.serial();
|
||||
e.install(z, diffs);
|
||||
Ok(RefreshOutcome::Updated { serial, kind: "IXFR" })
|
||||
}
|
||||
Err(err) => Err(format!("transfer rejected: {err}")),
|
||||
}
|
||||
}
|
||||
};
|
||||
ev.duration_ms = started.elapsed().as_millis() as u64;
|
||||
match &outcome {
|
||||
Ok(RefreshOutcome::Updated { serial, .. }) | Ok(RefreshOutcome::UpToDate(serial)) => {
|
||||
ev.ok = true;
|
||||
ev.serial = Some(*serial);
|
||||
}
|
||||
Err(err) => ev.error = Some(err.clone()),
|
||||
}
|
||||
e.record_transfer(ev);
|
||||
outcome
|
||||
}
|
||||
|
||||
/// One refresh cycle against the configured primaries (in order).
|
||||
pub async fn refresh_once(e: &ZoneEntry) -> Result<RefreshOutcome, String> {
|
||||
let mut errors = Vec::new();
|
||||
for &primary in &e.config.primaries {
|
||||
let remote = match primary_serial(e, primary).await {
|
||||
Ok(s) => s,
|
||||
Err(err) => {
|
||||
errors.push(err);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let current = e.snapshot_any();
|
||||
if let Some(z) = ¤t
|
||||
&& !dns_core::serial::is_newer(remote, z.serial())
|
||||
{
|
||||
if remote != z.serial() {
|
||||
tracing::warn!(zone = %e.name, local = z.serial(), remote, %primary, "primary serial is older than ours; not transferring");
|
||||
}
|
||||
persist_meta_only(e, primary);
|
||||
return Ok(RefreshOutcome::UpToDate(z.serial()));
|
||||
}
|
||||
let want_ixfr = e.config.transfer.prefer == TransferPreference::Ixfr && current.is_some();
|
||||
let res = match do_transfer(e, primary, want_ixfr).await {
|
||||
Err(err) if want_ixfr && e.config.transfer.fallback_axfr => {
|
||||
tracing::warn!(zone = %e.name, %primary, error = %err, "IXFR failed; falling back to AXFR");
|
||||
do_transfer(e, primary, false).await
|
||||
}
|
||||
r => r,
|
||||
};
|
||||
match res {
|
||||
Ok(o) => {
|
||||
persist(e, primary);
|
||||
e.update_status(|s| s.source = Some(primary.to_string()));
|
||||
return Ok(o);
|
||||
}
|
||||
Err(err) => errors.push(format!("{primary}: {err}")),
|
||||
}
|
||||
}
|
||||
Err(if errors.is_empty() { "no primaries configured".into() } else { errors.join("; ") })
|
||||
}
|
||||
|
||||
fn persist_meta_only(e: &ZoneEntry, primary: SocketAddr) {
|
||||
if let Some(z) = e.snapshot_any() {
|
||||
let meta = Meta { last_success_unix: now(), serial: z.serial(), primary: primary.to_string() };
|
||||
if let Ok(s) = serde_json::to_string(&meta) {
|
||||
let _ = dns_core::zonefile::atomic_write(&meta_path(e), s.as_bytes());
|
||||
}
|
||||
if !e.file.is_file() {
|
||||
persist(e, primary);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Long-running refresh task for one secondary zone.
|
||||
pub async fn run(e: Arc<ZoneEntry>, on_update: impl Fn(&Arc<ZoneEntry>) + Send + 'static) {
|
||||
let mut next = Duration::ZERO;
|
||||
loop {
|
||||
if e.shutdown.load(Ordering::Acquire) {
|
||||
tracing::info!(zone = %e.name, "secondary task stopped");
|
||||
return;
|
||||
}
|
||||
e.update_status(|s| s.next_refresh_unix = Some(now() + next.as_secs()));
|
||||
tokio::select! {
|
||||
_ = tokio::time::sleep(next) => {}
|
||||
_ = e.refresh_trigger.notified() => {}
|
||||
}
|
||||
if e.shutdown.load(Ordering::Acquire) {
|
||||
return;
|
||||
}
|
||||
let result = refresh_once(&e).await;
|
||||
let t = now();
|
||||
let (refresh, retry, expire, _) = e.snapshot_any().map(|z| z.soa_timers()).unwrap_or((3600, 60, 604_800, 300));
|
||||
// Never hammer primaries: clamp timers to sane minimums.
|
||||
let (refresh, retry) = (refresh.max(5), retry.max(5));
|
||||
match result {
|
||||
Ok(outcome) => {
|
||||
tracing::info!(zone = %e.name, ?outcome, "refresh ok");
|
||||
e.set_expired(false);
|
||||
e.update_status(|s| {
|
||||
s.last_refresh_unix = Some(t);
|
||||
s.last_success_unix = Some(t);
|
||||
s.expires_at_unix = Some(t + u64::from(expire));
|
||||
s.last_error = None;
|
||||
});
|
||||
if matches!(outcome, RefreshOutcome::Updated { .. }) {
|
||||
on_update(&e);
|
||||
}
|
||||
next = Duration::from_secs(u64::from(refresh));
|
||||
}
|
||||
Err(err) => {
|
||||
tracing::warn!(zone = %e.name, error = %err, "refresh failed");
|
||||
let st = e.status();
|
||||
let expired = match st.last_success_unix {
|
||||
Some(last) => t.saturating_sub(last) > u64::from(expire),
|
||||
None => e.snapshot_any().is_none(),
|
||||
};
|
||||
if expired && !e.is_expired() && e.snapshot_any().is_some() {
|
||||
tracing::error!(zone = %e.name, "zone EXPIRED: no successful refresh within SOA expire; answering SERVFAIL");
|
||||
}
|
||||
e.set_expired(expired);
|
||||
e.update_status(|s| {
|
||||
s.last_refresh_unix = Some(t);
|
||||
s.last_error = Some(err);
|
||||
});
|
||||
next = Duration::from_secs(u64::from(retry));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-exported so the server can record outbound transfers without depending on internals.
|
||||
pub fn status_snapshot(e: &ZoneEntry) -> crate::store::ZoneStatus {
|
||||
crate::store::status_lock(e).clone()
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
//! Online DNSSEC signing of primary zones (NSEC, RFC 4033–4035).
|
||||
//!
|
||||
//! Keys live in `keys_dir` as `<zone>.<tag>.<ksk|zsk|csk>.key` (PKCS#8). A KSK (flag 257)
|
||||
//! signs the DNSKEY RRset, ZSKs sign everything else, a CSK does both. Rollover is done by
|
||||
//! adding the new key file, reloading (both keys are published), and removing the old file
|
||||
//! after the DNSKEY TTL (+ DS TTL for KSKs) has passed.
|
||||
use std::collections::{BTreeMap, BTreeSet, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use dns_config::DnssecZoneConfig;
|
||||
use dns_core::dnssec::{ZoneKey, is_dnssec_type, key_file_contents, nsec_record, parse_key_file, rrsig_info};
|
||||
use dns_core::proto::rr::{LowerName, Name, RData, Record, RecordType};
|
||||
|
||||
use crate::zone::Zone;
|
||||
|
||||
pub struct ZoneSigner {
|
||||
pub keys: Vec<ZoneKey>,
|
||||
pub validity: u32,
|
||||
pub resign_before: u32,
|
||||
pub keys_dir: PathBuf,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ZoneSigner {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("ZoneSigner").field("keys", &self.keys).finish()
|
||||
}
|
||||
}
|
||||
|
||||
fn zone_prefix(zone: &Name) -> String {
|
||||
let s = zone.to_ascii().to_ascii_lowercase();
|
||||
if s == "." { "root.".into() } else { s }
|
||||
}
|
||||
|
||||
impl ZoneSigner {
|
||||
/// Load keys for `zone`, generating a CSK when allowed and none exist.
|
||||
pub fn load(cfg: &DnssecZoneConfig, keys_dir: &Path, zone: &Name) -> Result<Self, String> {
|
||||
let prefix = zone_prefix(zone);
|
||||
let mut keys = Vec::new();
|
||||
if let Ok(rd) = std::fs::read_dir(keys_dir) {
|
||||
let mut files: Vec<PathBuf> = rd.filter_map(|e| e.ok().map(|e| e.path())).collect();
|
||||
files.sort();
|
||||
for f in files {
|
||||
let fname = f.file_name().map(|n| n.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
|
||||
if !fname.starts_with(&prefix) || !fname.ends_with(".key") {
|
||||
continue;
|
||||
}
|
||||
let text = std::fs::read_to_string(&f).map_err(|e| format!("{}: {e}", f.display()))?;
|
||||
keys.push(parse_key_file(&text).map_err(|e| format!("{}: {e}", f.display()))?);
|
||||
}
|
||||
}
|
||||
if keys.is_empty() {
|
||||
if !cfg.auto_generate {
|
||||
return Err(format!("no DNSSEC keys for {zone} in {}", keys_dir.display()));
|
||||
}
|
||||
let (pk, key) = ZoneKey::generate(cfg.algorithm, true).map_err(|e| e.to_string())?;
|
||||
std::fs::create_dir_all(keys_dir).map_err(|e| format!("{}: {e}", keys_dir.display()))?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let _ = std::fs::set_permissions(keys_dir, std::fs::Permissions::from_mode(0o700));
|
||||
}
|
||||
let path = keys_dir.join(format!("{prefix}{}.csk.key", key.tag));
|
||||
dns_core::zonefile::atomic_write(&path, key_file_contents(cfg.algorithm, true, &pk).as_bytes()).map_err(|e| e.to_string())?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600));
|
||||
}
|
||||
if let Ok(ds) = key.ds_record(zone, 3600) {
|
||||
tracing::warn!(zone = %zone, key_tag = key.tag, ds = %ds.data, "generated new DNSSEC key: publish this DS record in the parent zone");
|
||||
}
|
||||
keys.push(key);
|
||||
}
|
||||
if !keys.iter().any(|k| k.ksk) {
|
||||
return Err(format!("{zone}: at least one KSK/CSK (flags 257) is required"));
|
||||
}
|
||||
Ok(Self {
|
||||
keys,
|
||||
validity: cfg.signature_validity.as_secs() as u32,
|
||||
resign_before: cfg.resign_before.as_secs() as u32,
|
||||
keys_dir: keys_dir.to_path_buf(),
|
||||
})
|
||||
}
|
||||
|
||||
fn zsks(&self) -> Vec<&ZoneKey> {
|
||||
let z: Vec<&ZoneKey> = self.keys.iter().filter(|k| !k.ksk).collect();
|
||||
if z.is_empty() { self.keys.iter().collect() } else { z }
|
||||
}
|
||||
|
||||
/// DS records for the parent.
|
||||
pub fn ds_records(&self, zone: &Name) -> Vec<Record> {
|
||||
self.keys.iter().filter(|k| k.ksk).filter_map(|k| k.ds_record(zone, 3600).ok()).collect()
|
||||
}
|
||||
|
||||
/// Sign the unsigned `source` zone, producing a new zone with DNSKEY, NSEC and RRSIG records.
|
||||
pub fn sign(&self, source: &Zone, now: u32) -> Result<Zone, String> {
|
||||
let origin = source.origin().clone();
|
||||
let (_, _, _, minimum) = source.soa_timers();
|
||||
let neg_ttl = source.soa().ttl.min(minimum);
|
||||
let inception = now.saturating_sub(3600);
|
||||
let expiration = now.saturating_add(self.validity);
|
||||
let mut records: Vec<Record> = source.all_records().into_iter().filter(|r| !is_dnssec_type(r.record_type())).collect();
|
||||
let dnskey_ttl = source.soa().ttl;
|
||||
for k in &self.keys {
|
||||
records.push(k.dnskey_record(&origin, dnskey_ttl));
|
||||
}
|
||||
// group RRsets
|
||||
let mut sets: BTreeMap<(Name, u16), Vec<Record>> = BTreeMap::new();
|
||||
for r in &records {
|
||||
sets.entry((r.name.to_lowercase(), u16::from(r.record_type()))).or_default().push(r.clone());
|
||||
}
|
||||
let olabels = origin.num_labels();
|
||||
let cuts: HashSet<LowerName> = sets
|
||||
.keys()
|
||||
.filter(|(n, t)| *t == u16::from(RecordType::NS) && n.num_labels() > olabels)
|
||||
.map(|(n, _)| LowerName::new(n))
|
||||
.collect();
|
||||
let below_cut =
|
||||
|n: &Name| -> bool { (olabels + 1..n.num_labels()).any(|l| cuts.contains(&LowerName::new(&n.trim_to(l as usize)))) };
|
||||
// NSEC chain over authoritative names + delegation points (canonical order)
|
||||
let mut names: BTreeMap<Name, BTreeSet<u16>> = BTreeMap::new();
|
||||
for (n, t) in sets.keys() {
|
||||
if below_cut(n) {
|
||||
continue;
|
||||
}
|
||||
names.entry(n.clone()).or_default().insert(*t);
|
||||
}
|
||||
let ordered: Vec<Name> = names.keys().cloned().collect();
|
||||
let mut out: Vec<Record> = records.clone();
|
||||
for (i, n) in ordered.iter().enumerate() {
|
||||
let next = &ordered[(i + 1) % ordered.len()];
|
||||
let mut types: Vec<RecordType> = names[n].iter().map(|t| RecordType::from(*t)).collect();
|
||||
types.push(RecordType::NSEC);
|
||||
types.push(RecordType::RRSIG);
|
||||
let nsec = nsec_record(n, next, types, neg_ttl);
|
||||
sets.insert((n.clone(), u16::from(RecordType::NSEC)), vec![nsec.clone()]);
|
||||
out.push(nsec);
|
||||
}
|
||||
// signatures
|
||||
for ((n, t), set) in &sets {
|
||||
let rtype = RecordType::from(*t);
|
||||
if below_cut(n) {
|
||||
continue; // glue / occluded data is not signed
|
||||
}
|
||||
let at_cut = cuts.contains(&LowerName::new(n));
|
||||
if at_cut && !matches!(rtype, RecordType::DS | RecordType::NSEC) {
|
||||
continue; // delegation NS is not signed
|
||||
}
|
||||
let signers: Vec<&ZoneKey> =
|
||||
if rtype == RecordType::DNSKEY { self.keys.iter().filter(|k| k.ksk).collect() } else { self.zsks() };
|
||||
for k in signers {
|
||||
out.push(k.sign(&origin, set, inception, expiration).map_err(|e| format!("signing {n} {rtype}: {e}"))?);
|
||||
}
|
||||
}
|
||||
Zone::from_records(&origin, out).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Earliest RRSIG expiration in a signed zone.
|
||||
pub fn min_expiration(zone: &Zone) -> Option<u32> {
|
||||
zone.all_records()
|
||||
.iter()
|
||||
.filter_map(|r| match &r.data {
|
||||
RData::DNSSEC(dns_core::proto::dnssec::rdata::DNSSECRData::RRSIG(s)) => Some(s.input().sig_expiration.get()),
|
||||
_ => None,
|
||||
})
|
||||
.min()
|
||||
}
|
||||
|
||||
/// Does the zone need re-signing at `now`?
|
||||
pub fn needs_resign(&self, zone: &Zone, now: u32) -> bool {
|
||||
match Self::min_expiration(zone) {
|
||||
Some(exp) => !dns_core::serial::is_newer(exp, now.saturating_add(self.resign_before)),
|
||||
None => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Are all key tags used in the zone still present in the key set?
|
||||
pub fn keys_match(&self, zone: &Zone) -> bool {
|
||||
let tags: BTreeSet<u16> = self.keys.iter().map(|k| k.tag).collect();
|
||||
let used: BTreeSet<u16> = zone.all_records().iter().filter_map(rrsig_info).map(|(_, _, t)| t).collect();
|
||||
used == tags || (used.is_subset(&tags) && self.keys.len() == 1)
|
||||
}
|
||||
}
|
||||
|
||||
/// Strip DNSSEC records (to compare a signed zone with its unsigned source).
|
||||
pub fn unsigned_view(z: &Zone) -> Vec<Record> {
|
||||
z.all_records().into_iter().filter(|r| !is_dnssec_type(r.record_type())).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use dns_core::zonefile::parse_str;
|
||||
|
||||
#[test]
|
||||
fn sign_zone_and_validate_every_rrset() {
|
||||
let origin = Name::from_ascii("example.").unwrap();
|
||||
let text = "$TTL 300\n@ IN SOA ns hm 1 3600 600 86400 60\n@ IN NS ns\nns IN A 192.0.2.1\nwww IN A 192.0.2.2\n*.w IN TXT \"x\"\nsub IN NS ns.sub\nns.sub IN A 192.0.2.3\nsec IN NS ns.sub\nsec IN DS 1 8 2 49FD46E6C4B45C55D4AC69CBD3CD34AC1AFE51DE1A6D5C4C9F2A4DFA2D5E7F3A\n";
|
||||
let src = Zone::from_records(&origin, parse_str(text, &origin, None).unwrap()).unwrap();
|
||||
let dir = std::env::temp_dir().join(format!("edns-keys-{}", rand::random::<u32>()));
|
||||
let cfg = DnssecZoneConfig::default();
|
||||
let s = ZoneSigner::load(&cfg, &dir, &origin).unwrap();
|
||||
assert_eq!(s.keys.len(), 1);
|
||||
let now = 1_800_000_000;
|
||||
let signed = s.sign(&src, now).unwrap();
|
||||
let keys: Vec<_> = s.keys.iter().map(|k| k.dnskey.clone()).collect();
|
||||
let all = signed.all_records();
|
||||
let sigs: Vec<Record> = all.iter().filter(|r| r.record_type() == RecordType::RRSIG).cloned().collect();
|
||||
let mut sets: BTreeMap<(Name, RecordType), Vec<Record>> = BTreeMap::new();
|
||||
for r in all.iter().filter(|r| r.record_type() != RecordType::RRSIG) {
|
||||
sets.entry((r.name.clone(), r.record_type())).or_default().push(r.clone());
|
||||
}
|
||||
let mut signed_sets = 0;
|
||||
for ((n, t), set) in &sets {
|
||||
let unsigned_expected =
|
||||
(*t == RecordType::NS && n.num_labels() > 1) || n.to_string().ends_with("sub.example.") && *t == RecordType::A;
|
||||
let res = dns_core::dnssec::verify_rrset(n, set, &sigs, &keys, &origin, now);
|
||||
if unsigned_expected {
|
||||
assert!(res.is_err(), "{n} {t} must not be signed");
|
||||
} else {
|
||||
res.unwrap_or_else(|e| panic!("{n} {t}: {e}"));
|
||||
signed_sets += 1;
|
||||
}
|
||||
}
|
||||
assert!(signed_sets >= 8);
|
||||
// the NSEC chain is closed and excludes glue
|
||||
let nsecs = all.iter().filter(|r| r.record_type() == RecordType::NSEC).count();
|
||||
assert_eq!(nsecs, 6); // example, ns, sec, sub, www, *.w
|
||||
// reloading keys gives the same tag; needs_resign logic
|
||||
let s2 = ZoneSigner::load(&cfg, &dir, &origin).unwrap();
|
||||
assert_eq!(s2.keys[0].tag, s.keys[0].tag);
|
||||
assert!(!s.needs_resign(&signed, now));
|
||||
assert!(s.needs_resign(&signed, now + 8 * 86_400));
|
||||
assert_eq!(unsigned_view(&signed).len(), src.all_records().len());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,615 @@
|
||||
//! The set of zones served by this node, with atomic snapshot swaps.
|
||||
use std::collections::VecDeque;
|
||||
use std::net::IpAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex, RwLock};
|
||||
use std::time::Duration;
|
||||
|
||||
use dns_config::{Config, ZoneConfig, ZoneType};
|
||||
use dns_core::proto::rr::{LowerName, Name, RData, Record};
|
||||
use dns_core::tsig::{KeyRing, TsigKey, now};
|
||||
use ipnet::IpNet;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::journal::{Diff, Journal};
|
||||
use crate::zone::{Zone, ZoneRef};
|
||||
|
||||
/// Role of a zone on this node.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ZoneKind {
|
||||
Primary,
|
||||
Secondary,
|
||||
}
|
||||
|
||||
/// Observable zone state (API, metrics, `easydns zones show`).
|
||||
#[derive(Debug, Clone, Default, Serialize)]
|
||||
pub struct ZoneStatus {
|
||||
pub serial: Option<u32>,
|
||||
pub loaded: bool,
|
||||
pub expired: bool,
|
||||
pub records: usize,
|
||||
pub source: Option<String>,
|
||||
pub last_refresh_unix: Option<u64>,
|
||||
pub last_success_unix: Option<u64>,
|
||||
pub next_refresh_unix: Option<u64>,
|
||||
pub expires_at_unix: Option<u64>,
|
||||
pub last_error: Option<String>,
|
||||
pub notifies_sent: u64,
|
||||
pub notifies_failed: u64,
|
||||
}
|
||||
|
||||
/// One transfer (in or out) for the history endpoint.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct TransferEvent {
|
||||
pub time_unix: u64,
|
||||
pub direction: &'static str,
|
||||
pub kind: String,
|
||||
pub peer: String,
|
||||
pub serial: Option<u32>,
|
||||
pub records: usize,
|
||||
pub ok: bool,
|
||||
pub error: Option<String>,
|
||||
pub duration_ms: u64,
|
||||
}
|
||||
|
||||
fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
|
||||
m.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// Changes whenever any zone snapshot is published or a zone expires/recovers. Caches of
|
||||
/// encoded answers compare it to detect stale entries.
|
||||
static DATA_GENERATION: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
/// Current zone data generation.
|
||||
pub fn data_generation() -> u64 {
|
||||
DATA_GENERATION.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
fn bump_data_generation() {
|
||||
DATA_GENERATION.fetch_add(1, Ordering::AcqRel);
|
||||
}
|
||||
|
||||
/// A served zone (primary or secondary).
|
||||
pub struct ZoneEntry {
|
||||
pub name: Name,
|
||||
pub lname: LowerName,
|
||||
pub kind: ZoneKind,
|
||||
pub config: ZoneConfig,
|
||||
pub views: Vec<String>,
|
||||
data: RwLock<Option<ZoneRef>>,
|
||||
expired: AtomicBool,
|
||||
pub journal: Mutex<Journal>,
|
||||
status: Mutex<ZoneStatus>,
|
||||
history: Mutex<VecDeque<TransferEvent>>,
|
||||
/// Wakes the secondary refresh task (NOTIFY / manual sync).
|
||||
pub refresh_trigger: tokio::sync::Notify,
|
||||
pub shutdown: AtomicBool,
|
||||
write_lock: Mutex<()>,
|
||||
pub transfer_acl: Vec<IpNet>,
|
||||
pub notify_acl: Vec<IpNet>,
|
||||
pub update_acl: Vec<IpNet>,
|
||||
pub transfer_key: Option<TsigKey>,
|
||||
pub notify_key: Option<TsigKey>,
|
||||
pub client_key: Option<TsigKey>,
|
||||
pub update_keys: Vec<TsigKey>,
|
||||
pub update_policy: Vec<crate::update::PolicyRule>,
|
||||
/// Primary: zone file. Secondary: snapshot file.
|
||||
pub file: PathBuf,
|
||||
pub notify_count: AtomicU64,
|
||||
pub max_records: usize,
|
||||
/// DNSSEC signer (primary zones with `dnssec:`).
|
||||
signer: Mutex<Option<crate::signing::ZoneSigner>>,
|
||||
/// Unsigned source of a signed zone.
|
||||
source: Mutex<Option<Zone>>,
|
||||
signed_file: PathBuf,
|
||||
keys_dir: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ZoneEntry {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("ZoneEntry").field("name", &self.name.to_string()).field("kind", &self.kind).finish()
|
||||
}
|
||||
}
|
||||
|
||||
fn acl_contains(acl: &[IpNet], ip: IpAddr) -> bool {
|
||||
let ip = match ip {
|
||||
IpAddr::V6(v6) => v6.to_ipv4_mapped().map(IpAddr::V4).unwrap_or(IpAddr::V6(v6)),
|
||||
v4 => v4,
|
||||
};
|
||||
acl.iter().any(|n| n.contains(&ip))
|
||||
}
|
||||
|
||||
/// Default copy of a secondary zone: `<data_dir>/zones/secondary/<zone>.zone`.
|
||||
///
|
||||
/// Versions before 0.1.x-unreleased kept it in `<data_dir>/secondary/`. An existing old
|
||||
/// copy (with its `.meta.json`) is moved to the new place, so an upgrade keeps serving
|
||||
/// the zone from the local copy instead of transferring everything again.
|
||||
fn default_secondary_file(data_dir: &Path, zone_ascii: &str) -> PathBuf {
|
||||
let new = data_dir.join("zones").join("secondary").join(format!("{zone_ascii}zone"));
|
||||
let old = data_dir.join("secondary").join(format!("{zone_ascii}zone"));
|
||||
if !new.exists() && old.is_file() {
|
||||
let meta = |p: &Path| {
|
||||
let mut m = p.as_os_str().to_owned();
|
||||
m.push(".meta.json");
|
||||
PathBuf::from(m)
|
||||
};
|
||||
let moved = new
|
||||
.parent()
|
||||
.map_or(Ok(()), std::fs::create_dir_all)
|
||||
.and_then(|_| std::fs::rename(&old, &new))
|
||||
.and_then(|_| if meta(&old).exists() { std::fs::rename(meta(&old), meta(&new)) } else { Ok(()) });
|
||||
match moved {
|
||||
Ok(()) => tracing::info!(from = %old.display(), to = %new.display(), "moved secondary zone copy to the new location"),
|
||||
Err(e) => {
|
||||
tracing::warn!(path = %old.display(), error = %e, "could not move secondary zone copy; using the old location");
|
||||
return old;
|
||||
}
|
||||
}
|
||||
}
|
||||
new
|
||||
}
|
||||
|
||||
impl ZoneEntry {
|
||||
fn new(cfg: &Config, zc: &ZoneConfig, ring: &KeyRing) -> Result<Self, String> {
|
||||
let name = dns_core::names::parse_name(&zc.name).map_err(|e| e.to_string())?;
|
||||
let key = |k: &Option<String>| -> Result<Option<TsigKey>, String> {
|
||||
match k {
|
||||
None => Ok(None),
|
||||
Some(n) => ring.get_str(n).cloned().map(Some).ok_or_else(|| format!("zone {}: unknown key {n}", zc.name)),
|
||||
}
|
||||
};
|
||||
let mut notify_acl = cfg.expand_acl(&zc.allow_notify)?;
|
||||
if notify_acl.is_empty() {
|
||||
notify_acl = zc.primaries.iter().map(|a| IpNet::from(a.ip())).collect();
|
||||
}
|
||||
let kind = match zc.zone_type {
|
||||
ZoneType::Primary => ZoneKind::Primary,
|
||||
ZoneType::Secondary => ZoneKind::Secondary,
|
||||
};
|
||||
let file = match (&zc.file, kind) {
|
||||
(Some(f), _) => cfg.zone_file_path(f),
|
||||
(None, _) => default_secondary_file(&cfg.data_dir(), &name.to_ascii()),
|
||||
};
|
||||
let journal_path = cfg.data_dir().join("journal").join(format!("{}jnl", name.to_ascii()));
|
||||
let mut update_keys = Vec::new();
|
||||
for k in &zc.update_keys {
|
||||
update_keys.push(ring.get_str(k).cloned().ok_or_else(|| format!("zone {}: unknown key {k}", zc.name))?);
|
||||
}
|
||||
let keys_dir = zc.dnssec.as_ref().map(|d| cfg.resolve_path(&d.keys_dir));
|
||||
let signer = match (&zc.dnssec, &keys_dir) {
|
||||
(Some(d), Some(dir)) if zc.zone_type == ZoneType::Primary => {
|
||||
Some(crate::signing::ZoneSigner::load(d, dir, &name).map_err(|e| format!("zone {}: {e}", zc.name))?)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let signed_file = cfg.data_dir().join("signed").join(format!("{}zone", name.to_ascii()));
|
||||
Ok(Self {
|
||||
signer: Mutex::new(signer),
|
||||
source: Mutex::new(None),
|
||||
signed_file,
|
||||
keys_dir,
|
||||
lname: LowerName::new(&name),
|
||||
name,
|
||||
kind,
|
||||
config: zc.clone(),
|
||||
views: zc.views.clone(),
|
||||
data: RwLock::new(None),
|
||||
expired: AtomicBool::new(false),
|
||||
journal: Mutex::new(Journal::load(&journal_path, zc.journal_size)),
|
||||
status: Mutex::new(ZoneStatus::default()),
|
||||
history: Mutex::new(VecDeque::new()),
|
||||
refresh_trigger: tokio::sync::Notify::new(),
|
||||
shutdown: AtomicBool::new(false),
|
||||
write_lock: Mutex::new(()),
|
||||
transfer_acl: cfg.expand_acl(&zc.transfer_acl)?,
|
||||
notify_acl,
|
||||
update_acl: cfg.expand_acl(&zc.update_acl)?,
|
||||
transfer_key: key(&zc.transfer_tsig_key)?,
|
||||
notify_key: key(&zc.notify_tsig_key)?,
|
||||
client_key: key(&zc.transfer.tsig_key)?,
|
||||
update_keys,
|
||||
update_policy: crate::update::compile_policy(&zc.update_policy).map_err(|e| format!("zone {}: update_policy: {e}", zc.name))?,
|
||||
file,
|
||||
notify_count: AtomicU64::new(0),
|
||||
max_records: zc.transfer.max_records,
|
||||
})
|
||||
}
|
||||
|
||||
/// Current snapshot, or `None` if not loaded / expired.
|
||||
pub fn current(&self) -> Option<ZoneRef> {
|
||||
if self.expired.load(Ordering::Acquire) {
|
||||
return None;
|
||||
}
|
||||
self.data.read().unwrap_or_else(|e| e.into_inner()).clone()
|
||||
}
|
||||
|
||||
/// Snapshot regardless of expiry (for refresh logic and diagnostics).
|
||||
pub fn snapshot_any(&self) -> Option<ZoneRef> {
|
||||
self.data.read().unwrap_or_else(|e| e.into_inner()).clone()
|
||||
}
|
||||
|
||||
pub fn is_expired(&self) -> bool {
|
||||
self.expired.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub fn set_expired(&self, v: bool) {
|
||||
if self.expired.swap(v, Ordering::AcqRel) != v {
|
||||
bump_data_generation();
|
||||
}
|
||||
lock(&self.status).expired = v;
|
||||
}
|
||||
|
||||
/// Atomically publish a new snapshot; queries see either the old or the new zone.
|
||||
pub fn install(&self, zone: Zone, diffs: Vec<Diff>) {
|
||||
let serial = zone.serial();
|
||||
let records = zone.record_count();
|
||||
{
|
||||
let mut j = lock(&self.journal);
|
||||
for d in diffs {
|
||||
j.push(d);
|
||||
}
|
||||
}
|
||||
*self.data.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(zone));
|
||||
bump_data_generation();
|
||||
let mut st = lock(&self.status);
|
||||
st.serial = Some(serial);
|
||||
st.loaded = true;
|
||||
st.records = records;
|
||||
}
|
||||
|
||||
pub fn status(&self) -> ZoneStatus {
|
||||
lock(&self.status).clone()
|
||||
}
|
||||
|
||||
pub fn update_status(&self, f: impl FnOnce(&mut ZoneStatus)) {
|
||||
f(&mut lock(&self.status));
|
||||
}
|
||||
|
||||
pub fn record_transfer(&self, ev: TransferEvent) {
|
||||
let mut h = lock(&self.history);
|
||||
if h.len() >= 100 {
|
||||
h.pop_front();
|
||||
}
|
||||
h.push_back(ev);
|
||||
}
|
||||
|
||||
pub fn transfers(&self) -> Vec<TransferEvent> {
|
||||
lock(&self.history).iter().cloned().collect()
|
||||
}
|
||||
|
||||
pub fn transfer_allowed_from(&self, ip: IpAddr) -> bool {
|
||||
acl_contains(&self.transfer_acl, ip)
|
||||
}
|
||||
pub fn notify_allowed_from(&self, ip: IpAddr) -> bool {
|
||||
acl_contains(&self.notify_acl, ip)
|
||||
}
|
||||
/// Whether `ip` is in `update_acl` (true when the list is empty).
|
||||
pub fn update_allowed_from(&self, ip: IpAddr) -> bool {
|
||||
self.update_acl.is_empty() || acl_contains(&self.update_acl, ip)
|
||||
}
|
||||
|
||||
pub fn visible_in(&self, view: Option<&str>) -> bool {
|
||||
self.views.is_empty() || view.is_some_and(|v| self.views.iter().any(|x| x == v))
|
||||
}
|
||||
|
||||
// ---------------- Primary operations ----------------
|
||||
|
||||
pub fn is_signed(&self) -> bool {
|
||||
lock(&self.signer).is_some()
|
||||
}
|
||||
|
||||
/// DS records to publish in the parent (signed zones).
|
||||
pub fn ds_records(&self) -> Vec<Record> {
|
||||
lock(&self.signer).as_ref().map(|s| s.ds_records(&self.name)).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn with_serial(zone: &Zone, serial: u32) -> Result<Zone, String> {
|
||||
let mut soa = zone.soa().clone();
|
||||
if let RData::SOA(s) = &mut soa.data {
|
||||
s.serial = serial;
|
||||
}
|
||||
zone.apply(&[], &[], soa, usize::MAX).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn persist_signed(&self, z: &Zone) {
|
||||
let text = dns_core::zonefile::emit(&self.name, &z.all_records());
|
||||
if let Err(e) = dns_core::zonefile::atomic_write(&self.signed_file, text.as_bytes()) {
|
||||
tracing::error!(zone = %self.name, error = %e, "cannot persist signed zone");
|
||||
}
|
||||
}
|
||||
|
||||
/// Sign `src` with `serial` and publish it (signed zones only).
|
||||
fn publish_signed(&self, signer: &crate::signing::ZoneSigner, src: Zone, serial: u32) -> Result<(), String> {
|
||||
let src = Self::with_serial(&src, serial)?;
|
||||
let signed = signer.sign(&src, now() as u32)?;
|
||||
let diffs = match self.snapshot_any() {
|
||||
Some(old) => {
|
||||
let (rm, add) = old.diff(&signed);
|
||||
vec![Diff { from_soa: old.soa().clone(), to_soa: signed.soa().clone(), removed: rm, added: add }]
|
||||
}
|
||||
None => Vec::new(),
|
||||
};
|
||||
self.persist_signed(&signed);
|
||||
self.install(signed, diffs);
|
||||
*lock(&self.source) = Some(src);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// (Re)load a primary zone from its file. Returns `Ok(true)` if a new version was published.
|
||||
pub fn load_primary_file(&self) -> Result<bool, String> {
|
||||
let _g = lock(&self.write_lock);
|
||||
let records = dns_core::zonefile::parse_file(&self.file, &self.name).map_err(|e| e.to_string())?;
|
||||
let records: Vec<Record> =
|
||||
records.into_iter().filter(|r| !(self.is_signed() && dns_core::dnssec::is_dnssec_type(r.record_type()))).collect();
|
||||
let new = Zone::from_records(&self.name, records).map_err(|e| format!("{}: {e}", self.file.display()))?;
|
||||
if self.is_signed() {
|
||||
return self.load_signed(new);
|
||||
}
|
||||
let cur = self.snapshot_any();
|
||||
let changed = match &cur {
|
||||
None => {
|
||||
self.install(new, Vec::new());
|
||||
true
|
||||
}
|
||||
Some(old) => {
|
||||
let (rm, add) = old.diff(&new);
|
||||
let soa_changed = old.soa().data != new.soa().data;
|
||||
if rm.is_empty() && add.is_empty() && !soa_changed {
|
||||
false
|
||||
} else if !dns_core::serial::is_newer(new.serial(), old.serial()) {
|
||||
return Err(format!(
|
||||
"zone {} changed but SOA serial {} is not newer than {} – keeping the old version",
|
||||
self.name,
|
||||
new.serial(),
|
||||
old.serial()
|
||||
));
|
||||
} else {
|
||||
let diff = Diff { from_soa: old.soa().clone(), to_soa: new.soa().clone(), removed: rm, added: add };
|
||||
self.install(new, vec![diff]);
|
||||
true
|
||||
}
|
||||
}
|
||||
};
|
||||
self.update_status(|s| {
|
||||
s.source = Some(self.file.display().to_string());
|
||||
s.last_success_unix = Some(now());
|
||||
s.last_error = None;
|
||||
});
|
||||
Ok(changed)
|
||||
}
|
||||
|
||||
fn load_signed(&self, src: Zone) -> Result<bool, String> {
|
||||
// refresh keys from disk (rollover: keys added/removed)
|
||||
if let (Some(dir), Some(d)) = (&self.keys_dir, &self.config.dnssec) {
|
||||
let fresh = crate::signing::ZoneSigner::load(d, dir, &self.name)?;
|
||||
*lock(&self.signer) = Some(fresh);
|
||||
}
|
||||
let signer_guard = lock(&self.signer);
|
||||
let Some(signer) = signer_guard.as_ref() else { return Err("signer missing".into()) };
|
||||
let t = now() as u32;
|
||||
let same_source = |a: &Zone| {
|
||||
let (rm, add) = a.diff(&src);
|
||||
rm.is_empty() && add.is_empty()
|
||||
};
|
||||
let cur = self.snapshot_any();
|
||||
// Startup: reuse the persisted signed zone if it matches the source and keys.
|
||||
if cur.is_none()
|
||||
&& self.signed_file.is_file()
|
||||
&& let Ok(recs) = dns_core::zonefile::parse_file(&self.signed_file, &self.name)
|
||||
&& let Ok(signed) = Zone::from_records(&self.name, recs)
|
||||
{
|
||||
let unsigned = Zone::from_records(&self.name, crate::signing::unsigned_view(&signed)).ok();
|
||||
let reusable = unsigned.as_ref().is_some_and(&same_source)
|
||||
&& signer.keys_match(&signed)
|
||||
&& !signer.needs_resign(&signed, t)
|
||||
&& !dns_core::serial::is_newer(src.serial(), signed.serial());
|
||||
let prev_serial = signed.serial();
|
||||
if reusable {
|
||||
let serial = signed.serial();
|
||||
self.install(signed, Vec::new());
|
||||
*lock(&self.source) = Some(Self::with_serial(&src, serial)?);
|
||||
tracing::info!(zone = %self.name, serial, "loaded persisted signed zone");
|
||||
return Ok(true);
|
||||
}
|
||||
let serial = if dns_core::serial::is_newer(src.serial(), prev_serial) { src.serial() } else { prev_serial.wrapping_add(1) };
|
||||
self.publish_signed(signer, src, serial)?;
|
||||
return Ok(true);
|
||||
}
|
||||
match cur {
|
||||
None => {
|
||||
let serial = src.serial();
|
||||
self.publish_signed(signer, src, serial)?;
|
||||
Ok(true)
|
||||
}
|
||||
Some(signed) => {
|
||||
let unchanged = lock(&self.source).as_ref().is_some_and(&same_source);
|
||||
if unchanged && signer.keys_match(&signed) && !signer.needs_resign(&signed, t) {
|
||||
return Ok(false);
|
||||
}
|
||||
let serial =
|
||||
if dns_core::serial::is_newer(src.serial(), signed.serial()) { src.serial() } else { signed.serial().wrapping_add(1) };
|
||||
self.publish_signed(signer, src, serial)?;
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-sign a signed zone when signatures approach expiry. Returns `true` when re-signed.
|
||||
pub fn resign_if_needed(&self) -> Result<bool, String> {
|
||||
let _g = lock(&self.write_lock);
|
||||
let signer_guard = lock(&self.signer);
|
||||
let (Some(signer), Some(cur)) = (signer_guard.as_ref(), self.snapshot_any()) else { return Ok(false) };
|
||||
if !signer.needs_resign(&cur, now() as u32) {
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(src) = lock(&self.source).clone() else { return Ok(false) };
|
||||
let serial = dns_core::serial::next_serial(cur.serial(), self.config.serial_strategy, now());
|
||||
self.publish_signed(signer, src, serial)?;
|
||||
tracing::info!(zone = %self.name, serial, "zone re-signed");
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Apply a change to a primary zone (API / dynamic update): bump the serial, validate,
|
||||
/// persist the zone file atomically, publish and record the IXFR diff.
|
||||
/// Returns the new serial.
|
||||
pub fn modify(&self, removed: &[Record], added: &[Record]) -> Result<u32, String> {
|
||||
if self.kind != ZoneKind::Primary {
|
||||
return Err("zone is not a primary zone".into());
|
||||
}
|
||||
let _g = lock(&self.write_lock);
|
||||
let cur = self.snapshot_any().ok_or("zone not loaded")?;
|
||||
if removed.iter().chain(added.iter()).any(|r| self.is_signed() && dns_core::dnssec::is_dnssec_type(r.record_type())) {
|
||||
return Err("DNSSEC records of a signed zone are managed automatically".into());
|
||||
}
|
||||
let base = if self.is_signed() { lock(&self.source).clone().ok_or("source not loaded")? } else { (*cur).clone() };
|
||||
let mut soa = base.soa().clone();
|
||||
let new_serial = dns_core::serial::next_serial(cur.serial(), self.config.serial_strategy, now());
|
||||
if let RData::SOA(s) = &mut soa.data {
|
||||
s.serial = new_serial;
|
||||
} else {
|
||||
return Err("invalid SOA".into());
|
||||
}
|
||||
let new_src = base.apply(removed, added, soa, usize::MAX).map_err(|e| e.to_string())?;
|
||||
let (rm, add) = base.diff(&new_src);
|
||||
if rm.is_empty() && add.is_empty() {
|
||||
return Ok(cur.serial());
|
||||
}
|
||||
let text = dns_core::zonefile::emit(&self.name, &new_src.all_records());
|
||||
dns_core::zonefile::atomic_write(&self.file, text.as_bytes()).map_err(|e| e.to_string())?;
|
||||
let signer_guard = lock(&self.signer);
|
||||
if let Some(signer) = signer_guard.as_ref() {
|
||||
self.publish_signed(signer, new_src, new_serial)?;
|
||||
} else {
|
||||
let diff = Diff { from_soa: cur.soa().clone(), to_soa: new_src.soa().clone(), removed: rm, added: add };
|
||||
self.install(new_src, vec![diff]);
|
||||
}
|
||||
Ok(new_serial)
|
||||
}
|
||||
|
||||
/// Send NOTIFY to all configured targets (fire-and-forget, with retries).
|
||||
pub fn send_notifies(self: &Arc<Self>) {
|
||||
let Some(zone) = self.current() else { return };
|
||||
for target in self.config.notify.clone() {
|
||||
let me = Arc::clone(self);
|
||||
let soa = zone.soa().clone();
|
||||
tokio::spawn(async move {
|
||||
let mut ok = false;
|
||||
for attempt in 0..3u32 {
|
||||
match dns_core::client::notify(target, &me.name, Some(&soa), me.notify_key.as_ref(), Duration::from_secs(2)).await {
|
||||
Ok(rc) => {
|
||||
tracing::info!(zone = %me.name, %target, rcode = %rc, "NOTIFY acknowledged");
|
||||
ok = true;
|
||||
break;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(zone = %me.name, %target, attempt, error = %e, "NOTIFY failed");
|
||||
tokio::time::sleep(Duration::from_secs(1 << attempt)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
me.notify_count.fetch_add(1, Ordering::Relaxed);
|
||||
me.update_status(|s| if ok { s.notifies_sent += 1 } else { s.notifies_failed += 1 });
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// All zones served by the node.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ZoneStore {
|
||||
zones: Vec<Arc<ZoneEntry>>,
|
||||
}
|
||||
|
||||
impl ZoneStore {
|
||||
/// Build the store from configuration, reusing unchanged entries from `previous`
|
||||
/// (so running secondary tasks and loaded data survive a reload).
|
||||
pub fn build(cfg: &Config, ring: &KeyRing, previous: Option<&ZoneStore>) -> Result<(Self, Vec<Arc<ZoneEntry>>), String> {
|
||||
let mut zones = Vec::new();
|
||||
let mut fresh = Vec::new();
|
||||
for zc in &cfg.zones {
|
||||
let reuse =
|
||||
previous.and_then(|p| p.zones.iter().find(|e| serde_json::to_string(&e.config).ok() == serde_json::to_string(zc).ok()));
|
||||
match reuse {
|
||||
Some(e) => {
|
||||
if e.kind == ZoneKind::Primary {
|
||||
match e.load_primary_file() {
|
||||
Ok(true) => e.send_notifies(),
|
||||
Ok(false) => {}
|
||||
Err(err) => {
|
||||
tracing::error!(zone = %e.name, error = %err, "reload failed; keeping previous version");
|
||||
e.update_status(|s| s.last_error = Some(err));
|
||||
}
|
||||
}
|
||||
}
|
||||
zones.push(Arc::clone(e));
|
||||
}
|
||||
None => {
|
||||
let e = Arc::new(ZoneEntry::new(cfg, zc, ring)?);
|
||||
match e.kind {
|
||||
ZoneKind::Primary => {
|
||||
e.load_primary_file().map_err(|err| format!("zone {}: {err}", e.name))?;
|
||||
}
|
||||
ZoneKind::Secondary => crate::secondary::load_snapshot(&e),
|
||||
}
|
||||
fresh.push(Arc::clone(&e));
|
||||
zones.push(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(p) = previous {
|
||||
for old in &p.zones {
|
||||
if !zones.iter().any(|z| Arc::ptr_eq(z, old)) {
|
||||
old.shutdown.store(true, Ordering::Release);
|
||||
old.refresh_trigger.notify_one();
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok((Self { zones }, fresh))
|
||||
}
|
||||
|
||||
/// Longest-match zone for `qname` visible in `view`.
|
||||
pub fn find(&self, qname: &LowerName, view: Option<&str>) -> Option<Arc<ZoneEntry>> {
|
||||
self.zones.iter().filter(|z| z.visible_in(view) && z.lname.zone_of(qname)).max_by_key(|z| z.lname.num_labels()).cloned()
|
||||
}
|
||||
|
||||
/// Exact zone by name (any view).
|
||||
pub fn get(&self, name: &Name) -> Option<Arc<ZoneEntry>> {
|
||||
let l = LowerName::new(name);
|
||||
self.zones.iter().find(|z| z.lname == l).cloned()
|
||||
}
|
||||
|
||||
pub fn all(&self) -> &[Arc<ZoneEntry>] {
|
||||
&self.zones
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn status_lock(e: &ZoneEntry) -> std::sync::MutexGuard<'_, ZoneStatus> {
|
||||
lock(&e.status)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod migration_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn old_secondary_copy_is_moved_to_new_location() {
|
||||
let d = std::env::temp_dir().join(format!("edns-sec-mig-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(d.join("secondary")).unwrap();
|
||||
std::fs::write(d.join("secondary/example.com.zone"), "zone").unwrap();
|
||||
std::fs::write(d.join("secondary/example.com.zone.meta.json"), "{}").unwrap();
|
||||
let p = default_secondary_file(&d, "example.com.");
|
||||
assert_eq!(p, d.join("zones/secondary/example.com.zone"));
|
||||
assert_eq!(std::fs::read_to_string(&p).unwrap(), "zone");
|
||||
assert!(d.join("zones/secondary/example.com.zone.meta.json").is_file());
|
||||
assert!(!d.join("secondary/example.com.zone").exists());
|
||||
// second call: nothing to move, same path
|
||||
assert_eq!(default_secondary_file(&d, "example.com."), p);
|
||||
// no old copy at all: new path
|
||||
assert_eq!(default_secondary_file(&d, "example.net."), d.join("zones/secondary/example.net.zone"));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
//! RFC 2136 dynamic updates for primary zones.
|
||||
//!
|
||||
//! Authorisation models (see `ZoneConfig::update_*`), chosen per zone:
|
||||
//! * `update_policy` – every updated record must be granted by a rule for the signing key;
|
||||
//! * `update_keys` – a valid TSIG by one of these keys may change the whole zone;
|
||||
//! * only `update_acl` – unsigned updates from listed addresses (BIND `allow-update { IPs; }`).
|
||||
//!
|
||||
//! `update_acl` also restricts sources in the first two models when set. Every accepted
|
||||
//! or refused update is logged for the audit trail by the caller.
|
||||
use std::collections::HashSet;
|
||||
|
||||
use dns_core::proto::op::{Message, ResponseCode};
|
||||
use dns_core::proto::rr::{DNSClass, LowerName, Name, RData, Record, RecordType};
|
||||
|
||||
use dns_config::update_policy::{UpdateMatch, UpdateRule};
|
||||
|
||||
use crate::store::{ZoneEntry, ZoneKind};
|
||||
use crate::zone::Zone;
|
||||
|
||||
/// Outcome for the audit log.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct UpdateOutcome {
|
||||
pub rcode: ResponseCode,
|
||||
pub new_serial: Option<u32>,
|
||||
pub added: usize,
|
||||
pub removed: usize,
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
fn fail(rcode: ResponseCode, reason: impl Into<String>) -> UpdateOutcome {
|
||||
UpdateOutcome { rcode, new_serial: None, added: 0, removed: 0, reason: reason.into() }
|
||||
}
|
||||
|
||||
fn same_rdata(a: &RData, b: &RData) -> bool {
|
||||
a.to_string().eq_ignore_ascii_case(&b.to_string())
|
||||
}
|
||||
|
||||
/// Check RFC 2136 §3.2 prerequisites against `zone`.
|
||||
fn check_prereqs(zone: &Zone, prereqs: &[Record]) -> Result<(), UpdateOutcome> {
|
||||
// value-dependent RRset prerequisites are grouped per (name, type)
|
||||
let mut value_sets: Vec<(LowerName, RecordType, Vec<RData>)> = Vec::new();
|
||||
for r in prereqs {
|
||||
let lname = LowerName::new(&r.name);
|
||||
if !zone.origin_lower().zone_of(&lname) {
|
||||
return Err(fail(ResponseCode::NotZone, format!("prerequisite {} outside zone", r.name)));
|
||||
}
|
||||
if r.ttl != 0 {
|
||||
return Err(fail(ResponseCode::FormErr, "prerequisite TTL must be 0"));
|
||||
}
|
||||
let rtype = r.record_type();
|
||||
match r.dns_class {
|
||||
DNSClass::ANY => {
|
||||
if rtype == RecordType::ANY {
|
||||
if !zone.name_exists(&lname) {
|
||||
return Err(fail(ResponseCode::NXDomain, format!("{} is not in use", r.name)));
|
||||
}
|
||||
} else if zone.rrset(&lname, rtype).is_none_or(|s| s.records.is_empty()) {
|
||||
return Err(fail(ResponseCode::NXRRSet, format!("{} {rtype} does not exist", r.name)));
|
||||
}
|
||||
}
|
||||
DNSClass::NONE => {
|
||||
if rtype == RecordType::ANY {
|
||||
if zone.name_exists(&lname) {
|
||||
return Err(fail(ResponseCode::YXDomain, format!("{} is in use", r.name)));
|
||||
}
|
||||
} else if zone.rrset(&lname, rtype).is_some_and(|s| !s.records.is_empty()) {
|
||||
return Err(fail(ResponseCode::YXRRSet, format!("{} {rtype} exists", r.name)));
|
||||
}
|
||||
}
|
||||
DNSClass::IN => match value_sets.iter_mut().find(|(n, t, _)| *n == lname && *t == rtype) {
|
||||
Some((_, _, v)) => v.push(r.data.clone()),
|
||||
None => value_sets.push((lname, rtype, vec![r.data.clone()])),
|
||||
},
|
||||
_ => return Err(fail(ResponseCode::FormErr, "bad prerequisite class")),
|
||||
}
|
||||
}
|
||||
for (name, rtype, want) in value_sets {
|
||||
let have: Vec<RData> = zone.rrset(&name, rtype).map(|s| s.records.iter().map(|r| r.data.clone()).collect()).unwrap_or_default();
|
||||
let ok = have.len() == want.len() && want.iter().all(|w| have.iter().any(|h| same_rdata(h, w)));
|
||||
if !ok {
|
||||
return Err(fail(ResponseCode::NXRRSet, format!("{name} {rtype} does not match")));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Translate the update section into (removed, added) record lists (RFC 2136 §3.4).
|
||||
fn plan(zone: &Zone, updates: &[Record]) -> Result<(Vec<Record>, Vec<Record>), UpdateOutcome> {
|
||||
let apex = zone.origin_lower().clone();
|
||||
let mut removed: Vec<Record> = Vec::new();
|
||||
let mut added: Vec<Record> = Vec::new();
|
||||
let mut removed_keys: HashSet<(LowerName, RecordType, String)> = HashSet::new();
|
||||
let mut remove = |r: &Record, removed: &mut Vec<Record>| {
|
||||
let k = (LowerName::new(&r.name), r.record_type(), r.data.to_string());
|
||||
if removed_keys.insert(k) {
|
||||
removed.push(r.clone());
|
||||
}
|
||||
};
|
||||
for u in updates {
|
||||
let lname = LowerName::new(&u.name);
|
||||
if !zone.origin_lower().zone_of(&lname) {
|
||||
return Err(fail(ResponseCode::NotZone, format!("update {} outside zone", u.name)));
|
||||
}
|
||||
let rtype = u.record_type();
|
||||
if matches!(rtype, RecordType::AXFR | RecordType::IXFR | RecordType::OPT | RecordType::TSIG) {
|
||||
return Err(fail(ResponseCode::FormErr, format!("type {rtype} not allowed in updates")));
|
||||
}
|
||||
match u.dns_class {
|
||||
DNSClass::IN => {
|
||||
if rtype == RecordType::SOA {
|
||||
// SOA changes are managed by the serial strategy; ignore (RFC 2136 §3.4.2.2 allows).
|
||||
continue;
|
||||
}
|
||||
added.push(u.clone());
|
||||
}
|
||||
DNSClass::ANY => {
|
||||
if u.ttl != 0 || !matches!(u.data, RData::Update0(_)) {
|
||||
return Err(fail(ResponseCode::FormErr, "delete with ANY class must have TTL 0 and no RDATA"));
|
||||
}
|
||||
if rtype == RecordType::ANY {
|
||||
for t in [
|
||||
RecordType::A,
|
||||
RecordType::AAAA,
|
||||
RecordType::CNAME,
|
||||
RecordType::MX,
|
||||
RecordType::TXT,
|
||||
RecordType::SRV,
|
||||
RecordType::PTR,
|
||||
RecordType::CAA,
|
||||
RecordType::NAPTR,
|
||||
RecordType::SVCB,
|
||||
RecordType::HTTPS,
|
||||
RecordType::NS,
|
||||
RecordType::DS,
|
||||
] {
|
||||
if lname == apex && t == RecordType::NS {
|
||||
continue;
|
||||
}
|
||||
if let Some(s) = zone.rrset(&lname, t) {
|
||||
for r in &s.records {
|
||||
remove(r, &mut removed);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if lname == apex && matches!(rtype, RecordType::SOA | RecordType::NS) {
|
||||
continue;
|
||||
}
|
||||
if let Some(s) = zone.rrset(&lname, rtype) {
|
||||
for r in &s.records {
|
||||
remove(r, &mut removed);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
DNSClass::NONE => {
|
||||
if u.ttl != 0 {
|
||||
return Err(fail(ResponseCode::FormErr, "delete with NONE class must have TTL 0"));
|
||||
}
|
||||
if rtype == RecordType::SOA {
|
||||
continue;
|
||||
}
|
||||
if let Some(s) = zone.rrset(&lname, rtype) {
|
||||
let apex_ns_last = lname == apex && rtype == RecordType::NS && s.records.len() <= 1;
|
||||
if apex_ns_last {
|
||||
continue;
|
||||
}
|
||||
for r in s.records.iter().filter(|r| same_rdata(&r.data, &u.data)) {
|
||||
remove(r, &mut removed);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => return Err(fail(ResponseCode::FormErr, "bad update class")),
|
||||
}
|
||||
}
|
||||
Ok((removed, added))
|
||||
}
|
||||
|
||||
/// Record types a rule without a type list does not cover (as in BIND).
|
||||
const DEFAULT_EXCLUDED: &[RecordType] = &[RecordType::SOA, RecordType::NS, RecordType::RRSIG, RecordType::NSEC, RecordType::NSEC3];
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
enum Types {
|
||||
Default,
|
||||
Any,
|
||||
List(Vec<RecordType>),
|
||||
}
|
||||
|
||||
/// A compiled `update_policy` rule.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PolicyRule {
|
||||
grant: bool,
|
||||
/// None = any valid key (`*`).
|
||||
identity: Option<LowerName>,
|
||||
matches: UpdateMatch,
|
||||
/// For `wildcard`: the base name below the `*` label.
|
||||
name: Option<LowerName>,
|
||||
types: Types,
|
||||
}
|
||||
|
||||
fn abs_name(s: &str) -> Result<LowerName, String> {
|
||||
let mut n = Name::from_utf8(s).map_err(|e| format!("{s}: {e}"))?;
|
||||
n.set_fqdn(true);
|
||||
Ok(LowerName::new(&n))
|
||||
}
|
||||
|
||||
/// Compile configured rules (names are absolute, as in named.conf).
|
||||
pub fn compile_policy(rules: &[UpdateRule]) -> Result<Vec<PolicyRule>, String> {
|
||||
rules
|
||||
.iter()
|
||||
.map(|r| {
|
||||
let identity = if r.identity == "*" { None } else { Some(abs_name(&r.identity)?) };
|
||||
let name = match (&r.name, r.matches) {
|
||||
(Some(n), UpdateMatch::Wildcard) => Some(abs_name(n.trim_start_matches("*."))?),
|
||||
(Some(n), _) => Some(abs_name(n)?),
|
||||
(None, _) => None,
|
||||
};
|
||||
let types = if r.types.is_empty() {
|
||||
Types::Default
|
||||
} else if r.types.iter().any(|t| t == "ANY") {
|
||||
Types::Any
|
||||
} else {
|
||||
Types::List(r.types.iter().map(|t| t.parse::<RecordType>().map_err(|e| format!("{t}: {e}"))).collect::<Result<_, _>>()?)
|
||||
};
|
||||
Ok(PolicyRule { grant: r.grant, identity, matches: r.matches, name, types })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl PolicyRule {
|
||||
fn applies(&self, signer: &LowerName, owner: &LowerName, rtype: RecordType) -> bool {
|
||||
if self.identity.as_ref().is_some_and(|i| i != signer) {
|
||||
return false;
|
||||
}
|
||||
let name_ok = match (self.matches, &self.name) {
|
||||
(UpdateMatch::Name, Some(n)) => owner == n,
|
||||
(UpdateMatch::Subdomain, Some(n)) => n.zone_of(owner),
|
||||
(UpdateMatch::Wildcard, Some(base)) => base.zone_of(owner) && owner != base,
|
||||
(UpdateMatch::Zonesub, _) => true, // owner is already checked to be inside the zone
|
||||
(UpdateMatch::SelfName, _) => owner == signer,
|
||||
(UpdateMatch::Selfsub, _) => signer.zone_of(owner),
|
||||
_ => false,
|
||||
};
|
||||
name_ok
|
||||
&& match &self.types {
|
||||
Types::Any => true,
|
||||
// deleting all RRsets at a name needs a rule covering every type
|
||||
Types::Default => rtype != RecordType::ANY && !DEFAULT_EXCLUDED.contains(&rtype),
|
||||
Types::List(l) => rtype != RecordType::ANY && l.contains(&rtype),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// First matching rule decides; no match = not permitted.
|
||||
pub fn policy_permits(rules: &[PolicyRule], signer: &LowerName, owner: &LowerName, rtype: RecordType) -> bool {
|
||||
rules.iter().find(|r| r.applies(signer, owner, rtype)).is_some_and(|r| r.grant)
|
||||
}
|
||||
|
||||
/// Who is asking: the name of a valid TSIG key (any key known to the server), and whether
|
||||
/// the source address is in `update_acl`.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Requester<'a> {
|
||||
pub signer: Option<&'a Name>,
|
||||
pub addr_ok: bool,
|
||||
}
|
||||
|
||||
fn authorize(entry: &ZoneEntry, msg: &Message, who: Requester<'_>) -> Result<(), UpdateOutcome> {
|
||||
let refuse = |m: String| Err(fail(ResponseCode::Refused, m));
|
||||
let acl_set = !entry.update_acl.is_empty();
|
||||
if !entry.update_policy.is_empty() {
|
||||
let Some(signer) = who.signer else {
|
||||
return refuse("update_policy requires a TSIG-signed update".into());
|
||||
};
|
||||
if acl_set && !who.addr_ok {
|
||||
return refuse("client address not in update_acl".into());
|
||||
}
|
||||
let signer = LowerName::new(signer);
|
||||
for r in &msg.authorities {
|
||||
let owner = LowerName::new(&r.name);
|
||||
if !policy_permits(&entry.update_policy, &signer, &owner, r.record_type()) {
|
||||
return refuse(format!("{} {} not permitted for key {} by update_policy", r.name, r.record_type(), Name::from(&signer)));
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if !entry.update_keys.is_empty() {
|
||||
let key_ok = who.signer.is_some_and(|s| entry.update_keys.iter().any(|k| &k.name == s));
|
||||
if !key_ok {
|
||||
return refuse("update not signed with an authorised TSIG key".into());
|
||||
}
|
||||
if acl_set && !who.addr_ok {
|
||||
return refuse("client address not in update_acl".into());
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if acl_set {
|
||||
// IP-only model (BIND allow-update { addresses; })
|
||||
return if who.addr_ok { Ok(()) } else { refuse("client address not in update_acl".into()) };
|
||||
}
|
||||
refuse("dynamic updates are disabled for this zone".into())
|
||||
}
|
||||
|
||||
/// Process an UPDATE message for `entry`.
|
||||
pub fn apply(entry: &ZoneEntry, msg: &Message, who: Requester<'_>) -> UpdateOutcome {
|
||||
if entry.kind != ZoneKind::Primary {
|
||||
return fail(ResponseCode::NotImp, "updates are only accepted by the primary");
|
||||
}
|
||||
if let Err(o) = authorize(entry, msg, who) {
|
||||
return o;
|
||||
}
|
||||
let Some(zone) = entry.current() else {
|
||||
return fail(ResponseCode::ServFail, "zone not loaded");
|
||||
};
|
||||
if let Err(o) = check_prereqs(&zone, &msg.answers) {
|
||||
return o;
|
||||
}
|
||||
let (removed, added) = match plan(&zone, &msg.authorities) {
|
||||
Ok(p) => p,
|
||||
Err(o) => return o,
|
||||
};
|
||||
if removed.is_empty() && added.is_empty() {
|
||||
return UpdateOutcome {
|
||||
rcode: ResponseCode::NoError,
|
||||
new_serial: Some(zone.serial()),
|
||||
added: 0,
|
||||
removed: 0,
|
||||
reason: "no changes".into(),
|
||||
};
|
||||
}
|
||||
match entry.modify(&removed, &added) {
|
||||
Ok(serial) => UpdateOutcome {
|
||||
rcode: ResponseCode::NoError,
|
||||
new_serial: Some(serial),
|
||||
added: added.len(),
|
||||
removed: removed.len(),
|
||||
reason: "applied".into(),
|
||||
},
|
||||
Err(e) => fail(ResponseCode::Refused, format!("update rejected: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper used by tools and tests: build an UPDATE message for `zone`.
|
||||
pub fn build_update(zone: &Name, prereqs: Vec<Record>, updates: Vec<Record>) -> Message {
|
||||
use dns_core::proto::op::{MessageType, OpCode, Query};
|
||||
let mut m = Message::new(rand::random::<u16>(), MessageType::Query, OpCode::Update);
|
||||
let mut q = Query::query(zone.clone(), RecordType::SOA);
|
||||
q.set_query_class(DNSClass::IN);
|
||||
m.add_query(q);
|
||||
m.answers = prereqs;
|
||||
m.authorities = updates;
|
||||
m
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
//! Zone transfer responses (server side) and transfer stream application (client side).
|
||||
use dns_core::proto::op::{Message, MessageType};
|
||||
use dns_core::proto::rr::{Name, Record, RecordType};
|
||||
use dns_core::proto::serialize::binary::BinEncodable;
|
||||
|
||||
use crate::journal::{Diff, Journal, soa_serial};
|
||||
use crate::zone::{Zone, ZoneError};
|
||||
|
||||
/// Soft limit for a single transfer message (bytes); TCP allows 64 KiB.
|
||||
pub const MESSAGE_BUDGET: usize = 16 * 1024;
|
||||
|
||||
fn new_response(req: &Message) -> Message {
|
||||
let mut m = Message::new(req.metadata.id, MessageType::Response, req.metadata.op_code);
|
||||
m.metadata.authoritative = true;
|
||||
m.queries = req.queries.clone();
|
||||
m
|
||||
}
|
||||
|
||||
/// Split a record stream into response messages of at most ~[`MESSAGE_BUDGET`] bytes.
|
||||
pub fn chunk(req: &Message, records: Vec<Record>) -> Vec<Message> {
|
||||
let mut out = Vec::new();
|
||||
let mut cur = new_response(req);
|
||||
let mut size = 64usize;
|
||||
for r in records {
|
||||
let rs = r.to_bytes().map(|b| b.len()).unwrap_or(512);
|
||||
if size + rs > MESSAGE_BUDGET && !cur.answers.is_empty() {
|
||||
out.push(std::mem::replace(&mut cur, new_response(req)));
|
||||
cur.queries.clear(); // question only in the first message (RFC 5936 §2.2)
|
||||
size = 64;
|
||||
}
|
||||
size += rs;
|
||||
cur.answers.push(r);
|
||||
}
|
||||
out.push(cur);
|
||||
out
|
||||
}
|
||||
|
||||
/// Full AXFR record stream: SOA, records..., SOA.
|
||||
pub fn axfr_records(zone: &Zone) -> Vec<Record> {
|
||||
let mut v = zone.all_records();
|
||||
v.push(zone.soa().clone());
|
||||
v
|
||||
}
|
||||
|
||||
/// IXFR record stream for a client at `client_serial` (RFC 1995).
|
||||
/// Falls back to AXFR-style when the journal cannot bridge the gap.
|
||||
pub fn ixfr_records(zone: &Zone, journal: &Journal, client_serial: u32) -> (Vec<Record>, bool) {
|
||||
if !dns_core::serial::is_newer(zone.serial(), client_serial) {
|
||||
return (vec![zone.soa().clone()], true);
|
||||
}
|
||||
match journal.since(client_serial) {
|
||||
Some(chain) if chain.last().map(|d| d.to_serial()) == Some(zone.serial()) => {
|
||||
let mut v = vec![zone.soa().clone()];
|
||||
for d in chain {
|
||||
v.push(d.from_soa.clone());
|
||||
v.extend(d.removed.iter().cloned());
|
||||
v.push(d.to_soa.clone());
|
||||
v.extend(d.added.iter().cloned());
|
||||
}
|
||||
v.push(zone.soa().clone());
|
||||
(v, true)
|
||||
}
|
||||
_ => (axfr_records(zone), false),
|
||||
}
|
||||
}
|
||||
|
||||
/// Outcome of applying a received transfer.
|
||||
#[derive(Debug)]
|
||||
pub enum Applied {
|
||||
UpToDate,
|
||||
Full(Zone),
|
||||
Incremental(Zone, Vec<Diff>),
|
||||
}
|
||||
|
||||
/// Build a zone from an AXFR (or AXFR-style IXFR) record stream.
|
||||
pub fn zone_from_axfr(origin: &Name, records: &[Record], limit: usize) -> Result<Zone, String> {
|
||||
let (Some(first), Some(last)) = (records.first(), records.last()) else {
|
||||
return Err("empty transfer".into());
|
||||
};
|
||||
if first.record_type() != RecordType::SOA || last.record_type() != RecordType::SOA || records.len() < 2 {
|
||||
return Err("transfer is not framed by SOA records".into());
|
||||
}
|
||||
if first.data != last.data {
|
||||
return Err("first and last SOA differ (zone changed during transfer)".into());
|
||||
}
|
||||
if !first.name.eq_ignore_root_case(origin) {
|
||||
return Err(format!("SOA owner {} does not match zone {origin}", first.name));
|
||||
}
|
||||
let body = records[..records.len() - 1].to_vec();
|
||||
Zone::from_records_limited(origin, body, limit).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Apply an IXFR/AXFR stream on top of `current` (if any).
|
||||
pub fn apply_transfer(origin: &Name, current: Option<&Zone>, records: &[Record], limit: usize) -> Result<Applied, String> {
|
||||
if records.len() == 1 {
|
||||
return Ok(Applied::UpToDate);
|
||||
}
|
||||
let incremental = records.len() >= 2 && records[1].record_type() == RecordType::SOA;
|
||||
if !incremental {
|
||||
return zone_from_axfr(origin, records, limit).map(Applied::Full);
|
||||
}
|
||||
let Some(cur) = current else {
|
||||
return Err("incremental transfer received but no local zone to apply it to".into());
|
||||
};
|
||||
let final_serial = soa_serial(&records[0]);
|
||||
let mut zone = cur.clone();
|
||||
let mut diffs = Vec::new();
|
||||
let mut i = 1;
|
||||
let body_end = records.len() - 1; // last record is the closing SOA
|
||||
while i < body_end {
|
||||
let from = &records[i];
|
||||
if from.record_type() != RecordType::SOA {
|
||||
return Err("malformed IXFR: expected SOA at start of difference sequence".into());
|
||||
}
|
||||
if soa_serial(from) != zone.serial() {
|
||||
return Err(format!("IXFR difference starts at serial {} but local zone has {}", soa_serial(from), zone.serial()));
|
||||
}
|
||||
i += 1;
|
||||
let mut removed = Vec::new();
|
||||
while i < body_end && records[i].record_type() != RecordType::SOA {
|
||||
removed.push(records[i].clone());
|
||||
i += 1;
|
||||
}
|
||||
if i >= body_end {
|
||||
return Err("malformed IXFR: missing new SOA in difference sequence".into());
|
||||
}
|
||||
let to = records[i].clone();
|
||||
i += 1;
|
||||
let mut added = Vec::new();
|
||||
while i < body_end && records[i].record_type() != RecordType::SOA {
|
||||
added.push(records[i].clone());
|
||||
i += 1;
|
||||
}
|
||||
zone = zone.apply(&removed, &added, to.clone(), limit).map_err(|e: ZoneError| e.to_string())?;
|
||||
diffs.push(Diff { from_soa: from.clone(), to_soa: to, removed, added });
|
||||
}
|
||||
if zone.serial() != final_serial || records[body_end].data != records[0].data {
|
||||
return Err("IXFR did not end at the announced serial".into());
|
||||
}
|
||||
Ok(Applied::Incremental(zone, diffs))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use dns_core::zonefile::parse_str;
|
||||
|
||||
const Z1: &str = "$TTL 60\n@ IN SOA ns hm 1 3600 600 86400 60\n@ IN NS ns\nns IN A 192.0.2.1\nwww IN A 192.0.2.10\n";
|
||||
|
||||
fn z(text: &str) -> Zone {
|
||||
let o = Name::from_ascii("example.com.").unwrap();
|
||||
Zone::from_records(&o, parse_str(text, &o, None).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn axfr_roundtrip_and_chunking() {
|
||||
let mut text = Z1.to_string();
|
||||
for i in 0..2000 {
|
||||
text.push_str(&format!("h{i} IN TXT \"{:0>100}\"\n", i));
|
||||
}
|
||||
let zone = z(&text);
|
||||
let recs = axfr_records(&zone);
|
||||
let req = Message::query();
|
||||
let msgs = chunk(&req, recs.clone());
|
||||
assert!(msgs.len() > 5);
|
||||
for m in &msgs {
|
||||
assert!(m.to_vec().unwrap().len() <= MESSAGE_BUDGET + 600);
|
||||
}
|
||||
let flat: Vec<Record> = msgs.into_iter().flat_map(|m| m.answers).collect();
|
||||
let o = Name::from_ascii("example.com.").unwrap();
|
||||
let back = zone_from_axfr(&o, &flat, usize::MAX).unwrap();
|
||||
assert_eq!(back.record_count(), zone.record_count());
|
||||
// truncated stream is rejected
|
||||
assert!(zone_from_axfr(&o, &flat[..flat.len() - 1], usize::MAX).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ixfr_incremental_and_fallback() {
|
||||
let z1 = z(Z1);
|
||||
let z2 = z(&Z1.replace("hm 1 ", "hm 2 ").replace("192.0.2.10", "192.0.2.11"));
|
||||
let z3 = z(&Z1.replace("hm 1 ", "hm 3 ").replace("192.0.2.10", "192.0.2.12"));
|
||||
let mut j = Journal::in_memory(10);
|
||||
for (a, b) in [(&z1, &z2), (&z2, &z3)] {
|
||||
let (rm, add) = a.diff(b);
|
||||
j.push(Diff { from_soa: a.soa().clone(), to_soa: b.soa().clone(), removed: rm, added: add });
|
||||
}
|
||||
let (recs, incr) = ixfr_records(&z3, &j, 1);
|
||||
assert!(incr);
|
||||
let o = Name::from_ascii("example.com.").unwrap();
|
||||
match apply_transfer(&o, Some(&z1), &recs, usize::MAX).unwrap() {
|
||||
Applied::Incremental(z, diffs) => {
|
||||
assert_eq!(z.serial(), 3);
|
||||
assert_eq!(diffs.len(), 2);
|
||||
assert!(z.diff(&z3).0.is_empty());
|
||||
}
|
||||
o => panic!("{o:?}"),
|
||||
}
|
||||
// up to date
|
||||
let (recs, _) = ixfr_records(&z3, &j, 3);
|
||||
assert!(matches!(apply_transfer(&o, Some(&z3), &recs, usize::MAX).unwrap(), Applied::UpToDate));
|
||||
// unknown serial -> AXFR style
|
||||
let (recs, incr) = ixfr_records(&z3, &j, 0);
|
||||
assert!(!incr);
|
||||
assert!(matches!(apply_transfer(&o, Some(&z1), &recs, usize::MAX).unwrap(), Applied::Full(_)));
|
||||
// applying an incremental stream to the wrong base fails
|
||||
let (recs, _) = ixfr_records(&z3, &j, 2);
|
||||
assert!(apply_transfer(&o, Some(&z1), &recs, usize::MAX).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,701 @@
|
||||
//! Immutable zone snapshot and the RFC 1034 §4.3.2 / RFC 4592 lookup algorithm.
|
||||
use std::collections::{BTreeSet, HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use dns_core::proto::rr::{DNSClass, LowerName, Name, RData, Record, RecordType};
|
||||
|
||||
/// A set of records with the same owner, class and type.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RRset {
|
||||
pub rtype: RecordType,
|
||||
pub records: Vec<Record>,
|
||||
pub rrsigs: Vec<Record>,
|
||||
}
|
||||
|
||||
impl RRset {
|
||||
pub fn ttl(&self) -> u32 {
|
||||
self.records.iter().map(|r| r.ttl).min().unwrap_or(0)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
struct Node {
|
||||
rrsets: HashMap<RecordType, RRset>,
|
||||
}
|
||||
|
||||
/// Errors that make a zone unloadable.
|
||||
#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)]
|
||||
pub enum ZoneError {
|
||||
#[error("zone has no SOA record at the apex")]
|
||||
NoSoa,
|
||||
#[error("zone has more than one SOA record")]
|
||||
MultipleSoa,
|
||||
#[error("zone has no NS records at the apex")]
|
||||
NoApexNs,
|
||||
#[error("record {0} is outside of zone {1}")]
|
||||
OutOfZone(String, String),
|
||||
#[error("CNAME at {0} coexists with other data")]
|
||||
CnameConflict(String),
|
||||
#[error("CNAME at the zone apex is not allowed")]
|
||||
CnameAtApex,
|
||||
#[error("multiple CNAME records at {0}")]
|
||||
MultipleCname(String),
|
||||
#[error("unsupported class {0} for record {1}")]
|
||||
BadClass(String, String),
|
||||
#[error("zone exceeds limit of {0} records")]
|
||||
TooLarge(usize),
|
||||
}
|
||||
|
||||
/// Immutable, validated zone contents. Cheap to share via `Arc`.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Zone {
|
||||
origin: Name,
|
||||
origin_lower: LowerName,
|
||||
nodes: HashMap<LowerName, Node>,
|
||||
/// All existing names including empty non-terminals.
|
||||
names: HashSet<LowerName>,
|
||||
soa: Record,
|
||||
count: usize,
|
||||
/// Owners of NSEC records (canonical order) – non-empty for signed zones.
|
||||
nsec_names: BTreeSet<Name>,
|
||||
}
|
||||
|
||||
/// Result of a lookup within one zone.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Lookup {
|
||||
/// Authoritative positive answer (may include a CNAME chain and wildcard expansion).
|
||||
Answer { answers: Vec<Record>, additional: Vec<Record>, wildcard: bool, authority: Vec<Record> },
|
||||
/// CNAME whose target is outside this zone; caller may continue resolution.
|
||||
CnameOut { answers: Vec<Record>, target: Name },
|
||||
/// Name exists, type does not.
|
||||
NoData { soa: Record, proof: Vec<Record> },
|
||||
/// Name does not exist (possibly after following a CNAME: `answers` holds the chain).
|
||||
NxDomain { soa: Record, answers: Vec<Record>, proof: Vec<Record> },
|
||||
/// Delegation to a child zone (not authoritative).
|
||||
Referral { ns: Vec<Record>, glue: Vec<Record>, ds: Vec<Record> },
|
||||
}
|
||||
|
||||
/// Limit on CNAME chains followed inside one zone.
|
||||
pub const MAX_CNAME_CHAIN: usize = 8;
|
||||
|
||||
fn is_meta(t: RecordType) -> bool {
|
||||
matches!(t, RecordType::RRSIG | RecordType::NSEC | RecordType::NSEC3)
|
||||
}
|
||||
|
||||
impl Zone {
|
||||
/// Build and validate a zone from records.
|
||||
pub fn from_records(origin: &Name, records: Vec<Record>) -> Result<Self, ZoneError> {
|
||||
Self::from_records_limited(origin, records, usize::MAX)
|
||||
}
|
||||
|
||||
pub fn from_records_limited(origin: &Name, records: Vec<Record>, limit: usize) -> Result<Self, ZoneError> {
|
||||
if records.len() > limit {
|
||||
return Err(ZoneError::TooLarge(limit));
|
||||
}
|
||||
let mut origin = origin.clone();
|
||||
origin.set_fqdn(true);
|
||||
let origin_lower = LowerName::new(&origin);
|
||||
let mut nodes: HashMap<LowerName, Node> = HashMap::new();
|
||||
let mut soa: Option<Record> = None;
|
||||
let mut count = 0;
|
||||
let mut seen: HashSet<(LowerName, RecordType, String)> = HashSet::new();
|
||||
for r in records {
|
||||
if r.dns_class != DNSClass::IN {
|
||||
return Err(ZoneError::BadClass(r.dns_class.to_string(), r.name.to_string()));
|
||||
}
|
||||
let lname = LowerName::new(&r.name);
|
||||
if !origin_lower.zone_of(&lname) {
|
||||
return Err(ZoneError::OutOfZone(r.name.to_string(), origin.to_string()));
|
||||
}
|
||||
let rtype = r.record_type();
|
||||
if rtype == RecordType::SOA {
|
||||
if lname != origin_lower {
|
||||
return Err(ZoneError::OutOfZone(format!("SOA {}", r.name), origin.to_string()));
|
||||
}
|
||||
if soa.is_some() {
|
||||
// identical duplicate SOA lines are tolerated
|
||||
if soa.as_ref().map(|s| s.data.to_string()) != Some(r.data.to_string()) {
|
||||
return Err(ZoneError::MultipleSoa);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
soa = Some(r.clone());
|
||||
}
|
||||
// de-duplicate identical RRs (RFC 2181 §5)
|
||||
if !seen.insert((lname.clone(), rtype, r.data.to_string())) {
|
||||
continue;
|
||||
}
|
||||
let node = nodes.entry(lname).or_default();
|
||||
let set_type = if rtype == RecordType::RRSIG {
|
||||
match &r.data {
|
||||
RData::DNSSEC(dns_core::proto::dnssec::rdata::DNSSECRData::RRSIG(sig)) => sig.input().type_covered,
|
||||
_ => rtype,
|
||||
}
|
||||
} else {
|
||||
rtype
|
||||
};
|
||||
let set = node.rrsets.entry(set_type).or_insert_with(|| RRset { rtype: set_type, records: Vec::new(), rrsigs: Vec::new() });
|
||||
if rtype == RecordType::RRSIG {
|
||||
set.rrsigs.push(r);
|
||||
} else {
|
||||
set.records.push(r);
|
||||
}
|
||||
count += 1;
|
||||
}
|
||||
let soa = soa.ok_or(ZoneError::NoSoa)?;
|
||||
let apex = nodes.get(&origin_lower);
|
||||
if apex.and_then(|n| n.rrsets.get(&RecordType::NS)).is_none_or(|s| s.records.is_empty()) {
|
||||
return Err(ZoneError::NoApexNs);
|
||||
}
|
||||
for (name, node) in &nodes {
|
||||
if let Some(c) = node.rrsets.get(&RecordType::CNAME) {
|
||||
if c.records.len() > 1 {
|
||||
return Err(ZoneError::MultipleCname(name.to_string()));
|
||||
}
|
||||
if *name == origin_lower {
|
||||
return Err(ZoneError::CnameAtApex);
|
||||
}
|
||||
if node.rrsets.iter().any(|(t, s)| *t != RecordType::CNAME && !is_meta(*t) && !s.records.is_empty()) {
|
||||
return Err(ZoneError::CnameConflict(name.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
// normalise RRset TTLs (RFC 2181 §5.2): use the minimum
|
||||
for node in nodes.values_mut() {
|
||||
for set in node.rrsets.values_mut() {
|
||||
let ttl = set.ttl();
|
||||
for r in &mut set.records {
|
||||
r.ttl = ttl;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut names = HashSet::new();
|
||||
for n in nodes.keys() {
|
||||
let mut cur: Name = n.into();
|
||||
loop {
|
||||
let l = LowerName::new(&cur);
|
||||
if !names.insert(l.clone()) || l == origin_lower {
|
||||
break;
|
||||
}
|
||||
cur = cur.base_name();
|
||||
}
|
||||
}
|
||||
let nsec_names = nodes
|
||||
.iter()
|
||||
.filter(|(_, n)| n.rrsets.get(&RecordType::NSEC).is_some_and(|s| !s.records.is_empty()))
|
||||
.map(|(k, _)| Name::from(k).to_lowercase())
|
||||
.collect();
|
||||
Ok(Self { origin, origin_lower, nodes, names, soa, count, nsec_names })
|
||||
}
|
||||
|
||||
pub fn origin(&self) -> &Name {
|
||||
&self.origin
|
||||
}
|
||||
pub fn origin_lower(&self) -> &LowerName {
|
||||
&self.origin_lower
|
||||
}
|
||||
pub fn soa(&self) -> &Record {
|
||||
&self.soa
|
||||
}
|
||||
pub fn serial(&self) -> u32 {
|
||||
match &self.soa.data {
|
||||
RData::SOA(s) => s.serial,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
/// (refresh, retry, expire, minimum)
|
||||
pub fn soa_timers(&self) -> (u32, u32, u32, u32) {
|
||||
match &self.soa.data {
|
||||
RData::SOA(s) => (s.refresh.max(0) as u32, s.retry.max(0) as u32, s.expire.max(0) as u32, s.minimum),
|
||||
_ => (3600, 600, 604_800, 300),
|
||||
}
|
||||
}
|
||||
pub fn record_count(&self) -> usize {
|
||||
self.count
|
||||
}
|
||||
|
||||
/// Negative-answer SOA with TTL = min(SOA TTL, SOA MINIMUM) (RFC 2308 §3).
|
||||
pub fn negative_soa(&self) -> Record {
|
||||
let mut s = self.soa.clone();
|
||||
if let RData::SOA(d) = &self.soa.data {
|
||||
s.ttl = s.ttl.min(d.minimum);
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// All records, SOA first (AXFR order). RRSIGs included.
|
||||
pub fn all_records(&self) -> Vec<Record> {
|
||||
let mut out = Vec::with_capacity(self.count);
|
||||
out.push(self.soa.clone());
|
||||
let mut keys: Vec<&LowerName> = self.nodes.keys().collect();
|
||||
keys.sort();
|
||||
for k in keys {
|
||||
if let Some(node) = self.nodes.get(k) {
|
||||
let mut types: Vec<&RecordType> = node.rrsets.keys().collect();
|
||||
types.sort_by_key(|t| u16::from(**t));
|
||||
for t in types {
|
||||
if let Some(set) = node.rrsets.get(t) {
|
||||
for r in &set.records {
|
||||
if r.record_type() != RecordType::SOA {
|
||||
out.push(r.clone());
|
||||
}
|
||||
}
|
||||
out.extend(set.rrsigs.iter().cloned());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Is the zone DNSSEC-signed (has an NSEC chain)?
|
||||
pub fn is_signed(&self) -> bool {
|
||||
!self.nsec_names.is_empty()
|
||||
}
|
||||
|
||||
fn with_sigs(&self, name: &LowerName, t: RecordType) -> Vec<Record> {
|
||||
self.rrset(name, t).map(|s| s.records.iter().chain(s.rrsigs.iter()).cloned().collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// NSEC (+RRSIG) owned by `name`.
|
||||
fn nsec_at(&self, name: &Name) -> Vec<Record> {
|
||||
self.with_sigs(&LowerName::new(name), RecordType::NSEC)
|
||||
}
|
||||
|
||||
/// NSEC (+RRSIG) whose span covers `name` (canonical predecessor, wrapping).
|
||||
fn nsec_covering(&self, name: &Name) -> Vec<Record> {
|
||||
let key = name.to_lowercase();
|
||||
let owner = self.nsec_names.range(..=key).next_back().or_else(|| self.nsec_names.iter().next_back());
|
||||
owner.map(|o| self.nsec_at(o)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// SOA (+RRSIG) for negative answers.
|
||||
fn negative_authority(&self, dnssec: bool) -> (Record, Vec<Record>) {
|
||||
let soa = self.negative_soa();
|
||||
let sigs =
|
||||
if dnssec { self.rrset(&self.origin_lower, RecordType::SOA).map(|s| s.rrsigs.clone()).unwrap_or_default() } else { Vec::new() };
|
||||
(soa, sigs)
|
||||
}
|
||||
|
||||
fn closest_encloser(&self, name: &Name) -> Name {
|
||||
let mut ce = name.base_name();
|
||||
while !self.names.contains(&LowerName::new(&ce)) && ce.num_labels() > self.origin.num_labels() {
|
||||
ce = ce.base_name();
|
||||
}
|
||||
if ce.num_labels() < self.origin.num_labels() { self.origin.clone() } else { ce }
|
||||
}
|
||||
|
||||
fn dedup(mut v: Vec<Record>) -> Vec<Record> {
|
||||
let mut seen = HashSet::new();
|
||||
v.retain(|r| seen.insert((r.name.to_lowercase(), r.record_type(), r.data.to_string())));
|
||||
v
|
||||
}
|
||||
|
||||
/// Get an RRset by exact name/type.
|
||||
pub fn rrset(&self, name: &LowerName, rtype: RecordType) -> Option<&RRset> {
|
||||
self.nodes.get(name)?.rrsets.get(&rtype)
|
||||
}
|
||||
|
||||
/// Does the name exist (including empty non-terminals)?
|
||||
pub fn name_exists(&self, name: &LowerName) -> bool {
|
||||
self.names.contains(name)
|
||||
}
|
||||
|
||||
fn find_cut(&self, qname: &LowerName) -> Option<(LowerName, &RRset)> {
|
||||
// Walk from just below the apex down to qname.
|
||||
let q: Name = qname.into();
|
||||
let total = q.num_labels();
|
||||
let apex = self.origin.num_labels();
|
||||
for n in (apex + 1)..=total {
|
||||
let cand = LowerName::new(&q.trim_to(n as usize));
|
||||
if let Some(set) = self.rrset(&cand, RecordType::NS)
|
||||
&& !set.records.is_empty()
|
||||
{
|
||||
return Some((cand, set));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn glue_for(&self, targets: impl Iterator<Item = Name>) -> Vec<Record> {
|
||||
let mut out = Vec::new();
|
||||
for t in targets {
|
||||
let l = LowerName::new(&t);
|
||||
if !self.origin_lower.zone_of(&l) {
|
||||
continue;
|
||||
}
|
||||
for rt in [RecordType::A, RecordType::AAAA] {
|
||||
if let Some(s) = self.rrset(&l, rt) {
|
||||
out.extend(s.records.iter().cloned());
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn additional_targets(records: &[Record]) -> Vec<Name> {
|
||||
records
|
||||
.iter()
|
||||
.filter_map(|r| match &r.data {
|
||||
RData::MX(mx) => Some(mx.exchange.clone()),
|
||||
RData::NS(ns) => Some(ns.0.clone()),
|
||||
RData::SRV(srv) => Some(srv.target.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Lookup `qname`/`qtype`. `qname` must be at or below the origin. With `dnssec`
|
||||
/// (DO bit) RRSIGs are included and, for signed zones, NSEC denial proofs.
|
||||
pub fn lookup(&self, qname: &Name, qtype: RecordType, dnssec: bool) -> Lookup {
|
||||
let proofs = dnssec && self.is_signed();
|
||||
let mut answers: Vec<Record> = Vec::new();
|
||||
let mut authority: Vec<Record> = Vec::new();
|
||||
let mut current = qname.clone();
|
||||
let mut wildcard_used = false;
|
||||
let negative = |answers: Vec<Record>, mut proof: Vec<Record>, nx: bool| -> Lookup {
|
||||
let (soa, sigs) = self.negative_authority(dnssec);
|
||||
proof.extend(sigs);
|
||||
let proof = Self::dedup(proof);
|
||||
if nx {
|
||||
Lookup::NxDomain { soa, answers, proof }
|
||||
} else if answers.is_empty() {
|
||||
Lookup::NoData { soa, proof }
|
||||
} else {
|
||||
// CNAME chain ending in NODATA: still a NOERROR answer with the chain.
|
||||
Lookup::Answer { answers, additional: Vec::new(), wildcard: false, authority: proof }
|
||||
}
|
||||
};
|
||||
for _ in 0..=MAX_CNAME_CHAIN {
|
||||
let lq = LowerName::new(¤t);
|
||||
if !self.origin_lower.zone_of(&lq) {
|
||||
return Lookup::CnameOut { answers, target: current };
|
||||
}
|
||||
// Delegation (except DS at the cut, which the parent answers).
|
||||
if let Some((cut, ns)) = self.find_cut(&lq) {
|
||||
let ds_at_cut = cut == lq && qtype == RecordType::DS;
|
||||
if !ds_at_cut {
|
||||
if !answers.is_empty() {
|
||||
return Lookup::CnameOut { answers, target: current };
|
||||
}
|
||||
let glue = self.glue_for(ns.records.iter().filter_map(|r| match &r.data {
|
||||
RData::NS(n) => Some(n.0.clone()),
|
||||
_ => None,
|
||||
}));
|
||||
let mut ds = Vec::new();
|
||||
if dnssec {
|
||||
ds = self.with_sigs(&cut, RecordType::DS);
|
||||
if ds.is_empty() && proofs {
|
||||
ds = self.nsec_at(&Name::from(&cut)); // proves the child is unsigned
|
||||
}
|
||||
}
|
||||
return Lookup::Referral { ns: ns.records.clone(), glue, ds };
|
||||
}
|
||||
}
|
||||
let (node, synth_owner) = if let Some(n) = self.nodes.get(&lq) {
|
||||
(Some(n), None)
|
||||
} else if self.names.contains(&lq) {
|
||||
// empty non-terminal
|
||||
let proof = if proofs { self.nsec_covering(¤t) } else { Vec::new() };
|
||||
return negative(answers, proof, false);
|
||||
} else {
|
||||
let ce = self.closest_encloser(¤t);
|
||||
let wc = match Name::from_ascii("*").and_then(|w| w.append_domain(&ce)) {
|
||||
Ok(w) => w,
|
||||
Err(_) => return negative(answers, Vec::new(), true),
|
||||
};
|
||||
match self.nodes.get(&LowerName::new(&wc)) {
|
||||
Some(n) => {
|
||||
wildcard_used = true;
|
||||
if proofs {
|
||||
authority.extend(self.nsec_covering(¤t)); // no closer match exists
|
||||
}
|
||||
(Some(n), Some((current.clone(), wc)))
|
||||
}
|
||||
None => {
|
||||
let mut proof = Vec::new();
|
||||
if proofs {
|
||||
proof.extend(self.nsec_covering(¤t));
|
||||
proof.extend(self.nsec_covering(&wc));
|
||||
}
|
||||
return negative(answers, proof, true);
|
||||
}
|
||||
}
|
||||
};
|
||||
let Some(node) = node else {
|
||||
return negative(answers, Vec::new(), true);
|
||||
};
|
||||
let rewrite = |r: &Record| -> Record {
|
||||
let mut r = r.clone();
|
||||
if let Some((o, _)) = &synth_owner {
|
||||
r.name = o.clone();
|
||||
}
|
||||
r
|
||||
};
|
||||
let push_set = |set: &RRset, out: &mut Vec<Record>| {
|
||||
out.extend(set.records.iter().map(rewrite));
|
||||
if dnssec {
|
||||
out.extend(set.rrsigs.iter().map(rewrite));
|
||||
}
|
||||
};
|
||||
if qtype == RecordType::ANY {
|
||||
for (t, set) in &node.rrsets {
|
||||
if *t != RecordType::RRSIG {
|
||||
push_set(set, &mut answers);
|
||||
}
|
||||
}
|
||||
let add = self.glue_for(Self::additional_targets(&answers).into_iter());
|
||||
return Lookup::Answer { answers, additional: add, wildcard: wildcard_used, authority: Self::dedup(authority) };
|
||||
}
|
||||
if let Some(set) = node.rrsets.get(&qtype).filter(|s| !s.records.is_empty()) {
|
||||
push_set(set, &mut answers);
|
||||
let add = self.glue_for(Self::additional_targets(&set.records).into_iter());
|
||||
return Lookup::Answer { answers, additional: add, wildcard: wildcard_used, authority: Self::dedup(authority) };
|
||||
}
|
||||
if qtype != RecordType::CNAME
|
||||
&& let Some(set) = node.rrsets.get(&RecordType::CNAME).filter(|s| !s.records.is_empty())
|
||||
{
|
||||
push_set(set, &mut answers);
|
||||
let target = match set.records.first().map(|r| &r.data) {
|
||||
Some(RData::CNAME(c)) => c.0.clone(),
|
||||
_ => return Lookup::Answer { answers, additional: Vec::new(), wildcard: wildcard_used, authority },
|
||||
};
|
||||
current = target;
|
||||
continue;
|
||||
}
|
||||
// NODATA at an existing (or wildcard-synthesised) name.
|
||||
let mut proof = authority.clone();
|
||||
if proofs {
|
||||
match &synth_owner {
|
||||
Some((_, wc)) => proof.extend(self.nsec_at(wc)),
|
||||
None => proof.extend(self.nsec_at(¤t)),
|
||||
}
|
||||
}
|
||||
return negative(answers, proof, false);
|
||||
}
|
||||
// CNAME chain too long
|
||||
Lookup::Answer { answers, additional: Vec::new(), wildcard: wildcard_used, authority }
|
||||
}
|
||||
|
||||
/// Compute (removed, added) records to go from `self` to `new` (SOA excluded).
|
||||
pub fn diff(&self, new: &Zone) -> (Vec<Record>, Vec<Record>) {
|
||||
let key = |r: &Record| (LowerName::new(&r.name), r.record_type(), r.ttl, r.data.to_string());
|
||||
let old_set: HashMap<_, Record> =
|
||||
self.all_records().into_iter().filter(|r| r.record_type() != RecordType::SOA).map(|r| (key(&r), r)).collect();
|
||||
let new_set: HashMap<_, Record> =
|
||||
new.all_records().into_iter().filter(|r| r.record_type() != RecordType::SOA).map(|r| (key(&r), r)).collect();
|
||||
let removed = old_set.iter().filter(|(k, _)| !new_set.contains_key(*k)).map(|(_, r)| r.clone()).collect();
|
||||
let added = new_set.iter().filter(|(k, _)| !old_set.contains_key(*k)).map(|(_, r)| r.clone()).collect();
|
||||
(removed, added)
|
||||
}
|
||||
|
||||
/// Apply a diff (removing then adding) and install `new_soa`.
|
||||
pub fn apply(&self, removed: &[Record], added: &[Record], new_soa: Record, limit: usize) -> Result<Zone, ZoneError> {
|
||||
let key = |r: &Record| (LowerName::new(&r.name), r.record_type(), r.data.to_string());
|
||||
let rm: HashSet<_> = removed.iter().map(key).collect();
|
||||
let mut recs: Vec<Record> =
|
||||
self.all_records().into_iter().filter(|r| r.record_type() != RecordType::SOA && !rm.contains(&key(r))).collect();
|
||||
recs.extend(added.iter().filter(|r| r.record_type() != RecordType::SOA).cloned());
|
||||
recs.push(new_soa);
|
||||
Zone::from_records_limited(&self.origin, recs, limit)
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared handle to a zone snapshot.
|
||||
pub type ZoneRef = Arc<Zone>;
|
||||
|
||||
/// Non-fatal zone quality findings (named-checkzone style).
|
||||
pub fn lint(zone: &Zone) -> Vec<String> {
|
||||
let mut w = Vec::new();
|
||||
for (name, node) in &zone.nodes {
|
||||
for set in node.rrsets.values() {
|
||||
for r in &set.records {
|
||||
if r.ttl == 0 && r.record_type() != RecordType::SOA {
|
||||
w.push(format!("{} {}: TTL is 0", r.name, r.record_type()));
|
||||
}
|
||||
let target = match &r.data {
|
||||
RData::MX(mx) => Some(("MX", mx.exchange.clone())),
|
||||
RData::NS(ns) => Some(("NS", ns.0.clone())),
|
||||
RData::SRV(s) => Some(("SRV", s.target.clone())),
|
||||
_ => None,
|
||||
};
|
||||
if let Some((kind, t)) = target {
|
||||
let lt = LowerName::new(&t);
|
||||
if zone.origin_lower.zone_of(<) {
|
||||
let has_addr = zone.rrset(<, RecordType::A).is_some() || zone.rrset(<, RecordType::AAAA).is_some();
|
||||
let is_cname = zone.rrset(<, RecordType::CNAME).is_some();
|
||||
if is_cname {
|
||||
w.push(format!("{name} {kind} target {t} is a CNAME (RFC 2181 §10.3)"));
|
||||
} else if !has_addr && !(kind == "SRV" && t.is_root()) {
|
||||
w.push(format!("{name} {kind} target {t} has no A/AAAA record in the zone"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let (refresh, retry, expire, minimum) = zone.soa_timers();
|
||||
if retry >= refresh {
|
||||
w.push(format!("SOA retry ({retry}) should be lower than refresh ({refresh})"));
|
||||
}
|
||||
if expire < refresh.saturating_add(retry) {
|
||||
w.push(format!("SOA expire ({expire}) should be greater than refresh + retry"));
|
||||
}
|
||||
if minimum > 86_400 {
|
||||
w.push(format!("SOA minimum/negative TTL ({minimum}) is larger than one day"));
|
||||
}
|
||||
w.sort();
|
||||
w
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use dns_core::zonefile::parse_str;
|
||||
|
||||
pub(crate) const ZONE: &str = r#"
|
||||
$TTL 3600
|
||||
@ IN SOA ns1 hostmaster 2024010101 7200 3600 1209600 300
|
||||
IN NS ns1
|
||||
IN NS ns2
|
||||
IN MX 10 mail
|
||||
ns1 IN A 192.0.2.1
|
||||
ns2 IN A 192.0.2.2
|
||||
mail IN A 192.0.2.25
|
||||
www IN A 192.0.2.10
|
||||
www IN AAAA 2001:db8::10
|
||||
alias IN CNAME www
|
||||
ext IN CNAME www.example.net.
|
||||
loop1 IN CNAME loop2
|
||||
loop2 IN CNAME loop1
|
||||
*.wild IN A 192.0.2.99
|
||||
a.b.c IN TXT "deep"
|
||||
sub IN NS ns.sub
|
||||
ns.sub IN A 192.0.2.53
|
||||
sub IN DS 12345 8 2 49FD46E6C4B45C55D4AC69CBD3CD34AC1AFE51DE1A6D5C4C9F2A4DFA2D5E7F3A
|
||||
"#;
|
||||
|
||||
pub(crate) fn zone() -> Zone {
|
||||
let origin = Name::from_ascii("example.com.").unwrap();
|
||||
Zone::from_records(&origin, parse_str(ZONE, &origin, None).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn n(s: &str) -> Name {
|
||||
Name::from_ascii(s).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn positive_and_additional() {
|
||||
let z = zone();
|
||||
match z.lookup(&n("example.com."), RecordType::MX, false) {
|
||||
Lookup::Answer { answers, additional, .. } => {
|
||||
assert_eq!(answers.len(), 1);
|
||||
assert_eq!(additional.len(), 1);
|
||||
}
|
||||
o => panic!("{o:?}"),
|
||||
}
|
||||
// case-insensitive
|
||||
assert!(matches!(z.lookup(&n("WWW.Example.COM."), RecordType::AAAA, false), Lookup::Answer { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negative() {
|
||||
let z = zone();
|
||||
match z.lookup(&n("www.example.com."), RecordType::TXT, false) {
|
||||
Lookup::NoData { soa, .. } => assert_eq!(soa.ttl, 300),
|
||||
o => panic!("{o:?}"),
|
||||
}
|
||||
assert!(matches!(z.lookup(&n("nope.example.com."), RecordType::A, false), Lookup::NxDomain { .. }));
|
||||
// empty non-terminal b.c → NODATA, not NXDOMAIN
|
||||
assert!(matches!(z.lookup(&n("b.c.example.com."), RecordType::A, false), Lookup::NoData { .. }));
|
||||
assert!(matches!(z.lookup(&n("c.example.com."), RecordType::A, false), Lookup::NoData { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cname_chain() {
|
||||
let z = zone();
|
||||
match z.lookup(&n("alias.example.com."), RecordType::A, false) {
|
||||
Lookup::Answer { answers, .. } => {
|
||||
assert_eq!(answers.len(), 2);
|
||||
assert_eq!(answers[0].record_type(), RecordType::CNAME);
|
||||
}
|
||||
o => panic!("{o:?}"),
|
||||
}
|
||||
assert!(
|
||||
matches!(z.lookup(&n("alias.example.com."), RecordType::CNAME, false), Lookup::Answer { ref answers, .. } if answers.len() == 1)
|
||||
);
|
||||
assert!(matches!(z.lookup(&n("ext.example.com."), RecordType::A, false), Lookup::CnameOut { .. }));
|
||||
// loops terminate
|
||||
let _ = z.lookup(&n("loop1.example.com."), RecordType::A, false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wildcard() {
|
||||
let z = zone();
|
||||
match z.lookup(&n("foo.wild.example.com."), RecordType::A, false) {
|
||||
Lookup::Answer { answers, wildcard, .. } => {
|
||||
assert!(wildcard);
|
||||
assert_eq!(answers[0].name, n("foo.wild.example.com."));
|
||||
}
|
||||
o => panic!("{o:?}"),
|
||||
}
|
||||
assert!(matches!(z.lookup(&n("x.y.wild.example.com."), RecordType::A, false), Lookup::Answer { .. }));
|
||||
assert!(matches!(z.lookup(&n("foo.wild.example.com."), RecordType::MX, false), Lookup::NoData { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delegation() {
|
||||
let z = zone();
|
||||
match z.lookup(&n("host.sub.example.com."), RecordType::A, false) {
|
||||
Lookup::Referral { ns, glue, .. } => {
|
||||
assert_eq!(ns.len(), 1);
|
||||
assert_eq!(glue.len(), 1);
|
||||
}
|
||||
o => panic!("{o:?}"),
|
||||
}
|
||||
// DS at the cut is answered by the parent.
|
||||
assert!(matches!(z.lookup(&n("sub.example.com."), RecordType::DS, false), Lookup::Answer { .. }));
|
||||
match z.lookup(&n("sub.example.com."), RecordType::A, true) {
|
||||
Lookup::Referral { ds, .. } => assert_eq!(ds.len(), 1),
|
||||
o => panic!("{o:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validation_errors() {
|
||||
let origin = n("example.com.");
|
||||
let bad = "@ IN SOA ns hm 1 2 3 4 5\n@ IN NS ns\nx IN CNAME y\nx IN A 192.0.2.1\n";
|
||||
assert_eq!(
|
||||
Zone::from_records(&origin, parse_str(bad, &origin, None).unwrap()).unwrap_err(),
|
||||
ZoneError::CnameConflict("x.example.com.".into())
|
||||
);
|
||||
let nons = "@ IN SOA ns hm 1 2 3 4 5\n";
|
||||
assert_eq!(Zone::from_records(&origin, parse_str(nons, &origin, None).unwrap()).unwrap_err(), ZoneError::NoApexNs);
|
||||
let oz = "@ IN SOA ns hm 1 2 3 4 5\n@ IN NS ns\nwww.example.org. IN A 192.0.2.1\n";
|
||||
assert!(matches!(Zone::from_records(&origin, parse_str(oz, &origin, None).unwrap()), Err(ZoneError::OutOfZone(..))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diff_apply_roundtrip() {
|
||||
let z = zone();
|
||||
let origin = n("example.com.");
|
||||
let text = ZONE.replace("2024010101", "2024010102").replace("192.0.2.10", "192.0.2.11");
|
||||
let z2 = Zone::from_records(&origin, parse_str(&text, &origin, None).unwrap()).unwrap();
|
||||
let (rm, add) = z.diff(&z2);
|
||||
assert_eq!((rm.len(), add.len()), (1, 1));
|
||||
let z3 = z.apply(&rm, &add, z2.soa().clone(), usize::MAX).unwrap();
|
||||
assert_eq!(z3.serial(), 2024010102);
|
||||
let (rm, add) = z3.diff(&z2);
|
||||
assert!(rm.is_empty() && add.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lint_findings() {
|
||||
let origin = n("example.com.");
|
||||
let t = "@ IN SOA ns hm 1 3600 7200 100 5\n@ IN NS ns\n@ IN MX 10 nomail\n";
|
||||
let z = Zone::from_records(&origin, parse_str(t, &origin, None).unwrap()).unwrap();
|
||||
let w = lint(&z);
|
||||
assert!(w.iter().any(|s| s.contains("retry")));
|
||||
assert!(w.iter().any(|s| s.contains("nomail")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "dns-cache"
|
||||
description = "EasyDNS response/RRset cache with TTL, negative caching and LRU bound"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
dns-core.workspace = true
|
||||
dns-config.workspace = true
|
||||
lru.workspace = true
|
||||
serde.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,555 @@
|
||||
//! Bounded LRU cache for resolver/forwarder answers.
|
||||
//!
|
||||
//! * Keys are namespaced (`ns`): each resolution route (recursion, each forward zone)
|
||||
//! has its own namespace, so data from a private forwarder never answers a
|
||||
//! recursive lookup and vice versa. Authoritative data is never cached here.
|
||||
//! * Entries hold the full answer for (name, type, DO-bit) – the CNAME chain, or the
|
||||
//! negative proof (SOA) – plus infrastructure RRsets (NS, glue) used by the resolver.
|
||||
//! * TTLs are clamped to `[min_ttl, max_ttl]`, negative TTLs to `max_negative_ttl`
|
||||
//! (RFC 2308) and are never extended, except via explicit `serve_stale` (RFC 8767).
|
||||
//! * Ranking (RFC 2181 §5.4.1): glue/additional data never replaces answer data.
|
||||
//! * Concurrency: the cache is split into [`SHARDS`] independently locked LRU shards
|
||||
//! (chosen by key hash), and each lock is held only to touch the LRU list and clone
|
||||
//! an `Arc` – records are copied and TTL-adjusted after the lock is released. This
|
||||
//! removes the single global lock that serialised every lookup on many-core hosts.
|
||||
//! LRU order is per shard, i.e. approximately global; total capacity is unchanged.
|
||||
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
|
||||
|
||||
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 dns_core::answer::{Answer, Security, Source};
|
||||
use dns_core::proto::op::ResponseCode;
|
||||
use dns_core::proto::rr::{LowerName, Name, Record, RecordType};
|
||||
use lru::LruCache;
|
||||
|
||||
/// Trust rank of cached data (higher wins).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum Rank {
|
||||
Glue = 1,
|
||||
Authority = 2,
|
||||
Answer = 3,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct Key {
|
||||
pub ns: u16,
|
||||
pub name: LowerName,
|
||||
pub rtype: RecordType,
|
||||
pub dnssec: bool,
|
||||
}
|
||||
|
||||
/// Number of independently locked shards (power of two). Small caches use fewer
|
||||
/// shards so that per-shard LRU stays meaningful.
|
||||
pub const SHARDS: usize = 16;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Entry {
|
||||
rcode: ResponseCode,
|
||||
// Boxed slices: no spare Vec capacity is kept per cached entry.
|
||||
answers: Box<[Record]>,
|
||||
authority: Box<[Record]>,
|
||||
security: Security,
|
||||
rank: Rank,
|
||||
stored: Instant,
|
||||
ttl: u32,
|
||||
/// Hits since insertion (popularity for prefetch).
|
||||
hits: std::sync::atomic::AtomicU32,
|
||||
/// A background refresh has been started for this entry.
|
||||
prefetching: std::sync::atomic::AtomicBool,
|
||||
}
|
||||
|
||||
/// Cache statistics.
|
||||
#[derive(Debug, Clone, Default, serde::Serialize)]
|
||||
pub struct CacheStats {
|
||||
pub entries: usize,
|
||||
pub capacity: usize,
|
||||
pub hits: u64,
|
||||
pub misses: u64,
|
||||
pub inserts: u64,
|
||||
pub evictions: u64,
|
||||
pub expired: u64,
|
||||
pub stale_served: u64,
|
||||
pub prefetches: u64,
|
||||
}
|
||||
|
||||
type Shard = Mutex<LruCache<Key, Arc<Entry>>>;
|
||||
|
||||
pub struct Cache {
|
||||
shards: Box<[Shard]>,
|
||||
hasher: RandomState,
|
||||
enabled: bool,
|
||||
min_ttl: u32,
|
||||
max_ttl: u32,
|
||||
max_neg: u32,
|
||||
serve_stale: bool,
|
||||
stale_ttl: u32,
|
||||
prefetch: bool,
|
||||
prefetches: AtomicU64,
|
||||
hits: AtomicU64,
|
||||
misses: AtomicU64,
|
||||
inserts: AtomicU64,
|
||||
evictions: AtomicU64,
|
||||
expired: AtomicU64,
|
||||
stale_served: AtomicU64,
|
||||
}
|
||||
|
||||
/// Maximum time beyond expiry that stale data may be served.
|
||||
pub const MAX_STALE: Duration = Duration::from_secs(86_400);
|
||||
|
||||
impl Cache {
|
||||
pub fn new(cfg: &dns_config::CacheConfig) -> Self {
|
||||
let total = cfg.max_entries.max(1);
|
||||
// at least 64 entries per shard, at most SHARDS shards; capacities sum to `total`
|
||||
let n = (total / 64).clamp(1, SHARDS).next_power_of_two().min(SHARDS);
|
||||
let shards = (0..n)
|
||||
.map(|i| {
|
||||
let cap = total / n + usize::from(i < total % n);
|
||||
Mutex::new(LruCache::new(NonZeroUsize::new(cap).unwrap_or(NonZeroUsize::MIN)))
|
||||
})
|
||||
.collect();
|
||||
Self {
|
||||
shards,
|
||||
hasher: RandomState::new(),
|
||||
enabled: cfg.enabled,
|
||||
min_ttl: cfg.min_ttl,
|
||||
max_ttl: cfg.max_ttl,
|
||||
max_neg: cfg.max_negative_ttl,
|
||||
serve_stale: cfg.serve_stale,
|
||||
stale_ttl: cfg.stale_ttl,
|
||||
prefetch: cfg.prefetch,
|
||||
prefetches: AtomicU64::new(0),
|
||||
hits: AtomicU64::new(0),
|
||||
misses: AtomicU64::new(0),
|
||||
inserts: AtomicU64::new(0),
|
||||
evictions: AtomicU64::new(0),
|
||||
expired: AtomicU64::new(0),
|
||||
stale_served: AtomicU64::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
fn shard(&self, key: &Key) -> std::sync::MutexGuard<'_, LruCache<Key, Arc<Entry>>> {
|
||||
// shard count is a power of two
|
||||
let i = (self.hasher.hash_one(key) as usize) & (self.shards.len() - 1);
|
||||
Self::lock(&self.shards[i])
|
||||
}
|
||||
|
||||
fn lock(s: &Shard) -> std::sync::MutexGuard<'_, LruCache<Key, Arc<Entry>>> {
|
||||
s.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// Clamp a positive TTL.
|
||||
pub fn clamp(&self, ttl: u32) -> u32 {
|
||||
ttl.clamp(self.min_ttl, self.max_ttl.max(self.min_ttl))
|
||||
}
|
||||
|
||||
fn with_ttl(records: &[Record], ttl: u32) -> Box<[Record]> {
|
||||
records
|
||||
.iter()
|
||||
.map(|r| {
|
||||
let mut r = r.clone();
|
||||
r.ttl = r.ttl.min(ttl);
|
||||
r
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Look up a cached answer; TTLs in the returned records are the remaining TTLs.
|
||||
pub fn get(&self, key: &Key) -> Option<Answer> {
|
||||
if !self.enabled {
|
||||
return None;
|
||||
}
|
||||
let e = {
|
||||
let mut c = self.shard(key);
|
||||
let Some(e) = c.get(key) else {
|
||||
drop(c);
|
||||
self.misses.fetch_add(1, Relaxed);
|
||||
return None;
|
||||
};
|
||||
if e.stored.elapsed().as_secs() >= u64::from(e.ttl) {
|
||||
if !self.serve_stale {
|
||||
c.pop(key);
|
||||
}
|
||||
drop(c);
|
||||
self.expired.fetch_add(1, Relaxed);
|
||||
self.misses.fetch_add(1, Relaxed);
|
||||
return None;
|
||||
}
|
||||
Arc::clone(e)
|
||||
}; // lock released: records are copied below without holding it
|
||||
let age = (e.stored.elapsed().as_secs() as u32).min(e.ttl);
|
||||
let remaining = e.ttl - age;
|
||||
self.hits.fetch_add(1, Relaxed);
|
||||
e.hits.fetch_add(1, Relaxed);
|
||||
Some(Self::to_answer(&e, remaining, |r| {
|
||||
let mut r = r.clone();
|
||||
r.ttl = r.ttl.saturating_sub(age).min(remaining);
|
||||
r
|
||||
}))
|
||||
}
|
||||
|
||||
fn to_answer(e: &Entry, _remaining: u32, f: impl Fn(&Record) -> Record) -> Answer {
|
||||
let mut a = Answer::new(e.rcode, Source::Cache);
|
||||
a.answers = e.answers.iter().map(&f).collect();
|
||||
a.authority = e.authority.iter().map(&f).collect();
|
||||
a.security = e.security;
|
||||
a
|
||||
}
|
||||
|
||||
/// Prefetch: `true` (once per entry) when a popular entry is about to expire and should
|
||||
/// be refreshed in the background, so clients never wait for its re-resolution.
|
||||
/// Conditions: original TTL ≥ 20 s, at least 2 hits, and less than 10 % of the TTL
|
||||
/// (at least 2 s) left. Does not change LRU order.
|
||||
pub fn prefetch_due(&self, key: &Key) -> bool {
|
||||
if !self.enabled || !self.prefetch {
|
||||
return false;
|
||||
}
|
||||
let Some(e) = self.shard(key).peek(key).map(Arc::clone) else { return false };
|
||||
if e.ttl < 20 || e.hits.load(Relaxed) < 2 || e.rcode != ResponseCode::NoError {
|
||||
return false;
|
||||
}
|
||||
let age = e.stored.elapsed().as_secs();
|
||||
let remaining = u64::from(e.ttl).saturating_sub(age);
|
||||
let window = u64::from((e.ttl / 10).max(2));
|
||||
if remaining == 0 || remaining > window {
|
||||
return false;
|
||||
}
|
||||
let first = !e.prefetching.swap(true, Relaxed);
|
||||
if first {
|
||||
self.prefetches.fetch_add(1, Relaxed);
|
||||
}
|
||||
first
|
||||
}
|
||||
|
||||
/// RFC 8767: return expired data (TTL = `stale_ttl`) when fresh resolution failed.
|
||||
pub fn get_stale(&self, key: &Key) -> Option<Answer> {
|
||||
if !self.enabled || !self.serve_stale {
|
||||
return None;
|
||||
}
|
||||
let e = Arc::clone(self.shard(key).peek(key)?);
|
||||
if e.stored.elapsed() > Duration::from_secs(u64::from(e.ttl)) + MAX_STALE {
|
||||
return None;
|
||||
}
|
||||
self.stale_served.fetch_add(1, Relaxed);
|
||||
let st = self.stale_ttl;
|
||||
let mut a = Self::to_answer(&e, st, |r| {
|
||||
let mut r = r.clone();
|
||||
r.ttl = st;
|
||||
r
|
||||
});
|
||||
a.note = Some("stale".into());
|
||||
Some(a)
|
||||
}
|
||||
|
||||
fn put(&self, key: Key, e: Entry) {
|
||||
if !self.enabled || e.ttl == 0 {
|
||||
return;
|
||||
}
|
||||
let mut c = self.shard(&key);
|
||||
if let Some(old) = c.peek(&key) {
|
||||
let fresh = old.stored.elapsed().as_secs() < u64::from(old.ttl);
|
||||
if fresh && old.rank > e.rank {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if c.len() == c.cap().get() && !c.contains(&key) {
|
||||
self.evictions.fetch_add(1, Relaxed);
|
||||
}
|
||||
c.put(key, Arc::new(e));
|
||||
drop(c);
|
||||
self.inserts.fetch_add(1, Relaxed);
|
||||
}
|
||||
|
||||
/// Cache a complete answer (positive or negative) from resolution.
|
||||
pub fn insert_answer(&self, key: Key, a: &Answer) {
|
||||
if a.security == Security::Bogus {
|
||||
return;
|
||||
}
|
||||
let ttl = match a.rcode {
|
||||
ResponseCode::NoError if !a.answers.is_empty() => self.clamp(a.answers.iter().map(|r| r.ttl).min().unwrap_or(0)),
|
||||
ResponseCode::NoError | ResponseCode::NXDomain => {
|
||||
// RFC 2308 §5: negative TTL = min(SOA TTL, SOA MINIMUM); no SOA → don't cache
|
||||
let soa = a.authority.iter().find_map(|r| match &r.data {
|
||||
dns_core::proto::rr::RData::SOA(s) => Some(r.ttl.min(s.minimum)),
|
||||
_ => None,
|
||||
});
|
||||
match soa {
|
||||
Some(t) => t.min(self.max_neg),
|
||||
None => 0,
|
||||
}
|
||||
}
|
||||
// SERVFAIL etc.: brief caching protects authorities from retry storms (RFC 9520).
|
||||
ResponseCode::ServFail => 5,
|
||||
_ => 0,
|
||||
};
|
||||
let e = Entry {
|
||||
rcode: a.rcode,
|
||||
answers: Self::with_ttl(&a.answers, ttl),
|
||||
authority: Self::with_ttl(&a.authority, ttl),
|
||||
security: a.security,
|
||||
rank: Rank::Answer,
|
||||
stored: Instant::now(),
|
||||
ttl,
|
||||
hits: Default::default(),
|
||||
prefetching: Default::default(),
|
||||
};
|
||||
self.put(key, e);
|
||||
}
|
||||
|
||||
/// Cache an infrastructure RRset (NS set or addresses) learned from referrals.
|
||||
pub fn insert_rrset(&self, ns: u16, records: &[Record], rank: Rank) {
|
||||
let Some(first) = records.first() else { return };
|
||||
let ttl = self.clamp(records.iter().map(|r| r.ttl).min().unwrap_or(0));
|
||||
let key = Key { ns, name: LowerName::new(&first.name), rtype: first.record_type(), dnssec: false };
|
||||
self.put(
|
||||
key,
|
||||
Entry {
|
||||
rcode: ResponseCode::NoError,
|
||||
answers: Self::with_ttl(records, ttl),
|
||||
authority: Box::default(),
|
||||
security: Security::Indeterminate,
|
||||
rank,
|
||||
stored: Instant::now(),
|
||||
ttl,
|
||||
hits: Default::default(),
|
||||
prefetching: Default::default(),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Fetch a cached RRset (any rank) with remaining TTLs.
|
||||
pub fn get_rrset(&self, ns: u16, name: &Name, rtype: RecordType) -> Option<Vec<Record>> {
|
||||
let key = Key { ns, name: LowerName::new(name), rtype, dnssec: false };
|
||||
let a = self.get(&key)?;
|
||||
(a.rcode == ResponseCode::NoError && !a.answers.is_empty()).then_some(a.answers)
|
||||
}
|
||||
|
||||
pub fn clear(&self) -> usize {
|
||||
self.shards
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let mut c = Self::lock(s);
|
||||
let n = c.len();
|
||||
c.clear();
|
||||
n
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// Remove all entries at or below `name`.
|
||||
pub fn clear_domain(&self, name: &Name) -> usize {
|
||||
let l = LowerName::new(name);
|
||||
let mut removed = 0;
|
||||
for s in &*self.shards {
|
||||
let mut c = Self::lock(s);
|
||||
let keys: Vec<Key> = c.iter().filter(|(k, _)| l.zone_of(&k.name)).map(|(k, _)| k.clone()).collect();
|
||||
for k in &keys {
|
||||
c.pop(k);
|
||||
}
|
||||
removed += keys.len();
|
||||
}
|
||||
removed
|
||||
}
|
||||
|
||||
pub fn stats(&self) -> CacheStats {
|
||||
let (entries, capacity) = self.shards.iter().fold((0, 0), |(n, cap), s| {
|
||||
let c = Self::lock(s);
|
||||
(n + c.len(), cap + c.cap().get())
|
||||
});
|
||||
CacheStats {
|
||||
entries,
|
||||
capacity,
|
||||
hits: self.hits.load(Relaxed),
|
||||
misses: self.misses.load(Relaxed),
|
||||
inserts: self.inserts.load(Relaxed),
|
||||
evictions: self.evictions.load(Relaxed),
|
||||
expired: self.expired.load(Relaxed),
|
||||
stale_served: self.stale_served.load(Relaxed),
|
||||
prefetches: self.prefetches.load(Relaxed),
|
||||
}
|
||||
}
|
||||
|
||||
/// Prometheus families for the cache.
|
||||
pub fn render_metrics(&self) -> String {
|
||||
let s = self.stats();
|
||||
format!(
|
||||
"# HELP dns_cache_hits_total Cache hits\n# TYPE dns_cache_hits_total counter\ndns_cache_hits_total {}\n\
|
||||
# HELP dns_cache_misses_total Cache misses\n# TYPE dns_cache_misses_total counter\ndns_cache_misses_total {}\n\
|
||||
# HELP dns_cache_evictions_total LRU evictions\n# TYPE dns_cache_evictions_total counter\ndns_cache_evictions_total {}\n\
|
||||
# HELP dns_cache_entries Current cache entries\n# TYPE dns_cache_entries gauge\ndns_cache_entries {}\n\
|
||||
# HELP dns_cache_prefetches_total Popular entries refreshed before expiry\n# TYPE dns_cache_prefetches_total counter\ndns_cache_prefetches_total {}\n",
|
||||
s.hits, s.misses, s.evictions, s.entries, s.prefetches
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use dns_core::proto::rr::{
|
||||
RData,
|
||||
rdata::{A, SOA},
|
||||
};
|
||||
|
||||
fn cfg(max: usize) -> dns_config::CacheConfig {
|
||||
dns_config::CacheConfig { max_entries: max, max_ttl: 100, min_ttl: 0, ..Default::default() }
|
||||
}
|
||||
fn key(n: &str) -> Key {
|
||||
Key { ns: 0, name: LowerName::new(&Name::from_ascii(n).unwrap()), rtype: RecordType::A, dnssec: false }
|
||||
}
|
||||
fn ans(n: &str, ttl: u32) -> Answer {
|
||||
let mut a = Answer::new(ResponseCode::NoError, Source::Recursive);
|
||||
a.answers.push(Record::from_rdata(Name::from_ascii(n).unwrap(), ttl, RData::A(A::new(192, 0, 2, 1))));
|
||||
a
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ttl_clamp_and_hit() {
|
||||
let c = Cache::new(&cfg(10));
|
||||
c.insert_answer(key("a.example."), &ans("a.example.", 5000));
|
||||
let a = c.get(&key("a.example.")).unwrap();
|
||||
assert!(a.answers[0].ttl <= 100);
|
||||
assert_eq!(a.source, Source::Cache);
|
||||
assert!(c.get(&key("b.example.")).is_none());
|
||||
let s = c.stats();
|
||||
assert_eq!((s.hits, s.misses), (1, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negative_and_zero_ttl() {
|
||||
let c = Cache::new(&cfg(10));
|
||||
let mut neg = Answer::new(ResponseCode::NXDomain, Source::Recursive);
|
||||
let z = Name::from_ascii("example.").unwrap();
|
||||
neg.authority.push(Record::from_rdata(z.clone(), 3600, RData::SOA(SOA::new(z.clone(), z, 1, 1, 1, 1, 30))));
|
||||
c.insert_answer(key("x.example."), &neg);
|
||||
let a = c.get(&key("x.example.")).unwrap();
|
||||
assert_eq!(a.rcode, ResponseCode::NXDomain);
|
||||
assert!(a.authority[0].ttl <= 30);
|
||||
// negative without SOA is not cached
|
||||
c.insert_answer(key("y.example."), &Answer::new(ResponseCode::NXDomain, Source::Recursive));
|
||||
assert!(c.get(&key("y.example.")).is_none());
|
||||
c.insert_answer(key("z.example."), &ans("z.example.", 0));
|
||||
assert!(c.get(&key("z.example.")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lru_bound_rank_and_clear() {
|
||||
let c = Cache::new(&cfg(2));
|
||||
for n in ["a.ex.", "b.ex.", "c.ex."] {
|
||||
c.insert_answer(key(n), &ans(n, 50));
|
||||
}
|
||||
assert_eq!(c.stats().entries, 2);
|
||||
assert_eq!(c.stats().evictions, 1);
|
||||
// glue never replaces fresh answer data
|
||||
let glue = vec![Record::from_rdata(Name::from_ascii("c.ex.").unwrap(), 50, RData::A(A::new(10, 0, 0, 1)))];
|
||||
c.insert_rrset(0, &glue, Rank::Glue);
|
||||
assert_eq!(c.get(&key("c.ex.")).unwrap().answers[0].data, RData::A(A::new(192, 0, 2, 1)));
|
||||
assert_eq!(c.clear_domain(&Name::from_ascii("ex.").unwrap()), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn namespaces_isolated() {
|
||||
let c = Cache::new(&cfg(10));
|
||||
c.insert_answer(key("p.corp."), &ans("p.corp.", 50));
|
||||
let mut k = key("p.corp.");
|
||||
k.ns = 1;
|
||||
assert!(c.get(&k).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod shard_tests {
|
||||
use super::*;
|
||||
use dns_core::proto::rr::{RData, rdata::A};
|
||||
|
||||
fn key(i: usize) -> Key {
|
||||
Key { ns: 0, name: LowerName::new(&Name::from_ascii(format!("h{i}.example.")).unwrap()), rtype: RecordType::A, dnssec: false }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shards_keep_total_capacity_and_bound() {
|
||||
for cap in [1, 2, 63, 64, 1000, 100_000] {
|
||||
let c = Cache::new(&dns_config::CacheConfig { max_entries: cap, max_ttl: 100, ..Default::default() });
|
||||
assert_eq!(c.stats().capacity, cap, "capacity {cap}");
|
||||
assert!(c.shards.len().is_power_of_two() && c.shards.len() <= SHARDS);
|
||||
}
|
||||
let c = Cache::new(&dns_config::CacheConfig { max_entries: 1000, max_ttl: 100, ..Default::default() });
|
||||
for i in 0..5000 {
|
||||
let mut a = Answer::new(ResponseCode::NoError, Source::Recursive);
|
||||
a.answers.push(Record::from_rdata(Name::from_ascii(format!("h{i}.example.")).unwrap(), 50, RData::A(A::new(192, 0, 2, 1))));
|
||||
c.insert_answer(key(i), &a);
|
||||
}
|
||||
let s = c.stats();
|
||||
assert!(s.entries <= 1000 && s.entries > 900, "entries {}", s.entries);
|
||||
assert!(c.get(&key(4999)).is_some());
|
||||
assert_eq!(c.clear(), s.entries);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefetch_only_for_popular_entries_close_to_expiry() {
|
||||
let c = Cache::new(&dns_config::CacheConfig { max_entries: 1000, max_ttl: 100_000, ..Default::default() });
|
||||
let mk = |age: u64, ttl: u32| Entry {
|
||||
rcode: ResponseCode::NoError,
|
||||
answers: Box::default(),
|
||||
authority: Box::default(),
|
||||
security: Security::Indeterminate,
|
||||
rank: Rank::Answer,
|
||||
stored: Instant::now().checked_sub(Duration::from_secs(age)).unwrap(),
|
||||
ttl,
|
||||
hits: Default::default(),
|
||||
prefetching: Default::default(),
|
||||
};
|
||||
// 100 s TTL, 95 s old: inside the last 10 %
|
||||
c.put(key(1), mk(95, 100));
|
||||
assert!(!c.prefetch_due(&key(1)), "not popular yet");
|
||||
c.get(&key(1));
|
||||
c.get(&key(1));
|
||||
assert!(c.prefetch_due(&key(1)), "popular and about to expire");
|
||||
assert!(!c.prefetch_due(&key(1)), "only one refresh per entry");
|
||||
// young entry or short TTL: no prefetch
|
||||
c.put(key(2), mk(10, 100));
|
||||
c.get(&key(2));
|
||||
c.get(&key(2));
|
||||
assert!(!c.prefetch_due(&key(2)));
|
||||
c.put(key(3), mk(9, 10));
|
||||
c.get(&key(3));
|
||||
c.get(&key(3));
|
||||
assert!(!c.prefetch_due(&key(3)));
|
||||
assert_eq!(c.stats().prefetches, 1);
|
||||
// disabled by configuration
|
||||
let off = Cache::new(&dns_config::CacheConfig { prefetch: false, ..Default::default() });
|
||||
off.put(key(1), mk(95, 100));
|
||||
off.get(&key(1));
|
||||
off.get(&key(1));
|
||||
assert!(!off.prefetch_due(&key(1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_get_insert() {
|
||||
let c = Arc::new(Cache::new(&dns_config::CacheConfig { max_entries: 10_000, max_ttl: 100, ..Default::default() }));
|
||||
let hs: Vec<_> = (0..8)
|
||||
.map(|t| {
|
||||
let c = Arc::clone(&c);
|
||||
std::thread::spawn(move || {
|
||||
for i in 0..2000 {
|
||||
let mut a = Answer::new(ResponseCode::NoError, Source::Recursive);
|
||||
a.answers.push(Record::from_rdata(
|
||||
Name::from_ascii(format!("h{i}.example.")).unwrap(),
|
||||
50,
|
||||
RData::A(A::new(192, 0, 2, t)),
|
||||
));
|
||||
c.insert_answer(key(i), &a);
|
||||
assert!(c.get(&key(i)).is_some());
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
for h in hs {
|
||||
h.join().unwrap();
|
||||
}
|
||||
assert_eq!(c.stats().entries, 2000);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
[package]
|
||||
name = "dns-cli"
|
||||
description = "easydns / edns – EasyDNS server and administration CLI"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lib]
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "easydns"
|
||||
path = "src/bin/easydns.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "edns"
|
||||
path = "src/bin/edns.rs"
|
||||
|
||||
[dependencies]
|
||||
dns-core.workspace = true
|
||||
dns-authoritative.workspace = true
|
||||
dns-config.workspace = true
|
||||
dns-server.workspace = true
|
||||
dns-api.workspace = true
|
||||
dns-metrics.workspace = true
|
||||
dns-recursive.workspace = true
|
||||
tokio.workspace = true
|
||||
tracing.workspace = true
|
||||
serde_json.workspace = true
|
||||
clap.workspace = true
|
||||
clap_complete.workspace = true
|
||||
clap_mangen.workspace = true
|
||||
|
||||
[build-dependencies]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,11 @@
|
||||
fn main() {
|
||||
let commit = std::process::Command::new("git")
|
||||
.args(["rev-parse", "--short=12", "HEAD"])
|
||||
.output()
|
||||
.ok()
|
||||
.filter(|o| o.status.success())
|
||||
.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
|
||||
.unwrap_or_else(|| "unknown".into());
|
||||
println!("cargo:rustc-env=EASYDNS_COMMIT={commit}");
|
||||
println!("cargo:rerun-if-changed=../../.git/HEAD");
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_cli::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_cli::main()
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
//! Tiny blocking HTTP/1.1 client for the local admin API (plain HTTP on loopback).
|
||||
use std::io::{Read, Write};
|
||||
use std::net::{TcpStream, ToSocketAddrs};
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
pub fn request(method: &str, url: &str, token: Option<&str>, body: Option<&Value>) -> Result<(u16, Value), String> {
|
||||
let rest = url.strip_prefix("http://").ok_or("API URL must start with http:// (use a TLS proxy for remote access)")?;
|
||||
let (hostport, path) = rest.split_at(rest.find('/').unwrap_or(rest.len()));
|
||||
let path = if path.is_empty() { "/" } else { path };
|
||||
let addr = hostport.to_socket_addrs().map_err(|e| e.to_string())?.next().ok_or("cannot resolve API host")?;
|
||||
let mut s = TcpStream::connect_timeout(&addr, Duration::from_secs(3)).map_err(|e| e.to_string())?;
|
||||
s.set_read_timeout(Some(Duration::from_secs(120))).map_err(|e| e.to_string())?;
|
||||
let body = body.map(|b| b.to_string()).unwrap_or_default();
|
||||
let mut req = format!("{method} {path} HTTP/1.1\r\nHost: {hostport}\r\nConnection: close\r\nAccept: application/json\r\n");
|
||||
if let Some(t) = token {
|
||||
req.push_str(&format!("Authorization: Bearer {t}\r\n"));
|
||||
}
|
||||
if !body.is_empty() {
|
||||
req.push_str(&format!("Content-Type: application/json\r\nContent-Length: {}\r\n", body.len()));
|
||||
} else if method != "GET" {
|
||||
req.push_str("Content-Length: 0\r\n");
|
||||
}
|
||||
req.push_str("\r\n");
|
||||
req.push_str(&body);
|
||||
s.write_all(req.as_bytes()).map_err(|e| e.to_string())?;
|
||||
let mut buf = Vec::new();
|
||||
s.read_to_end(&mut buf).map_err(|e| e.to_string())?;
|
||||
let (status, body) = dns_core::tls::parse_http_response_limited(&buf, 64 * 1024 * 1024)
|
||||
.map_err(|e| e.to_string())?
|
||||
.or_else(|| {
|
||||
let p = buf.windows(4).position(|w| w == b"\r\n\r\n")?;
|
||||
let st = std::str::from_utf8(&buf[..p]).ok()?.split_whitespace().nth(1)?.parse().ok()?;
|
||||
Some((st, buf[p + 4..].to_vec()))
|
||||
})
|
||||
.ok_or("invalid HTTP response")?;
|
||||
let v = if body.is_empty() {
|
||||
Value::Null
|
||||
} else {
|
||||
serde_json::from_slice(&body).unwrap_or(Value::String(String::from_utf8_lossy(&body).into()))
|
||||
};
|
||||
Ok((status, v))
|
||||
}
|
||||
@@ -0,0 +1,789 @@
|
||||
//! `easydns` (short: `edns`) – run and administer an EasyDNS server.
|
||||
//!
|
||||
//! Exit codes: 0 ok, 1 runtime/operation error, 2 invalid usage or configuration,
|
||||
//! 3 cannot reach the local API.
|
||||
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
|
||||
|
||||
mod http;
|
||||
mod zonecreate;
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use clap::{CommandFactory, Parser, Subcommand};
|
||||
use dns_config::{Config, Overrides};
|
||||
use serde_json::Value;
|
||||
|
||||
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (commit ", env!("EASYDNS_COMMIT"), ")");
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "easydns", version = VERSION, about = "EasyDNS server and administration tool")]
|
||||
struct Cli {
|
||||
/// Configuration file
|
||||
#[arg(short, long, global = true, env = "EASYDNS_CONFIG", default_value = "/etc/easydns/config.yaml")]
|
||||
config: PathBuf,
|
||||
/// API base URL for admin commands (default: from config api.listen)
|
||||
#[arg(long, global = true, env = "EASYDNS_API")]
|
||||
api: Option<String>,
|
||||
/// API bearer token
|
||||
#[arg(long, global = true, env = "EASYDNS_API_TOKEN", hide_env_values = true)]
|
||||
token: Option<String>,
|
||||
/// Output JSON
|
||||
#[arg(long, global = true)]
|
||||
json: bool,
|
||||
#[command(subcommand)]
|
||||
cmd: Cmd,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Cmd {
|
||||
/// Run the server
|
||||
Run {
|
||||
/// Override listen addresses (repeatable)
|
||||
#[arg(long)]
|
||||
listen: Vec<SocketAddr>,
|
||||
#[arg(long)]
|
||||
log_level: Option<String>,
|
||||
#[arg(long)]
|
||||
data_dir: Option<PathBuf>,
|
||||
},
|
||||
/// Validate configuration and zone files offline
|
||||
CheckConfig,
|
||||
/// Configuration helpers
|
||||
Config {
|
||||
#[command(subcommand)]
|
||||
cmd: ConfigCmd,
|
||||
},
|
||||
/// Server status (via API)
|
||||
Status,
|
||||
/// Print version
|
||||
Version,
|
||||
/// Query through the local server (via API)
|
||||
Query {
|
||||
name: String,
|
||||
#[arg(default_value = "A")]
|
||||
rtype: String,
|
||||
},
|
||||
/// Zone management: `zone create` writes files; the rest goes through the API
|
||||
#[command(visible_alias = "zone")]
|
||||
Zones {
|
||||
#[command(subcommand)]
|
||||
cmd: ZonesCmd,
|
||||
},
|
||||
/// Cache management (via API)
|
||||
Cache {
|
||||
#[command(subcommand)]
|
||||
cmd: CacheCmd,
|
||||
},
|
||||
/// Upstream status (via API)
|
||||
Upstreams {
|
||||
#[command(subcommand)]
|
||||
cmd: UpstreamsCmd,
|
||||
},
|
||||
/// Block list maintenance
|
||||
Blocklists {
|
||||
#[command(subcommand)]
|
||||
cmd: BlocklistCmd,
|
||||
},
|
||||
/// Root hints maintenance
|
||||
RootHints {
|
||||
#[command(subcommand)]
|
||||
cmd: RootHintsCmd,
|
||||
},
|
||||
/// DNSSEC key management
|
||||
Dnssec {
|
||||
#[command(subcommand)]
|
||||
cmd: DnssecCmd,
|
||||
},
|
||||
/// Hot-reload configuration (via API)
|
||||
Reload,
|
||||
/// List the EasyDNS diagnostic tools
|
||||
Tools,
|
||||
/// Generate shell completions
|
||||
Completions { shell: clap_complete::Shell },
|
||||
/// Generate a man page
|
||||
Man,
|
||||
/// Print the SHA-256 hash of an API token (for `token: sha256:<hex>`)
|
||||
HashToken { token: String },
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum ConfigCmd {
|
||||
/// Validate (same as check-config)
|
||||
Validate,
|
||||
/// Print the effective configuration (after ENV overrides) as YAML
|
||||
Show,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum ZonesCmd {
|
||||
/// Create a new primary zone with minimal records (SOA, NS, glue) in <data_dir>/zones/
|
||||
Create(zonecreate::CreateArgs),
|
||||
List,
|
||||
Show {
|
||||
zone: String,
|
||||
},
|
||||
Sync {
|
||||
zone: String,
|
||||
},
|
||||
Notify {
|
||||
zone: String,
|
||||
},
|
||||
Transfers {
|
||||
zone: String,
|
||||
},
|
||||
Records {
|
||||
zone: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum CacheCmd {
|
||||
Clear {
|
||||
#[arg(long)]
|
||||
domain: Option<String>,
|
||||
},
|
||||
Stats,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum UpstreamsCmd {
|
||||
List,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum BlocklistCmd {
|
||||
/// Download remote (https) lists into <data_dir>/blocklists and reload
|
||||
Update,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum DnssecCmd {
|
||||
/// Generate a key for a zone (CSK by default)
|
||||
Keygen {
|
||||
#[arg(long)]
|
||||
zone: String,
|
||||
/// Keys directory (zone `dnssec.keys_dir`)
|
||||
#[arg(long)]
|
||||
dir: PathBuf,
|
||||
/// ksk | zsk | csk
|
||||
#[arg(long, default_value = "csk")]
|
||||
role: String,
|
||||
/// ed25519 | ecdsap256 | ecdsap384
|
||||
#[arg(long, default_value = "ed25519")]
|
||||
algorithm: String,
|
||||
},
|
||||
/// Print DS records (for the parent) and DNSKEYs of the keys in a directory
|
||||
Ds {
|
||||
#[arg(long)]
|
||||
zone: String,
|
||||
#[arg(long)]
|
||||
dir: PathBuf,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum RootHintsCmd {
|
||||
/// Download https://www.internic.net/domain/named.root, validate, and replace the hints file
|
||||
Update {
|
||||
#[arg(long, default_value = "https://www.internic.net/domain/named.root")]
|
||||
url: String,
|
||||
},
|
||||
}
|
||||
|
||||
fn load_config(path: &Path) -> Result<Config, ExitCode> {
|
||||
Config::load(path).map_err(|e| {
|
||||
eprintln!("easydns: {e}");
|
||||
ExitCode::from(2)
|
||||
})
|
||||
}
|
||||
|
||||
fn print_check(cfg: &Config, json: bool) -> ExitCode {
|
||||
let findings = dns_server::check::check_config(cfg);
|
||||
let errors = findings.iter().filter(|f| f.severity == "error").count();
|
||||
if json {
|
||||
println!("{}", serde_json::to_string_pretty(&findings).unwrap_or_default());
|
||||
} else {
|
||||
for f in &findings {
|
||||
if f.severity == "error" {
|
||||
eprintln!("{f}");
|
||||
} else {
|
||||
println!("{f}");
|
||||
}
|
||||
}
|
||||
println!("{} error(s), {} warning(s)", errors, findings.iter().filter(|f| f.severity == "warning").count());
|
||||
}
|
||||
if errors > 0 { ExitCode::from(2) } else { ExitCode::SUCCESS }
|
||||
}
|
||||
|
||||
fn running_as_root() -> bool {
|
||||
std::fs::read_to_string("/proc/self/status")
|
||||
.ok()
|
||||
.and_then(|s| s.lines().find(|l| l.starts_with("Uid:")).map(|l| l.split_whitespace().nth(2) == Some("0")))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
async fn run(cli: &Cli, listen: Vec<SocketAddr>, log_level: Option<String>, data_dir: Option<PathBuf>) -> ExitCode {
|
||||
let ov = Overrides { listen, log_level, data_dir, api_listen: None };
|
||||
let cfg = match Config::load_with(&cli.config, &ov) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
eprintln!("easydns: {e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
dns_metrics::init_logging(&cfg.logging.level, cfg.logging.format == dns_config::LogFormat::Json);
|
||||
if running_as_root() {
|
||||
tracing::warn!("running as root is discouraged: use a dedicated user with CAP_NET_BIND_SERVICE (see deploy/systemd)");
|
||||
}
|
||||
for f in dns_server::check::check_config(&cfg) {
|
||||
match f.severity {
|
||||
"error" => tracing::error!("{f}"),
|
||||
"warning" => tracing::warn!("{f}"),
|
||||
_ => tracing::info!("{f}"),
|
||||
}
|
||||
}
|
||||
let (api_cfg, metrics_cfg) = (cfg.api.clone(), cfg.metrics.clone());
|
||||
let auth = if api_cfg.enabled {
|
||||
match dns_api_auth(&cfg) {
|
||||
Ok(a) => Some(a),
|
||||
Err(e) => {
|
||||
tracing::error!("API configuration: {e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let server = match dns_server::Server::start(cfg, Some(cli.config.clone()), ov).await {
|
||||
Ok(s) => Arc::new(s),
|
||||
Err(e) => {
|
||||
tracing::error!("startup failed: {e}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
tracing::info!(version = VERSION, "EasyDNS started");
|
||||
if let Some(auth) = auth {
|
||||
let st = Arc::new(dns_api::ApiState { server: Arc::clone(&server), auth });
|
||||
if let Err(e) = dns_api::serve_api(st, api_cfg.listen, server.shutdown_signal()).await {
|
||||
tracing::error!("{e}");
|
||||
server.shutdown().await;
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
}
|
||||
if metrics_cfg.enabled
|
||||
&& let Err(e) = dns_api::serve_metrics(Arc::clone(&server), metrics_cfg.listen, server.shutdown_signal()).await
|
||||
{
|
||||
tracing::error!("{e}");
|
||||
}
|
||||
wait_for_signals(&server).await;
|
||||
tracing::info!("shutting down");
|
||||
server.shutdown().await;
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn dns_api_auth(cfg: &Config) -> Result<dns_api::Auth, String> {
|
||||
dns_api::Auth::from_config(cfg)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
async fn wait_for_signals(server: &dns_server::ServerHandle) {
|
||||
use tokio::signal::unix::{SignalKind, signal};
|
||||
let (Ok(mut hup), Ok(mut term), Ok(mut int)) =
|
||||
(signal(SignalKind::hangup()), signal(SignalKind::terminate()), signal(SignalKind::interrupt()))
|
||||
else {
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
return;
|
||||
};
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = hup.recv() => match server.reload() {
|
||||
Ok(r) => tracing::info!(?r, "reloaded on SIGHUP"),
|
||||
Err(e) => tracing::error!("reload failed, keeping previous configuration: {e}"),
|
||||
},
|
||||
_ = term.recv() => return,
|
||||
_ = int.recv() => return,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
async fn wait_for_signals(_server: &dns_server::ServerHandle) {
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
}
|
||||
|
||||
/// Write a private key: directory 0700, file created 0600 (never briefly readable). When
|
||||
/// run as root, both get the owner of the closest existing parent directory (the
|
||||
/// `easydns` user for `/etc/easydns/data/...`), so the server can read the key.
|
||||
fn write_private_key(dir: &Path, path: &Path, contents: &[u8]) -> std::io::Result<()> {
|
||||
let owner_src = dir.ancestors().find(|a| a.exists()).map(Path::to_path_buf);
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let mut o = std::fs::OpenOptions::new();
|
||||
o.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
|
||||
o.mode(0o600);
|
||||
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
|
||||
}
|
||||
std::io::Write::write_all(&mut o.open(path)?, contents)?;
|
||||
#[cfg(unix)]
|
||||
if let Some(meta) = owner_src.and_then(|p| std::fs::metadata(p).ok()) {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
for p in [dir, path] {
|
||||
let _ = std::os::unix::fs::chown(p, Some(meta.uid()), Some(meta.gid()));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn api_base(cli: &Cli) -> String {
|
||||
if let Some(a) = &cli.api {
|
||||
return a.trim_end_matches('/').to_string();
|
||||
}
|
||||
let listen = Config::load(&cli.config).map(|c| c.api.listen).unwrap_or_else(|_| SocketAddr::from(([127, 0, 0, 1], 9953)));
|
||||
format!("http://{listen}")
|
||||
}
|
||||
|
||||
/// Token for admin commands: `--token`/`EASYDNS_API_TOKEN`, otherwise the server's local
|
||||
/// control token (`<data_dir>/control.token`, readable by root and the `easydns` group).
|
||||
fn api_token(cli: &Cli) -> Result<Option<String>, ExitCode> {
|
||||
if let Some(t) = &cli.token {
|
||||
return Ok(Some(t.clone()));
|
||||
}
|
||||
let Ok(cfg) = Config::load(&cli.config) else { return Ok(None) };
|
||||
if !cfg.api.local_token {
|
||||
return Ok(None);
|
||||
}
|
||||
let path = cfg.control_token_path();
|
||||
match std::fs::read_to_string(&path) {
|
||||
Ok(t) => Ok(Some(t.trim().to_string())),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
|
||||
eprintln!(
|
||||
"easydns: cannot read {} (permission denied): run with sudo, or add your user to the 'easydns' group",
|
||||
path.display()
|
||||
);
|
||||
Err(ExitCode::from(1))
|
||||
}
|
||||
// server not started yet (token not created) – let the request report the real problem
|
||||
Err(_) => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn api(cli: &Cli, method: &str, path: &str, body: Option<&Value>) -> Result<Value, ExitCode> {
|
||||
let url = format!("{}/api/v1{path}", api_base(cli));
|
||||
let token = api_token(cli)?;
|
||||
match http::request(method, &url, token.as_deref(), body) {
|
||||
Ok((status, v)) if (200..300).contains(&status) => Ok(v),
|
||||
Ok((status, v)) => {
|
||||
let msg = v.pointer("/error/message").and_then(Value::as_str).unwrap_or("request failed");
|
||||
eprintln!("easydns: API error {status}: {msg}");
|
||||
Err(ExitCode::from(1))
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("easydns: cannot reach API at {url}: {e}");
|
||||
Err(ExitCode::from(3))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn show(cli: &Cli, v: &Value, human: impl Fn(&Value)) {
|
||||
if cli.json {
|
||||
println!("{}", serde_json::to_string_pretty(v).unwrap_or_default());
|
||||
} else {
|
||||
human(v);
|
||||
}
|
||||
}
|
||||
|
||||
fn s(v: &Value, p: &str) -> String {
|
||||
match v.pointer(p) {
|
||||
Some(Value::String(x)) => x.clone(),
|
||||
Some(Value::Null) | None => "-".into(),
|
||||
Some(o) => o.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn download_blocklists(cli: &Cli) -> ExitCode {
|
||||
let cfg = match load_config(&cli.config) {
|
||||
Ok(c) => c,
|
||||
Err(e) => return e,
|
||||
};
|
||||
let mut rc = ExitCode::SUCCESS;
|
||||
for b in cfg.policy.blocklists.iter().filter(|b| b.enabled) {
|
||||
let Some(url) = &b.url else { continue };
|
||||
match dns_core::tls::https_get(url, Duration::from_secs(60), 64 * 1024 * 1024).await {
|
||||
Ok((200, body)) => {
|
||||
let path = cfg.data_dir().join("blocklists").join(format!("{}.txt", b.name));
|
||||
match dns_core::zonefile::atomic_write(&path, &body) {
|
||||
Ok(()) => println!("{}: {} bytes -> {}", b.name, body.len(), path.display()),
|
||||
Err(e) => {
|
||||
eprintln!("{}: {e}", b.name);
|
||||
rc = ExitCode::from(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok((st, _)) => {
|
||||
eprintln!("{}: HTTP {st}", b.name);
|
||||
rc = ExitCode::from(1);
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("{}: {e}", b.name);
|
||||
rc = ExitCode::from(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
if rc == ExitCode::SUCCESS {
|
||||
let _ = api(cli, "POST", "/config/reload", None);
|
||||
}
|
||||
rc
|
||||
}
|
||||
|
||||
async fn update_root_hints(cli: &Cli, url: &str) -> ExitCode {
|
||||
let cfg = match load_config(&cli.config) {
|
||||
Ok(c) => c,
|
||||
Err(e) => return e,
|
||||
};
|
||||
let Some(path) = cfg.recursion.root_hints.as_ref().map(|p| cfg.resolve_path(p)) else {
|
||||
eprintln!("easydns: recursion.root_hints is not set (built-in hints are used)");
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
let body = match dns_core::tls::https_get(url, Duration::from_secs(60), 1024 * 1024).await {
|
||||
Ok((200, b)) => b,
|
||||
Ok((st, _)) => {
|
||||
eprintln!("easydns: HTTP {st}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("easydns: {e}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
let text = String::from_utf8_lossy(&body).to_string();
|
||||
let servers = match dns_recursive::hints::parse(&text).and_then(|h| dns_recursive::hints::root_servers(&h)) {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
eprintln!("easydns: downloaded hints are invalid, keeping the old file: {e}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
if servers.len() < 13 {
|
||||
eprintln!("easydns: only {} root servers in download, refusing to replace hints", servers.len());
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
if let Err(e) = dns_core::zonefile::atomic_write(&path, text.as_bytes()) {
|
||||
eprintln!("easydns: {e}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
println!("root hints updated: {} servers -> {}", servers.len(), path.display());
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
/// Entry point shared by the `easydns` and `edns` binaries.
|
||||
pub fn main() -> ExitCode {
|
||||
let cli = Cli::parse();
|
||||
// one-shot commands only: the server must never exit because of a pipe message
|
||||
if !matches!(cli.cmd, Cmd::Run { .. }) {
|
||||
dns_core::quiet_broken_pipe();
|
||||
}
|
||||
let rt = match tokio::runtime::Builder::new_multi_thread().enable_all().build() {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
eprintln!("easydns: cannot start runtime: {e}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
rt.block_on(async_main(cli))
|
||||
}
|
||||
|
||||
async fn async_main(cli: Cli) -> ExitCode {
|
||||
match &cli.cmd {
|
||||
Cmd::Run { listen, log_level, data_dir } => run(&cli, listen.clone(), log_level.clone(), data_dir.clone()).await,
|
||||
Cmd::CheckConfig | Cmd::Config { cmd: ConfigCmd::Validate } => match load_config(&cli.config) {
|
||||
Ok(c) => print_check(&c, cli.json),
|
||||
Err(e) => e,
|
||||
},
|
||||
Cmd::Config { cmd: ConfigCmd::Show } => match load_config(&cli.config) {
|
||||
Ok(c) => {
|
||||
println!("{}", serde_json::to_string_pretty(&c).unwrap_or_default());
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => e,
|
||||
},
|
||||
Cmd::Version => {
|
||||
println!("easydns {VERSION}");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Cmd::Status => match api(&cli, "GET", "/status", None) {
|
||||
Ok(v) => {
|
||||
show(&cli, &v, |v| {
|
||||
println!("EasyDNS {} mode: {} uptime: {}s", s(v, "/version"), s(v, "/mode"), s(v, "/uptime_seconds"));
|
||||
println!("roles: {}", v.pointer("/roles").map(|r| r.to_string()).unwrap_or_default());
|
||||
for z in v.pointer("/zones").and_then(Value::as_array).into_iter().flatten() {
|
||||
println!(
|
||||
" {:<30} {:<10} serial {:<12} {}",
|
||||
s(z, "/name"),
|
||||
s(z, "/kind"),
|
||||
s(z, "/serial"),
|
||||
if z.pointer("/expired") == Some(&Value::Bool(true)) { "EXPIRED" } else { "ok" }
|
||||
);
|
||||
}
|
||||
});
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => e,
|
||||
},
|
||||
Cmd::Query { name, rtype } => match api(&cli, "GET", &format!("/query?name={name}&type={rtype}"), None) {
|
||||
Ok(v) => {
|
||||
show(&cli, &v, |v| {
|
||||
println!(";; rcode {} aa {} ({} ms)", s(v, "/rcode"), s(v, "/aa"), s(v, "/elapsed_ms"));
|
||||
for a in v.pointer("/answers").and_then(Value::as_array).into_iter().flatten() {
|
||||
println!("{}\t{}\tIN\t{}\t{}", s(a, "/name"), s(a, "/ttl"), s(a, "/type"), s(a, "/data"));
|
||||
}
|
||||
});
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => e,
|
||||
},
|
||||
Cmd::Zones { cmd: ZonesCmd::Create(a) } => {
|
||||
let cfg = match Config::load(&cli.config) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
eprintln!("easydns: {e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
match zonecreate::create(&cfg, &cli.config, a) {
|
||||
Ok(c) => {
|
||||
if a.dry_run {
|
||||
println!("# {} (dry run)\n{}", c.zone_file.display(), c.zone_text);
|
||||
} else {
|
||||
println!("created {}", c.zone_file.display());
|
||||
}
|
||||
match &c.definition_file {
|
||||
Some(f) if !a.dry_run => println!("created {}", f.display()),
|
||||
Some(f) => println!("# {} (dry run)\n{}", f.display(), c.definition),
|
||||
None => println!("\nAdd this to `zones:` in {}:\n{}", cli.config.display(), c.definition),
|
||||
}
|
||||
if a.reload && !a.dry_run {
|
||||
return match api(&cli, "POST", "/config/reload", None) {
|
||||
Ok(_) => {
|
||||
println!("server reloaded");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(code) => code,
|
||||
};
|
||||
}
|
||||
if !a.dry_run {
|
||||
println!("next: easydns check-config && easydns reload");
|
||||
}
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("easydns: {e}");
|
||||
ExitCode::from(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
Cmd::Zones { cmd } => {
|
||||
let (m, p) = match cmd {
|
||||
ZonesCmd::Create(_) => unreachable!("handled above"),
|
||||
ZonesCmd::List => ("GET", "/zones".to_string()),
|
||||
ZonesCmd::Show { zone } => ("GET", format!("/zones/{zone}")),
|
||||
ZonesCmd::Sync { zone } => ("POST", format!("/zones/{zone}/sync")),
|
||||
ZonesCmd::Notify { zone } => ("POST", format!("/zones/{zone}/notify")),
|
||||
ZonesCmd::Transfers { zone } => ("GET", format!("/zones/{zone}/transfers")),
|
||||
ZonesCmd::Records { zone } => ("GET", format!("/zones/{zone}/records?per_page=1000")),
|
||||
};
|
||||
match api(&cli, m, &p, None) {
|
||||
Ok(v) => {
|
||||
show(&cli, &v, |v| match v.pointer("/items").and_then(Value::as_array) {
|
||||
Some(items) => {
|
||||
for i in items {
|
||||
if i.get("data").is_some() {
|
||||
println!(
|
||||
"{:<18} {}\t{}\t{}\t{}",
|
||||
s(i, "/id"),
|
||||
s(i, "/name"),
|
||||
s(i, "/ttl"),
|
||||
s(i, "/type"),
|
||||
s(i, "/data")
|
||||
);
|
||||
} else if i.get("direction").is_some() {
|
||||
println!(
|
||||
"{} {} {} {} serial {} records {} {}",
|
||||
s(i, "/time_unix"),
|
||||
s(i, "/direction"),
|
||||
s(i, "/kind"),
|
||||
s(i, "/peer"),
|
||||
s(i, "/serial"),
|
||||
s(i, "/records"),
|
||||
if i["ok"] == Value::Bool(true) { "ok".into() } else { s(i, "/error") }
|
||||
);
|
||||
} else {
|
||||
println!(
|
||||
"{:<30} {:<10} serial {:<12} records {}",
|
||||
s(i, "/name"),
|
||||
s(i, "/kind"),
|
||||
s(i, "/serial"),
|
||||
s(i, "/records")
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
None => println!("{}", serde_json::to_string_pretty(v).unwrap_or_default()),
|
||||
});
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => e,
|
||||
}
|
||||
}
|
||||
Cmd::Cache { cmd } => {
|
||||
let r = match cmd {
|
||||
CacheCmd::Clear { domain } => {
|
||||
api(&cli, "DELETE", &domain.as_ref().map(|d| format!("/cache?domain={d}")).unwrap_or_else(|| "/cache".into()), None)
|
||||
}
|
||||
CacheCmd::Stats => api(&cli, "GET", "/cache", None),
|
||||
};
|
||||
match r {
|
||||
Ok(v) => {
|
||||
show(&cli, &v, |v| println!("{}", serde_json::to_string_pretty(v).unwrap_or_default()));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => e,
|
||||
}
|
||||
}
|
||||
Cmd::Upstreams { cmd: UpstreamsCmd::List } => match api(&cli, "GET", "/upstreams", None) {
|
||||
Ok(v) => {
|
||||
show(&cli, &v, |v| {
|
||||
for g in v.pointer("/items").and_then(Value::as_array).into_iter().flatten() {
|
||||
println!("[{}] strategy {}", s(g, "/group"), s(g, "/strategy"));
|
||||
for sv in g.pointer("/servers").and_then(Value::as_array).into_iter().flatten() {
|
||||
println!(
|
||||
" {:<40} healthy {:<5} rtt {:>8} ms queries {} failures {}",
|
||||
s(sv, "/address"),
|
||||
s(sv, "/stats/healthy"),
|
||||
sv.pointer("/stats/ewma_rtt_ms").and_then(Value::as_f64).map(|x| format!("{x:.1}")).unwrap_or("-".into()),
|
||||
s(sv, "/stats/queries"),
|
||||
s(sv, "/stats/failures")
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => e,
|
||||
},
|
||||
Cmd::Reload => match api(&cli, "POST", "/config/reload", None) {
|
||||
Ok(v) => {
|
||||
show(&cli, &v, |v| println!("reloaded: {v}"));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => e,
|
||||
},
|
||||
Cmd::Blocklists { cmd: BlocklistCmd::Update } => download_blocklists(&cli).await,
|
||||
Cmd::RootHints { cmd: RootHintsCmd::Update { url } } => update_root_hints(&cli, url).await,
|
||||
Cmd::Dnssec { cmd } => dnssec_cmd(cmd),
|
||||
Cmd::Tools => {
|
||||
for (short, long, what) in TOOLS {
|
||||
println!("{short:<8} {long:<14} {what}");
|
||||
}
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Cmd::Completions { shell } => {
|
||||
clap_complete::generate(*shell, &mut Cli::command(), "easydns", &mut std::io::stdout());
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Cmd::Man => match clap_mangen::Man::new(Cli::command()).render(&mut std::io::stdout()) {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(_) => ExitCode::from(1),
|
||||
},
|
||||
Cmd::HashToken { token } => {
|
||||
println!("sha256:{}", dns_api::hash_token(token));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn dnssec_cmd(cmd: &DnssecCmd) -> ExitCode {
|
||||
use dns_core::dnssec::{KeyAlgorithm, ZoneKey, key_file_contents, parse_key_file};
|
||||
match cmd {
|
||||
DnssecCmd::Keygen { zone, dir, role, algorithm } => {
|
||||
let Ok(z) = dns_core::names::parse_name(zone) else { return ExitCode::from(2) };
|
||||
let alg: KeyAlgorithm = match serde_json::from_value(Value::String(algorithm.to_ascii_lowercase())) {
|
||||
Ok(a) => a,
|
||||
Err(_) => {
|
||||
eprintln!("easydns: unknown algorithm {algorithm}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
let ksk = role != "zsk";
|
||||
let (pk, key) = match ZoneKey::generate(alg, ksk) {
|
||||
Ok(k) => k,
|
||||
Err(e) => {
|
||||
eprintln!("easydns: {e}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
let prefix = if z.is_root() { "root.".to_string() } else { z.to_ascii().to_ascii_lowercase() };
|
||||
let path = dir.join(format!("{prefix}{}.{}.key", key.tag, role));
|
||||
if let Err(e) = write_private_key(dir, &path, key_file_contents(alg, ksk, &pk).as_bytes()) {
|
||||
eprintln!("easydns: {}: {e}", path.display());
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
println!("created {} (key tag {}, {role})", path.display(), key.tag);
|
||||
if ksk && let Ok(ds) = key.ds_record(&z, 3600) {
|
||||
println!("DS for the parent zone:\n{} {} IN DS {}", ds.name, ds.ttl, ds.data);
|
||||
}
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
DnssecCmd::Ds { zone, dir } => {
|
||||
let Ok(z) = dns_core::names::parse_name(zone) else { return ExitCode::from(2) };
|
||||
let prefix = if z.is_root() { "root.".to_string() } else { z.to_ascii().to_ascii_lowercase() };
|
||||
let mut found = 0;
|
||||
for e in std::fs::read_dir(dir).into_iter().flatten().flatten() {
|
||||
let name = e.file_name().to_string_lossy().to_ascii_lowercase();
|
||||
if !name.starts_with(&prefix) || !name.ends_with(".key") {
|
||||
continue;
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(e.path()) else { continue };
|
||||
match parse_key_file(&text) {
|
||||
Ok(k) => {
|
||||
found += 1;
|
||||
let dk = k.dnskey_record(&z, 3600);
|
||||
println!("{} {} IN DNSKEY {}", dk.name, dk.ttl, dk.data);
|
||||
if k.ksk
|
||||
&& let Ok(ds) = k.ds_record(&z, 3600)
|
||||
{
|
||||
println!("{} {} IN DS {}", ds.name, ds.ttl, ds.data);
|
||||
}
|
||||
}
|
||||
Err(err) => eprintln!("{}: {err}", e.path().display()),
|
||||
}
|
||||
}
|
||||
if found == 0 {
|
||||
eprintln!("easydns: no keys for {z} in {}", dir.display());
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const TOOLS: &[(&str, &str, &str)] = &[
|
||||
("ed", "easydig", "dig replacement"),
|
||||
("eh", "easyhost", "host replacement"),
|
||||
("ens", "easynslookup", "nslookup replacement (with interactive mode)"),
|
||||
("etrace", "easytrace", "dig +trace: delegation tracing from the root"),
|
||||
("ednssec", "easydnssec", "DNSSEC chain diagnostics (delv-like)"),
|
||||
("eptr", "easyptr", "reverse DNS lookups"),
|
||||
("ezone", "easyzone", "zone file validation (named-checkzone)"),
|
||||
("econf", "easyconf", "configuration validation (named-checkconf)"),
|
||||
("ebench", "easybench", "DNS load testing (dnsperf-like)"),
|
||||
("ewhois", "easywhois", "RDAP/WHOIS lookups"),
|
||||
("edoh", "easydoh", "DNS-over-HTTPS diagnostics"),
|
||||
("edot", "easydot", "DNS-over-TLS diagnostics"),
|
||||
("ediff", "easydiff", "compare answers of several resolvers"),
|
||||
];
|
||||
@@ -0,0 +1,291 @@
|
||||
//! `easydns zone create`: write a minimal, valid primary zone and its definition.
|
||||
//!
|
||||
//! Creates `<data_dir>/zones/<zone>.zone` (SOA, NS, glue for in-zone name servers and
|
||||
//! optional apex addresses) and `<config dir>/zones.d/<zone>.yaml`, which the default
|
||||
//! configuration includes. Nothing is overwritten without `--force`, and the zone is
|
||||
//! parsed and checked before anything is written.
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use dns_config::Config;
|
||||
use dns_core::proto::rr::Name;
|
||||
|
||||
#[derive(clap::Args, Debug, Clone)]
|
||||
pub struct CreateArgs {
|
||||
/// Zone name, e.g. example.com
|
||||
pub zone: String,
|
||||
/// Name server (repeatable). In-zone names need an address: `ns1.example.com=192.0.2.1`.
|
||||
/// Default: ns1.<zone>
|
||||
#[arg(long = "ns", value_name = "NAME[=IP]")]
|
||||
pub ns: Vec<String>,
|
||||
/// Address of the zone apex (`@ A`/`@ AAAA`), repeatable; also used as the glue of a
|
||||
/// default in-zone ns1 without its own address
|
||||
#[arg(long = "ip", value_name = "IP")]
|
||||
pub ip: Vec<IpAddr>,
|
||||
/// Responsible mailbox (`hostmaster@example.com`). Default: hostmaster@<zone>
|
||||
#[arg(long)]
|
||||
pub email: Option<String>,
|
||||
/// Default TTL in seconds
|
||||
#[arg(long, default_value_t = 3600)]
|
||||
pub ttl: u32,
|
||||
/// Secondary allowed to transfer the zone (IP or CIDR, repeatable). No TSIG key needed.
|
||||
#[arg(long = "allow-transfer", value_name = "IP")]
|
||||
pub allow_transfer: Vec<String>,
|
||||
/// Secondary to NOTIFY after changes (IP or IP:port, repeatable)
|
||||
#[arg(long = "notify", value_name = "IP[:PORT]")]
|
||||
pub notify: Vec<String>,
|
||||
/// Allow RFC 2136 updates from these addresses without a key (repeatable)
|
||||
#[arg(long = "allow-update", value_name = "IP")]
|
||||
pub allow_update: Vec<String>,
|
||||
/// Only write the zone file; print the zone definition instead of writing zones.d/
|
||||
#[arg(long)]
|
||||
pub no_config: bool,
|
||||
/// Overwrite existing files
|
||||
#[arg(long)]
|
||||
pub force: bool,
|
||||
/// Print what would be written, change nothing
|
||||
#[arg(long)]
|
||||
pub dry_run: bool,
|
||||
/// Reload the running server afterwards (via the local API)
|
||||
#[arg(long)]
|
||||
pub reload: bool,
|
||||
}
|
||||
|
||||
/// Files produced by `create`.
|
||||
#[derive(Debug)]
|
||||
pub struct Created {
|
||||
pub zone_file: PathBuf,
|
||||
pub zone_text: String,
|
||||
pub definition_file: Option<PathBuf>,
|
||||
pub definition: String,
|
||||
}
|
||||
|
||||
fn fqdn(s: &str) -> Result<Name, String> {
|
||||
let mut n = Name::from_utf8(s.trim()).map_err(|e| format!("invalid name '{s}': {e}"))?;
|
||||
n.set_fqdn(true);
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
fn today_serial() -> u32 {
|
||||
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
|
||||
dns_core::serial::next_serial(0, dns_core::serial::SerialStrategy::Date, now).wrapping_add(1)
|
||||
}
|
||||
|
||||
fn notify_addr(s: &str) -> Result<SocketAddr, String> {
|
||||
s.parse::<SocketAddr>()
|
||||
.or_else(|_| s.parse::<IpAddr>().map(|ip| SocketAddr::new(ip, 53)))
|
||||
.map_err(|_| format!("bad --notify address '{s}'"))
|
||||
}
|
||||
|
||||
/// Build the zone text and definition (pure; no file system access).
|
||||
pub fn render(a: &CreateArgs, serial: u32) -> Result<(String, String), String> {
|
||||
let zone = fqdn(&a.zone)?;
|
||||
if zone.is_root() {
|
||||
return Err("refusing to create the root zone".into());
|
||||
}
|
||||
let zname = zone.to_ascii();
|
||||
let bare = zname.trim_end_matches('.');
|
||||
let email = a.email.clone().unwrap_or_else(|| format!("hostmaster@{bare}"));
|
||||
let (local, domain) = email.split_once('@').ok_or("--email must look like user@domain")?;
|
||||
let rname = fqdn(&format!("{}.{}", local.replace('.', "\\."), domain))?;
|
||||
|
||||
let mut ns_list: Vec<(Name, Option<IpAddr>)> = Vec::new();
|
||||
for spec in if a.ns.is_empty() { vec![format!("ns1.{bare}")] } else { a.ns.clone() } {
|
||||
let (n, ip) = match spec.split_once('=') {
|
||||
Some((n, ip)) => (n, Some(ip.parse::<IpAddr>().map_err(|_| format!("bad address in --ns {spec}"))?)),
|
||||
None => (spec.as_str(), None),
|
||||
};
|
||||
ns_list.push((fqdn(n)?, ip));
|
||||
}
|
||||
let mut out = String::new();
|
||||
out.push_str(&format!("; {zname} – created by `easydns zone create`\n$ORIGIN {zname}\n$TTL {}\n", a.ttl));
|
||||
out.push_str(&format!(
|
||||
"@\tIN SOA {} {} (\n\t\t{serial} ; serial\n\t\t3600 ; refresh\n\t\t900 ; retry\n\t\t1209600 ; expire\n\t\t300 ) ; negative TTL\n",
|
||||
ns_list[0].0.to_ascii(),
|
||||
rname.to_ascii()
|
||||
));
|
||||
for (n, _) in &ns_list {
|
||||
out.push_str(&format!("@\tIN NS {}\n", n.to_ascii()));
|
||||
}
|
||||
let mut glue_used_apex = false;
|
||||
for (i, (n, ip)) in ns_list.iter().enumerate() {
|
||||
if !zone.zone_of(n) {
|
||||
continue;
|
||||
}
|
||||
let addrs: Vec<IpAddr> = match ip {
|
||||
Some(ip) => vec![*ip],
|
||||
None if i == 0 && !a.ip.is_empty() => {
|
||||
glue_used_apex = true;
|
||||
a.ip.clone()
|
||||
}
|
||||
None => {
|
||||
return Err(format!(
|
||||
"name server {} is inside the zone and needs an address: --ns {}=<IP>",
|
||||
n.to_ascii().trim_end_matches('.'),
|
||||
n.to_ascii().trim_end_matches('.')
|
||||
));
|
||||
}
|
||||
};
|
||||
let label = if n == &zone { "@".to_string() } else { n.to_ascii().trim_end_matches(&format!(".{zname}")).to_string() };
|
||||
for ip in addrs {
|
||||
out.push_str(&format!("{label}\tIN {} {ip}\n", if ip.is_ipv4() { "A " } else { "AAAA" }));
|
||||
}
|
||||
}
|
||||
for ip in &a.ip {
|
||||
out.push_str(&format!("@\tIN {} {ip}\n", if ip.is_ipv4() { "A " } else { "AAAA" }));
|
||||
}
|
||||
let _ = glue_used_apex;
|
||||
|
||||
let file = format!("zones/{bare}.zone");
|
||||
let mut def = format!("# {bare} – created by `easydns zone create`\n- name: {bare}\n type: primary\n file: {file}\n");
|
||||
let list = |v: &[String]| v.iter().map(|x| format!("\"{x}\"")).collect::<Vec<_>>().join(", ");
|
||||
if !a.allow_transfer.is_empty() {
|
||||
def.push_str(&format!(" transfer_acl: [{}] # IP only; add transfer_tsig_key to require a key\n", list(&a.allow_transfer)));
|
||||
}
|
||||
if !a.notify.is_empty() {
|
||||
let n: Vec<String> = a.notify.iter().map(|s| notify_addr(s).map(|x| x.to_string())).collect::<Result<_, _>>()?;
|
||||
def.push_str(&format!(" notify: [{}]\n", list(&n)));
|
||||
}
|
||||
if !a.allow_update.is_empty() {
|
||||
def.push_str(&format!(" update_acl: [{}] # RFC 2136 without a key\n", list(&a.allow_update)));
|
||||
}
|
||||
Ok((out, def))
|
||||
}
|
||||
|
||||
fn chown_like_parent(path: &Path) {
|
||||
#[cfg(unix)]
|
||||
if let Some(meta) = path.parent().and_then(|p| std::fs::metadata(p).ok()) {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
// as root: give the file to the owner of the directory (the easydns user)
|
||||
let _ = std::os::unix::fs::chown(path, Some(meta.uid()), Some(meta.gid()));
|
||||
}
|
||||
}
|
||||
|
||||
fn write_new(path: &Path, text: &str, force: bool, mode: u32) -> Result<(), String> {
|
||||
if path.exists() && !force {
|
||||
return Err(format!("{} already exists (use --force to overwrite)", path.display()));
|
||||
}
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
}
|
||||
dns_core::zonefile::atomic_write(path, text.as_bytes()).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode));
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
let _ = mode;
|
||||
chown_like_parent(path);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Create the zone for `cfg` (loaded from `config_path`).
|
||||
pub fn create(cfg: &Config, config_path: &Path, a: &CreateArgs) -> Result<Created, String> {
|
||||
let zone = fqdn(&a.zone)?;
|
||||
let bare = zone.to_ascii().trim_end_matches('.').to_string();
|
||||
if cfg.zones.iter().any(|z| z.name.trim_end_matches('.').eq_ignore_ascii_case(&bare)) && !a.force {
|
||||
return Err(format!("zone {bare} is already defined in the configuration"));
|
||||
}
|
||||
let (text, def) = render(a, today_serial())?;
|
||||
// validate before writing anything
|
||||
let records = dns_core::zonefile::parse_str(&text, &zone, None).map_err(|e| format!("generated zone does not parse: {e}"))?;
|
||||
dns_authoritative::Zone::from_records(&zone, records).map_err(|e| format!("generated zone is invalid: {e}"))?;
|
||||
|
||||
let zone_file = cfg.data_dir().join("zones").join(format!("{bare}.zone"));
|
||||
let conf_dir = config_path.parent().map(Path::to_path_buf).unwrap_or_default();
|
||||
let includes_zones_d = cfg.include.iter().any(|p| p.starts_with("zones.d/"));
|
||||
let definition_file = (!a.no_config && includes_zones_d).then(|| conf_dir.join("zones.d").join(format!("{bare}.yaml")));
|
||||
if !a.dry_run {
|
||||
write_new(&zone_file, &text, a.force, 0o640)?;
|
||||
if let Some(f) = &definition_file {
|
||||
write_new(f, &def, a.force, 0o640)?;
|
||||
}
|
||||
}
|
||||
Ok(Created { zone_file, zone_text: text, definition_file, definition: def })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn args(zone: &str) -> CreateArgs {
|
||||
CreateArgs {
|
||||
zone: zone.into(),
|
||||
ns: vec![],
|
||||
ip: vec![],
|
||||
email: None,
|
||||
ttl: 3600,
|
||||
allow_transfer: vec![],
|
||||
notify: vec![],
|
||||
allow_update: vec![],
|
||||
no_config: false,
|
||||
force: false,
|
||||
dry_run: false,
|
||||
reload: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn valid(text: &str, zone: &str) -> usize {
|
||||
let z = fqdn(zone).unwrap();
|
||||
let r = dns_core::zonefile::parse_str(text, &z, None).unwrap();
|
||||
let n = r.len();
|
||||
dns_authoritative::Zone::from_records(&z, r).unwrap();
|
||||
n
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn minimal_zone_with_glue_from_ip() {
|
||||
let mut a = args("example.com");
|
||||
a.ip = vec!["192.0.2.1".parse().unwrap()];
|
||||
let (t, def) = render(&a, 2026112201).unwrap();
|
||||
assert!(t.contains("@\tIN SOA ns1.example.com. hostmaster.example.com. ("));
|
||||
assert!(t.contains("ns1\tIN A 192.0.2.1"));
|
||||
assert!(t.contains("@\tIN A 192.0.2.1"));
|
||||
assert_eq!(valid(&t, "example.com"), 4); // SOA, NS, glue, apex A
|
||||
assert!(def.contains("file: zones/example.com.zone"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_and_in_zone_name_servers() {
|
||||
let mut a = args("example.org");
|
||||
a.ns = vec!["ns1.example.org=192.0.2.53".into(), "ns2.example.net".into(), "ns3.example.org=2001:db8::53".into()];
|
||||
a.email = Some("dns.admin@example.net".into());
|
||||
a.allow_transfer = vec!["192.0.2.20".into()];
|
||||
a.notify = vec!["192.0.2.20".into()];
|
||||
let (t, def) = render(&a, 1).unwrap();
|
||||
assert!(t.contains("dns\\.admin.example.net."));
|
||||
assert!(t.contains("ns3\tIN AAAA 2001:db8::53"));
|
||||
assert!(!t.contains("ns2\tIN"));
|
||||
assert_eq!(valid(&t, "example.org"), 6);
|
||||
assert!(def.contains("transfer_acl: [\"192.0.2.20\"]") && def.contains("notify: [\"192.0.2.20:53\"]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn in_zone_ns_without_address_is_an_error() {
|
||||
assert!(render(&args("example.com"), 1).unwrap_err().contains("needs an address"));
|
||||
assert!(render(&args("."), 1).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writes_files_and_refuses_overwrite() {
|
||||
let d = std::env::temp_dir().join(format!("edns-zc-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let cfgp = d.join("config.yaml");
|
||||
std::fs::write(&cfgp, "include: [\"zones.d/*.yaml\"]\nserver: { data_dir: data }\n").unwrap();
|
||||
let cfg = Config::load(&cfgp).unwrap();
|
||||
let mut a = args("example.com");
|
||||
a.ns = vec!["ns.example.net".into()];
|
||||
let c = create(&cfg, &cfgp, &a).unwrap();
|
||||
assert!(c.zone_file.ends_with("data/zones/example.com.zone") && c.zone_file.is_file());
|
||||
assert!(d.join("zones.d/example.com.yaml").is_file());
|
||||
// the new definition is picked up and the zone loads
|
||||
let cfg2 = Config::load(&cfgp).unwrap();
|
||||
assert_eq!(cfg2.zones.len(), 1);
|
||||
assert!(cfg2.validate().iter().all(|i| !i.is_error()));
|
||||
assert!(create(&cfg, &cfgp, &a).unwrap_err().contains("already exists"));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "dns-config"
|
||||
description = "EasyDNS configuration schema, loading and validation"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
dns-core.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
serde_norway.workspace = true
|
||||
ipnet.workspace = true
|
||||
thiserror.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,202 @@
|
||||
//! Reading TSIG keys written in BIND `named.conf` syntax, so key files can be copied
|
||||
//! from an existing BIND server and included unchanged:
|
||||
//!
|
||||
//! ```text
|
||||
//! key "ddns-key.example.com" {
|
||||
//! algorithm hmac-sha512;
|
||||
//! secret "base64 secret";
|
||||
//! };
|
||||
//! ```
|
||||
//!
|
||||
//! Only `key` statements are accepted (anything else is reported as an error rather than
|
||||
//! silently ignored). Comments `#`, `//` and `/* */` are allowed.
|
||||
|
||||
use crate::KeyConfig;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
enum Tok {
|
||||
Word(String),
|
||||
Str(String),
|
||||
Open,
|
||||
Close,
|
||||
Semi,
|
||||
}
|
||||
|
||||
fn tokenize(text: &str) -> Result<Vec<(Tok, usize)>, (usize, String)> {
|
||||
let b: Vec<char> = text.chars().collect();
|
||||
let (mut i, mut line) = (0usize, 1usize);
|
||||
let mut out = Vec::new();
|
||||
while i < b.len() {
|
||||
let c = b[i];
|
||||
match c {
|
||||
'\n' => {
|
||||
line += 1;
|
||||
i += 1;
|
||||
}
|
||||
c if c.is_whitespace() => i += 1,
|
||||
'#' => {
|
||||
while i < b.len() && b[i] != '\n' {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
'/' if b.get(i + 1) == Some(&'/') => {
|
||||
while i < b.len() && b[i] != '\n' {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
'/' if b.get(i + 1) == Some(&'*') => {
|
||||
let start = line;
|
||||
i += 2;
|
||||
loop {
|
||||
if i + 1 >= b.len() {
|
||||
return Err((start, "unterminated /* comment".into()));
|
||||
}
|
||||
if b[i] == '\n' {
|
||||
line += 1;
|
||||
}
|
||||
if b[i] == '*' && b[i + 1] == '/' {
|
||||
i += 2;
|
||||
break;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
'{' => {
|
||||
out.push((Tok::Open, line));
|
||||
i += 1;
|
||||
}
|
||||
'}' => {
|
||||
out.push((Tok::Close, line));
|
||||
i += 1;
|
||||
}
|
||||
';' => {
|
||||
out.push((Tok::Semi, line));
|
||||
i += 1;
|
||||
}
|
||||
'"' => {
|
||||
let start = line;
|
||||
i += 1;
|
||||
let mut s = String::new();
|
||||
while i < b.len() && b[i] != '"' {
|
||||
if b[i] == '\n' {
|
||||
line += 1;
|
||||
}
|
||||
s.push(b[i]);
|
||||
i += 1;
|
||||
}
|
||||
if i >= b.len() {
|
||||
return Err((start, "unterminated string".into()));
|
||||
}
|
||||
i += 1;
|
||||
out.push((Tok::Str(s), start));
|
||||
}
|
||||
_ => {
|
||||
let mut s = String::new();
|
||||
while i < b.len() && !b[i].is_whitespace() && !matches!(b[i], '{' | '}' | ';' | '"') {
|
||||
s.push(b[i]);
|
||||
i += 1;
|
||||
}
|
||||
out.push((Tok::Word(s), line));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// True when the first statement of `text` is a BIND `key` statement.
|
||||
pub(crate) fn looks_like_bind_keys(text: &str) -> bool {
|
||||
matches!(tokenize(text).ok().and_then(|t| t.into_iter().next()), Some((Tok::Word(w), _)) if w == "key")
|
||||
}
|
||||
|
||||
/// Parse `key` statements. Errors carry the line number.
|
||||
pub(crate) fn parse_keys(text: &str, file: &str) -> Result<Vec<KeyConfig>, (usize, String)> {
|
||||
let toks = tokenize(text)?;
|
||||
let mut it = toks.into_iter().peekable();
|
||||
let mut keys = Vec::new();
|
||||
while let Some((t, line)) = it.next() {
|
||||
match t {
|
||||
Tok::Word(w) if w == "key" => {}
|
||||
Tok::Semi => continue,
|
||||
other => return Err((line, format!("only `key` statements are supported in BIND-format includes, found {other:?}"))),
|
||||
}
|
||||
let name = match it.next() {
|
||||
Some((Tok::Str(s) | Tok::Word(s), _)) => s,
|
||||
_ => return Err((line, "key: expected a name".into())),
|
||||
};
|
||||
if !matches!(it.next(), Some((Tok::Open, _))) {
|
||||
return Err((line, format!("key \"{name}\": expected '{{'")));
|
||||
}
|
||||
let (mut algorithm, mut secret) = (None, None);
|
||||
loop {
|
||||
let (t, l) = it.next().ok_or((line, format!("key \"{name}\": missing '}}'")))?;
|
||||
match t {
|
||||
Tok::Close => break,
|
||||
Tok::Semi => {}
|
||||
Tok::Word(opt) => {
|
||||
let value = match it.next() {
|
||||
Some((Tok::Str(v) | Tok::Word(v), _)) => v,
|
||||
_ => return Err((l, format!("key \"{name}\": {opt} needs a value"))),
|
||||
};
|
||||
if !matches!(it.next(), Some((Tok::Semi, _))) {
|
||||
return Err((l, format!("key \"{name}\": expected ';' after {opt}")));
|
||||
}
|
||||
match opt.as_str() {
|
||||
"algorithm" => algorithm = Some(value.to_ascii_lowercase()),
|
||||
"secret" => secret = Some(value.split_whitespace().collect::<String>()),
|
||||
other => return Err((l, format!("key \"{name}\": unsupported option '{other}'"))),
|
||||
}
|
||||
}
|
||||
other => return Err((l, format!("key \"{name}\": unexpected {other:?}"))),
|
||||
}
|
||||
}
|
||||
if !matches!(it.peek(), Some((Tok::Semi, _))) {
|
||||
return Err((line, format!("key \"{name}\": expected ';' after '}}'")));
|
||||
}
|
||||
let algorithm = algorithm.ok_or((line, format!("key \"{name}\": missing algorithm")))?;
|
||||
let secret = secret.ok_or((line, format!("key \"{name}\": missing secret")))?;
|
||||
keys.push(KeyConfig { name, algorithm, secret: format!("base64:{secret}"), imported_from: Some(file.to_string()) });
|
||||
}
|
||||
Ok(keys)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const KEYS: &str = r#"
|
||||
# copied from /etc/bind/keys.conf
|
||||
key "wildcard.example.org" {
|
||||
algorithm hmac-sha512;
|
||||
secret "c2VjcmV0c2VjcmV0c2VjcmV0c2VjcmV0c2VjcmV0c2VjcmV0";
|
||||
};
|
||||
// second key
|
||||
key certbot-key. { algorithm HMAC-SHA256; secret "c2VjcmV0c2Vj
|
||||
cmV0c2VjcmV0"; };
|
||||
/* block
|
||||
comment */
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn parses_bind_key_statements() {
|
||||
assert!(looks_like_bind_keys(KEYS));
|
||||
assert!(!looks_like_bind_keys("keys: []\n"));
|
||||
let k = parse_keys(KEYS, "keys.conf").unwrap();
|
||||
assert_eq!(k.len(), 2);
|
||||
assert_eq!(k[0].name, "wildcard.example.org");
|
||||
assert_eq!(k[0].algorithm, "hmac-sha512");
|
||||
assert!(k[0].secret.starts_with("base64:c2Vj"));
|
||||
assert_eq!(k[1].name, "certbot-key.");
|
||||
assert_eq!(k[1].algorithm, "hmac-sha256");
|
||||
assert_eq!(k[1].secret, "base64:c2VjcmV0c2VjcmV0c2VjcmV0"); // whitespace inside the secret removed
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_other_statements_with_line() {
|
||||
let e = parse_keys("key \"a\" { algorithm hmac-sha256; secret \"eA==\"; };\nzone \"x\" { };\n", "f").unwrap_err();
|
||||
assert_eq!(e.0, 2);
|
||||
let e = parse_keys("key \"a\" { algorithm hmac-sha256; };", "f").unwrap_err();
|
||||
assert!(e.1.contains("missing secret"));
|
||||
assert!(parse_keys("key \"a\" { algorithm hmac-sha256; secret \"x\" }", "f").is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
//! Human readable durations for config files: `500ms`, `2s`, `5m`, `1h`, `1d` or a bare number of seconds.
|
||||
use std::time::Duration;
|
||||
|
||||
use serde::{Deserialize, Deserializer, Serializer};
|
||||
|
||||
/// Parse a duration string.
|
||||
pub fn parse(s: &str) -> Result<Duration, String> {
|
||||
let s = s.trim();
|
||||
let (num, unit) = match s.find(|c: char| !c.is_ascii_digit() && c != '.') {
|
||||
Some(i) => (&s[..i], &s[i..]),
|
||||
None => (s, "s"),
|
||||
};
|
||||
let v: f64 = num.parse().map_err(|_| format!("invalid duration '{s}'"))?;
|
||||
let secs = match unit {
|
||||
"ms" => v / 1000.0,
|
||||
"s" | "" => v,
|
||||
"m" => v * 60.0,
|
||||
"h" => v * 3600.0,
|
||||
"d" => v * 86400.0,
|
||||
_ => return Err(format!("invalid duration unit in '{s}' (use ms, s, m, h, d)")),
|
||||
};
|
||||
if !(0.0..=31_536_000.0).contains(&secs) {
|
||||
return Err(format!("duration out of range: '{s}'"));
|
||||
}
|
||||
Ok(Duration::from_secs_f64(secs))
|
||||
}
|
||||
|
||||
/// Format a duration compactly.
|
||||
pub fn format(d: &Duration) -> String {
|
||||
let ms = d.as_millis();
|
||||
if !ms.is_multiple_of(1000) { format!("{ms}ms") } else { format!("{}s", d.as_secs()) }
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum Raw {
|
||||
Num(u64),
|
||||
Str(String),
|
||||
}
|
||||
|
||||
pub fn serialize<S: Serializer>(d: &Duration, s: S) -> Result<S::Ok, S::Error> {
|
||||
s.serialize_str(&format(d))
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
|
||||
match Raw::deserialize(d)? {
|
||||
Raw::Num(n) => Ok(Duration::from_secs(n)),
|
||||
Raw::Str(s) => parse(&s).map_err(serde::de::Error::custom),
|
||||
}
|
||||
}
|
||||
|
||||
pub mod option {
|
||||
use super::*;
|
||||
pub fn serialize<S: Serializer>(d: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
|
||||
match d {
|
||||
Some(d) => s.serialize_str(&super::format(d)),
|
||||
None => s.serialize_none(),
|
||||
}
|
||||
}
|
||||
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
|
||||
Ok(Some(super::deserialize(d)?))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn parse_units() {
|
||||
assert_eq!(super::parse("500ms").unwrap().as_millis(), 500);
|
||||
assert_eq!(super::parse("2s").unwrap().as_secs(), 2);
|
||||
assert_eq!(super::parse("5m").unwrap().as_secs(), 300);
|
||||
assert_eq!(super::parse("10").unwrap().as_secs(), 10);
|
||||
assert!(super::parse("5y").is_err());
|
||||
assert!(super::parse("abc").is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
//! `include:` support: zone definitions (and keys, ACLs, forward zones) in separate files.
|
||||
//!
|
||||
//! An included file is either a YAML/JSON mapping
|
||||
//! ```yaml
|
||||
//! keys: [...] # optional
|
||||
//! acls: {...} # optional
|
||||
//! zones: [...]
|
||||
//! forward_zones: [...] # optional
|
||||
//! include: [...] # optional, relative to this file
|
||||
//! ```
|
||||
//! or simply a list of zone definitions (`- name: example.com ...`), or a BIND-format key
|
||||
//! file (`key "name" { algorithm hmac-sha512; secret "..."; };`, see `bindconf`).
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::{ConfigError, ForwardZoneConfig, KeyConfig, ZoneConfig};
|
||||
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
#[serde(deny_unknown_fields, default)]
|
||||
pub(crate) struct IncludeFile {
|
||||
pub zones: Vec<ZoneConfig>,
|
||||
pub keys: Vec<KeyConfig>,
|
||||
pub acls: BTreeMap<String, Vec<String>>,
|
||||
pub forward_zones: Vec<ForwardZoneConfig>,
|
||||
pub include: Vec<String>,
|
||||
}
|
||||
|
||||
fn perr(file: &str, line: Option<usize>, message: String) -> ConfigError {
|
||||
ConfigError::Parse { file: file.into(), line, message }
|
||||
}
|
||||
|
||||
pub(crate) fn parse(text: &str, file: &str) -> Result<IncludeFile, ConfigError> {
|
||||
let t = text.trim_start();
|
||||
if t.is_empty() {
|
||||
return Ok(IncludeFile::default());
|
||||
}
|
||||
// key files copied from BIND: `key "name" { algorithm ...; secret "..."; };`
|
||||
if crate::bindconf::looks_like_bind_keys(text) {
|
||||
let keys = crate::bindconf::parse_keys(text, file).map_err(|(line, m)| perr(file, Some(line), m))?;
|
||||
return Ok(IncludeFile { keys, ..Default::default() });
|
||||
}
|
||||
if t.starts_with('{') || t.starts_with('[') {
|
||||
if t.starts_with('[') {
|
||||
let zones: Vec<ZoneConfig> = serde_json::from_str(text).map_err(|e| perr(file, Some(e.line()), e.to_string()))?;
|
||||
return Ok(IncludeFile { zones, ..Default::default() });
|
||||
}
|
||||
return serde_json::from_str(text).map_err(|e| perr(file, Some(e.line()), e.to_string()));
|
||||
}
|
||||
let is_list = text.lines().map(str::trim).find(|l| !l.is_empty() && !l.starts_with('#')).is_some_and(|l| l.starts_with('-'));
|
||||
if is_list {
|
||||
let zones: Vec<ZoneConfig> = serde_norway::from_str(text).map_err(|e| perr(file, e.location().map(|l| l.line()), e.to_string()))?;
|
||||
return Ok(IncludeFile { zones, ..Default::default() });
|
||||
}
|
||||
serde_norway::from_str(text).map_err(|e| perr(file, e.location().map(|l| l.line()), e.to_string()))
|
||||
}
|
||||
|
||||
fn wildcard(pattern: &str, name: &str) -> bool {
|
||||
let (p, n): (Vec<char>, Vec<char>) = (pattern.chars().collect(), name.chars().collect());
|
||||
let (mut pi, mut ni, mut star, mut mark) = (0usize, 0usize, None::<usize>, 0usize);
|
||||
while ni < n.len() {
|
||||
if pi < p.len() && (p[pi] == '?' || p[pi] == n[ni]) {
|
||||
pi += 1;
|
||||
ni += 1;
|
||||
} else if pi < p.len() && p[pi] == '*' {
|
||||
star = Some(pi);
|
||||
mark = ni;
|
||||
pi += 1;
|
||||
} else if let Some(s) = star {
|
||||
pi = s + 1;
|
||||
mark += 1;
|
||||
ni = mark;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
while pi < p.len() && p[pi] == '*' {
|
||||
pi += 1;
|
||||
}
|
||||
pi == p.len()
|
||||
}
|
||||
|
||||
/// Expand one include pattern relative to `base`. A glob that matches nothing is not an
|
||||
/// error (an empty `zones.d/` is fine); a missing literal file is. Hidden files (`.x`) and
|
||||
/// editor backups (`~`) are skipped. Results are sorted.
|
||||
pub(crate) fn expand(base: &Path, pattern: &str) -> Result<Vec<PathBuf>, String> {
|
||||
let p = Path::new(pattern);
|
||||
let full = if p.is_absolute() { p.to_path_buf() } else { base.join(p) };
|
||||
let name = full.file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or_default();
|
||||
if !name.contains('*') && !name.contains('?') {
|
||||
if !full.is_file() {
|
||||
return Err(format!("included file not found: {}", full.display()));
|
||||
}
|
||||
return Ok(vec![full]);
|
||||
}
|
||||
let dir = full.parent().map(Path::to_path_buf).unwrap_or_default();
|
||||
if dir.to_string_lossy().contains(['*', '?']) {
|
||||
return Err(format!("wildcards are only supported in the file name: {pattern}"));
|
||||
}
|
||||
let rd = match std::fs::read_dir(&dir) {
|
||||
Ok(r) => r,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
|
||||
Err(e) => return Err(format!("{}: {e}", dir.display())),
|
||||
};
|
||||
let mut out: Vec<PathBuf> = rd
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.path())
|
||||
.filter(|f| f.is_file())
|
||||
.filter(|f| {
|
||||
let n = f.file_name().map(|x| x.to_string_lossy().to_string()).unwrap_or_default();
|
||||
!n.starts_with('.') && !n.ends_with('~') && wildcard(&name, &n)
|
||||
})
|
||||
.collect();
|
||||
out.sort();
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::Config;
|
||||
|
||||
#[test]
|
||||
fn wildcards() {
|
||||
assert!(wildcard("*.yaml", "a.yaml"));
|
||||
assert!(wildcard("zone-?.yml", "zone-1.yml"));
|
||||
assert!(!wildcard("*.yaml", "a.yml"));
|
||||
assert!(wildcard("*", "x"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn includes_merge_and_report_sources() {
|
||||
let d = std::env::temp_dir().join(format!("edns-inc-{}", std::process::id()));
|
||||
let zd = d.join("zones.d");
|
||||
std::fs::create_dir_all(zd.join("more")).unwrap();
|
||||
std::fs::write(
|
||||
d.join("main.yaml"),
|
||||
"include: [\"zones.d/*.yaml\", keys.yaml]\nzones:\n - { name: a.example, type: secondary, primaries: [\"192.0.2.1:53\"] }\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
d.join("keys.yaml"),
|
||||
"keys: [ { name: k1, secret: \"base64:c2VjcmV0c2VjcmV0c2VjcmV0c2VjcmV0\" } ]\nacls: { prim: [\"192.0.2.1/32\"] }\n",
|
||||
)
|
||||
.unwrap();
|
||||
// plain list form
|
||||
std::fs::write(zd.join("10-b.yaml"), "- { name: b.example, type: secondary, primaries: [\"192.0.2.1:53\"], allow_notify: [\"acl:prim\"] }\n- { name: c.example, type: secondary, primaries: [\"192.0.2.1:53\"], transfer: { tsig_key: k1 } }\n").unwrap();
|
||||
// mapping form with nested include (relative to this file)
|
||||
std::fs::write(
|
||||
zd.join("20-d.yaml"),
|
||||
"include: [\"more/*.yaml\"]\nzones:\n - { name: d.example, type: secondary, primaries: [\"192.0.2.1:53\"] }\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(zd.join("more").join("e.yaml"), "zones: [ { name: e.example, type: secondary, primaries: [\"192.0.2.1:53\"] } ]\n")
|
||||
.unwrap();
|
||||
std::fs::write(zd.join(".hidden.yaml"), "garbage: [").unwrap();
|
||||
std::fs::write(zd.join("x.yaml~"), "garbage: [").unwrap();
|
||||
let c = Config::load(&d.join("main.yaml")).unwrap();
|
||||
let names: Vec<_> = c.zones.iter().map(|z| z.name.as_str()).collect();
|
||||
assert_eq!(names, vec!["a.example", "b.example", "c.example", "d.example", "e.example"]);
|
||||
assert!(c.zones[1].source.as_deref().unwrap().ends_with("10-b.yaml"));
|
||||
assert_eq!(c.keys.len(), 1);
|
||||
assert!(c.validate().iter().all(|i| !i.is_error()), "{:?}", c.validate());
|
||||
|
||||
// duplicate zone → error naming the file
|
||||
std::fs::write(zd.join("30-dup.yaml"), "- { name: b.example, type: secondary, primaries: [\"192.0.2.9:53\"] }\n").unwrap();
|
||||
let c = Config::load(&d.join("main.yaml")).unwrap();
|
||||
let errs: Vec<String> = c.validate().into_iter().filter(|i| i.is_error()).map(|i| i.to_string()).collect();
|
||||
assert!(errs.iter().any(|e| e.contains("duplicate zone") && e.contains("30-dup.yaml")), "{errs:?}");
|
||||
std::fs::remove_file(zd.join("30-dup.yaml")).unwrap();
|
||||
|
||||
// syntax error → file and line of the included file
|
||||
std::fs::write(zd.join("40-bad.yaml"), "- { name: f.example, type: secondary }\n- { name: g.example, tpye: primary }\n").unwrap();
|
||||
let e = Config::load(&d.join("main.yaml")).unwrap_err().to_string();
|
||||
assert!(e.contains("40-bad.yaml"), "{e}");
|
||||
std::fs::remove_file(zd.join("40-bad.yaml")).unwrap();
|
||||
|
||||
// recursion is detected; missing literal file is an error; empty glob is fine
|
||||
std::fs::write(zd.join("more").join("loop.yaml"), "include: [\"../20-d.yaml\"]\n").unwrap();
|
||||
assert!(Config::load(&d.join("main.yaml")).unwrap_err().to_string().contains("included twice"));
|
||||
std::fs::remove_file(zd.join("more").join("loop.yaml")).unwrap();
|
||||
std::fs::write(d.join("m2.yaml"), "include: [nope.yaml]\n").unwrap();
|
||||
assert!(Config::load(&d.join("m2.yaml")).unwrap_err().to_string().contains("not found"));
|
||||
std::fs::write(d.join("m3.yaml"), "include: [\"empty.d/*.yaml\"]\n").unwrap();
|
||||
assert!(Config::load(&d.join("m3.yaml")).unwrap().zones.is_empty());
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,220 @@
|
||||
//! `update_policy`: fine-grained RFC 2136 rules in the style of BIND's `update-policy`.
|
||||
//!
|
||||
//! A rule can be written exactly as in BIND (without the trailing `;`):
|
||||
//!
|
||||
//! ```yaml
|
||||
//! update_policy:
|
||||
//! - "grant wildcard.h.example.com. zonesub TXT"
|
||||
//! - "grant certbot-key. name _acme-challenge.example.com. TXT"
|
||||
//! - "grant ddns.example.com. name h.ddns.example.com. A AAAA"
|
||||
//! - "grant host-key. wildcard *.dyn.example.com. A"
|
||||
//! ```
|
||||
//!
|
||||
//! or as a mapping: `{ grant: certbot-key, match: name, name: _acme-challenge.example.com, types: [TXT] }`
|
||||
//! (`deny:` instead of `grant:` for a deny rule).
|
||||
//!
|
||||
//! Rules are evaluated in order for every record of an update; the first rule whose
|
||||
//! identity, name and type match decides. No matching rule = refused.
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// How the owner name of an updated record is matched.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum UpdateMatch {
|
||||
/// Owner is exactly `name`.
|
||||
Name,
|
||||
/// Owner is `name` or below it.
|
||||
Subdomain,
|
||||
/// Owner is anywhere in the zone (no `name`).
|
||||
Zonesub,
|
||||
/// `name` is a wildcard (`*.dyn.example.com`); owner is strictly below its base.
|
||||
Wildcard,
|
||||
/// Owner equals the signing key's name.
|
||||
#[serde(rename = "self")]
|
||||
SelfName,
|
||||
/// Owner is the signing key's name or below it.
|
||||
Selfsub,
|
||||
}
|
||||
|
||||
impl UpdateMatch {
|
||||
fn parse(s: &str) -> Option<Self> {
|
||||
Some(match s.to_ascii_lowercase().as_str() {
|
||||
"name" => Self::Name,
|
||||
"subdomain" => Self::Subdomain,
|
||||
"zonesub" => Self::Zonesub,
|
||||
"wildcard" => Self::Wildcard,
|
||||
"self" => Self::SelfName,
|
||||
"selfsub" => Self::Selfsub,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the rule type takes a `name` field.
|
||||
pub fn needs_name(self) -> bool {
|
||||
matches!(self, Self::Name | Self::Subdomain | Self::Wildcard)
|
||||
}
|
||||
}
|
||||
|
||||
/// One rule after parsing.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
pub struct UpdateRule {
|
||||
pub grant: bool,
|
||||
/// TSIG key name (`*` = any valid key known to the server).
|
||||
pub identity: String,
|
||||
#[serde(rename = "match")]
|
||||
pub matches: UpdateMatch,
|
||||
pub name: Option<String>,
|
||||
/// Record types (upper case). Empty = all types except SOA, NS, RRSIG, NSEC, NSEC3
|
||||
/// (as in BIND); `ANY` = every type.
|
||||
pub types: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct RuleMap {
|
||||
#[serde(default)]
|
||||
grant: Option<String>,
|
||||
#[serde(default)]
|
||||
deny: Option<String>,
|
||||
#[serde(rename = "match")]
|
||||
matches: UpdateMatch,
|
||||
#[serde(default)]
|
||||
name: Option<String>,
|
||||
#[serde(default)]
|
||||
types: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum RuleRepr {
|
||||
Text(String),
|
||||
Map(RuleMap),
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for UpdateRule {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
match RuleRepr::deserialize(d)? {
|
||||
RuleRepr::Text(t) => UpdateRule::parse(&t).map_err(serde::de::Error::custom),
|
||||
RuleRepr::Map(m) => {
|
||||
let (grant, identity) = match (m.grant, m.deny) {
|
||||
(Some(i), None) => (true, i),
|
||||
(None, Some(i)) => (false, i),
|
||||
_ => return Err(serde::de::Error::custom("update_policy rule needs exactly one of grant: or deny:")),
|
||||
};
|
||||
let r = UpdateRule { grant, identity, matches: m.matches, name: m.name, types: upper(m.types) };
|
||||
r.check().map_err(serde::de::Error::custom)?;
|
||||
Ok(r)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn upper(v: Vec<String>) -> Vec<String> {
|
||||
v.into_iter().map(|t| t.to_ascii_uppercase()).collect()
|
||||
}
|
||||
|
||||
fn looks_like_type(s: &str) -> bool {
|
||||
if s == "*" {
|
||||
return false; // hickory parses "*" as ANY; in rules it is a name/identity placeholder
|
||||
}
|
||||
let u = s.to_ascii_uppercase();
|
||||
u == "ANY" || u.parse::<dns_core::proto::rr::RecordType>().is_ok_and(|t| !matches!(t, dns_core::proto::rr::RecordType::Unknown(_)))
|
||||
}
|
||||
|
||||
impl UpdateRule {
|
||||
/// Parse BIND syntax: `grant|deny <identity> <match> [<name>] [<type> ...]`.
|
||||
pub fn parse(text: &str) -> Result<Self, String> {
|
||||
let t: Vec<&str> = text.trim().trim_end_matches(';').split_whitespace().collect();
|
||||
let err = |m: &str| format!("update_policy \"{text}\": {m}");
|
||||
let grant = match t.first().map(|s| s.to_ascii_lowercase()).as_deref() {
|
||||
Some("grant") => true,
|
||||
Some("deny") => false,
|
||||
_ => return Err(err("must start with grant or deny")),
|
||||
};
|
||||
let identity = t.get(1).ok_or_else(|| err("missing identity (key name)"))?.to_string();
|
||||
let mt = t.get(2).ok_or_else(|| err("missing rule type"))?;
|
||||
let matches = UpdateMatch::parse(mt)
|
||||
.ok_or_else(|| err(&format!("unsupported rule type '{mt}' (supported: name, subdomain, zonesub, wildcard, self, selfsub)")))?;
|
||||
let mut rest = &t[3..];
|
||||
let mut name = None;
|
||||
if matches.needs_name() {
|
||||
name = Some(rest.first().ok_or_else(|| err("this rule type needs a name"))?.to_string());
|
||||
rest = &rest[1..];
|
||||
} else if matches!(matches, UpdateMatch::SelfName | UpdateMatch::Selfsub) {
|
||||
// BIND requires a (ignored) name field for self/selfsub, usually the identity or `*`
|
||||
if rest.first().is_some_and(|f| *f == "*" || !looks_like_type(f)) {
|
||||
rest = &rest[1..];
|
||||
}
|
||||
}
|
||||
let r = UpdateRule { grant, identity, matches, name, types: upper(rest.iter().map(|s| s.to_string()).collect()) };
|
||||
r.check().map_err(|m| err(&m))?;
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
fn check(&self) -> Result<(), String> {
|
||||
if self.matches.needs_name() && self.name.is_none() {
|
||||
return Err("this rule type needs a name".into());
|
||||
}
|
||||
if !self.matches.needs_name() && self.name.is_some() {
|
||||
return Err("this rule type takes no name".into());
|
||||
}
|
||||
if self.matches == UpdateMatch::Wildcard && !self.name.as_deref().is_some_and(|n| n.starts_with("*.")) {
|
||||
return Err("wildcard rules need a name starting with '*.'".into());
|
||||
}
|
||||
if let Some(n) = &self.name {
|
||||
dns_core::proto::rr::Name::from_utf8(n).map_err(|e| format!("bad name '{n}': {e}"))?;
|
||||
}
|
||||
if self.identity != "*" {
|
||||
dns_core::proto::rr::Name::from_utf8(&self.identity).map_err(|e| format!("bad identity '{}': {e}", self.identity))?;
|
||||
}
|
||||
for ty in &self.types {
|
||||
if !looks_like_type(ty) {
|
||||
return Err(format!("unknown record type '{ty}'"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_bind_rules() {
|
||||
let r = UpdateRule::parse("grant wildcard.h.example.com. zonesub TXT;").unwrap();
|
||||
assert!(r.grant && r.matches == UpdateMatch::Zonesub && r.name.is_none());
|
||||
assert_eq!(r.types, vec!["TXT"]);
|
||||
let r = UpdateRule::parse("grant certbot-key. name _acme-challenge.example.com. txt").unwrap();
|
||||
assert_eq!(r.name.as_deref(), Some("_acme-challenge.example.com."));
|
||||
assert_eq!(r.types, vec!["TXT"]);
|
||||
let r = UpdateRule::parse("deny * wildcard *.dyn.example.com. A AAAA").unwrap();
|
||||
assert!(!r.grant && r.identity == "*" && r.types.len() == 2);
|
||||
let r = UpdateRule::parse("grant * self * A").unwrap();
|
||||
assert_eq!(r.matches, UpdateMatch::SelfName);
|
||||
assert_eq!(r.types, vec!["A"]);
|
||||
let r = UpdateRule::parse("grant host-key. selfsub AAAA").unwrap();
|
||||
assert_eq!(r.types, vec!["AAAA"]);
|
||||
assert!(UpdateRule::parse("grant k zonesub").unwrap().types.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_bad_rules() {
|
||||
assert!(UpdateRule::parse("allow k zonesub TXT").is_err());
|
||||
assert!(UpdateRule::parse("grant k name").is_err());
|
||||
assert!(UpdateRule::parse("grant k krb5-self . A").is_err());
|
||||
assert!(UpdateRule::parse("grant k wildcard dyn.example.com A").is_err());
|
||||
assert!(UpdateRule::parse("grant k zonesub NOTATYPE").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_form() {
|
||||
let r: UpdateRule =
|
||||
serde_norway::from_str("{ grant: certbot-key, match: name, name: _acme-challenge.example.com, types: [txt] }").unwrap();
|
||||
assert!(r.grant && r.types == vec!["TXT"]);
|
||||
assert!(serde_norway::from_str::<UpdateRule>("{ match: zonesub }").is_err());
|
||||
let v: Vec<UpdateRule> = serde_norway::from_str("- \"grant k zonesub TXT\"\n- { deny: '*', match: zonesub }\n").unwrap();
|
||||
assert_eq!(v.len(), 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
//! Upstream server address syntax.
|
||||
use std::net::SocketAddr;
|
||||
|
||||
/// Protocol used to talk to an upstream.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum UpstreamProto {
|
||||
Udp,
|
||||
Tcp,
|
||||
Tls,
|
||||
Https,
|
||||
}
|
||||
|
||||
/// Parsed upstream: `1.1.1.1`, `1.1.1.1:53`, `[2606:4700::1111]:53`, `tcp://...`,
|
||||
/// `tls://1.1.1.1:853#cloudflare-dns.com`, `https://1.1.1.1/dns-query#cloudflare-dns.com`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
|
||||
pub struct UpstreamAddr {
|
||||
pub proto: UpstreamProto,
|
||||
pub addr: SocketAddr,
|
||||
/// TLS server name (SNI / certificate name) for tls/https.
|
||||
pub tls_name: Option<String>,
|
||||
/// HTTP path for https.
|
||||
pub path: String,
|
||||
pub original: String,
|
||||
}
|
||||
|
||||
impl UpstreamAddr {
|
||||
pub fn parse(s: &str) -> Result<Self, String> {
|
||||
let original = s.to_string();
|
||||
let (proto, rest) = if let Some(r) = s.strip_prefix("udp://") {
|
||||
(UpstreamProto::Udp, r)
|
||||
} else if let Some(r) = s.strip_prefix("tcp://") {
|
||||
(UpstreamProto::Tcp, r)
|
||||
} else if let Some(r) = s.strip_prefix("tls://") {
|
||||
(UpstreamProto::Tls, r)
|
||||
} else if let Some(r) = s.strip_prefix("https://") {
|
||||
(UpstreamProto::Https, r)
|
||||
} else {
|
||||
(UpstreamProto::Udp, s)
|
||||
};
|
||||
let (rest, tls_name) = match rest.split_once('#') {
|
||||
Some((a, n)) => (a, Some(n.to_string())),
|
||||
None => (rest, None),
|
||||
};
|
||||
let (hostport, path) = match rest.find('/') {
|
||||
Some(i) => (&rest[..i], rest[i..].to_string()),
|
||||
None => (rest, "/dns-query".to_string()),
|
||||
};
|
||||
let default_port = match proto {
|
||||
UpstreamProto::Udp | UpstreamProto::Tcp => 53,
|
||||
UpstreamProto::Tls => 853,
|
||||
UpstreamProto::Https => 443,
|
||||
};
|
||||
let addr: SocketAddr = if let Ok(a) = hostport.parse() {
|
||||
a
|
||||
} else if let Ok(ip) = hostport.trim_start_matches('[').trim_end_matches(']').parse::<std::net::IpAddr>() {
|
||||
SocketAddr::new(ip, default_port)
|
||||
} else {
|
||||
return Err(format!("invalid upstream '{s}': must be an IP address (optionally with port); use '#name' for the TLS name"));
|
||||
};
|
||||
if matches!(proto, UpstreamProto::Tls | UpstreamProto::Https) && tls_name.is_none() {
|
||||
return Err(format!("upstream '{s}': TLS upstreams require '#<server-name>' for certificate validation"));
|
||||
}
|
||||
Ok(Self { proto, addr, tls_name, path, original })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn parse_forms() {
|
||||
assert_eq!(UpstreamAddr::parse("1.1.1.1").unwrap().addr.port(), 53);
|
||||
assert_eq!(UpstreamAddr::parse("[::1]:5353").unwrap().addr.port(), 5353);
|
||||
let t = UpstreamAddr::parse("tls://1.1.1.1#cloudflare-dns.com").unwrap();
|
||||
assert_eq!((t.proto, t.addr.port()), (UpstreamProto::Tls, 853));
|
||||
let h = UpstreamAddr::parse("https://9.9.9.9/dns-query#dns.quad9.net").unwrap();
|
||||
assert_eq!(h.path, "/dns-query");
|
||||
assert!(UpstreamAddr::parse("tls://1.1.1.1").is_err());
|
||||
assert!(UpstreamAddr::parse("dns.google").is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,421 @@
|
||||
//! Offline validation with precise locations.
|
||||
use std::collections::HashSet;
|
||||
use std::fmt;
|
||||
|
||||
use crate::{Config, DefaultResolution, Mode, ZoneType, upstream::UpstreamAddr};
|
||||
|
||||
/// Error loading a configuration file.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ConfigError {
|
||||
#[error("{file}: {message}")]
|
||||
Io { file: String, message: String },
|
||||
#[error("{file}{}: {message}", line.map(|l| format!(":{l}")).unwrap_or_default())]
|
||||
Parse { file: String, line: Option<usize>, message: String },
|
||||
#[error("environment variable {var}: {message}")]
|
||||
Env { var: String, message: String },
|
||||
#[error("configuration is invalid ({0} error(s))")]
|
||||
Invalid(usize),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Severity {
|
||||
Error,
|
||||
Warning,
|
||||
}
|
||||
|
||||
/// A single validation finding, e.g. `zones[1].primaries: ...`.
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct ValidationIssue {
|
||||
pub severity: Severity,
|
||||
pub path: String,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl fmt::Display for ValidationIssue {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let s = match self.severity {
|
||||
Severity::Error => "error",
|
||||
Severity::Warning => "warning",
|
||||
};
|
||||
write!(f, "{s}: {}: {}", self.path, self.message)
|
||||
}
|
||||
}
|
||||
|
||||
impl ValidationIssue {
|
||||
pub fn is_error(&self) -> bool {
|
||||
self.severity == Severity::Error
|
||||
}
|
||||
}
|
||||
|
||||
struct V(Vec<ValidationIssue>);
|
||||
|
||||
impl V {
|
||||
fn err(&mut self, path: impl Into<String>, msg: impl Into<String>) {
|
||||
self.0.push(ValidationIssue { severity: Severity::Error, path: path.into(), message: msg.into() });
|
||||
}
|
||||
fn warn(&mut self, path: impl Into<String>, msg: impl Into<String>) {
|
||||
self.0.push(ValidationIssue { severity: Severity::Warning, path: path.into(), message: msg.into() });
|
||||
}
|
||||
}
|
||||
|
||||
fn is_open(nets: &[ipnet::IpNet]) -> bool {
|
||||
nets.iter().any(|n| n.prefix_len() == 0)
|
||||
}
|
||||
|
||||
pub(crate) fn validate(c: &Config) -> Vec<ValidationIssue> {
|
||||
let mut v = V(Vec::new());
|
||||
|
||||
// server
|
||||
if !c.server.udp && !c.server.tcp {
|
||||
v.err("server", "at least one of udp/tcp must be enabled");
|
||||
}
|
||||
if c.server.listen.is_empty() {
|
||||
v.err("server.listen", "no listen addresses");
|
||||
}
|
||||
if c.server.max_udp_payload < 512 {
|
||||
v.err("server.max_udp_payload", "must be >= 512");
|
||||
}
|
||||
if c.server.max_udp_payload > 4096 {
|
||||
v.warn("server.max_udp_payload", "values above 1232 risk IP fragmentation");
|
||||
}
|
||||
if c.server.max_tcp_connections == 0 || c.server.max_inflight == 0 {
|
||||
v.err("server", "max_tcp_connections and max_inflight must be > 0");
|
||||
}
|
||||
if !["error", "warn", "info", "debug", "trace"].contains(&c.logging.level.as_str()) && !c.logging.level.contains('=') {
|
||||
v.err("logging.level", format!("unknown level '{}'", c.logging.level));
|
||||
}
|
||||
|
||||
// keys
|
||||
let mut key_names = HashSet::new();
|
||||
for (i, k) in c.keys.iter().enumerate() {
|
||||
let p = format!("keys[{i}]");
|
||||
if !key_names.insert(k.name.to_ascii_lowercase().trim_end_matches('.').to_string()) {
|
||||
v.err(&p, format!("duplicate key name '{}'", k.name));
|
||||
}
|
||||
if let Err(e) = dns_core::tsig::parse_algorithm(&k.algorithm) {
|
||||
v.err(format!("{p}.algorithm"), e.to_string());
|
||||
}
|
||||
match c.resolve_secret(&k.secret) {
|
||||
Ok(s) => {
|
||||
if let Err(e) = dns_core::tsig::TsigKey::new(&k.name, &k.algorithm, &s) {
|
||||
v.err(format!("{p}.secret"), e.to_string());
|
||||
}
|
||||
}
|
||||
Err(e) if k.secret.starts_with("env:") => v.warn(format!("{p}.secret"), e),
|
||||
Err(e) => v.err(format!("{p}.secret"), e),
|
||||
}
|
||||
match &k.imported_from {
|
||||
// BIND key files hold the secret by design; they must not be world-readable
|
||||
Some(f) =>
|
||||
{
|
||||
#[cfg(unix)]
|
||||
if let Ok(m) = std::fs::metadata(f) {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
if m.permissions().mode() & 0o004 != 0 {
|
||||
v.warn(format!("{p} ({f})"), "key file is world-readable; use chmod 640 and group easydns");
|
||||
}
|
||||
}
|
||||
}
|
||||
None if k.secret.starts_with("base64:") => {
|
||||
v.warn(format!("{p}.secret"), "inline secret in config file; prefer env: or file:");
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
let key_exists = |n: &str| key_names.contains(n.to_ascii_lowercase().trim_end_matches('.'));
|
||||
|
||||
for (name, list) in &c.acls {
|
||||
if let Err(e) = c.expand_acl(list) {
|
||||
v.err(format!("acls.{name}"), e);
|
||||
}
|
||||
}
|
||||
|
||||
// recursion
|
||||
let rec_acl = c.expand_acl(&c.recursion.allowed_clients);
|
||||
match &rec_acl {
|
||||
Err(e) => v.err("recursion.allowed_clients", e.clone()),
|
||||
Ok(n) if is_open(n) && c.recursion.enabled => {
|
||||
v.warn("recursion.allowed_clients", "recursion is open to ANY client (open resolver) – this enables DNS amplification abuse")
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if c.recursion.enabled {
|
||||
if let Some(h) = &c.recursion.root_hints
|
||||
&& !c.resolve_path(h).is_file()
|
||||
{
|
||||
v.err("recursion.root_hints", format!("file not found: {}", c.resolve_path(h).display()));
|
||||
}
|
||||
if let Some(t) = &c.recursion.trust_anchors
|
||||
&& !c.resolve_path(t).is_file()
|
||||
{
|
||||
v.err("recursion.trust_anchors", format!("file not found: {}", c.resolve_path(t).display()));
|
||||
}
|
||||
if c.recursion.max_queries == 0 || c.recursion.max_depth == 0 {
|
||||
v.err("recursion", "max_queries and max_depth must be > 0");
|
||||
}
|
||||
} else if c.recursion.dnssec_validation {
|
||||
v.warn("recursion.dnssec_validation", "has no effect while recursion is disabled");
|
||||
}
|
||||
for (i, s) in c.recursion.local_only_suffixes.iter().enumerate() {
|
||||
if dns_core::names::parse_name(s).is_err() {
|
||||
v.err(format!("recursion.local_only_suffixes[{i}]"), format!("invalid name '{s}'"));
|
||||
}
|
||||
}
|
||||
|
||||
// zones
|
||||
let mut zone_names = HashSet::new();
|
||||
let view_names: HashSet<&str> = c.resolution.views.iter().map(|v| v.name.as_str()).collect();
|
||||
for (i, z) in c.zones.iter().enumerate() {
|
||||
let p = match &z.source {
|
||||
Some(src) => format!("zones[{i}] '{}' ({src})", z.name),
|
||||
None => format!("zones[{i}]"),
|
||||
};
|
||||
match dns_core::names::parse_name(&z.name) {
|
||||
Ok(n) => {
|
||||
let key = (n.to_string(), z.views.clone());
|
||||
if !zone_names.insert(key) {
|
||||
v.err(&p, format!("duplicate zone '{}'", z.name));
|
||||
}
|
||||
}
|
||||
Err(e) => v.err(format!("{p}.name"), e.to_string()),
|
||||
}
|
||||
for (field, list) in [("transfer_acl", &z.transfer_acl), ("allow_notify", &z.allow_notify), ("update_acl", &z.update_acl)] {
|
||||
match c.expand_acl(list) {
|
||||
Err(e) => v.err(format!("{p}.{field}"), e),
|
||||
Ok(n) if is_open(&n) && field == "transfer_acl" && z.transfer_tsig_key.is_none() => {
|
||||
v.warn(format!("{p}.transfer_acl"), "zone transfers open to any address without TSIG")
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
for (field, k) in [
|
||||
("transfer_tsig_key", &z.transfer_tsig_key),
|
||||
("notify_tsig_key", &z.notify_tsig_key),
|
||||
("transfer.tsig_key", &z.transfer.tsig_key),
|
||||
] {
|
||||
if let Some(k) = k
|
||||
&& !key_exists(k)
|
||||
{
|
||||
v.err(format!("{p}.{field}"), format!("unknown key '{k}'"));
|
||||
}
|
||||
}
|
||||
if !z.update_policy.is_empty() && !z.update_keys.is_empty() {
|
||||
v.err(
|
||||
format!("{p}.update_policy"),
|
||||
"use either update_policy or update_keys, not both (like BIND's update-policy vs allow-update)",
|
||||
);
|
||||
}
|
||||
if z.update_policy.is_empty() && z.update_keys.is_empty() && !z.update_acl.is_empty() {
|
||||
let open = c.expand_acl(&z.update_acl).map(|n| is_open(&n)).unwrap_or(false);
|
||||
if open {
|
||||
v.err(format!("{p}.update_acl"), "unsigned updates from any address would let anyone change the zone");
|
||||
} else {
|
||||
v.warn(
|
||||
format!("{p}.update_acl"),
|
||||
"updates authorised by source IP only (no TSIG); spoofed UDP sources are possible – keep the list narrow",
|
||||
);
|
||||
}
|
||||
}
|
||||
for (j, r) in z.update_policy.iter().enumerate() {
|
||||
if r.identity != "*" && !key_exists(&r.identity) {
|
||||
v.err(format!("{p}.update_policy[{j}]"), format!("unknown key '{}'", r.identity));
|
||||
}
|
||||
if let Some(n) = &r.name {
|
||||
let n = n.trim_start_matches("*.").trim_end_matches('.').to_ascii_lowercase();
|
||||
let zn = z.name.trim_end_matches('.').to_ascii_lowercase();
|
||||
if n != zn && !n.ends_with(&format!(".{zn}")) {
|
||||
v.warn(format!("{p}.update_policy[{j}]"), format!("name {n} is outside zone {zn}; the rule never matches"));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (j, k) in z.update_keys.iter().enumerate() {
|
||||
if !key_exists(k) {
|
||||
v.err(format!("{p}.update_keys[{j}]"), format!("unknown key '{k}'"));
|
||||
}
|
||||
}
|
||||
for view in &z.views {
|
||||
if !view_names.contains(view.as_str()) {
|
||||
v.err(format!("{p}.views"), format!("unknown view '{view}'"));
|
||||
}
|
||||
}
|
||||
if let Some(d) = &z.dnssec {
|
||||
if z.zone_type != ZoneType::Primary {
|
||||
v.err(format!("{p}.dnssec"), "signing is only supported on primary zones (secondaries transfer signed data)");
|
||||
}
|
||||
if d.resign_before >= d.signature_validity {
|
||||
v.err(format!("{p}.dnssec.resign_before"), "must be shorter than signature_validity");
|
||||
}
|
||||
if d.signature_validity.as_secs() < 3600 {
|
||||
v.err(format!("{p}.dnssec.signature_validity"), "must be at least 1h");
|
||||
}
|
||||
}
|
||||
match z.zone_type {
|
||||
ZoneType::Primary => {
|
||||
match &z.file {
|
||||
None => v.err(format!("{p}.file"), "primary zone requires a zone file"),
|
||||
Some(f) if !c.zone_file_path(f).is_file() => {
|
||||
v.err(format!("{p}.file"), format!("file not found: {}", c.zone_file_path(f).display()))
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if !z.primaries.is_empty() {
|
||||
v.err(format!("{p}.primaries"), "only valid for secondary zones");
|
||||
}
|
||||
}
|
||||
ZoneType::Secondary => {
|
||||
if z.primaries.is_empty() {
|
||||
v.err(format!("{p}.primaries"), "secondary zone requires at least one primary");
|
||||
}
|
||||
if !z.notify.is_empty() {
|
||||
v.warn(format!("{p}.notify"), "secondary will also NOTIFY these servers after updates");
|
||||
}
|
||||
if !z.update_keys.is_empty() || !z.update_policy.is_empty() || !z.update_acl.is_empty() {
|
||||
v.err(format!("{p}.update_*"), "dynamic updates are only supported on primary zones");
|
||||
}
|
||||
// No TSIG is a supported, documented setup (IP-based transfers); see
|
||||
// docs/zone-transfer-variants.md. The key is optional.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// forwarding
|
||||
for (i, f) in c.forward_zones.iter().enumerate() {
|
||||
let p = format!("forward_zones[{i}]");
|
||||
if dns_core::names::parse_name(&f.domain).is_err() {
|
||||
v.err(format!("{p}.domain"), format!("invalid domain '{}'", f.domain));
|
||||
}
|
||||
if f.upstreams.is_empty() {
|
||||
v.err(format!("{p}.upstreams"), "at least one upstream required");
|
||||
}
|
||||
for (j, u) in f.upstreams.iter().enumerate() {
|
||||
if let Err(e) = UpstreamAddr::parse(u) {
|
||||
v.err(format!("{p}.upstreams[{j}]"), e);
|
||||
}
|
||||
}
|
||||
if let Err(e) = c.expand_acl(&f.clients) {
|
||||
v.err(format!("{p}.clients"), e);
|
||||
}
|
||||
if f.fallback_recursion && !c.recursion.enabled {
|
||||
v.err(format!("{p}.fallback_recursion"), "requires recursion.enabled");
|
||||
}
|
||||
}
|
||||
for (j, u) in c.upstreams.servers.iter().enumerate() {
|
||||
if let Err(e) = UpstreamAddr::parse(u) {
|
||||
v.err(format!("upstreams.servers[{j}]"), e);
|
||||
}
|
||||
}
|
||||
|
||||
match c.resolution.default {
|
||||
DefaultResolution::Recursive if !c.recursion.enabled => v.err("resolution.default", "'recursive' requires recursion.enabled: true"),
|
||||
DefaultResolution::Forward | DefaultResolution::ForwardThenRecursive if c.upstreams.servers.is_empty() => {
|
||||
v.err("resolution.default", "forwarding requires upstreams.servers")
|
||||
}
|
||||
DefaultResolution::ForwardThenRecursive if !c.recursion.enabled => {
|
||||
v.err("resolution.default", "'forwardthenrecursive' requires recursion.enabled: true")
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
for (i, view) in c.resolution.views.iter().enumerate() {
|
||||
if let Err(e) = c.expand_acl(&view.clients) {
|
||||
v.err(format!("resolution.views[{i}].clients"), e);
|
||||
}
|
||||
}
|
||||
|
||||
// mode consistency
|
||||
let has_primary = c.zones.iter().any(|z| z.zone_type == ZoneType::Primary);
|
||||
let has_secondary = c.zones.iter().any(|z| z.zone_type == ZoneType::Secondary);
|
||||
match c.server.mode {
|
||||
Mode::Primary if !has_primary => v.err("server.mode", "mode 'primary' but no primary zones"),
|
||||
Mode::Secondary if !has_secondary => v.err("server.mode", "mode 'secondary' but no secondary zones"),
|
||||
Mode::Recursive if !c.recursion.enabled => v.err("server.mode", "mode 'recursive' requires recursion.enabled"),
|
||||
Mode::Recursive if c.resolution.default != DefaultResolution::Recursive => {
|
||||
v.err("server.mode", "mode 'recursive' requires resolution.default: recursive")
|
||||
}
|
||||
Mode::Forwarder if c.upstreams.servers.is_empty() && c.forward_zones.is_empty() => {
|
||||
v.err("server.mode", "mode 'forwarder' requires upstreams or forward_zones")
|
||||
}
|
||||
Mode::CacheOnly if !c.zones.is_empty() => v.err("server.mode", "mode 'cache-only' must not define zones"),
|
||||
Mode::CacheOnly if c.resolution.default == DefaultResolution::Refuse => {
|
||||
v.err("server.mode", "mode 'cache-only' requires a recursive or forward default")
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
// cache / policy / ratelimit
|
||||
if c.cache.min_ttl > c.cache.max_ttl {
|
||||
v.err("cache", "min_ttl must be <= max_ttl");
|
||||
}
|
||||
if c.cache.min_ttl > 300 {
|
||||
v.warn("cache.min_ttl", "large minimum TTL extends records beyond their published TTL");
|
||||
}
|
||||
for (i, b) in c.policy.blocklists.iter().enumerate() {
|
||||
let p = format!("policy.blocklists[{i}]");
|
||||
match (&b.file, &b.url) {
|
||||
(None, None) => v.err(&p, "requires file or url"),
|
||||
(Some(f), _) if b.enabled && b.url.is_none() && !c.resolve_path(f).is_file() => {
|
||||
v.err(format!("{p}.file"), format!("file not found: {}", c.resolve_path(f).display()))
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if let Some(u) = &b.url
|
||||
&& !u.starts_with("https://")
|
||||
{
|
||||
v.err(format!("{p}.url"), "only https:// URLs are allowed");
|
||||
}
|
||||
}
|
||||
if let Err(e) = c.expand_acl(&c.policy.exempt_clients) {
|
||||
v.err("policy.exempt_clients", e);
|
||||
}
|
||||
if c.rate_limit.enabled && (c.rate_limit.per_client_qps == 0 || c.rate_limit.burst == 0) {
|
||||
v.err("rate_limit", "per_client_qps and burst must be > 0 when enabled");
|
||||
}
|
||||
if let Err(e) = c.expand_acl(&c.rate_limit.exempt_clients) {
|
||||
v.err("rate_limit.exempt_clients", e);
|
||||
}
|
||||
|
||||
// TLS
|
||||
let needs_tls = !c.tls.dot_listen.is_empty() || (!c.tls.doh_listen.is_empty() && !c.tls.doh_plaintext_behind_proxy);
|
||||
if needs_tls {
|
||||
for (f, val) in [("tls.cert_file", &c.tls.cert_file), ("tls.key_file", &c.tls.key_file)] {
|
||||
match val {
|
||||
None => v.err(f, "required when DoT/DoH listeners are configured"),
|
||||
Some(p) if !c.resolve_path(p).is_file() => v.err(f, format!("file not found: {}", c.resolve_path(p).display())),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
if c.tls.doh_plaintext_behind_proxy {
|
||||
for a in &c.tls.doh_listen {
|
||||
if !a.ip().is_loopback() {
|
||||
v.warn("tls.doh_listen", format!("{a}: plaintext DoH on a non-loopback address"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// API
|
||||
if c.api.enabled {
|
||||
if !c.api.listen.ip().is_loopback() {
|
||||
if !c.api.auth_required {
|
||||
v.err("api.auth_required", "API on a non-loopback address must require authentication");
|
||||
} else {
|
||||
v.warn("api.listen", "API is reachable from the network; protect it with a firewall/TLS proxy");
|
||||
}
|
||||
}
|
||||
if c.api.auth_required && c.api.tokens.is_empty() && !c.api.local_token {
|
||||
v.warn("api.tokens", "no API tokens defined: every authenticated endpoint will be refused");
|
||||
}
|
||||
for (i, t) in c.api.tokens.iter().enumerate() {
|
||||
if !(t.token.starts_with("env:") || t.token.starts_with("file:") || t.token.starts_with("sha256:")) {
|
||||
v.err(format!("api.tokens[{i}].token"), "token must be env:, file: or sha256:<hex>");
|
||||
}
|
||||
}
|
||||
if let Err(e) = c.expand_acl(&c.api.allowed_clients) {
|
||||
v.err("api.allowed_clients", e);
|
||||
}
|
||||
}
|
||||
if c.metrics.enabled && !c.metrics.listen.ip().is_loopback() {
|
||||
v.warn("metrics.listen", "metrics exposed on a non-loopback address");
|
||||
}
|
||||
v.0
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
[package]
|
||||
name = "dns-core"
|
||||
description = "EasyDNS core: protocol helpers, zone files, TSIG, DNS client"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
hickory-proto.workspace = true
|
||||
tokio.workspace = true
|
||||
hyper.workspace = true
|
||||
hyper-util.workspace = true
|
||||
http-body-util.workspace = true
|
||||
bytes.workspace = true
|
||||
thiserror.workspace = true
|
||||
tracing.workspace = true
|
||||
rand.workspace = true
|
||||
data-encoding.workspace = true
|
||||
serde.workspace = true
|
||||
rustls.workspace = true
|
||||
tokio-rustls.workspace = true
|
||||
webpki-roots.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
rcgen.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,73 @@
|
||||
//! Resolution result shared by the cache, recursive resolver, forwarder and server.
|
||||
use hickory_proto::op::ResponseCode;
|
||||
use hickory_proto::rr::Record;
|
||||
|
||||
/// DNSSEC validation state (RFC 4035 §4.3).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, Default)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Security {
|
||||
Secure,
|
||||
Insecure,
|
||||
Bogus,
|
||||
#[default]
|
||||
Indeterminate,
|
||||
}
|
||||
|
||||
/// Where an answer came from (for logging/metrics; low cardinality).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Source {
|
||||
Authoritative,
|
||||
Cache,
|
||||
Recursive,
|
||||
Forward,
|
||||
Blocked,
|
||||
Local,
|
||||
Refused,
|
||||
}
|
||||
|
||||
impl Source {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Source::Authoritative => "authoritative",
|
||||
Source::Cache => "cache",
|
||||
Source::Recursive => "recursive",
|
||||
Source::Forward => "forward",
|
||||
Source::Blocked => "blocked",
|
||||
Source::Local => "local",
|
||||
Source::Refused => "refused",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A resolved answer.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Answer {
|
||||
pub rcode: ResponseCode,
|
||||
pub answers: Vec<Record>,
|
||||
pub authority: Vec<Record>,
|
||||
pub additional: Vec<Record>,
|
||||
pub security: Security,
|
||||
pub source: Source,
|
||||
/// Free-form note (upstream used, block reason) for logs.
|
||||
pub note: Option<String>,
|
||||
}
|
||||
|
||||
impl Answer {
|
||||
pub fn new(rcode: ResponseCode, source: Source) -> Self {
|
||||
Self {
|
||||
rcode,
|
||||
answers: Vec::new(),
|
||||
authority: Vec::new(),
|
||||
additional: Vec::new(),
|
||||
security: Security::Indeterminate,
|
||||
source,
|
||||
note: None,
|
||||
}
|
||||
}
|
||||
pub fn servfail(source: Source, note: impl Into<String>) -> Self {
|
||||
let mut a = Self::new(ResponseCode::ServFail, source);
|
||||
a.note = Some(note.into());
|
||||
a
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
//! Async DNS client: UDP with TCP fallback, TCP streams and zone transfers.
|
||||
//!
|
||||
//! Anti-spoofing measures: random 16-bit IDs, a fresh ephemeral UDP socket
|
||||
//! (random source port) per exchange, `connect()`ed sockets so only the server
|
||||
//! address is accepted, and question matching on every response.
|
||||
use std::net::SocketAddr;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use hickory_proto::op::{Edns, Message, MessageType, OpCode, Query, ResponseCode};
|
||||
use hickory_proto::rr::{DNSClass, Name, RData, Record, RecordType};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::{TcpStream, UdpSocket};
|
||||
|
||||
use crate::tsig::{ResponseVerifier, TsigKey};
|
||||
use crate::wire::{DEFAULT_EDNS_PAYLOAD, response_matches};
|
||||
use crate::{CoreError, CoreResult};
|
||||
|
||||
/// Transport actually used for an exchange.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Transport {
|
||||
Udp,
|
||||
Tcp,
|
||||
}
|
||||
|
||||
/// Options for a single query.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct QueryOptions {
|
||||
pub timeout: Duration,
|
||||
pub retries: u32,
|
||||
pub tcp_only: bool,
|
||||
/// Do not retry over TCP when the UDP answer is truncated.
|
||||
pub ignore_tc: bool,
|
||||
pub edns: bool,
|
||||
pub edns_payload: u16,
|
||||
pub dnssec_ok: bool,
|
||||
pub recursion_desired: bool,
|
||||
pub checking_disabled: bool,
|
||||
pub tsig: Option<TsigKey>,
|
||||
}
|
||||
|
||||
impl Default for QueryOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
timeout: Duration::from_secs(2),
|
||||
retries: 2,
|
||||
tcp_only: false,
|
||||
ignore_tc: false,
|
||||
edns: true,
|
||||
edns_payload: DEFAULT_EDNS_PAYLOAD,
|
||||
dnssec_ok: false,
|
||||
recursion_desired: true,
|
||||
checking_disabled: false,
|
||||
tsig: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A completed exchange.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Exchange {
|
||||
pub server: SocketAddr,
|
||||
pub message: Message,
|
||||
pub transport: Transport,
|
||||
pub elapsed: Duration,
|
||||
pub size: usize,
|
||||
pub tsig_verified: bool,
|
||||
}
|
||||
|
||||
/// Build a query message with a random ID.
|
||||
pub fn build_query(name: &Name, rtype: RecordType, opts: &QueryOptions) -> Message {
|
||||
let mut m = Message::new(rand::random::<u16>(), MessageType::Query, OpCode::Query);
|
||||
m.metadata.recursion_desired = opts.recursion_desired;
|
||||
m.metadata.checking_disabled = opts.checking_disabled;
|
||||
let mut q = Query::query(name.clone(), rtype);
|
||||
q.set_query_class(DNSClass::IN);
|
||||
m.add_query(q);
|
||||
if opts.edns {
|
||||
let mut e = Edns::new();
|
||||
e.set_max_payload(opts.edns_payload.max(512));
|
||||
e.set_dnssec_ok(opts.dnssec_ok);
|
||||
m.set_edns(e);
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// Query `server` for `name`/`rtype`.
|
||||
pub async fn query(server: SocketAddr, name: &Name, rtype: RecordType, opts: &QueryOptions) -> CoreResult<Exchange> {
|
||||
let msg = build_query(name, rtype, opts);
|
||||
exchange(server, msg, opts).await
|
||||
}
|
||||
|
||||
/// Send a prepared message (signing it with TSIG if configured), with retries and
|
||||
/// automatic UDP→TCP fallback on truncation.
|
||||
pub async fn exchange(server: SocketAddr, mut msg: Message, opts: &QueryOptions) -> CoreResult<Exchange> {
|
||||
let req_mac = match &opts.tsig {
|
||||
Some(k) => Some(k.sign_request(&mut msg)?),
|
||||
None => None,
|
||||
};
|
||||
let bytes = msg.to_vec()?;
|
||||
let start = Instant::now();
|
||||
let mut last_err = CoreError::Timeout(opts.timeout);
|
||||
let attempts = opts.retries + 1;
|
||||
for _ in 0..attempts {
|
||||
let res = if opts.tcp_only {
|
||||
tcp_exchange(server, &bytes, &msg, opts.timeout).await.map(|r| (r, Transport::Tcp))
|
||||
} else {
|
||||
match udp_exchange(server, &bytes, &msg, opts.timeout).await {
|
||||
Ok((_, m)) if m.metadata.truncation && !opts.ignore_tc => {
|
||||
tcp_exchange(server, &bytes, &msg, opts.timeout).await.map(|r| (r, Transport::Tcp))
|
||||
}
|
||||
Ok(r) => Ok((r, Transport::Udp)),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
};
|
||||
match res {
|
||||
Ok(((raw, m), transport)) => {
|
||||
let mut verified = false;
|
||||
if let (Some(k), Some(mac)) = (&opts.tsig, &req_mac) {
|
||||
let mut v = ResponseVerifier::new(k.clone(), mac.clone());
|
||||
verified = v.verify(&raw, &m)?;
|
||||
if !verified {
|
||||
return Err(CoreError::Tsig("response is not signed".into()));
|
||||
}
|
||||
}
|
||||
return Ok(Exchange { server, size: raw.len(), message: m, transport, elapsed: start.elapsed(), tsig_verified: verified });
|
||||
}
|
||||
Err(e @ CoreError::Tsig(_)) => return Err(e),
|
||||
Err(e) => last_err = e,
|
||||
}
|
||||
}
|
||||
Err(last_err)
|
||||
}
|
||||
|
||||
async fn udp_exchange(server: SocketAddr, bytes: &[u8], query: &Message, timeout: Duration) -> CoreResult<(Vec<u8>, Message)> {
|
||||
let bind: SocketAddr = if server.is_ipv4() {
|
||||
"0.0.0.0:0".parse().map_err(|_| CoreError::Invalid("bind".into()))?
|
||||
} else {
|
||||
"[::]:0".parse().map_err(|_| CoreError::Invalid("bind".into()))?
|
||||
};
|
||||
let sock = UdpSocket::bind(bind).await?;
|
||||
sock.connect(server).await?;
|
||||
sock.send(bytes).await?;
|
||||
let deadline = Instant::now() + timeout;
|
||||
let mut buf = vec![0u8; 65_535];
|
||||
loop {
|
||||
let remaining = deadline.saturating_duration_since(Instant::now());
|
||||
if remaining.is_zero() {
|
||||
return Err(CoreError::Timeout(timeout));
|
||||
}
|
||||
let n = match tokio::time::timeout(remaining, sock.recv(&mut buf)).await {
|
||||
Ok(r) => r?,
|
||||
Err(_) => return Err(CoreError::Timeout(timeout)),
|
||||
};
|
||||
let raw = &buf[..n];
|
||||
let Ok(m) = Message::from_vec(raw) else { continue };
|
||||
if response_matches(query, &m) {
|
||||
return Ok((raw.to_vec(), m));
|
||||
}
|
||||
// Mismatched ID/question: ignore (possible spoofing attempt) and keep waiting.
|
||||
tracing::debug!(%server, "ignoring mismatched UDP response");
|
||||
}
|
||||
}
|
||||
|
||||
async fn tcp_exchange(server: SocketAddr, bytes: &[u8], query: &Message, timeout: Duration) -> CoreResult<(Vec<u8>, Message)> {
|
||||
let fut = async {
|
||||
let mut s = TcpStream::connect(server).await?;
|
||||
s.set_nodelay(true)?;
|
||||
write_tcp_msg(&mut s, bytes).await?;
|
||||
let raw = read_tcp_msg(&mut s).await?;
|
||||
let m = Message::from_vec(&raw).map_err(|e| CoreError::Proto(e.to_string()))?;
|
||||
if !response_matches(query, &m) {
|
||||
return Err(CoreError::Mismatch("TCP response does not match query".into()));
|
||||
}
|
||||
Ok((raw, m))
|
||||
};
|
||||
tokio::time::timeout(timeout, fut).await.map_err(|_| CoreError::Timeout(timeout))?
|
||||
}
|
||||
|
||||
/// Write a 2-byte length-prefixed DNS message.
|
||||
pub async fn write_tcp_msg<W: AsyncWriteExt + Unpin>(w: &mut W, bytes: &[u8]) -> CoreResult<()> {
|
||||
if bytes.len() > u16::MAX as usize {
|
||||
return Err(CoreError::Invalid("message too large for TCP".into()));
|
||||
}
|
||||
let mut buf = Vec::with_capacity(bytes.len() + 2);
|
||||
buf.extend_from_slice(&(bytes.len() as u16).to_be_bytes());
|
||||
buf.extend_from_slice(bytes);
|
||||
w.write_all(&buf).await?;
|
||||
w.flush().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Read a 2-byte length-prefixed DNS message.
|
||||
pub async fn read_tcp_msg<R: AsyncReadExt + Unpin>(r: &mut R) -> CoreResult<Vec<u8>> {
|
||||
let mut len = [0u8; 2];
|
||||
r.read_exact(&mut len).await?;
|
||||
let len = u16::from_be_bytes(len) as usize;
|
||||
if len < 12 {
|
||||
return Err(CoreError::Proto("TCP message shorter than DNS header".into()));
|
||||
}
|
||||
let mut buf = vec![0u8; len];
|
||||
r.read_exact(&mut buf).await?;
|
||||
Ok(buf)
|
||||
}
|
||||
|
||||
/// Kind of zone transfer.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum TransferKind {
|
||||
Axfr,
|
||||
/// IXFR from the given client SOA (RFC 1995: SOA goes in the authority section).
|
||||
Ixfr {
|
||||
current_soa: Box<Record>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Result of a zone transfer: the flat record stream as received.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TransferStream {
|
||||
pub records: Vec<Record>,
|
||||
pub messages: usize,
|
||||
pub bytes: usize,
|
||||
pub tsig_verified: bool,
|
||||
pub elapsed: Duration,
|
||||
}
|
||||
|
||||
/// Limits applied to an incoming transfer.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct TransferLimits {
|
||||
pub timeout: Duration,
|
||||
pub max_records: usize,
|
||||
pub max_bytes: usize,
|
||||
}
|
||||
|
||||
impl Default for TransferLimits {
|
||||
fn default() -> Self {
|
||||
Self { timeout: Duration::from_secs(120), max_records: 2_000_000, max_bytes: 512 * 1024 * 1024 }
|
||||
}
|
||||
}
|
||||
|
||||
fn soa_serial(r: &Record) -> Option<u32> {
|
||||
match &r.data {
|
||||
RData::SOA(s) => Some(s.serial),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Perform an AXFR/IXFR over TCP and return the record stream. The stream is
|
||||
/// complete (terminating SOA seen) when this returns `Ok`.
|
||||
pub async fn transfer(
|
||||
server: SocketAddr,
|
||||
zone: &Name,
|
||||
kind: &TransferKind,
|
||||
tsig: Option<&TsigKey>,
|
||||
limits: TransferLimits,
|
||||
) -> CoreResult<TransferStream> {
|
||||
let start = Instant::now();
|
||||
let rtype = match kind {
|
||||
TransferKind::Axfr => RecordType::AXFR,
|
||||
TransferKind::Ixfr { .. } => RecordType::IXFR,
|
||||
};
|
||||
let mut msg = Message::new(rand::random::<u16>(), MessageType::Query, OpCode::Query);
|
||||
msg.add_query(Query::query(zone.clone(), rtype));
|
||||
let client_serial = if let TransferKind::Ixfr { current_soa } = kind {
|
||||
let soa: &Record = current_soa;
|
||||
msg.add_authority(soa.clone());
|
||||
soa_serial(current_soa)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let req_mac = match tsig {
|
||||
Some(k) => Some(k.sign_request(&mut msg)?),
|
||||
None => None,
|
||||
};
|
||||
let bytes = msg.to_vec()?;
|
||||
let mut verifier = match (tsig, req_mac) {
|
||||
(Some(k), Some(mac)) => Some(ResponseVerifier::new(k.clone(), mac)),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let fut = async {
|
||||
let mut s = TcpStream::connect(server).await?;
|
||||
s.set_nodelay(true)?;
|
||||
write_tcp_msg(&mut s, &bytes).await?;
|
||||
let mut records: Vec<Record> = Vec::new();
|
||||
let mut messages = 0usize;
|
||||
let mut total = 0usize;
|
||||
let mut final_serial: Option<u32> = None;
|
||||
let mut incremental: Option<bool> = None;
|
||||
let mut final_soa_seen = 0usize;
|
||||
loop {
|
||||
let raw = read_tcp_msg(&mut s).await?;
|
||||
total += raw.len();
|
||||
if total > limits.max_bytes {
|
||||
return Err(CoreError::Transfer("transfer exceeds byte limit".into()));
|
||||
}
|
||||
let m = Message::from_vec(&raw).map_err(|e| CoreError::Proto(e.to_string()))?;
|
||||
if m.metadata.id != msg.metadata.id || m.metadata.message_type != MessageType::Response {
|
||||
return Err(CoreError::Mismatch("transfer response id mismatch".into()));
|
||||
}
|
||||
if let Some(v) = verifier.as_mut() {
|
||||
v.verify(&raw, &m)?;
|
||||
}
|
||||
if m.metadata.response_code != ResponseCode::NoError {
|
||||
return Err(CoreError::Transfer(format!("server answered {}", m.metadata.response_code)));
|
||||
}
|
||||
messages += 1;
|
||||
for r in m.answers {
|
||||
if records.is_empty() {
|
||||
let Some(s) = soa_serial(&r) else {
|
||||
return Err(CoreError::Transfer("first transfer record is not SOA".into()));
|
||||
};
|
||||
final_serial = Some(s);
|
||||
final_soa_seen = 1;
|
||||
} else {
|
||||
if records.len() == 1 {
|
||||
incremental = Some(rtype == RecordType::IXFR && r.record_type() == RecordType::SOA);
|
||||
}
|
||||
if soa_serial(&r) == final_serial {
|
||||
final_soa_seen += 1;
|
||||
}
|
||||
}
|
||||
records.push(r);
|
||||
if records.len() > limits.max_records {
|
||||
return Err(CoreError::Transfer("transfer exceeds record limit".into()));
|
||||
}
|
||||
}
|
||||
// Termination conditions.
|
||||
let done = match (records.len(), incremental) {
|
||||
(0, _) => false,
|
||||
// Single SOA: IXFR "up to date" reply when serial is not newer.
|
||||
(1, _) => {
|
||||
rtype == RecordType::IXFR
|
||||
&& match (final_serial, client_serial) {
|
||||
(Some(f), Some(c)) => !crate::serial::is_newer(f, c),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
(_, Some(true)) => final_soa_seen >= 3 && records.last().and_then(soa_serial) == final_serial,
|
||||
(_, _) => final_soa_seen >= 2 && records.last().and_then(soa_serial) == final_serial,
|
||||
};
|
||||
if done {
|
||||
if let Some(v) = &verifier {
|
||||
v.finish()?;
|
||||
}
|
||||
return Ok(TransferStream { records, messages, bytes: total, tsig_verified: verifier.is_some(), elapsed: start.elapsed() });
|
||||
}
|
||||
}
|
||||
};
|
||||
tokio::time::timeout(limits.timeout, fut).await.map_err(|_| CoreError::Timeout(limits.timeout))?
|
||||
}
|
||||
|
||||
/// Send a NOTIFY for `zone` (optionally carrying the new SOA) and wait for the ack.
|
||||
pub async fn notify(
|
||||
server: SocketAddr,
|
||||
zone: &Name,
|
||||
soa: Option<&Record>,
|
||||
tsig: Option<&TsigKey>,
|
||||
timeout: Duration,
|
||||
) -> CoreResult<ResponseCode> {
|
||||
let mut m = Message::new(rand::random::<u16>(), MessageType::Query, OpCode::Notify);
|
||||
m.metadata.authoritative = true;
|
||||
m.add_query(Query::query(zone.clone(), RecordType::SOA));
|
||||
if let Some(s) = soa {
|
||||
m.add_answer(s.clone());
|
||||
}
|
||||
let opts = QueryOptions { timeout, retries: 2, edns: false, recursion_desired: false, tsig: tsig.cloned(), ..Default::default() };
|
||||
let ex = exchange(server, m, &opts).await?;
|
||||
Ok(ex.message.metadata.response_code)
|
||||
}
|
||||
@@ -0,0 +1,468 @@
|
||||
//! DNSSEC primitives shared by the signer (primary) and the validator (resolver, ednssec):
|
||||
//! key generation/loading, RRset signing, RRSIG verification, DS matching and
|
||||
//! NSEC/NSEC3 denial-of-existence checks (RFC 4033–4035, RFC 5155).
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use data_encoding::{BASE32_DNSSEC, BASE64};
|
||||
use hickory_proto::dnssec::crypto::{EcdsaSigningKey, Ed25519SigningKey};
|
||||
use hickory_proto::dnssec::rdata::{DNSKEY, DNSSECRData, DS, NSEC, NSEC3, RRSIG, SigInput};
|
||||
use hickory_proto::dnssec::{Algorithm, DigestType, Nsec3HashAlgorithm, SigningKey, TBS, Verifier};
|
||||
use hickory_proto::rr::{DNSClass, Name, RData, Record, RecordType, SerialNumber};
|
||||
use rustls::pki_types::PrivatePkcs8KeyDer;
|
||||
|
||||
use crate::{CoreError, CoreResult};
|
||||
|
||||
/// Supported signing algorithms.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, Default)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum KeyAlgorithm {
|
||||
#[default]
|
||||
Ed25519,
|
||||
Ecdsap256,
|
||||
Ecdsap384,
|
||||
}
|
||||
|
||||
impl KeyAlgorithm {
|
||||
pub fn dnssec(self) -> Algorithm {
|
||||
match self {
|
||||
KeyAlgorithm::Ed25519 => Algorithm::ED25519,
|
||||
KeyAlgorithm::Ecdsap256 => Algorithm::ECDSAP256SHA256,
|
||||
KeyAlgorithm::Ecdsap384 => Algorithm::ECDSAP384SHA384,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A private key with its public DNSKEY.
|
||||
pub struct ZoneKey {
|
||||
pub dnskey: DNSKEY,
|
||||
pub tag: u16,
|
||||
pub ksk: bool,
|
||||
signing: Box<dyn SigningKey>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ZoneKey {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "ZoneKey(tag {}, {}, {:?})", self.tag, if self.ksk { "KSK" } else { "ZSK" }, self.dnskey.algorithm())
|
||||
}
|
||||
}
|
||||
|
||||
fn signer(alg: KeyAlgorithm, pkcs8: &[u8]) -> CoreResult<Box<dyn SigningKey>> {
|
||||
let der = PrivatePkcs8KeyDer::from(pkcs8.to_vec());
|
||||
let k: Box<dyn SigningKey> = match alg {
|
||||
KeyAlgorithm::Ed25519 => Box::new(Ed25519SigningKey::from_pkcs8(&der).map_err(|e| CoreError::Invalid(e.to_string()))?),
|
||||
a => Box::new(EcdsaSigningKey::from_pkcs8(&der, a.dnssec()).map_err(|e| CoreError::Invalid(e.to_string()))?),
|
||||
};
|
||||
Ok(k)
|
||||
}
|
||||
|
||||
impl ZoneKey {
|
||||
/// Generate a new key; returns the PKCS#8 private key bytes and the key.
|
||||
pub fn generate(alg: KeyAlgorithm, ksk: bool) -> CoreResult<(Vec<u8>, Self)> {
|
||||
let der = match alg {
|
||||
KeyAlgorithm::Ed25519 => Ed25519SigningKey::generate_pkcs8(),
|
||||
a => EcdsaSigningKey::generate_pkcs8(a.dnssec()),
|
||||
}
|
||||
.map_err(|e| CoreError::Invalid(e.to_string()))?;
|
||||
let bytes = der.secret_pkcs8_der().to_vec();
|
||||
let k = Self::from_pkcs8(alg, &bytes, ksk)?;
|
||||
Ok((bytes, k))
|
||||
}
|
||||
|
||||
pub fn from_pkcs8(alg: KeyAlgorithm, pkcs8: &[u8], ksk: bool) -> CoreResult<Self> {
|
||||
let signing = signer(alg, pkcs8)?;
|
||||
let public = signing.to_public_key().map_err(|e| CoreError::Invalid(e.to_string()))?;
|
||||
let dnskey = DNSKEY::new(true, ksk, false, public);
|
||||
let tag = dnskey.calculate_key_tag().map_err(|e| CoreError::Invalid(e.to_string()))?;
|
||||
Ok(Self { dnskey, tag, ksk, signing })
|
||||
}
|
||||
|
||||
/// DNSKEY record for the zone apex.
|
||||
pub fn dnskey_record(&self, zone: &Name, ttl: u32) -> Record {
|
||||
Record::from_rdata(zone.clone(), ttl, RData::DNSSEC(DNSSECRData::DNSKEY(self.dnskey.clone())))
|
||||
}
|
||||
|
||||
/// DS record (SHA-256) to publish in the parent zone.
|
||||
pub fn ds_record(&self, zone: &Name, ttl: u32) -> CoreResult<Record> {
|
||||
let digest = self.dnskey.to_digest(zone, DigestType::SHA256).map_err(|e| CoreError::Invalid(e.to_string()))?;
|
||||
let ds = DS::new(self.tag, self.dnskey.algorithm(), DigestType::SHA256, digest.as_ref().to_vec());
|
||||
Ok(Record::from_rdata(zone.clone(), ttl, RData::DNSSEC(DNSSECRData::DS(ds))))
|
||||
}
|
||||
|
||||
/// Sign an RRset (all records must share owner/type/class). `zone` is the signer name.
|
||||
pub fn sign(&self, zone: &Name, rrset: &[Record], inception: u32, expiration: u32) -> CoreResult<Record> {
|
||||
let first = rrset.first().ok_or_else(|| CoreError::Invalid("empty RRset".into()))?;
|
||||
let labels = if first.name.is_wildcard() { first.name.num_labels() - 1 } else { first.name.num_labels() };
|
||||
let ttl = rrset.iter().map(|r| r.ttl).min().unwrap_or(first.ttl);
|
||||
let input = SigInput {
|
||||
type_covered: first.record_type(),
|
||||
algorithm: self.dnskey.algorithm(),
|
||||
num_labels: labels,
|
||||
original_ttl: ttl,
|
||||
sig_expiration: SerialNumber::new(expiration),
|
||||
sig_inception: SerialNumber::new(inception),
|
||||
key_tag: self.tag,
|
||||
signer_name: zone.clone(),
|
||||
};
|
||||
let tbs = TBS::from_input(&first.name, first.dns_class, &input, rrset.iter()).map_err(|e| CoreError::Invalid(e.to_string()))?;
|
||||
let sig = self.signing.sign(&tbs).map_err(|e| CoreError::Invalid(e.to_string()))?;
|
||||
let rrsig = RRSIG::from_sig(input, sig);
|
||||
let mut r = Record::from_rdata(first.name.clone(), ttl, RData::DNSSEC(DNSSECRData::RRSIG(rrsig)));
|
||||
r.dns_class = first.dns_class;
|
||||
Ok(r)
|
||||
}
|
||||
}
|
||||
|
||||
/// Serialise a private key for storage (`<zone>.<tag>.<ksk|zsk>.key`).
|
||||
pub fn key_file_contents(alg: KeyAlgorithm, ksk: bool, pkcs8: &[u8]) -> String {
|
||||
format!(
|
||||
"; EasyDNS DNSSEC private key – keep secret\nalgorithm: {}\nflags: {}\npkcs8: {}\n",
|
||||
serde_json::to_value(alg).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default(),
|
||||
if ksk { 257 } else { 256 },
|
||||
BASE64.encode(pkcs8)
|
||||
)
|
||||
}
|
||||
|
||||
/// Parse a stored private key.
|
||||
pub fn parse_key_file(text: &str) -> CoreResult<ZoneKey> {
|
||||
let mut alg = None;
|
||||
let mut ksk = false;
|
||||
let mut pk = None;
|
||||
for l in text.lines().map(str::trim).filter(|l| !l.starts_with(';') && !l.is_empty()) {
|
||||
let Some((k, v)) = l.split_once(':') else { continue };
|
||||
match k.trim() {
|
||||
"algorithm" => alg = serde_json::from_value::<KeyAlgorithm>(serde_json::Value::String(v.trim().into())).ok(),
|
||||
"flags" => ksk = v.trim() == "257",
|
||||
"pkcs8" => pk = BASE64.decode(v.trim().as_bytes()).ok(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let (Some(alg), Some(pk)) = (alg, pk) else {
|
||||
return Err(CoreError::Invalid("key file must contain algorithm and pkcs8".into()));
|
||||
};
|
||||
ZoneKey::from_pkcs8(alg, &pk, ksk)
|
||||
}
|
||||
|
||||
fn rrsig_of(r: &Record) -> Option<&RRSIG> {
|
||||
match &r.data {
|
||||
RData::DNSSEC(DNSSECRData::RRSIG(s)) => Some(s),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dnskey_of(r: &Record) -> Option<&DNSKEY> {
|
||||
match &r.data {
|
||||
RData::DNSSEC(DNSSECRData::DNSKEY(k)) => Some(k),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ds_of(r: &Record) -> Option<&DS> {
|
||||
match &r.data {
|
||||
RData::DNSSEC(DNSSECRData::DS(d)) => Some(d),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Signer name and covered type of an RRSIG record.
|
||||
pub fn rrsig_info(r: &Record) -> Option<(Name, RecordType, u16)> {
|
||||
rrsig_of(r).map(|s| (s.input().signer_name.clone(), s.input().type_covered, s.input().key_tag))
|
||||
}
|
||||
|
||||
/// Algorithms we can verify.
|
||||
pub fn algorithm_supported(a: Algorithm) -> bool {
|
||||
matches!(a, Algorithm::RSASHA256 | Algorithm::RSASHA512 | Algorithm::ECDSAP256SHA256 | Algorithm::ECDSAP384SHA384 | Algorithm::ED25519)
|
||||
}
|
||||
|
||||
/// Verify that `rrset` is signed by one of `rrsigs` using one of `keys`, at time `now`.
|
||||
/// Returns the key tag that validated. RFC 4035 §5.3.
|
||||
pub fn verify_rrset(owner: &Name, rrset: &[Record], rrsigs: &[Record], keys: &[DNSKEY], signer: &Name, now: u32) -> Result<u16, String> {
|
||||
let Some(first) = rrset.first() else { return Err("empty RRset".into()) };
|
||||
let rtype = first.record_type();
|
||||
let mut errors = Vec::new();
|
||||
for r in rrsigs {
|
||||
let Some(sig) = rrsig_of(r) else { continue };
|
||||
let i = sig.input();
|
||||
if i.type_covered != rtype || !r.name.eq_ignore_root_case(owner) {
|
||||
continue;
|
||||
}
|
||||
if !i.signer_name.eq_ignore_root_case(signer) || !signer.zone_of(owner) {
|
||||
errors.push(format!("RRSIG signer {} is not the zone {signer}", i.signer_name));
|
||||
continue;
|
||||
}
|
||||
let (inc, exp) = (i.sig_inception.get(), i.sig_expiration.get());
|
||||
if crate::serial::is_newer(inc, now) {
|
||||
errors.push(format!("RRSIG not yet valid (inception {inc})"));
|
||||
continue;
|
||||
}
|
||||
if crate::serial::is_newer(now, exp) {
|
||||
errors.push(format!("RRSIG expired (expiration {exp})"));
|
||||
continue;
|
||||
}
|
||||
if u32::from(i.num_labels) > owner.num_labels() as u32 {
|
||||
errors.push("RRSIG labels field larger than owner".into());
|
||||
continue;
|
||||
}
|
||||
for k in keys.iter().filter(|k| k.zone_key() && !k.revoke() && k.algorithm() == i.algorithm) {
|
||||
if k.calculate_key_tag().ok() != Some(i.key_tag) {
|
||||
continue;
|
||||
}
|
||||
// RFC 4035 §5.3.3: verify using the original TTL, owner per labels field.
|
||||
let mut set: Vec<Record> = rrset.to_vec();
|
||||
for x in &mut set {
|
||||
x.ttl = i.original_ttl;
|
||||
}
|
||||
match k.verify_rrsig(owner, first.dns_class, sig, set.iter()) {
|
||||
Ok(()) => return Ok(i.key_tag),
|
||||
Err(e) => errors.push(format!("signature by key {} invalid: {e}", i.key_tag)),
|
||||
}
|
||||
}
|
||||
}
|
||||
if errors.is_empty() { Err(format!("no usable RRSIG for {owner} {rtype}")) } else { Err(errors.join("; ")) }
|
||||
}
|
||||
|
||||
/// Does `ds` match `key` for zone `owner`?
|
||||
pub fn ds_matches(ds: &DS, owner: &Name, key: &DNSKEY) -> bool {
|
||||
ds.key_tag() == key.calculate_key_tag().unwrap_or(0) && ds.algorithm() == key.algorithm() && ds.covers(owner, key).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// RFC 4034 §6.1 canonical ordering helper: is `name` strictly between `owner` and `next`
|
||||
/// (taking the wrap-around at the end of the chain into account)?
|
||||
pub fn nsec_covers(owner: &Name, next: &Name, name: &Name) -> bool {
|
||||
if owner < next {
|
||||
owner < name && name < next
|
||||
} else {
|
||||
// last NSEC in the chain: covers everything after owner (or before next)
|
||||
name > owner || name < next
|
||||
}
|
||||
}
|
||||
|
||||
/// Outcome of a denial-of-existence check.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Denial {
|
||||
/// The name does not exist (NXDOMAIN proven).
|
||||
NxDomain,
|
||||
/// The name exists but not the type (NODATA proven).
|
||||
NoData,
|
||||
/// Insecure delegation (no DS) / opt-out proven.
|
||||
InsecureDelegation,
|
||||
/// Records do not prove the claim.
|
||||
Unproven(String),
|
||||
}
|
||||
|
||||
fn nsec_of(r: &Record) -> Option<&NSEC> {
|
||||
match &r.data {
|
||||
RData::DNSSEC(DNSSECRData::NSEC(n)) => Some(n),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn nsec3_of(r: &Record) -> Option<&NSEC3> {
|
||||
match &r.data {
|
||||
RData::DNSSEC(DNSSECRData::NSEC3(n)) => Some(n),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Check NSEC records (already signature-verified) for qname/qtype. `zone` is the signer.
|
||||
pub fn check_nsec(records: &[Record], qname: &Name, qtype: RecordType, zone: &Name) -> Denial {
|
||||
let nsecs: Vec<(&Record, &NSEC)> = records.iter().filter_map(|r| nsec_of(r).map(|n| (r, n))).collect();
|
||||
if nsecs.is_empty() {
|
||||
return Denial::Unproven("no NSEC records".into());
|
||||
}
|
||||
// NODATA: NSEC at qname without the type (and without CNAME)
|
||||
if let Some((_, n)) = nsecs.iter().find(|(r, _)| r.name.eq_ignore_root_case(qname)) {
|
||||
let types: BTreeSet<RecordType> = n.type_bit_maps().collect();
|
||||
if qtype == RecordType::DS {
|
||||
return if types.contains(&RecordType::DS) {
|
||||
Denial::Unproven("NSEC shows DS exists".into())
|
||||
} else if types.contains(&RecordType::NS) && !types.contains(&RecordType::SOA) {
|
||||
Denial::InsecureDelegation
|
||||
} else {
|
||||
Denial::NoData
|
||||
};
|
||||
}
|
||||
if types.contains(&qtype) || types.contains(&RecordType::CNAME) {
|
||||
return Denial::Unproven(format!("NSEC shows {qtype} exists"));
|
||||
}
|
||||
// An NSEC from the parent side of a delegation cannot prove NODATA below the cut.
|
||||
if types.contains(&RecordType::NS) && !types.contains(&RecordType::SOA) && !qname.eq_ignore_root_case(zone) {
|
||||
return Denial::Unproven("NSEC from delegation point".into());
|
||||
}
|
||||
return Denial::NoData;
|
||||
}
|
||||
// NXDOMAIN: an NSEC covers qname, and an NSEC covers the wildcard at the closest encloser.
|
||||
let covering = nsecs.iter().find(|(r, n)| nsec_covers(&r.name, n.next_domain_name(), qname));
|
||||
let Some((cov, cov_n)) = covering else {
|
||||
return Denial::Unproven(format!("no NSEC covers {qname}"));
|
||||
};
|
||||
// closest encloser = longest common ancestor of qname with owner/next of the covering NSEC
|
||||
let common = |a: &Name, b: &Name| -> usize {
|
||||
let la: Vec<_> = a.iter().rev().collect();
|
||||
let lb: Vec<_> = b.iter().rev().collect();
|
||||
la.iter().zip(lb.iter()).take_while(|(x, y)| x.eq_ignore_ascii_case(y)).count()
|
||||
};
|
||||
let ce_labels = common(qname, &cov.name).max(common(qname, cov_n.next_domain_name())).max(zone.num_labels() as usize);
|
||||
let ce = qname.trim_to(ce_labels);
|
||||
let Ok(wc) = Name::from_ascii("*").and_then(|w| w.append_domain(&ce)) else {
|
||||
return Denial::Unproven("bad wildcard".into());
|
||||
};
|
||||
let wc_denied = nsecs.iter().any(|(r, n)| {
|
||||
nsec_covers(&r.name, n.next_domain_name(), &wc) || (r.name.eq_ignore_root_case(&wc) && !n.type_bit_maps().any(|t| t == qtype))
|
||||
});
|
||||
if wc_denied || wc.eq_ignore_root_case(qname) { Denial::NxDomain } else { Denial::Unproven("wildcard not denied".into()) }
|
||||
}
|
||||
|
||||
/// RFC 5155 hash of a name, base32hex (lowercase) label.
|
||||
pub fn nsec3_hash(name: &Name, salt: &[u8], iterations: u16) -> Option<String> {
|
||||
let d = Nsec3HashAlgorithm::SHA1.hash(salt, name, iterations).ok()?;
|
||||
Some(BASE32_DNSSEC.encode(d.as_ref()).to_ascii_lowercase())
|
||||
}
|
||||
|
||||
/// Check NSEC3 records (already signature-verified). Iterations above 150 are treated as
|
||||
/// insecure per RFC 9276.
|
||||
pub fn check_nsec3(records: &[Record], qname: &Name, qtype: RecordType, zone: &Name) -> Denial {
|
||||
let n3: Vec<(String, &NSEC3)> = records
|
||||
.iter()
|
||||
.filter_map(|r| {
|
||||
nsec3_of(r).map(|n| (r.name.iter().next().map(|l| String::from_utf8_lossy(l).to_ascii_lowercase()).unwrap_or_default(), n))
|
||||
})
|
||||
.collect();
|
||||
let Some((_, p)) = n3.first() else { return Denial::Unproven("no NSEC3 records".into()) };
|
||||
if p.iterations() > 150 {
|
||||
return Denial::InsecureDelegation;
|
||||
}
|
||||
let (salt, it) = (p.salt().to_vec(), p.iterations());
|
||||
let hash = |n: &Name| nsec3_hash(n, &salt, it).unwrap_or_default();
|
||||
let next_of = |n: &NSEC3| BASE32_DNSSEC.encode(n.next_hashed_owner_name()).to_ascii_lowercase();
|
||||
let matching = |h: &str| n3.iter().find(|(o, _)| o == h).map(|(_, n)| *n);
|
||||
let covering = |h: &str| {
|
||||
n3.iter()
|
||||
.find(|(o, n)| {
|
||||
let nx = next_of(n);
|
||||
if o.as_str() < nx.as_str() { o.as_str() < h && h < nx.as_str() } else { h > o.as_str() || h < nx.as_str() }
|
||||
})
|
||||
.map(|(_, n)| *n)
|
||||
};
|
||||
let qh = hash(qname);
|
||||
if let Some(m) = matching(&qh) {
|
||||
let types: BTreeSet<RecordType> = m.type_bit_maps().collect();
|
||||
if qtype == RecordType::DS {
|
||||
if types.contains(&RecordType::DS) {
|
||||
return Denial::Unproven("NSEC3 shows DS exists".into());
|
||||
}
|
||||
return if types.contains(&RecordType::NS) && !types.contains(&RecordType::SOA) {
|
||||
Denial::InsecureDelegation
|
||||
} else {
|
||||
Denial::NoData
|
||||
};
|
||||
}
|
||||
if types.contains(&qtype) || types.contains(&RecordType::CNAME) {
|
||||
return Denial::Unproven(format!("NSEC3 shows {qtype} exists"));
|
||||
}
|
||||
return Denial::NoData;
|
||||
}
|
||||
// closest encloser proof
|
||||
let mut ce: Option<Name> = None;
|
||||
for anc in crate::names::ancestors(qname).skip(1) {
|
||||
if !zone.zone_of(&anc) {
|
||||
break;
|
||||
}
|
||||
if matching(&hash(&anc)).is_some() {
|
||||
ce = Some(anc);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let Some(ce) = ce else { return Denial::Unproven("no closest encloser".into()) };
|
||||
let next_closer = qname.trim_to(ce.num_labels() as usize + 1);
|
||||
let Some(nc) = covering(&hash(&next_closer)) else { return Denial::Unproven("next closer name not covered".into()) };
|
||||
if qtype == RecordType::DS && nc.opt_out() {
|
||||
return Denial::InsecureDelegation;
|
||||
}
|
||||
let Ok(wc) = Name::from_ascii("*").and_then(|w| w.append_domain(&ce)) else { return Denial::Unproven("bad wildcard".into()) };
|
||||
if covering(&hash(&wc)).is_some() {
|
||||
Denial::NxDomain
|
||||
} else if nc.opt_out() {
|
||||
Denial::InsecureDelegation
|
||||
} else {
|
||||
Denial::Unproven("wildcard not denied".into())
|
||||
}
|
||||
}
|
||||
|
||||
/// Build an NSEC record.
|
||||
pub fn nsec_record(owner: &Name, next: &Name, types: impl IntoIterator<Item = RecordType>, ttl: u32) -> Record {
|
||||
Record::from_rdata(owner.clone(), ttl, RData::DNSSEC(DNSSECRData::NSEC(NSEC::new(next.clone(), types))))
|
||||
}
|
||||
|
||||
/// DNSSEC-related record type?
|
||||
pub fn is_dnssec_type(t: RecordType) -> bool {
|
||||
matches!(t, RecordType::RRSIG | RecordType::NSEC | RecordType::NSEC3 | RecordType::NSEC3PARAM | RecordType::DNSKEY)
|
||||
}
|
||||
|
||||
/// The class used everywhere.
|
||||
pub const CLASS: DNSClass = DNSClass::IN;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use hickory_proto::rr::rdata::A;
|
||||
|
||||
fn n(s: &str) -> Name {
|
||||
Name::from_ascii(s).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sign_verify_and_ds() {
|
||||
for alg in [KeyAlgorithm::Ed25519, KeyAlgorithm::Ecdsap256] {
|
||||
let zone = n("example.");
|
||||
let (pk, key) = ZoneKey::generate(alg, true).unwrap();
|
||||
let again = parse_key_file(&key_file_contents(alg, true, &pk)).unwrap();
|
||||
assert_eq!(again.tag, key.tag);
|
||||
let rrset = vec![
|
||||
Record::from_rdata(n("www.example."), 300, RData::A(A::new(192, 0, 2, 1))),
|
||||
Record::from_rdata(n("www.example."), 300, RData::A(A::new(192, 0, 2, 2))),
|
||||
];
|
||||
let now = 1_800_000_000u32;
|
||||
let sig = key.sign(&zone, &rrset, now - 100, now + 1000).unwrap();
|
||||
let keys = [key.dnskey.clone()];
|
||||
assert!(verify_rrset(&n("www.example."), &rrset, std::slice::from_ref(&sig), &keys, &zone, now).is_ok());
|
||||
// order and TTL decrements do not matter
|
||||
let mut rev = rrset.clone();
|
||||
rev.reverse();
|
||||
rev[0].ttl = 10;
|
||||
assert!(verify_rrset(&n("www.example."), &rev, std::slice::from_ref(&sig), &keys, &zone, now).is_ok());
|
||||
// tampering is detected
|
||||
let mut bad = rrset.clone();
|
||||
bad[0].data = RData::A(A::new(192, 0, 2, 99));
|
||||
assert!(verify_rrset(&n("www.example."), &bad, std::slice::from_ref(&sig), &keys, &zone, now).is_err());
|
||||
// expired
|
||||
assert!(verify_rrset(&n("www.example."), &rrset, &[sig], &keys, &zone, now + 5000).is_err());
|
||||
let ds = key.ds_record(&zone, 3600).unwrap();
|
||||
assert!(ds_matches(ds_of(&ds).unwrap(), &zone, &key.dnskey));
|
||||
assert!(!ds_matches(ds_of(&ds).unwrap(), &n("other."), &key.dnskey));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nsec_logic() {
|
||||
let z = n("example.");
|
||||
assert!(nsec_covers(&n("a.example."), &n("c.example."), &n("b.example.")));
|
||||
assert!(!nsec_covers(&n("a.example."), &n("c.example."), &n("d.example.")));
|
||||
assert!(nsec_covers(&n("x.example."), &n("example."), &n("z.example.")));
|
||||
let recs = vec![
|
||||
nsec_record(&n("example."), &n("a.example."), [RecordType::SOA, RecordType::NS], 300),
|
||||
nsec_record(&n("a.example."), &n("example."), [RecordType::A], 300),
|
||||
];
|
||||
assert_eq!(check_nsec(&recs, &n("b.example."), RecordType::A, &z), Denial::NxDomain);
|
||||
assert_eq!(check_nsec(&recs, &n("a.example."), RecordType::MX, &z), Denial::NoData);
|
||||
assert!(matches!(check_nsec(&recs, &n("a.example."), RecordType::A, &z), Denial::Unproven(_)));
|
||||
let deleg = vec![nsec_record(&n("sub.example."), &n("example."), [RecordType::NS], 300)];
|
||||
assert_eq!(check_nsec(&deleg, &n("sub.example."), RecordType::DS, &z), Denial::InsecureDelegation);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nsec3_hash_vector() {
|
||||
// RFC 5155 Appendix A: H(example) = 0p9mhaveqvm6t7vbl5lop2u3t2rp3tom (salt aabbccdd, 12 iterations)
|
||||
let h = nsec3_hash(&n("example."), &[0xaa, 0xbb, 0xcc, 0xdd], 12).unwrap();
|
||||
assert_eq!(h, "0p9mhaveqvm6t7vbl5lop2u3t2rp3tom");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
//! Common error type.
|
||||
use thiserror::Error;
|
||||
|
||||
/// Errors produced by the core library.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum CoreError {
|
||||
#[error("I/O error: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
#[error("protocol error: {0}")]
|
||||
Proto(String),
|
||||
#[error("zone file error: {0}")]
|
||||
ZoneFile(String),
|
||||
#[error("timeout after {0:?}")]
|
||||
Timeout(std::time::Duration),
|
||||
#[error("TSIG error: {0}")]
|
||||
Tsig(String),
|
||||
#[error("response mismatch: {0}")]
|
||||
Mismatch(String),
|
||||
#[error("transfer error: {0}")]
|
||||
Transfer(String),
|
||||
#[error("invalid input: {0}")]
|
||||
Invalid(String),
|
||||
}
|
||||
|
||||
impl From<hickory_proto::ProtoError> for CoreError {
|
||||
fn from(e: hickory_proto::ProtoError) -> Self {
|
||||
CoreError::Proto(e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// Result alias.
|
||||
pub type CoreResult<T> = Result<T, CoreError>;
|
||||
@@ -0,0 +1,54 @@
|
||||
//! EasyDNS core library.
|
||||
//!
|
||||
//! Shared protocol primitives used by every EasyDNS crate:
|
||||
//! * re-export of [`hickory_proto`] (wire format, record types, DNSSEC primitives),
|
||||
//! * RFC 1982 serial number arithmetic ([`serial`]),
|
||||
//! * BIND-style zone file parsing and emitting ([`zonefile`]),
|
||||
//! * TSIG (RFC 8945) signing and verification helpers ([`tsig`]),
|
||||
//! * an async DNS client with UDP→TCP fallback and zone-transfer streaming ([`client`]),
|
||||
//! * name normalisation helpers ([`names`]) and wire helpers ([`wire`]).
|
||||
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
|
||||
|
||||
pub use hickory_proto as proto;
|
||||
|
||||
pub mod client;
|
||||
pub mod error;
|
||||
pub mod names;
|
||||
pub mod serial;
|
||||
pub mod tsig;
|
||||
pub mod wire;
|
||||
pub mod zonefile;
|
||||
pub mod zonefile_ext;
|
||||
|
||||
pub use error::{CoreError, CoreResult};
|
||||
|
||||
/// Commonly used re-exports.
|
||||
pub mod prelude {
|
||||
pub use hickory_proto::op::{Edns, Message, MessageType, OpCode, Query, ResponseCode};
|
||||
pub use hickory_proto::rr::{DNSClass, LowerName, Name, RData, Record, RecordType};
|
||||
}
|
||||
|
||||
pub mod answer;
|
||||
pub mod dnssec;
|
||||
pub mod tls;
|
||||
pub mod tls_pool;
|
||||
|
||||
/// Make command-line programs behave like classic Unix tools when their output pipe is
|
||||
/// closed early (`easydns … | head`): exit quietly with status 141 (128 + SIGPIPE)
|
||||
/// instead of printing a panic. Safe Rust cannot restore the default SIGPIPE action, so
|
||||
/// the panic raised by `println!` on EPIPE is recognised in a panic hook.
|
||||
pub fn quiet_broken_pipe() {
|
||||
let default = std::panic::take_hook();
|
||||
std::panic::set_hook(Box::new(move |info| {
|
||||
let msg = info
|
||||
.payload()
|
||||
.downcast_ref::<String>()
|
||||
.map(String::as_str)
|
||||
.or_else(|| info.payload().downcast_ref::<&str>().copied())
|
||||
.unwrap_or("");
|
||||
if msg.contains("Broken pipe") || msg.contains("os error 32") {
|
||||
std::process::exit(141);
|
||||
}
|
||||
default(info);
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
//! Name normalisation, validation and IDNA helpers.
|
||||
use hickory_proto::rr::{LowerName, Name};
|
||||
|
||||
use crate::{CoreError, CoreResult};
|
||||
|
||||
/// Parse a user-supplied domain name (ASCII or Unicode/IDN), returning a
|
||||
/// fully-qualified, lower-cased name.
|
||||
pub fn parse_name(input: &str) -> CoreResult<Name> {
|
||||
let s = input.trim();
|
||||
if s.is_empty() {
|
||||
return Err(CoreError::Invalid("empty domain name".into()));
|
||||
}
|
||||
let mut name = if s.is_ascii() { Name::from_ascii(s) } else { Name::from_utf8(s) }
|
||||
.map_err(|e| CoreError::Invalid(format!("invalid domain name '{s}': {e}")))?;
|
||||
name.set_fqdn(true);
|
||||
Ok(name.to_lowercase())
|
||||
}
|
||||
|
||||
/// Parse a name and return its [`LowerName`].
|
||||
pub fn parse_lower(input: &str) -> CoreResult<LowerName> {
|
||||
Ok(LowerName::new(&parse_name(input)?))
|
||||
}
|
||||
|
||||
/// Iterate over `name` and all of its ancestors, most specific first
|
||||
/// (`a.b.c.` → `a.b.c.`, `b.c.`, `c.`, `.`).
|
||||
pub fn ancestors(name: &Name) -> impl Iterator<Item = Name> + '_ {
|
||||
let n = name.num_labels() as usize;
|
||||
(0..=n).map(move |i| name.trim_to(n - i))
|
||||
}
|
||||
|
||||
/// Build the reverse-lookup name for an IP address (in-addr.arpa / ip6.arpa).
|
||||
pub fn reverse_name(ip: std::net::IpAddr) -> Name {
|
||||
Name::from(ip)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_and_idn() {
|
||||
assert_eq!(parse_name("Example.COM").unwrap().to_string(), "example.com.");
|
||||
assert_eq!(parse_name("zażółć.pl").unwrap().to_ascii(), "xn--za-6ja4f8n1l.pl.");
|
||||
assert!(parse_name("").is_err());
|
||||
assert!(parse_name("a..b").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ancestor_walk() {
|
||||
let n = parse_name("a.b.c").unwrap();
|
||||
let v: Vec<String> = ancestors(&n).map(|n| n.to_string()).collect();
|
||||
assert_eq!(v, vec!["a.b.c.", "b.c.", "c.", "."]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reverse() {
|
||||
let n = reverse_name("192.0.2.1".parse().unwrap());
|
||||
assert_eq!(n.to_string(), "1.2.0.192.in-addr.arpa.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
//! RFC 1982 serial number arithmetic (32-bit SOA serials).
|
||||
use std::cmp::Ordering;
|
||||
|
||||
/// Compare two SOA serials according to RFC 1982.
|
||||
///
|
||||
/// Returns `None` when the comparison is undefined (the values are exactly
|
||||
/// 2^31 apart), in which case callers must treat the serials as incomparable.
|
||||
pub fn compare(a: u32, b: u32) -> Option<Ordering> {
|
||||
if a == b {
|
||||
return Some(Ordering::Equal);
|
||||
}
|
||||
let diff = b.wrapping_sub(a);
|
||||
if diff == 1 << 31 {
|
||||
return None;
|
||||
}
|
||||
if diff < (1 << 31) { Some(Ordering::Less) } else { Some(Ordering::Greater) }
|
||||
}
|
||||
|
||||
/// `true` when `new` is strictly newer than `old` (RFC 1982).
|
||||
pub fn is_newer(new: u32, old: u32) -> bool {
|
||||
compare(new, old) == Some(Ordering::Greater)
|
||||
}
|
||||
|
||||
/// Serial number generation strategy used when a primary zone changes.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, Default)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum SerialStrategy {
|
||||
/// serial + 1
|
||||
#[default]
|
||||
Increment,
|
||||
/// UNIX time in seconds (never decreases below serial + 1)
|
||||
Unixtime,
|
||||
/// YYYYMMDDnn
|
||||
Date,
|
||||
}
|
||||
|
||||
/// Compute the next serial for `current` using `strategy`; `now_unix` is the
|
||||
/// current UNIX time. The result is always RFC 1982-newer than `current`.
|
||||
pub fn next_serial(current: u32, strategy: SerialStrategy, now_unix: u64) -> u32 {
|
||||
let candidate = match strategy {
|
||||
SerialStrategy::Increment => current.wrapping_add(1),
|
||||
SerialStrategy::Unixtime => now_unix as u32,
|
||||
SerialStrategy::Date => {
|
||||
let days = now_unix / 86_400;
|
||||
let (y, m, d) = civil_from_days(days as i64);
|
||||
let base = (y as u32) * 1_000_000 + m * 10_000 + d * 100;
|
||||
let cur_base = current - current % 100;
|
||||
if cur_base == base && current % 100 < 99 { current + 1 } else { base }
|
||||
}
|
||||
};
|
||||
if is_newer(candidate, current) { candidate } else { current.wrapping_add(1) }
|
||||
}
|
||||
|
||||
/// Convert days since 1970-01-01 into (year, month, day). (H. Hinnant's algorithm)
|
||||
fn civil_from_days(z: i64) -> (i64, u32, u32) {
|
||||
let z = z + 719_468;
|
||||
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
|
||||
let doe = (z - era * 146_097) as u64;
|
||||
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||||
let y = yoe as i64 + era * 400;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
|
||||
let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
|
||||
(if m <= 2 { y + 1 } else { y }, m, d)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rfc1982_basic() {
|
||||
assert_eq!(compare(1, 2), Some(Ordering::Less));
|
||||
assert_eq!(compare(2, 1), Some(Ordering::Greater));
|
||||
assert_eq!(compare(5, 5), Some(Ordering::Equal));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rfc1982_wrap() {
|
||||
assert!(is_newer(0, u32::MAX));
|
||||
assert!(is_newer(10, 4_294_967_290));
|
||||
assert!(!is_newer(4_294_967_290, 10));
|
||||
assert_eq!(compare(0, 1 << 31), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_serial_strategies() {
|
||||
assert_eq!(next_serial(41, SerialStrategy::Increment, 0), 42);
|
||||
assert_eq!(next_serial(u32::MAX, SerialStrategy::Increment, 0), 0);
|
||||
// 2026-11-21 00:00:00 UTC
|
||||
let t = 1_795_219_200;
|
||||
assert_eq!(next_serial(1, SerialStrategy::Date, t), 2026112100);
|
||||
assert_eq!(next_serial(2026112100, SerialStrategy::Date, t), 2026112101);
|
||||
assert_eq!(next_serial(5, SerialStrategy::Unixtime, t), t as u32);
|
||||
// unixtime never goes backwards
|
||||
assert_eq!(next_serial(t as u32 + 10, SerialStrategy::Unixtime, t), t as u32 + 11);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
//! DNS-over-TLS (RFC 7858) and DNS-over-HTTPS (RFC 8484) client transports on rustls.
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use data_encoding::BASE64URL_NOPAD;
|
||||
use rustls::pki_types::ServerName;
|
||||
use rustls::{ClientConfig, RootCertStore};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpStream;
|
||||
use tokio_rustls::TlsConnector;
|
||||
|
||||
use crate::client::{read_tcp_msg, write_tcp_msg};
|
||||
use crate::{CoreError, CoreResult};
|
||||
|
||||
/// Maximum DoH response body we accept.
|
||||
pub const MAX_DOH_BODY: usize = 65_535;
|
||||
|
||||
/// Details of the TLS session, for diagnostics tools.
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct TlsInfo {
|
||||
pub protocol: String,
|
||||
pub cipher_suite: String,
|
||||
pub alpn: Option<String>,
|
||||
pub connect_ms: f64,
|
||||
pub handshake_ms: f64,
|
||||
pub peer_certificates: usize,
|
||||
}
|
||||
|
||||
/// Build a rustls client config with the Mozilla root store (webpki-roots), plus optional
|
||||
/// extra PEM roots. `insecure` disables certificate verification (diagnostics only).
|
||||
pub fn client_config(extra_roots_pem: Option<&[u8]>, insecure: bool, alpn: &[&[u8]]) -> CoreResult<Arc<ClientConfig>> {
|
||||
let provider = Arc::new(rustls::crypto::ring::default_provider());
|
||||
let builder = ClientConfig::builder_with_provider(provider.clone())
|
||||
.with_safe_default_protocol_versions()
|
||||
.map_err(|e| CoreError::Invalid(e.to_string()))?;
|
||||
let mut cfg = if insecure {
|
||||
builder.dangerous().with_custom_certificate_verifier(Arc::new(NoVerify(provider))).with_no_client_auth()
|
||||
} else {
|
||||
let mut roots = RootCertStore::empty();
|
||||
roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
|
||||
if let Some(pem) = extra_roots_pem {
|
||||
use rustls::pki_types::{CertificateDer, pem::PemObject};
|
||||
for c in CertificateDer::pem_slice_iter(pem) {
|
||||
let c = c.map_err(|e| CoreError::Invalid(format!("bad CA PEM: {e}")))?;
|
||||
roots.add(c).map_err(|e| CoreError::Invalid(format!("bad CA cert: {e}")))?;
|
||||
}
|
||||
}
|
||||
builder.with_root_certificates(roots).with_no_client_auth()
|
||||
};
|
||||
cfg.alpn_protocols = alpn.iter().map(|a| a.to_vec()).collect();
|
||||
Ok(Arc::new(cfg))
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct NoVerify(Arc<rustls::crypto::CryptoProvider>);
|
||||
|
||||
impl rustls::client::danger::ServerCertVerifier for NoVerify {
|
||||
fn verify_server_cert(
|
||||
&self,
|
||||
_: &rustls::pki_types::CertificateDer<'_>,
|
||||
_: &[rustls::pki_types::CertificateDer<'_>],
|
||||
_: &ServerName<'_>,
|
||||
_: &[u8],
|
||||
_: rustls::pki_types::UnixTime,
|
||||
) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
|
||||
Ok(rustls::client::danger::ServerCertVerified::assertion())
|
||||
}
|
||||
fn verify_tls12_signature(
|
||||
&self,
|
||||
m: &[u8],
|
||||
c: &rustls::pki_types::CertificateDer<'_>,
|
||||
d: &rustls::DigitallySignedStruct,
|
||||
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
|
||||
rustls::crypto::verify_tls12_signature(m, c, d, &self.0.signature_verification_algorithms)
|
||||
}
|
||||
fn verify_tls13_signature(
|
||||
&self,
|
||||
m: &[u8],
|
||||
c: &rustls::pki_types::CertificateDer<'_>,
|
||||
d: &rustls::DigitallySignedStruct,
|
||||
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
|
||||
rustls::crypto::verify_tls13_signature(m, c, d, &self.0.signature_verification_algorithms)
|
||||
}
|
||||
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
|
||||
self.0.signature_verification_algorithms.supported_schemes()
|
||||
}
|
||||
}
|
||||
|
||||
async fn connect_tls(
|
||||
addr: SocketAddr,
|
||||
server_name: &str,
|
||||
cfg: Arc<ClientConfig>,
|
||||
) -> CoreResult<(tokio_rustls::client::TlsStream<TcpStream>, f64, f64)> {
|
||||
let t0 = Instant::now();
|
||||
let tcp = TcpStream::connect(addr).await?;
|
||||
tcp.set_nodelay(true)?;
|
||||
let connect_ms = t0.elapsed().as_secs_f64() * 1000.0;
|
||||
let name = ServerName::try_from(server_name.to_string())
|
||||
.map_err(|e| CoreError::Invalid(format!("invalid TLS server name '{server_name}': {e}")))?;
|
||||
let t1 = Instant::now();
|
||||
let tls =
|
||||
TlsConnector::from(cfg).connect(name, tcp).await.map_err(|e| CoreError::Proto(format!("TLS handshake with {addr} failed: {e}")))?;
|
||||
Ok((tls, connect_ms, t1.elapsed().as_secs_f64() * 1000.0))
|
||||
}
|
||||
|
||||
/// Open a TLS connection (TCP_NODELAY set), without timing details.
|
||||
pub async fn connect_tls_stream(
|
||||
addr: SocketAddr,
|
||||
server_name: &str,
|
||||
cfg: Arc<ClientConfig>,
|
||||
) -> CoreResult<tokio_rustls::client::TlsStream<TcpStream>> {
|
||||
connect_tls(addr, server_name, cfg).await.map(|(s, _, _)| s)
|
||||
}
|
||||
|
||||
fn info(s: &tokio_rustls::client::TlsStream<TcpStream>, connect_ms: f64, handshake_ms: f64) -> TlsInfo {
|
||||
let (_, c) = s.get_ref();
|
||||
TlsInfo {
|
||||
protocol: c.protocol_version().map(|v| format!("{v:?}")).unwrap_or_default(),
|
||||
cipher_suite: c.negotiated_cipher_suite().map(|s| format!("{:?}", s.suite())).unwrap_or_default(),
|
||||
alpn: c.alpn_protocol().map(|a| String::from_utf8_lossy(a).to_string()),
|
||||
connect_ms,
|
||||
handshake_ms,
|
||||
peer_certificates: c.peer_certificates().map(|p| p.len()).unwrap_or(0),
|
||||
}
|
||||
}
|
||||
|
||||
/// One DoT exchange. Returns the raw response and TLS details.
|
||||
pub async fn dot_exchange(
|
||||
addr: SocketAddr,
|
||||
server_name: &str,
|
||||
query: &[u8],
|
||||
timeout: Duration,
|
||||
cfg: Arc<ClientConfig>,
|
||||
) -> CoreResult<(Vec<u8>, TlsInfo)> {
|
||||
let fut = async {
|
||||
let (mut s, c, h) = connect_tls(addr, server_name, cfg).await?;
|
||||
write_tcp_msg(&mut s, query).await?;
|
||||
let raw = read_tcp_msg(&mut s).await?;
|
||||
let i = info(&s, c, h);
|
||||
let _ = s.shutdown().await;
|
||||
Ok((raw, i))
|
||||
};
|
||||
tokio::time::timeout(timeout, fut).await.map_err(|_| CoreError::Timeout(timeout))?
|
||||
}
|
||||
|
||||
/// HTTP method used for DoH.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DohMethod {
|
||||
Get,
|
||||
Post,
|
||||
}
|
||||
|
||||
/// One DoH exchange over HTTP/1.1. Returns (status, raw body, TLS info).
|
||||
pub async fn doh_exchange(
|
||||
addr: SocketAddr,
|
||||
server_name: &str,
|
||||
path: &str,
|
||||
query: &[u8],
|
||||
method: DohMethod,
|
||||
timeout: Duration,
|
||||
cfg: Arc<ClientConfig>,
|
||||
) -> CoreResult<(u16, Vec<u8>, TlsInfo)> {
|
||||
let fut = async {
|
||||
let (mut s, c, h) = connect_tls(addr, server_name, cfg).await?;
|
||||
let req = match method {
|
||||
DohMethod::Post => {
|
||||
let mut r = format!(
|
||||
"POST {path} HTTP/1.1\r\nHost: {server_name}\r\nUser-Agent: EasyDNS\r\nContent-Type: application/dns-message\r\nAccept: application/dns-message\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
|
||||
query.len()
|
||||
)
|
||||
.into_bytes();
|
||||
r.extend_from_slice(query);
|
||||
r
|
||||
}
|
||||
DohMethod::Get => {
|
||||
// RFC 8484 §4.1: use ID 0 for cache friendliness.
|
||||
let mut q = query.to_vec();
|
||||
if q.len() >= 2 {
|
||||
q[0] = 0;
|
||||
q[1] = 0;
|
||||
}
|
||||
let sep = if path.contains('?') { '&' } else { '?' };
|
||||
format!(
|
||||
"GET {path}{sep}dns={} HTTP/1.1\r\nHost: {server_name}\r\nUser-Agent: EasyDNS\r\nAccept: application/dns-message\r\nConnection: close\r\n\r\n",
|
||||
BASE64URL_NOPAD.encode(&q)
|
||||
)
|
||||
.into_bytes()
|
||||
}
|
||||
};
|
||||
s.write_all(&req).await?;
|
||||
s.flush().await?;
|
||||
let i = info(&s, c, h);
|
||||
let mut buf = Vec::new();
|
||||
let mut chunk = [0u8; 8192];
|
||||
loop {
|
||||
let n = match s.read(&mut chunk).await {
|
||||
Ok(0) => break,
|
||||
Ok(n) => n,
|
||||
// Many servers close without close_notify after `Connection: close`.
|
||||
Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => break,
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
buf.extend_from_slice(&chunk[..n]);
|
||||
if buf.len() > MAX_DOH_BODY + 16_384 {
|
||||
return Err(CoreError::Proto("DoH response too large".into()));
|
||||
}
|
||||
if let Some((status, body)) = parse_http_response(&buf)? {
|
||||
return Ok((status, body, i));
|
||||
}
|
||||
}
|
||||
match parse_http_response(&buf)? {
|
||||
Some((status, body)) => Ok((status, body, i)),
|
||||
None => Err(CoreError::Proto("incomplete HTTP response".into())),
|
||||
}
|
||||
};
|
||||
tokio::time::timeout(timeout, fut).await.map_err(|_| CoreError::Timeout(timeout))?
|
||||
}
|
||||
|
||||
/// Parse a complete HTTP/1.1 response (Content-Length or chunked). `Ok(None)` = need more data.
|
||||
pub fn parse_http_response(buf: &[u8]) -> CoreResult<Option<(u16, Vec<u8>)>> {
|
||||
parse_http_response_limited(buf, MAX_DOH_BODY)
|
||||
}
|
||||
|
||||
/// Like [`parse_http_response`] with a custom body limit.
|
||||
pub fn parse_http_response_limited(buf: &[u8], max_body: usize) -> CoreResult<Option<(u16, Vec<u8>)>> {
|
||||
let Some(hdr_end) = buf.windows(4).position(|w| w == b"\r\n\r\n") else {
|
||||
return Ok(None);
|
||||
};
|
||||
let head = std::str::from_utf8(&buf[..hdr_end]).map_err(|_| CoreError::Proto("non-UTF8 HTTP headers".into()))?;
|
||||
let mut lines = head.split("\r\n");
|
||||
let status_line = lines.next().unwrap_or("");
|
||||
let status: u16 = status_line
|
||||
.split_whitespace()
|
||||
.nth(1)
|
||||
.and_then(|s| s.parse().ok())
|
||||
.ok_or_else(|| CoreError::Proto(format!("bad HTTP status line '{status_line}'")))?;
|
||||
let mut clen: Option<usize> = None;
|
||||
let mut chunked = false;
|
||||
for l in lines {
|
||||
if let Some((k, v)) = l.split_once(':') {
|
||||
let k = k.trim().to_ascii_lowercase();
|
||||
let v = v.trim();
|
||||
if k == "content-length" {
|
||||
clen = v.parse().ok();
|
||||
} else if k == "transfer-encoding" && v.to_ascii_lowercase().contains("chunked") {
|
||||
chunked = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
let body = &buf[hdr_end + 4..];
|
||||
if chunked {
|
||||
let mut out = Vec::new();
|
||||
let mut rest = body;
|
||||
loop {
|
||||
let Some(le) = rest.windows(2).position(|w| w == b"\r\n") else { return Ok(None) };
|
||||
let size_str = std::str::from_utf8(&rest[..le]).unwrap_or("").split(';').next().unwrap_or("").trim();
|
||||
let size = usize::from_str_radix(size_str, 16).map_err(|_| CoreError::Proto("bad chunk size".into()))?;
|
||||
if size == 0 {
|
||||
return Ok(Some((status, out)));
|
||||
}
|
||||
if rest.len() < le + 2 + size + 2 {
|
||||
return Ok(None);
|
||||
}
|
||||
out.extend_from_slice(&rest[le + 2..le + 2 + size]);
|
||||
if out.len() > max_body {
|
||||
return Err(CoreError::Proto("HTTP body too large".into()));
|
||||
}
|
||||
rest = &rest[le + 2 + size + 2..];
|
||||
}
|
||||
}
|
||||
match clen {
|
||||
Some(n) if n > max_body => Err(CoreError::Proto("HTTP body too large".into())),
|
||||
Some(n) if body.len() >= n => Ok(Some((status, body[..n].to_vec()))),
|
||||
Some(_) => Ok(None),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Minimal HTTPS GET (HTTP/1.1, system resolver, webpki roots). Used for block lists,
|
||||
/// root hints updates and RDAP. Returns (status, body).
|
||||
pub async fn https_get(url: &str, timeout: Duration, max_body: usize) -> CoreResult<(u16, Vec<u8>)> {
|
||||
let rest = url.strip_prefix("https://").ok_or_else(|| CoreError::Invalid("only https:// URLs are supported".into()))?;
|
||||
let (hostport, path) = match rest.find('/') {
|
||||
Some(i) => (&rest[..i], &rest[i..]),
|
||||
None => (rest, "/"),
|
||||
};
|
||||
let (host, port) = match hostport.rsplit_once(':') {
|
||||
Some((h, p)) if !h.contains(']') || h.ends_with(']') => (h.trim_matches(['[', ']']), p.parse().unwrap_or(443)),
|
||||
_ => (hostport, 443u16),
|
||||
};
|
||||
let fut = async {
|
||||
let addr =
|
||||
tokio::net::lookup_host((host, port)).await?.next().ok_or_else(|| CoreError::Invalid(format!("cannot resolve {host}")))?;
|
||||
let cfg = client_config(None, false, &[b"http/1.1"])?;
|
||||
let (mut s, _, _) = connect_tls(addr, host, cfg).await?;
|
||||
let req = format!("GET {path} HTTP/1.1\r\nHost: {host}\r\nUser-Agent: EasyDNS\r\nAccept: */*\r\nConnection: close\r\n\r\n");
|
||||
s.write_all(req.as_bytes()).await?;
|
||||
let mut buf = Vec::new();
|
||||
let mut chunk = [0u8; 16384];
|
||||
loop {
|
||||
let n = match s.read(&mut chunk).await {
|
||||
Ok(0) => break,
|
||||
Ok(n) => n,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => break,
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
buf.extend_from_slice(&chunk[..n]);
|
||||
if buf.len() > max_body + 65_536 {
|
||||
return Err(CoreError::Proto("HTTP response too large".into()));
|
||||
}
|
||||
}
|
||||
match parse_http_response_limited(&buf, max_body)? {
|
||||
Some(r) => Ok(r),
|
||||
None => {
|
||||
// Connection: close without Content-Length: body is the rest of the stream.
|
||||
let p = buf.windows(4).position(|w| w == b"\r\n\r\n").ok_or_else(|| CoreError::Proto("incomplete HTTP response".into()))?;
|
||||
let status =
|
||||
std::str::from_utf8(&buf[..p]).ok().and_then(|h| h.split_whitespace().nth(1)).and_then(|s| s.parse().ok()).unwrap_or(0);
|
||||
Ok((status, buf[p + 4..].to_vec()))
|
||||
}
|
||||
}
|
||||
};
|
||||
tokio::time::timeout(timeout, fut).await.map_err(|_| CoreError::Timeout(timeout))?
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn http_parsing() {
|
||||
let r = b"HTTP/1.1 200 OK\r\nContent-Type: application/dns-message\r\nContent-Length: 3\r\n\r\nabc";
|
||||
assert_eq!(parse_http_response(r).unwrap(), Some((200, b"abc".to_vec())));
|
||||
assert_eq!(parse_http_response(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nab").unwrap(), None);
|
||||
let c = b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nabc\r\n2\r\nde\r\n0\r\n\r\n";
|
||||
assert_eq!(parse_http_response(c).unwrap(), Some((200, b"abcde".to_vec())));
|
||||
assert!(parse_http_response(b"garbage\r\n\r\n").is_err());
|
||||
}
|
||||
#[test]
|
||||
fn config_builds() {
|
||||
assert!(client_config(None, false, &[b"h2"]).is_ok());
|
||||
assert!(client_config(None, true, &[]).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
//! Persistent encrypted upstream connections for the forwarder.
|
||||
//!
|
||||
//! Opening a TLS connection costs one TCP and one TLS round trip plus the handshake CPU;
|
||||
//! doing it per query (as the one-shot helpers in [`crate::tls`] do) makes encrypted
|
||||
//! forwarding several times slower than plain DNS. These clients keep connections open:
|
||||
//!
|
||||
//! * [`DotPool`] – DNS-over-TLS (RFC 7858): a small pool of idle connections, each used
|
||||
//! for one query at a time (RFC 7766 framing), reused while the server keeps it open.
|
||||
//! * [`DohClient`] – DNS-over-HTTPS (RFC 8484) over **HTTP/2**: one multiplexed
|
||||
//! connection carries all concurrent queries; falls back to HTTP/1.1 when the server
|
||||
//! does not offer `h2` in ALPN.
|
||||
//!
|
||||
//! A reused connection that turns out to be closed is retried once on a fresh one.
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use bytes::Bytes;
|
||||
use http_body_util::{BodyExt, Full, Limited};
|
||||
use hyper::client::conn::http2;
|
||||
use hyper_util::rt::{TokioExecutor, TokioIo};
|
||||
use rustls::ClientConfig;
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio_rustls::client::TlsStream;
|
||||
|
||||
use crate::client::{read_tcp_msg, write_tcp_msg};
|
||||
use crate::tls::{DohMethod, connect_tls_stream, doh_exchange};
|
||||
use crate::{CoreError, CoreResult};
|
||||
|
||||
/// Idle connections older than this are not reused (servers close idle DoT after ~10–30 s).
|
||||
const MAX_IDLE: Duration = Duration::from_secs(20);
|
||||
/// Largest accepted DoH response body.
|
||||
const MAX_BODY: usize = 65_535;
|
||||
|
||||
fn with_alpn(base: &Arc<ClientConfig>, alpn: &[&[u8]]) -> Arc<ClientConfig> {
|
||||
let mut c = (**base).clone();
|
||||
c.alpn_protocols = alpn.iter().map(|a| a.to_vec()).collect();
|
||||
Arc::new(c)
|
||||
}
|
||||
|
||||
/// Pool of DNS-over-TLS connections to one upstream.
|
||||
pub struct DotPool {
|
||||
addr: SocketAddr,
|
||||
name: String,
|
||||
cfg: Arc<ClientConfig>,
|
||||
idle: Mutex<Vec<(TlsStream<TcpStream>, Instant)>>,
|
||||
max_idle: usize,
|
||||
}
|
||||
|
||||
impl DotPool {
|
||||
pub fn new(addr: SocketAddr, tls_name: &str, base: &Arc<ClientConfig>, max_idle: usize) -> Self {
|
||||
Self { addr, name: tls_name.to_string(), cfg: with_alpn(base, &[b"dot"]), idle: Mutex::new(Vec::new()), max_idle: max_idle.max(1) }
|
||||
}
|
||||
|
||||
async fn checkout(&self) -> Option<TlsStream<TcpStream>> {
|
||||
let mut idle = self.idle.lock().await;
|
||||
while let Some((s, t)) = idle.pop() {
|
||||
if t.elapsed() < MAX_IDLE {
|
||||
return Some(s);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
async fn checkin(&self, s: TlsStream<TcpStream>) {
|
||||
let mut idle = self.idle.lock().await;
|
||||
if idle.len() < self.max_idle {
|
||||
idle.push((s, Instant::now()));
|
||||
}
|
||||
}
|
||||
|
||||
/// Number of idle pooled connections (for tests and status).
|
||||
pub async fn idle_connections(&self) -> usize {
|
||||
self.idle.lock().await.len()
|
||||
}
|
||||
|
||||
/// Send one DNS message and return the raw response.
|
||||
pub async fn exchange(&self, query: &[u8], timeout: Duration) -> CoreResult<Vec<u8>> {
|
||||
let deadline = Instant::now() + timeout;
|
||||
for attempt in 0..2 {
|
||||
let (mut s, reused) = match self.checkout().await {
|
||||
Some(s) if attempt == 0 => (s, true),
|
||||
_ => (connect_tls_stream(self.addr, &self.name, Arc::clone(&self.cfg)).await?, false),
|
||||
};
|
||||
let left = deadline.saturating_duration_since(Instant::now());
|
||||
let r = tokio::time::timeout(left, async {
|
||||
write_tcp_msg(&mut s, query).await?;
|
||||
read_tcp_msg(&mut s).await
|
||||
})
|
||||
.await;
|
||||
match r {
|
||||
Ok(Ok(raw)) => {
|
||||
self.checkin(s).await;
|
||||
return Ok(raw);
|
||||
}
|
||||
// the server closed an idle connection: try once more on a new one
|
||||
Ok(Err(_)) if reused => continue,
|
||||
Ok(Err(e)) => return Err(e),
|
||||
Err(_) => return Err(CoreError::Timeout(timeout)),
|
||||
}
|
||||
}
|
||||
Err(CoreError::Proto("DoT exchange failed".into()))
|
||||
}
|
||||
}
|
||||
|
||||
enum DohConn {
|
||||
H2(http2::SendRequest<Full<Bytes>>),
|
||||
/// Server did not negotiate h2: use one HTTP/1.1 exchange per query.
|
||||
Http1,
|
||||
}
|
||||
|
||||
/// DNS-over-HTTPS client for one upstream, multiplexing queries over HTTP/2.
|
||||
pub struct DohClient {
|
||||
addr: SocketAddr,
|
||||
name: String,
|
||||
path: String,
|
||||
cfg: Arc<ClientConfig>,
|
||||
h1_cfg: Arc<ClientConfig>,
|
||||
conn: Mutex<Option<http2::SendRequest<Full<Bytes>>>>,
|
||||
http1_only: std::sync::atomic::AtomicBool,
|
||||
}
|
||||
|
||||
impl DohClient {
|
||||
pub fn new(addr: SocketAddr, tls_name: &str, path: &str, base: &Arc<ClientConfig>) -> Self {
|
||||
Self {
|
||||
addr,
|
||||
name: tls_name.to_string(),
|
||||
path: if path.is_empty() { "/dns-query".into() } else { path.to_string() },
|
||||
cfg: with_alpn(base, &[b"h2", b"http/1.1"]),
|
||||
h1_cfg: with_alpn(base, &[b"http/1.1"]),
|
||||
conn: Mutex::new(None),
|
||||
http1_only: std::sync::atomic::AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the last connection negotiated HTTP/2.
|
||||
pub fn uses_http2(&self) -> bool {
|
||||
!self.http1_only.load(std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
|
||||
async fn sender(&self, fresh: bool) -> CoreResult<DohConn> {
|
||||
if self.http1_only.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
return Ok(DohConn::Http1);
|
||||
}
|
||||
let mut slot = self.conn.lock().await;
|
||||
if !fresh {
|
||||
if let Some(s) = slot.as_ref().filter(|s| !s.is_closed()) {
|
||||
return Ok(DohConn::H2(s.clone()));
|
||||
}
|
||||
}
|
||||
let tls = connect_tls_stream(self.addr, &self.name, Arc::clone(&self.cfg)).await?;
|
||||
if tls.get_ref().1.alpn_protocol() != Some(b"h2") {
|
||||
self.http1_only.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
return Ok(DohConn::Http1);
|
||||
}
|
||||
let (send, conn) = http2::Builder::new(TokioExecutor::new())
|
||||
.handshake(TokioIo::new(tls))
|
||||
.await
|
||||
.map_err(|e| CoreError::Proto(format!("HTTP/2 handshake with {} failed: {e}", self.addr)))?;
|
||||
let addr = self.addr;
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = conn.await {
|
||||
tracing::debug!(%addr, error = %e, "DoH HTTP/2 connection closed");
|
||||
}
|
||||
});
|
||||
*slot = Some(send.clone());
|
||||
Ok(DohConn::H2(send))
|
||||
}
|
||||
|
||||
async fn h2_request(&self, mut send: http2::SendRequest<Full<Bytes>>, query: &[u8], method: DohMethod) -> CoreResult<(u16, Vec<u8>)> {
|
||||
let base = format!("https://{}{}", self.name, self.path);
|
||||
let req = match method {
|
||||
DohMethod::Post => hyper::Request::post(base)
|
||||
.header("content-type", "application/dns-message")
|
||||
.header("accept", "application/dns-message")
|
||||
.body(Full::new(Bytes::copy_from_slice(query))),
|
||||
DohMethod::Get => {
|
||||
let mut q = query.to_vec();
|
||||
if q.len() >= 2 {
|
||||
q[0] = 0;
|
||||
q[1] = 0; // RFC 8484 §4.1: ID 0 for cache friendliness
|
||||
}
|
||||
let sep = if base.contains('?') { '&' } else { '?' };
|
||||
hyper::Request::get(format!("{base}{sep}dns={}", data_encoding::BASE64URL_NOPAD.encode(&q)))
|
||||
.header("accept", "application/dns-message")
|
||||
.body(Full::new(Bytes::new()))
|
||||
}
|
||||
}
|
||||
.map_err(|e| CoreError::Invalid(e.to_string()))?;
|
||||
send.ready().await.map_err(|e| CoreError::Proto(format!("DoH connection: {e}")))?;
|
||||
let resp = send.send_request(req).await.map_err(|e| CoreError::Proto(format!("DoH request: {e}")))?;
|
||||
let status = resp.status().as_u16();
|
||||
let body = Limited::new(resp.into_body(), MAX_BODY)
|
||||
.collect()
|
||||
.await
|
||||
.map_err(|e| CoreError::Proto(format!("DoH response body: {e}")))?
|
||||
.to_bytes();
|
||||
Ok((status, body.to_vec()))
|
||||
}
|
||||
|
||||
/// One DoH exchange: (HTTP status, body).
|
||||
pub async fn exchange(&self, query: &[u8], method: DohMethod, timeout: Duration) -> CoreResult<(u16, Vec<u8>)> {
|
||||
let fut = async {
|
||||
for attempt in 0..2 {
|
||||
match self.sender(attempt > 0).await? {
|
||||
DohConn::Http1 => {
|
||||
let (st, body, _) =
|
||||
doh_exchange(self.addr, &self.name, &self.path, query, method, timeout, Arc::clone(&self.h1_cfg)).await?;
|
||||
return Ok((st, body));
|
||||
}
|
||||
DohConn::H2(send) => match self.h2_request(send, query, method).await {
|
||||
Ok(r) => return Ok(r),
|
||||
Err(e) if attempt == 0 => tracing::debug!(error = %e, "DoH: retrying on a new connection"),
|
||||
Err(e) => return Err(e),
|
||||
},
|
||||
}
|
||||
}
|
||||
Err(CoreError::Proto("DoH exchange failed".into()))
|
||||
};
|
||||
tokio::time::timeout(timeout, fut).await.map_err(|_| CoreError::Timeout(timeout))?
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for DotPool {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("DotPool").field("addr", &self.addr).field("name", &self.name).finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for DohClient {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("DohClient").field("addr", &self.addr).field("name", &self.name).field("path", &self.path).finish()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
//! TSIG (RFC 8945) helpers built on hickory-proto's HMAC primitives.
|
||||
//!
|
||||
//! * [`TsigKey::sign_request`] – client side request signing.
|
||||
//! * [`verify_request`] – server side verification of a signed request.
|
||||
//! * [`ResponseSigner`] – server side signing of (multi-message) responses.
|
||||
//! * [`ResponseVerifier`] – client side verification of (multi-message) responses,
|
||||
//! including the RFC 8945 §5.3.1 rule that intermediate messages may be unsigned.
|
||||
use std::collections::HashMap;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use data_encoding::BASE64;
|
||||
use hickory_proto::op::Message;
|
||||
use hickory_proto::rr::rdata::tsig::{TSIG, TsigAlgorithm, make_tsig_record, signed_bitmessage_to_buf};
|
||||
use hickory_proto::rr::{Name, TSigner};
|
||||
use hickory_proto::serialize::binary::BinEncoder;
|
||||
|
||||
use crate::{CoreError, CoreResult};
|
||||
|
||||
/// Default allowed clock skew in seconds.
|
||||
pub const DEFAULT_FUDGE: u16 = 300;
|
||||
/// RFC 8945 §5.3.1: at most 99 unsigned messages between signed ones.
|
||||
pub const MAX_UNSIGNED_RUN: usize = 99;
|
||||
|
||||
/// Current UNIX time in seconds.
|
||||
pub fn now() -> u64 {
|
||||
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// A named shared secret. The secret is never printed by `Debug`.
|
||||
#[derive(Clone)]
|
||||
pub struct TsigKey {
|
||||
pub name: Name,
|
||||
pub algorithm: TsigAlgorithm,
|
||||
secret: Vec<u8>,
|
||||
signer: TSigner,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for TsigKey {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("TsigKey")
|
||||
.field("name", &self.name.to_string())
|
||||
.field("algorithm", &self.algorithm.to_string())
|
||||
.field("secret", &"<redacted>")
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse an algorithm name (`hmac-sha256`, `hmac-sha512`, ...).
|
||||
pub fn parse_algorithm(s: &str) -> CoreResult<TsigAlgorithm> {
|
||||
let n = Name::from_ascii(s.trim_end_matches('.')).map_err(|e| CoreError::Tsig(format!("bad algorithm {s}: {e}")))?;
|
||||
let alg = TsigAlgorithm::from_name(n);
|
||||
if !alg.supported() || matches!(alg, TsigAlgorithm::HmacMd5) {
|
||||
return Err(CoreError::Tsig(format!("unsupported TSIG algorithm '{s}'")));
|
||||
}
|
||||
Ok(alg)
|
||||
}
|
||||
|
||||
impl TsigKey {
|
||||
/// Build a key from its name, algorithm and base64 secret.
|
||||
pub fn new(name: &str, algorithm: &str, secret_b64: &str) -> CoreResult<Self> {
|
||||
let secret = BASE64
|
||||
.decode(secret_b64.trim().as_bytes())
|
||||
.map_err(|e| CoreError::Tsig(format!("key {name}: secret is not valid base64: {e}")))?;
|
||||
if secret.len() < 16 {
|
||||
return Err(CoreError::Tsig(format!("key {name}: secret too short (<128 bits)")));
|
||||
}
|
||||
let mut kname = crate::names::parse_name(name)?;
|
||||
kname.set_fqdn(true);
|
||||
let algorithm = parse_algorithm(algorithm)?;
|
||||
let signer =
|
||||
TSigner::new(secret.clone(), algorithm.clone(), kname.clone(), DEFAULT_FUDGE).map_err(|e| CoreError::Tsig(e.to_string()))?;
|
||||
Ok(Self { name: kname, algorithm, secret, signer })
|
||||
}
|
||||
|
||||
/// Secret length (for diagnostics only).
|
||||
pub fn secret_len(&self) -> usize {
|
||||
self.secret.len()
|
||||
}
|
||||
|
||||
fn mac(&self, tbs: &[u8]) -> CoreResult<Vec<u8>> {
|
||||
self.signer.sign(tbs).map_err(|e| CoreError::Tsig(e.to_string()))
|
||||
}
|
||||
|
||||
/// Sign a request in place; returns the request MAC (needed to verify the response).
|
||||
pub fn sign_request(&self, msg: &mut Message) -> CoreResult<Vec<u8>> {
|
||||
msg.signature = None;
|
||||
let (rec, _) = self.signer.sign_message(msg, now()).map_err(|e| CoreError::Tsig(e.to_string()))?;
|
||||
let mac = rec.data.mac.clone();
|
||||
msg.signature = Some(rec);
|
||||
Ok(mac)
|
||||
}
|
||||
}
|
||||
|
||||
/// Collection of keys indexed by (lower-case) key name.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct KeyRing {
|
||||
keys: HashMap<String, TsigKey>,
|
||||
}
|
||||
|
||||
impl KeyRing {
|
||||
pub fn insert(&mut self, key: TsigKey) {
|
||||
self.keys.insert(key.name.to_lowercase().to_string(), key);
|
||||
}
|
||||
pub fn get(&self, name: &Name) -> Option<&TsigKey> {
|
||||
self.keys.get(&name.to_lowercase().to_string())
|
||||
}
|
||||
pub fn get_str(&self, name: &str) -> Option<&TsigKey> {
|
||||
let n = crate::names::parse_name(name).ok()?;
|
||||
self.get(&n)
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.keys.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Result of checking a request's TSIG.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum TsigStatus {
|
||||
/// Request carries no TSIG.
|
||||
Unsigned,
|
||||
/// Valid signature by `key`; `mac` must be used when signing the response.
|
||||
Valid { key: TsigKey, mac: Vec<u8> },
|
||||
/// Signature present but invalid (unknown key, bad MAC, bad time).
|
||||
Invalid(String),
|
||||
}
|
||||
|
||||
/// Verify the TSIG (if any) of a raw request.
|
||||
pub fn verify_request(raw: &[u8], msg: &Message, ring: &KeyRing) -> TsigStatus {
|
||||
let Some(sig) = &msg.signature else {
|
||||
return TsigStatus::Unsigned;
|
||||
};
|
||||
let Some(key) = ring.get(&sig.name) else {
|
||||
return TsigStatus::Invalid(format!("unknown key {}", sig.name));
|
||||
};
|
||||
match key.signer.verify_message_byte(raw, None, true) {
|
||||
Ok((mac, _time, range)) => {
|
||||
let n = now();
|
||||
if range.contains(&n) || range.end == n {
|
||||
TsigStatus::Valid { key: key.clone(), mac }
|
||||
} else {
|
||||
TsigStatus::Invalid("signature time outside fudge window (BADTIME)".into())
|
||||
}
|
||||
}
|
||||
Err(e) => TsigStatus::Invalid(format!("bad signature: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Signs a sequence of response messages (e.g. an AXFR stream).
|
||||
pub struct ResponseSigner {
|
||||
key: TsigKey,
|
||||
prev_mac: Vec<u8>,
|
||||
first: bool,
|
||||
pending: Vec<u8>,
|
||||
}
|
||||
|
||||
impl ResponseSigner {
|
||||
pub fn new(key: TsigKey, request_mac: Vec<u8>) -> Self {
|
||||
Self { key, prev_mac: request_mac, first: true, pending: Vec::new() }
|
||||
}
|
||||
|
||||
/// Encode an intermediate message without a signature (RFC 8945 §5.3.1).
|
||||
/// The next signed message covers it.
|
||||
pub fn emit_unsigned(&mut self, msg: &mut Message) -> CoreResult<Vec<u8>> {
|
||||
if self.first {
|
||||
return Err(CoreError::Tsig("first message must be signed".into()));
|
||||
}
|
||||
msg.signature = None;
|
||||
let raw = msg.to_vec()?;
|
||||
self.pending.extend_from_slice(&raw);
|
||||
Ok(raw)
|
||||
}
|
||||
|
||||
/// Sign `msg` (which must not already carry a signature) and return the encoded bytes.
|
||||
pub fn sign(&mut self, msg: &mut Message) -> CoreResult<Vec<u8>> {
|
||||
msg.signature = None;
|
||||
let unsigned = msg.to_vec()?;
|
||||
let time = now();
|
||||
let stub = TSIG::new(self.key.algorithm.clone(), time, DEFAULT_FUDGE, Vec::new(), msg.metadata.id, None, Vec::new());
|
||||
let mut tbs = Vec::with_capacity(unsigned.len() + 128);
|
||||
{
|
||||
let mut enc = BinEncoder::new(&mut tbs);
|
||||
enc.emit_u16(self.prev_mac.len() as u16)?;
|
||||
enc.emit_vec(&self.prev_mac)?;
|
||||
enc.emit_vec(&self.pending)?;
|
||||
enc.emit_vec(&unsigned)?;
|
||||
if self.first {
|
||||
stub.emit_tsig_for_mac(&mut enc, &self.key.name)?;
|
||||
} else {
|
||||
enc.emit_u16((time >> 32) as u16)?;
|
||||
enc.emit_u32(time as u32)?;
|
||||
enc.emit_u16(DEFAULT_FUDGE)?;
|
||||
}
|
||||
}
|
||||
let mac = self.key.mac(&tbs)?;
|
||||
let rec = make_tsig_record(self.key.name.clone(), stub.set_mac(mac.clone()));
|
||||
msg.signature = Some(Box::new(rec));
|
||||
self.prev_mac = mac;
|
||||
self.first = false;
|
||||
self.pending.clear();
|
||||
Ok(msg.to_vec()?)
|
||||
}
|
||||
}
|
||||
|
||||
/// Verifies a sequence of TSIG-signed response messages.
|
||||
pub struct ResponseVerifier {
|
||||
key: TsigKey,
|
||||
prev_mac: Vec<u8>,
|
||||
first: bool,
|
||||
unsigned: Vec<u8>,
|
||||
unsigned_run: usize,
|
||||
}
|
||||
|
||||
impl ResponseVerifier {
|
||||
pub fn new(key: TsigKey, request_mac: Vec<u8>) -> Self {
|
||||
Self { key, prev_mac: request_mac, first: true, unsigned: Vec::new(), unsigned_run: 0 }
|
||||
}
|
||||
|
||||
/// Feed the next raw message. Returns `Ok(true)` if it was signed and verified,
|
||||
/// `Ok(false)` if it was an allowed unsigned intermediate message.
|
||||
pub fn verify(&mut self, raw: &[u8], parsed: &Message) -> CoreResult<bool> {
|
||||
if parsed.signature.is_none() {
|
||||
if self.first {
|
||||
return Err(CoreError::Tsig("first response message is not signed".into()));
|
||||
}
|
||||
self.unsigned_run += 1;
|
||||
if self.unsigned_run > MAX_UNSIGNED_RUN {
|
||||
return Err(CoreError::Tsig("too many unsigned messages in a row".into()));
|
||||
}
|
||||
self.unsigned.extend_from_slice(raw);
|
||||
return Ok(false);
|
||||
}
|
||||
let (body, rec) = signed_bitmessage_to_buf(raw, None, self.first)?;
|
||||
if rec.name != self.key.name || rec.data.algorithm != self.key.algorithm {
|
||||
return Err(CoreError::Tsig("response signed with unexpected key".into()));
|
||||
}
|
||||
let mut tbs = Vec::with_capacity(body.len() + self.unsigned.len() + 64);
|
||||
tbs.extend_from_slice(&(self.prev_mac.len() as u16).to_be_bytes());
|
||||
tbs.extend_from_slice(&self.prev_mac);
|
||||
tbs.extend_from_slice(&self.unsigned);
|
||||
tbs.extend_from_slice(&body);
|
||||
self.key.signer.verify(&tbs, &rec.data.mac).map_err(|_| CoreError::Tsig("response MAC verification failed (BADSIG)".into()))?;
|
||||
let t = rec.data.time;
|
||||
let n = now();
|
||||
let fudge = u64::from(rec.data.fudge);
|
||||
if n + fudge < t || t + fudge < n {
|
||||
return Err(CoreError::Tsig("response time outside fudge window (BADTIME)".into()));
|
||||
}
|
||||
self.prev_mac = rec.data.mac.clone();
|
||||
self.first = false;
|
||||
self.unsigned.clear();
|
||||
self.unsigned_run = 0;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// The last message of a stream must be signed.
|
||||
pub fn finish(&self) -> CoreResult<()> {
|
||||
if self.unsigned_run > 0 || self.first {
|
||||
return Err(CoreError::Tsig("last response message is not signed".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use hickory_proto::op::{Message, MessageType, OpCode, Query};
|
||||
use hickory_proto::rr::{RData, Record, RecordType, rdata::A};
|
||||
|
||||
fn key() -> TsigKey {
|
||||
TsigKey::new("xfr-key", "hmac-sha256", "c2VjcmV0c2VjcmV0c2VjcmV0c2VjcmV0").unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_roundtrip_and_tamper() {
|
||||
let k = key();
|
||||
let mut ring = KeyRing::default();
|
||||
ring.insert(k.clone());
|
||||
let mut q = Message::query();
|
||||
q.add_query(Query::query(Name::from_ascii("example.com.").unwrap(), RecordType::AXFR));
|
||||
let mac = k.sign_request(&mut q).unwrap();
|
||||
let raw = q.to_vec().unwrap();
|
||||
let parsed = Message::from_vec(&raw).unwrap();
|
||||
match verify_request(&raw, &parsed, &ring) {
|
||||
TsigStatus::Valid { mac: m, .. } => assert_eq!(m, mac),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
let mut bad = raw.clone();
|
||||
bad[13] ^= 0x20; // flip case of a question byte -> MAC invalid
|
||||
let parsed = Message::from_vec(&bad).unwrap();
|
||||
assert!(matches!(verify_request(&bad, &parsed, &ring), TsigStatus::Invalid(_)));
|
||||
let other = KeyRing::default();
|
||||
let parsed = Message::from_vec(&raw).unwrap();
|
||||
assert!(matches!(verify_request(&raw, &parsed, &other), TsigStatus::Invalid(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_message_chain() {
|
||||
let k = key();
|
||||
let mut q = Message::query();
|
||||
q.add_query(Query::query(Name::from_ascii("example.com.").unwrap(), RecordType::AXFR));
|
||||
let mac = k.sign_request(&mut q).unwrap();
|
||||
let mut signer = ResponseSigner::new(k.clone(), mac.clone());
|
||||
let mut verifier = ResponseVerifier::new(k.clone(), mac);
|
||||
for i in 0..3u8 {
|
||||
let mut m = Message::new(q.metadata.id, MessageType::Response, OpCode::Query);
|
||||
m.add_answer(Record::from_rdata(Name::from_ascii("a.example.com.").unwrap(), 60, RData::A(A::new(192, 0, 2, i))));
|
||||
let raw = if i == 1 { signer.emit_unsigned(&mut m).unwrap() } else { signer.sign(&mut m).unwrap() };
|
||||
let parsed = Message::from_vec(&raw).unwrap();
|
||||
assert_eq!(verifier.verify(&raw, &parsed).unwrap(), i != 1);
|
||||
}
|
||||
verifier.finish().unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
//! Wire-format helpers: safe decoding, response construction and UDP truncation.
|
||||
use hickory_proto::op::{Edns, Message, MessageType, OpCode, ResponseCode};
|
||||
|
||||
/// Default EDNS UDP payload we advertise and accept (DNS Flag Day 2020).
|
||||
pub const DEFAULT_EDNS_PAYLOAD: u16 = 1232;
|
||||
/// Absolute maximum size of a DNS message.
|
||||
pub const MAX_MESSAGE: usize = 65_535;
|
||||
|
||||
/// Build an empty response for `req` (copies id, opcode, question, RD, CD).
|
||||
pub fn response_for(req: &Message) -> Message {
|
||||
let mut resp = Message::new(req.metadata.id, MessageType::Response, req.metadata.op_code);
|
||||
resp.metadata.recursion_desired = req.metadata.recursion_desired;
|
||||
resp.metadata.checking_disabled = req.metadata.checking_disabled;
|
||||
resp.queries = req.queries.clone();
|
||||
if let Some(edns) = &req.edns {
|
||||
let mut e = Edns::new();
|
||||
e.set_max_payload(DEFAULT_EDNS_PAYLOAD);
|
||||
e.set_dnssec_ok(edns.flags().dnssec_ok);
|
||||
resp.edns = Some(e);
|
||||
}
|
||||
resp
|
||||
}
|
||||
|
||||
/// Build an error response to a raw packet whose header could be read but
|
||||
/// whose body failed to parse (FORMERR). Returns `None` if even the ID is unreadable.
|
||||
pub fn formerr_from_raw(raw: &[u8]) -> Option<Vec<u8>> {
|
||||
if raw.len() < 12 {
|
||||
return None;
|
||||
}
|
||||
// Never answer a packet that claims to be a response (reflection loop protection).
|
||||
if raw[2] & 0x80 != 0 {
|
||||
return None;
|
||||
}
|
||||
let id = u16::from_be_bytes([raw[0], raw[1]]);
|
||||
let opcode = OpCode::from_u8((raw[2] >> 3) & 0x0f);
|
||||
let msg = Message::error_msg(id, opcode, ResponseCode::FormErr);
|
||||
msg.to_vec().ok()
|
||||
}
|
||||
|
||||
/// Maximum UDP response size a client accepts.
|
||||
pub fn client_udp_limit(req: &Message, server_max: u16) -> usize {
|
||||
let client = req.edns.as_ref().map(|e| e.max_payload().max(512)).unwrap_or(512);
|
||||
client.min(server_max.max(512)) as usize
|
||||
}
|
||||
|
||||
/// Encode `resp` for UDP, setting TC and stripping records when it does not fit.
|
||||
pub fn encode_udp(resp: &Message, limit: usize) -> Option<Vec<u8>> {
|
||||
let bytes = resp.to_vec().ok()?;
|
||||
if bytes.len() <= limit {
|
||||
return Some(bytes);
|
||||
}
|
||||
let mut t = resp.clone();
|
||||
t.answers.clear();
|
||||
t.authorities.clear();
|
||||
t.additionals.clear();
|
||||
t.metadata.truncation = true;
|
||||
t.to_vec().ok()
|
||||
}
|
||||
|
||||
/// Encode for TCP (64 KiB limit, otherwise SERVFAIL).
|
||||
pub fn encode_tcp(resp: &Message) -> Option<Vec<u8>> {
|
||||
match resp.to_vec() {
|
||||
Ok(b) if b.len() <= MAX_MESSAGE => Some(b),
|
||||
_ => {
|
||||
let mut e = response_shell(resp);
|
||||
e.metadata.response_code = ResponseCode::ServFail;
|
||||
e.to_vec().ok()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn response_shell(resp: &Message) -> Message {
|
||||
let mut m = Message::new(resp.metadata.id, MessageType::Response, resp.metadata.op_code);
|
||||
m.queries = resp.queries.clone();
|
||||
m.metadata.recursion_desired = resp.metadata.recursion_desired;
|
||||
m.metadata.recursion_available = resp.metadata.recursion_available;
|
||||
m
|
||||
}
|
||||
|
||||
/// Lightweight check that a response matches the query we sent (anti-spoofing).
|
||||
pub fn response_matches(query: &Message, resp: &Message) -> bool {
|
||||
if resp.metadata.id != query.metadata.id || resp.metadata.message_type != MessageType::Response {
|
||||
return false;
|
||||
}
|
||||
// Some error responses (FORMERR/NOTIMP) legitimately omit the question.
|
||||
if resp.queries.is_empty() {
|
||||
return resp.metadata.response_code != ResponseCode::NoError;
|
||||
}
|
||||
match (query.queries.first(), resp.queries.first()) {
|
||||
(Some(q), Some(r)) => q.query_type == r.query_type && q.query_class == r.query_class && q.name.eq_ignore_root_case(&r.name),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use hickory_proto::op::Query;
|
||||
use hickory_proto::rr::{Name, RData, Record, RecordType, rdata::TXT};
|
||||
|
||||
#[test]
|
||||
fn truncation() {
|
||||
let mut q = Message::query();
|
||||
q.add_query(Query::query(Name::from_ascii("a.example.").unwrap(), RecordType::TXT));
|
||||
let mut r = response_for(&q);
|
||||
for i in 0..40 {
|
||||
r.add_answer(Record::from_rdata(Name::from_ascii("a.example.").unwrap(), 60, RData::TXT(TXT::new(vec![format!("{i:0>30}")]))));
|
||||
}
|
||||
let b = encode_udp(&r, 512).unwrap();
|
||||
let m = Message::from_vec(&b).unwrap();
|
||||
assert!(m.metadata.truncation);
|
||||
assert!(m.answers.is_empty());
|
||||
let b = encode_udp(&r, 4096).unwrap();
|
||||
assert!(!Message::from_vec(&b).unwrap().metadata.truncation);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formerr_raw() {
|
||||
assert!(formerr_from_raw(&[1, 2]).is_none());
|
||||
let raw = [0xab, 0xcd, 0x01, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0xff];
|
||||
let b = formerr_from_raw(&raw).unwrap();
|
||||
let m = Message::from_vec(&b).unwrap();
|
||||
assert_eq!(m.metadata.id, 0xabcd);
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::FormErr);
|
||||
// responses are never answered
|
||||
let raw = [0xab, 0xcd, 0x81, 0, 0, 0, 0, 0, 0, 0, 0, 0];
|
||||
assert!(formerr_from_raw(&raw).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
//! BIND-compatible zone file parsing and emitting.
|
||||
//!
|
||||
//! Parsing is delegated to the (RFC 1035 master-file) parser in hickory-proto,
|
||||
//! including `$ORIGIN`, `$TTL` and `$INCLUDE`. This module flattens the result
|
||||
//! into a list of records and offers a stable, sorted text serialisation.
|
||||
use std::path::Path;
|
||||
|
||||
use hickory_proto::rr::{Name, RData, Record, RecordType};
|
||||
use hickory_proto::serialize::txt::Parser;
|
||||
|
||||
use crate::{CoreError, CoreResult};
|
||||
|
||||
/// Default TTL used when a zone file lacks `$TTL`.
|
||||
pub const DEFAULT_TTL: u32 = 3600;
|
||||
|
||||
/// Maximum accepted zone file size (bytes) to protect against resource exhaustion.
|
||||
pub const MAX_ZONE_FILE_BYTES: u64 = 256 * 1024 * 1024;
|
||||
|
||||
/// Parse zone file text. `path` is used to resolve relative `$INCLUDE`s.
|
||||
///
|
||||
/// When the file has no `$TTL` directive, records without an explicit TTL get
|
||||
/// [`DEFAULT_TTL`] (BIND would use the SOA MINIMUM field and warn).
|
||||
pub fn parse_str(text: &str, origin: &Name, path: Option<&Path>) -> CoreResult<Vec<Record>> {
|
||||
let (pass, extra) = crate::zonefile_ext::extract(text, origin, DEFAULT_TTL)
|
||||
.map_err(|e| CoreError::ZoneFile(format!("{}: {e}", path.map(|p| p.display().to_string()).unwrap_or_else(|| "<text>".into()))))?;
|
||||
let text = format!("$TTL {DEFAULT_TTL}\n$ORIGIN {origin}\n{pass}");
|
||||
let parser = Parser::new(text.as_str(), path.map(Path::to_path_buf), Some(origin.clone()));
|
||||
let (_origin, sets) = parser
|
||||
.parse()
|
||||
.map_err(|e| CoreError::ZoneFile(format!("{}: {e}", path.map(|p| p.display().to_string()).unwrap_or_else(|| "<text>".into()))))?;
|
||||
let mut out = extra;
|
||||
for (_k, set) in sets {
|
||||
for r in set.records_without_rrsigs() {
|
||||
out.push(r.clone());
|
||||
}
|
||||
for r in set.rrsigs() {
|
||||
out.push(r.clone());
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Read and parse a zone file from disk.
|
||||
pub fn parse_file(path: &Path, origin: &Name) -> CoreResult<Vec<Record>> {
|
||||
let meta = std::fs::metadata(path)?;
|
||||
if meta.len() > MAX_ZONE_FILE_BYTES {
|
||||
return Err(CoreError::ZoneFile(format!("{}: file too large ({} bytes)", path.display(), meta.len())));
|
||||
}
|
||||
let text = std::fs::read_to_string(path)?;
|
||||
parse_str(&text, origin, Some(path))
|
||||
}
|
||||
|
||||
/// Serialise records as zone file text: SOA first, then sorted by owner/type.
|
||||
pub fn emit(origin: &Name, records: &[Record]) -> String {
|
||||
let mut recs: Vec<&Record> = records.iter().collect();
|
||||
recs.sort_by(|a, b| {
|
||||
let a_soa = a.record_type() == RecordType::SOA;
|
||||
let b_soa = b.record_type() == RecordType::SOA;
|
||||
b_soa
|
||||
.cmp(&a_soa)
|
||||
.then_with(|| a.name.cmp(&b.name))
|
||||
.then_with(|| u16::from(a.record_type()).cmp(&u16::from(b.record_type())))
|
||||
.then_with(|| a.data.to_string().cmp(&b.data.to_string()))
|
||||
});
|
||||
let mut s = format!("; zone {origin} written by EasyDNS\n$ORIGIN {origin}\n");
|
||||
for r in recs {
|
||||
let data = match &r.data {
|
||||
RData::Unknown { .. } => crate::zonefile_ext::generic_rdata(&r.data).unwrap_or_default(),
|
||||
d => d.to_string(),
|
||||
};
|
||||
let t = match r.record_type() {
|
||||
RecordType::Unknown(c) => format!("TYPE{c}"),
|
||||
t => t.to_string(),
|
||||
};
|
||||
s.push_str(&format!("{} {} {} {} {}\n", r.name, r.ttl, r.dns_class, t, data));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// Atomically write `contents` to `path` (temp file + fsync + rename + dir fsync).
|
||||
pub fn atomic_write(path: &Path, contents: &[u8]) -> CoreResult<()> {
|
||||
use std::io::Write;
|
||||
let dir = path.parent().unwrap_or_else(|| Path::new("."));
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let file_name = path.file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or_else(|| "zone".into());
|
||||
let tmp = dir.join(format!(".{file_name}.tmp.{}", std::process::id()));
|
||||
{
|
||||
let mut f = std::fs::File::create(&tmp)?;
|
||||
f.write_all(contents)?;
|
||||
f.sync_all()?;
|
||||
}
|
||||
std::fs::rename(&tmp, path)?;
|
||||
if let Ok(d) = std::fs::File::open(dir) {
|
||||
let _ = d.sync_all();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const ZONE: &str = r#"
|
||||
$TTL 3600
|
||||
@ IN SOA ns1 hostmaster 2024010101 7200 3600 1209600 300
|
||||
IN NS ns1
|
||||
IN NS ns2.example.net.
|
||||
ns1 IN A 192.0.2.1
|
||||
www 300 IN A 192.0.2.10
|
||||
www IN AAAA 2001:db8::10
|
||||
*.wild IN TXT "wildcard"
|
||||
mail IN MX 10 mx.example.com.
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn parse_and_roundtrip() {
|
||||
let origin = Name::from_ascii("example.com.").unwrap();
|
||||
let recs = parse_str(ZONE, &origin, None).unwrap();
|
||||
assert_eq!(recs.len(), 8);
|
||||
let text = emit(&origin, &recs);
|
||||
assert!(text.lines().nth(2).unwrap().contains("SOA"));
|
||||
let again = parse_str(&text, &origin, None).unwrap();
|
||||
assert_eq!(again.len(), recs.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dnssec_and_generic_types_roundtrip() {
|
||||
let origin = Name::from_ascii("example.").unwrap();
|
||||
let text = r#"$TTL 300
|
||||
@ IN SOA ns hm 1 2 3 4 5
|
||||
IN NS ns
|
||||
@ 3600 IN DNSKEY 257 3 15 ( l02Woi0iS8Aa25FQkUd9RMzZHJpBoRQwAQEX1SxZJA4= )
|
||||
@ IN RRSIG DNSKEY 15 1 3600 20261231000000 20261101000000 12345 example. ( dGVzdHNpZ25hdHVyZQ== )
|
||||
www IN NSEC example. A RRSIG NSEC
|
||||
x IN TYPE65280 \# 3 abcdef
|
||||
y IN A \# 4 c0000201
|
||||
1 IN NSEC3 1 1 12 aabbccdd 2t7b4g4vsa5smi47k61mv5bv1a22bojr A RRSIG
|
||||
@ IN NSEC3PARAM 1 0 12 aabbccdd
|
||||
"#;
|
||||
let recs = parse_str(text, &origin, None).unwrap();
|
||||
assert_eq!(recs.len(), 9);
|
||||
let out = emit(&origin, &recs);
|
||||
let again = parse_str(&out, &origin, None).unwrap();
|
||||
let mut a: Vec<String> = recs.iter().map(|r| format!("{} {} {}", r.name, r.record_type(), r.data)).collect();
|
||||
let mut b: Vec<String> = again.iter().map(|r| format!("{} {} {}", r.name, r.record_type(), r.data)).collect();
|
||||
a.sort();
|
||||
b.sort();
|
||||
assert_eq!(a, b);
|
||||
assert!(out.contains("TYPE65280 \\# 3 abcdef"));
|
||||
assert!(recs.iter().any(|r| r.name.to_string() == "y.example." && r.data.to_string() == "192.0.2.1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_error_is_reported() {
|
||||
let origin = Name::from_ascii("example.com.").unwrap();
|
||||
assert!(parse_str("@ IN A not-an-ip\n", &origin, None).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
//! Zone-file pre-processor for record types the hickory text parser does not accept:
|
||||
//! DNSKEY, CDNSKEY, RRSIG, NSEC, NSEC3, NSEC3PARAM and RFC 3597 generic syntax
|
||||
//! (`TYPE65534 \# 3 abcdef`, or `\#` RDATA for any type).
|
||||
//!
|
||||
//! Every record line is re-emitted with an explicit owner so that removing a special
|
||||
//! line never changes which owner a following continuation line inherits.
|
||||
use data_encoding::{BASE32_DNSSEC, BASE64, HEXUPPER_PERMISSIVE};
|
||||
use hickory_proto::dnssec::rdata::{DNSKEY, DNSSECRData, NSEC, NSEC3, NSEC3PARAM, RRSIG, SigInput};
|
||||
use hickory_proto::dnssec::{Algorithm, Nsec3HashAlgorithm, PublicKeyBuf};
|
||||
use hickory_proto::rr::rdata::NULL;
|
||||
use hickory_proto::rr::{DNSClass, Name, RData, Record, RecordType, SerialNumber};
|
||||
use hickory_proto::serialize::binary::{BinDecoder, Restrict};
|
||||
|
||||
use crate::{CoreError, CoreResult};
|
||||
|
||||
const SPECIAL: &[&str] = &["DNSKEY", "CDNSKEY", "RRSIG", "NSEC", "NSEC3", "NSEC3PARAM"];
|
||||
|
||||
/// Split text into logical lines: comments removed, parenthesised continuations joined.
|
||||
/// Returns (starts_with_whitespace, tokens) per line, keeping quoted strings intact.
|
||||
fn logical_lines(text: &str) -> Vec<(bool, Vec<String>)> {
|
||||
let mut out = Vec::new();
|
||||
let mut tokens: Vec<String> = Vec::new();
|
||||
let mut cur = String::new();
|
||||
let mut depth = 0i32;
|
||||
let mut in_quote = false;
|
||||
let mut escaped = false;
|
||||
let mut line_start_ws: Option<bool> = None;
|
||||
let mut chars = text.chars().peekable();
|
||||
let flush_tok = |cur: &mut String, tokens: &mut Vec<String>| {
|
||||
if !cur.is_empty() {
|
||||
tokens.push(std::mem::take(cur));
|
||||
}
|
||||
};
|
||||
while let Some(c) = chars.next() {
|
||||
if line_start_ws.is_none() && c != '\n' {
|
||||
line_start_ws = Some(c == ' ' || c == '\t');
|
||||
}
|
||||
if in_quote {
|
||||
cur.push(c);
|
||||
if escaped {
|
||||
escaped = false;
|
||||
} else if c == '\\' {
|
||||
escaped = true;
|
||||
} else if c == '"' {
|
||||
in_quote = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
'"' => {
|
||||
in_quote = true;
|
||||
cur.push(c);
|
||||
}
|
||||
'\\' => {
|
||||
cur.push(c);
|
||||
if let Some(n) = chars.next() {
|
||||
cur.push(n);
|
||||
}
|
||||
}
|
||||
';' => {
|
||||
while let Some(&n) = chars.peek() {
|
||||
if n == '\n' {
|
||||
break;
|
||||
}
|
||||
chars.next();
|
||||
}
|
||||
}
|
||||
'(' => {
|
||||
flush_tok(&mut cur, &mut tokens);
|
||||
depth += 1;
|
||||
}
|
||||
')' => {
|
||||
flush_tok(&mut cur, &mut tokens);
|
||||
depth -= 1;
|
||||
}
|
||||
'\n' => {
|
||||
flush_tok(&mut cur, &mut tokens);
|
||||
if depth <= 0 {
|
||||
depth = 0;
|
||||
if !tokens.is_empty() {
|
||||
out.push((line_start_ws.unwrap_or(false), std::mem::take(&mut tokens)));
|
||||
}
|
||||
line_start_ws = None;
|
||||
}
|
||||
}
|
||||
' ' | '\t' | '\r' => flush_tok(&mut cur, &mut tokens),
|
||||
_ => cur.push(c),
|
||||
}
|
||||
}
|
||||
flush_tok(&mut cur, &mut tokens);
|
||||
if !tokens.is_empty() {
|
||||
out.push((line_start_ws.unwrap_or(false), tokens));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn absolute(s: &str, origin: &Name) -> CoreResult<Name> {
|
||||
if s == "@" {
|
||||
return Ok(origin.clone());
|
||||
}
|
||||
let n = Name::from_ascii(s).map_err(|e| CoreError::ZoneFile(format!("bad name '{s}': {e}")))?;
|
||||
if s.ends_with('.') { Ok(n) } else { n.append_domain(origin).map_err(|e| CoreError::ZoneFile(e.to_string())) }
|
||||
}
|
||||
|
||||
fn is_ttl(s: &str) -> bool {
|
||||
s.chars().next().is_some_and(|c| c.is_ascii_digit()) && crate::proto::serialize::txt::parse_ttl(s).is_ok()
|
||||
}
|
||||
|
||||
fn is_class(s: &str) -> bool {
|
||||
matches!(s.to_ascii_uppercase().as_str(), "IN" | "CH" | "HS" | "NONE" | "ANY")
|
||||
}
|
||||
|
||||
fn parse_alg(s: &str) -> CoreResult<Algorithm> {
|
||||
if let Ok(n) = s.parse::<u8>() {
|
||||
return Ok(Algorithm::from_u8(n));
|
||||
}
|
||||
let n = match s.to_ascii_uppercase().as_str() {
|
||||
"RSASHA1" => 5,
|
||||
"RSASHA1-NSEC3-SHA1" | "NSEC3RSASHA1" => 7,
|
||||
"RSASHA256" => 8,
|
||||
"RSASHA512" => 10,
|
||||
"ECDSAP256SHA256" => 13,
|
||||
"ECDSAP384SHA384" => 14,
|
||||
"ED25519" => 15,
|
||||
"ED448" => 16,
|
||||
other => return Err(CoreError::ZoneFile(format!("unknown DNSSEC algorithm {other}"))),
|
||||
};
|
||||
Ok(Algorithm::from_u8(n))
|
||||
}
|
||||
|
||||
/// RRSIG times: YYYYMMDDHHmmSS or a plain integer.
|
||||
fn parse_time(s: &str) -> CoreResult<u32> {
|
||||
if s.len() == 14 && s.chars().all(|c| c.is_ascii_digit()) {
|
||||
let p = |a: usize, b: usize| s[a..b].parse::<i64>().unwrap_or(0);
|
||||
let (y, mo, d, h, mi, se) = (p(0, 4), p(4, 6), p(6, 8), p(8, 10), p(10, 12), p(12, 14));
|
||||
// days from civil (H. Hinnant)
|
||||
let y2 = if mo <= 2 { y - 1 } else { y };
|
||||
let era = y2.div_euclid(400);
|
||||
let yoe = y2 - era * 400;
|
||||
let mp = (mo + 9) % 12;
|
||||
let doy = (153 * mp + 2) / 5 + d - 1;
|
||||
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
|
||||
let days = era * 146_097 + doe - 719_468;
|
||||
return Ok((days * 86_400 + h * 3600 + mi * 60 + se) as u32);
|
||||
}
|
||||
s.parse::<u32>().map_err(|_| CoreError::ZoneFile(format!("bad RRSIG time '{s}'")))
|
||||
}
|
||||
|
||||
fn parse_types(toks: &[String]) -> CoreResult<Vec<RecordType>> {
|
||||
toks.iter()
|
||||
.map(|t| {
|
||||
let u = t.to_ascii_uppercase();
|
||||
if let Some(n) = u.strip_prefix("TYPE") {
|
||||
return n.parse::<u16>().map(RecordType::from).map_err(|_| CoreError::ZoneFile(format!("bad type {t}")));
|
||||
}
|
||||
u.parse::<RecordType>().map_err(|_| CoreError::ZoneFile(format!("bad type {t}")))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn generic(rtype: RecordType, rd: &[String]) -> CoreResult<RData> {
|
||||
// \# <len> <hex...>
|
||||
let len: usize = rd.get(1).and_then(|l| l.parse().ok()).ok_or_else(|| CoreError::ZoneFile("bad \\# length".into()))?;
|
||||
let hex: String = rd[2..].concat();
|
||||
let bytes = HEXUPPER_PERMISSIVE.decode(hex.as_bytes()).map_err(|_| CoreError::ZoneFile("bad \\# hex data".into()))?;
|
||||
if bytes.len() != len {
|
||||
return Err(CoreError::ZoneFile(format!("\\# length {len} does not match data ({} bytes)", bytes.len())));
|
||||
}
|
||||
if matches!(rtype, RecordType::Unknown(_)) {
|
||||
return Ok(RData::Unknown { code: rtype, rdata: NULL::with(bytes) });
|
||||
}
|
||||
let mut d = BinDecoder::new(&bytes);
|
||||
RData::read(&mut d, rtype, Restrict::new(len as u16)).map_err(|e| CoreError::ZoneFile(format!("invalid {rtype} RDATA: {e}")))
|
||||
}
|
||||
|
||||
fn special(rtype: &str, rd: &[String], origin: &Name) -> CoreResult<RData> {
|
||||
let need = |n: usize| -> CoreResult<()> {
|
||||
if rd.len() < n { Err(CoreError::ZoneFile(format!("{rtype}: expected at least {n} fields"))) } else { Ok(()) }
|
||||
};
|
||||
let num = |s: &String| -> CoreResult<u32> { s.parse::<u32>().map_err(|_| CoreError::ZoneFile(format!("{rtype}: bad number '{s}'"))) };
|
||||
Ok(match rtype {
|
||||
"DNSKEY" | "CDNSKEY" => {
|
||||
need(4)?;
|
||||
let flags = num(&rd[0])? as u16;
|
||||
let alg = parse_alg(&rd[2])?;
|
||||
let key = BASE64.decode(rd[3..].concat().as_bytes()).map_err(|_| CoreError::ZoneFile("DNSKEY: bad base64".into()))?;
|
||||
let k = DNSKEY::with_flags(flags, PublicKeyBuf::new(key, alg));
|
||||
if rtype == "DNSKEY" {
|
||||
RData::DNSSEC(DNSSECRData::DNSKEY(k))
|
||||
} else {
|
||||
return Err(CoreError::ZoneFile("CDNSKEY records are not supported in zone files".into()));
|
||||
}
|
||||
}
|
||||
"RRSIG" => {
|
||||
need(9)?;
|
||||
let covered = parse_types(&rd[0..1])?[0];
|
||||
let input = SigInput {
|
||||
type_covered: covered,
|
||||
algorithm: parse_alg(&rd[1])?,
|
||||
num_labels: num(&rd[2])? as u8,
|
||||
original_ttl: num(&rd[3])?,
|
||||
sig_expiration: SerialNumber::new(parse_time(&rd[4])?),
|
||||
sig_inception: SerialNumber::new(parse_time(&rd[5])?),
|
||||
key_tag: num(&rd[6])? as u16,
|
||||
signer_name: absolute(&rd[7], origin)?,
|
||||
};
|
||||
let sig = BASE64.decode(rd[8..].concat().as_bytes()).map_err(|_| CoreError::ZoneFile("RRSIG: bad base64".into()))?;
|
||||
RData::DNSSEC(DNSSECRData::RRSIG(RRSIG::from_sig(input, sig)))
|
||||
}
|
||||
"NSEC" => {
|
||||
need(1)?;
|
||||
RData::DNSSEC(DNSSECRData::NSEC(NSEC::new(absolute(&rd[0], origin)?, parse_types(&rd[1..])?)))
|
||||
}
|
||||
"NSEC3" => {
|
||||
need(5)?;
|
||||
let alg = Nsec3HashAlgorithm::try_from(num(&rd[0])? as u8).map_err(|e| CoreError::ZoneFile(e.to_string()))?;
|
||||
let flags = num(&rd[1])?;
|
||||
let salt = if rd[3] == "-" {
|
||||
Vec::new()
|
||||
} else {
|
||||
HEXUPPER_PERMISSIVE.decode(rd[3].as_bytes()).map_err(|_| CoreError::ZoneFile("NSEC3: bad salt".into()))?
|
||||
};
|
||||
let next = BASE32_DNSSEC
|
||||
.decode(rd[4].to_ascii_lowercase().as_bytes())
|
||||
.map_err(|_| CoreError::ZoneFile("NSEC3: bad next hash".into()))?;
|
||||
RData::DNSSEC(DNSSECRData::NSEC3(NSEC3::new(alg, flags & 1 == 1, num(&rd[2])? as u16, salt, next, parse_types(&rd[5..])?)))
|
||||
}
|
||||
"NSEC3PARAM" => {
|
||||
need(4)?;
|
||||
let alg = Nsec3HashAlgorithm::try_from(num(&rd[0])? as u8).map_err(|e| CoreError::ZoneFile(e.to_string()))?;
|
||||
let salt = if rd[3] == "-" {
|
||||
Vec::new()
|
||||
} else {
|
||||
HEXUPPER_PERMISSIVE.decode(rd[3].as_bytes()).map_err(|_| CoreError::ZoneFile("NSEC3PARAM: bad salt".into()))?
|
||||
};
|
||||
RData::DNSSEC(DNSSECRData::NSEC3PARAM(NSEC3PARAM::new(alg, num(&rd[1])? & 1 == 1, num(&rd[2])? as u16, salt)))
|
||||
}
|
||||
_ => return Err(CoreError::ZoneFile(format!("unsupported type {rtype}"))),
|
||||
})
|
||||
}
|
||||
|
||||
/// Pre-process: returns text for the hickory parser plus records parsed here.
|
||||
pub fn extract(text: &str, origin: &Name, default_ttl: u32) -> CoreResult<(String, Vec<Record>)> {
|
||||
let mut origin = origin.clone();
|
||||
let mut ttl = default_ttl;
|
||||
let mut last_owner: Option<Name> = None;
|
||||
let mut last_ttl: Option<u32> = None;
|
||||
let mut pass = String::with_capacity(text.len());
|
||||
let mut extra = Vec::new();
|
||||
for (ws, toks) in logical_lines(text) {
|
||||
let first = toks[0].to_ascii_uppercase();
|
||||
if first.starts_with('$') {
|
||||
match first.as_str() {
|
||||
"$ORIGIN" => {
|
||||
if let Some(o) = toks.get(1) {
|
||||
origin = absolute(o, &origin)?;
|
||||
}
|
||||
}
|
||||
"$TTL" => {
|
||||
if let Some(t) = toks.get(1) {
|
||||
ttl = crate::proto::serialize::txt::parse_ttl(t).map_err(|e| CoreError::ZoneFile(e.to_string()))?;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
pass.push_str(&toks.join(" "));
|
||||
pass.push('\n');
|
||||
continue;
|
||||
}
|
||||
let (owner, mut i) = if ws {
|
||||
(last_owner.clone().ok_or_else(|| CoreError::ZoneFile("record without owner".into()))?, 0)
|
||||
} else {
|
||||
(absolute(&toks[0], &origin)?, 1)
|
||||
};
|
||||
let mut rec_ttl: Option<u32> = None;
|
||||
let mut class = DNSClass::IN;
|
||||
while i < toks.len() {
|
||||
if is_ttl(&toks[i]) && rec_ttl.is_none() {
|
||||
rec_ttl = crate::proto::serialize::txt::parse_ttl(&toks[i]).ok();
|
||||
i += 1;
|
||||
} else if is_class(&toks[i]) {
|
||||
class = toks[i].to_ascii_uppercase().parse().unwrap_or(DNSClass::IN);
|
||||
i += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let Some(tname) = toks.get(i) else {
|
||||
return Err(CoreError::ZoneFile(format!("{owner}: missing record type")));
|
||||
};
|
||||
let tu = tname.to_ascii_uppercase();
|
||||
let rd = &toks[i + 1..];
|
||||
let generic_syntax = rd.first().is_some_and(|t| t == "\\#");
|
||||
let record_ttl = rec_ttl.or(if ws { last_ttl } else { None }).unwrap_or(ttl);
|
||||
last_owner = Some(owner.clone());
|
||||
last_ttl = Some(record_ttl);
|
||||
let rtype_generic = tu.strip_prefix("TYPE").and_then(|n| n.parse::<u16>().ok()).map(RecordType::from);
|
||||
if SPECIAL.contains(&tu.as_str()) || generic_syntax || rtype_generic.is_some() {
|
||||
let data = if generic_syntax {
|
||||
let rt = match rtype_generic {
|
||||
Some(t) => t,
|
||||
None => tu.parse::<RecordType>().map_err(|_| CoreError::ZoneFile(format!("unknown type {tname}")))?,
|
||||
};
|
||||
generic(rt, rd)?
|
||||
} else if let Some(t) = rtype_generic {
|
||||
return Err(CoreError::ZoneFile(format!("{owner} {t}: unknown types must use RFC 3597 \\# syntax")));
|
||||
} else {
|
||||
special(&tu, rd, &origin).map_err(|e| CoreError::ZoneFile(format!("{owner}: {e}")))?
|
||||
};
|
||||
let mut r = Record::from_rdata(owner, record_ttl, data);
|
||||
r.dns_class = class;
|
||||
extra.push(r);
|
||||
continue;
|
||||
}
|
||||
// pass through with explicit owner/TTL/class
|
||||
pass.push_str(&format!("{owner} {record_ttl} {class} "));
|
||||
pass.push_str(&toks[i..].join(" "));
|
||||
pass.push('\n');
|
||||
}
|
||||
Ok((pass, extra))
|
||||
}
|
||||
|
||||
/// RFC 3597 presentation of RDATA (`\# len hex`).
|
||||
pub fn generic_rdata(data: &RData) -> Option<String> {
|
||||
use crate::proto::serialize::binary::BinEncodable;
|
||||
let b = data.to_bytes().ok()?;
|
||||
Some(format!("\\# {} {}", b.len(), data_encoding::HEXLOWER.encode(&b)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn logical_lines_and_comments() {
|
||||
let l = logical_lines("a IN TXT \"x ; not comment\" ; comment\n IN SOA ns hm (\n 1 2 ; c\n 3 4 5 )\n");
|
||||
assert_eq!(l.len(), 2);
|
||||
assert_eq!(l[0].1, vec!["a", "IN", "TXT", "\"x ; not comment\""]);
|
||||
assert!(l[1].0);
|
||||
assert_eq!(l[1].1.len(), 9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn times() {
|
||||
assert_eq!(parse_time("20260101000000").unwrap(), 1_767_225_600);
|
||||
assert_eq!(parse_time("1767225600").unwrap(), 1_767_225_600);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "dns-forwarder"
|
||||
description = "EasyDNS forwarder: upstream pools, strategies, health checks, circuit breaker"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
dns-core.workspace = true
|
||||
dns-config.workspace = true
|
||||
tokio.workspace = true
|
||||
tracing.workspace = true
|
||||
rand.workspace = true
|
||||
serde.workspace = true
|
||||
rustls.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,329 @@
|
||||
//! Upstream pools used by the forwarder role.
|
||||
//!
|
||||
//! * strategies: round-robin, fastest (EWMA RTT), failover, random, priority,
|
||||
//! * circuit breaker: after 3 consecutive failures an upstream is skipped for an
|
||||
//! exponentially growing period (30 s … 5 min); health checks close it again,
|
||||
//! * SERVFAIL/REFUSED/timeouts count as failures and the next upstream is tried,
|
||||
//! * transports: UDP (TCP fallback), TCP, DoT (pooled persistent connections),
|
||||
//! DoH (POST over a persistent, multiplexed HTTP/2 connection; HTTP/1.1 fallback).
|
||||
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
|
||||
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use dns_config::Strategy;
|
||||
use dns_config::upstream::{UpstreamAddr, UpstreamProto};
|
||||
use dns_core::client::{QueryOptions, build_query, exchange};
|
||||
use dns_core::proto::op::{Message, ResponseCode};
|
||||
use dns_core::proto::rr::{Name, RecordType};
|
||||
use dns_core::wire::response_matches;
|
||||
use serde::Serialize;
|
||||
|
||||
const FAILS_TO_OPEN: u32 = 3;
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize)]
|
||||
pub struct UpstreamStats {
|
||||
pub queries: u64,
|
||||
pub failures: u64,
|
||||
pub consecutive_failures: u32,
|
||||
pub ewma_rtt_ms: Option<f64>,
|
||||
pub circuit_open_for_ms: Option<u64>,
|
||||
pub last_error: Option<String>,
|
||||
pub healthy: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct State {
|
||||
stats: UpstreamStats,
|
||||
open_until: Option<Instant>,
|
||||
opens: u32,
|
||||
}
|
||||
|
||||
/// Persistent encrypted transport of an upstream.
|
||||
#[derive(Debug)]
|
||||
enum Encrypted {
|
||||
Dot(dns_core::tls_pool::DotPool),
|
||||
Doh(dns_core::tls_pool::DohClient),
|
||||
}
|
||||
|
||||
/// Idle DoT connections kept per upstream.
|
||||
const DOT_POOL_SIZE: usize = 8;
|
||||
|
||||
/// One upstream server.
|
||||
#[derive(Debug)]
|
||||
pub struct Upstream {
|
||||
pub addr: UpstreamAddr,
|
||||
pub priority: usize,
|
||||
state: Mutex<State>,
|
||||
enc: Option<Encrypted>,
|
||||
}
|
||||
|
||||
impl Upstream {
|
||||
fn new(addr: UpstreamAddr, priority: usize, tls: Option<&Arc<rustls::ClientConfig>>) -> Self {
|
||||
let name = addr.tls_name.clone().unwrap_or_default();
|
||||
let enc = match (addr.proto, tls) {
|
||||
(UpstreamProto::Tls, Some(c)) => Some(Encrypted::Dot(dns_core::tls_pool::DotPool::new(addr.addr, &name, c, DOT_POOL_SIZE))),
|
||||
(UpstreamProto::Https, Some(c)) => Some(Encrypted::Doh(dns_core::tls_pool::DohClient::new(addr.addr, &name, &addr.path, c))),
|
||||
_ => None,
|
||||
};
|
||||
Self {
|
||||
addr,
|
||||
priority,
|
||||
state: Mutex::new(State { stats: UpstreamStats { healthy: true, ..Default::default() }, open_until: None, opens: 0 }),
|
||||
enc,
|
||||
}
|
||||
}
|
||||
fn lock(&self) -> std::sync::MutexGuard<'_, State> {
|
||||
self.state.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
fn is_open(&self) -> bool {
|
||||
self.lock().open_until.is_some_and(|t| t > Instant::now())
|
||||
}
|
||||
fn rtt(&self) -> f64 {
|
||||
self.lock().stats.ewma_rtt_ms.unwrap_or(50.0)
|
||||
}
|
||||
fn success(&self, rtt: Duration) {
|
||||
let mut s = self.lock();
|
||||
let ms = rtt.as_secs_f64() * 1000.0;
|
||||
s.stats.ewma_rtt_ms = Some(match s.stats.ewma_rtt_ms {
|
||||
Some(o) => o * 0.7 + ms * 0.3,
|
||||
None => ms,
|
||||
});
|
||||
s.stats.queries += 1;
|
||||
s.stats.consecutive_failures = 0;
|
||||
s.stats.healthy = true;
|
||||
s.open_until = None;
|
||||
s.opens = 0;
|
||||
}
|
||||
fn failure(&self, err: &str) {
|
||||
let mut s = self.lock();
|
||||
s.stats.queries += 1;
|
||||
s.stats.failures += 1;
|
||||
s.stats.consecutive_failures += 1;
|
||||
s.stats.last_error = Some(err.to_string());
|
||||
// penalise RTT so `fastest` moves away
|
||||
s.stats.ewma_rtt_ms = Some(s.stats.ewma_rtt_ms.unwrap_or(50.0) * 1.5 + 100.0);
|
||||
if s.stats.consecutive_failures >= FAILS_TO_OPEN {
|
||||
let secs = (30u64 << s.opens.min(4)).min(300);
|
||||
s.open_until = Some(Instant::now() + Duration::from_secs(secs));
|
||||
s.opens += 1;
|
||||
s.stats.healthy = false;
|
||||
tracing::warn!(upstream = %self.addr.original, secs, "circuit opened for upstream");
|
||||
}
|
||||
}
|
||||
pub fn stats(&self) -> UpstreamStats {
|
||||
let s = self.lock();
|
||||
let mut st = s.stats.clone();
|
||||
st.circuit_open_for_ms = s.open_until.and_then(|t| t.checked_duration_since(Instant::now())).map(|d| d.as_millis() as u64);
|
||||
st
|
||||
}
|
||||
}
|
||||
|
||||
/// Result of a forwarded query.
|
||||
#[derive(Debug)]
|
||||
pub struct Forwarded {
|
||||
pub message: Message,
|
||||
pub upstream: String,
|
||||
pub elapsed: Duration,
|
||||
pub reason: &'static str,
|
||||
}
|
||||
|
||||
/// A group of upstreams with a selection strategy.
|
||||
#[derive(Debug)]
|
||||
pub struct Pool {
|
||||
pub name: String,
|
||||
pub strategy: Strategy,
|
||||
pub upstreams: Vec<Arc<Upstream>>,
|
||||
pub timeout: Duration,
|
||||
rr: AtomicUsize,
|
||||
}
|
||||
|
||||
impl Pool {
|
||||
pub fn new(name: &str, servers: &[String], strategy: Strategy, timeout: Duration) -> Result<Self, String> {
|
||||
Self::with_tls_roots(name, servers, strategy, timeout, None)
|
||||
}
|
||||
|
||||
/// Like [`Pool::new`], with extra trusted CA certificates (PEM) for DoT/DoH upstreams.
|
||||
pub fn with_tls_roots(
|
||||
name: &str,
|
||||
servers: &[String],
|
||||
strategy: Strategy,
|
||||
timeout: Duration,
|
||||
extra_roots_pem: Option<&[u8]>,
|
||||
) -> Result<Self, String> {
|
||||
let addrs = servers.iter().map(|s| UpstreamAddr::parse(s)).collect::<Result<Vec<_>, _>>()?;
|
||||
if addrs.is_empty() {
|
||||
return Err(format!("pool {name}: no upstreams"));
|
||||
}
|
||||
let needs_tls = addrs.iter().any(|a| matches!(a.proto, UpstreamProto::Tls | UpstreamProto::Https));
|
||||
let tls =
|
||||
if needs_tls { Some(dns_core::tls::client_config(extra_roots_pem, false, &[]).map_err(|e| e.to_string())?) } else { None };
|
||||
let ups: Vec<Arc<Upstream>> = addrs.into_iter().enumerate().map(|(i, a)| Arc::new(Upstream::new(a, i, tls.as_ref()))).collect();
|
||||
Ok(Self { name: name.into(), strategy, upstreams: ups, timeout, rr: AtomicUsize::new(0) })
|
||||
}
|
||||
|
||||
/// Order upstreams for one query according to the strategy; open circuits go last.
|
||||
pub fn order(&self) -> (Vec<Arc<Upstream>>, &'static str) {
|
||||
let mut v: Vec<Arc<Upstream>> = self.upstreams.clone();
|
||||
let reason = match self.strategy {
|
||||
Strategy::Failover | Strategy::Priority => {
|
||||
v.sort_by_key(|u| u.priority);
|
||||
"priority order"
|
||||
}
|
||||
Strategy::RoundRobin => {
|
||||
let n = v.len();
|
||||
let k = self.rr.fetch_add(1, Ordering::Relaxed) % n;
|
||||
v.rotate_left(k);
|
||||
"round-robin"
|
||||
}
|
||||
Strategy::Random => {
|
||||
use rand::seq::SliceRandom;
|
||||
v.shuffle(&mut rand::rng());
|
||||
"random"
|
||||
}
|
||||
Strategy::Fastest => {
|
||||
v.sort_by(|a, b| a.rtt().total_cmp(&b.rtt()));
|
||||
// explore: occasionally try the second-fastest to refresh its RTT estimate
|
||||
if v.len() > 1 && rand::random::<u8>() < 13 {
|
||||
v.swap(0, 1);
|
||||
}
|
||||
"lowest RTT"
|
||||
}
|
||||
};
|
||||
let (closed, open): (Vec<_>, Vec<_>) = v.into_iter().partition(|u| !u.is_open());
|
||||
let mut out = closed;
|
||||
out.extend(open);
|
||||
(out, reason)
|
||||
}
|
||||
|
||||
async fn send(&self, u: &Upstream, msg: &Message, opts: &QueryOptions) -> Result<Message, String> {
|
||||
match u.addr.proto {
|
||||
UpstreamProto::Udp | UpstreamProto::Tcp => {
|
||||
let mut o = opts.clone();
|
||||
o.tcp_only = u.addr.proto == UpstreamProto::Tcp;
|
||||
o.retries = 0;
|
||||
exchange(u.addr.addr, msg.clone(), &o).await.map(|e| e.message).map_err(|e| e.to_string())
|
||||
}
|
||||
UpstreamProto::Tls | UpstreamProto::Https => {
|
||||
let bytes = msg.to_vec().map_err(|e| e.to_string())?;
|
||||
let raw = match &u.enc {
|
||||
Some(Encrypted::Dot(p)) => p.exchange(&bytes, self.timeout).await,
|
||||
Some(Encrypted::Doh(c)) => {
|
||||
c.exchange(&bytes, dns_core::tls::DohMethod::Post, self.timeout).await.and_then(|(st, body)| {
|
||||
if st == 200 { Ok(body) } else { Err(dns_core::CoreError::Proto(format!("HTTP status {st}"))) }
|
||||
})
|
||||
}
|
||||
None => return Err("TLS not configured".into()),
|
||||
}
|
||||
.map_err(|e| e.to_string())?;
|
||||
let m = Message::from_vec(&raw).map_err(|e| e.to_string())?;
|
||||
if !response_matches(msg, &m) {
|
||||
return Err("response does not match query".into());
|
||||
}
|
||||
Ok(m)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Forward a query; tries upstreams in strategy order until one gives a usable answer.
|
||||
pub async fn query(&self, name: &Name, qtype: RecordType, dnssec_ok: bool, cd: bool) -> Result<Forwarded, String> {
|
||||
let opts = QueryOptions {
|
||||
timeout: self.timeout,
|
||||
retries: 0,
|
||||
dnssec_ok,
|
||||
checking_disabled: cd,
|
||||
recursion_desired: true,
|
||||
..Default::default()
|
||||
};
|
||||
let (order, reason) = self.order();
|
||||
let mut errors = Vec::new();
|
||||
for u in order.iter().take(3) {
|
||||
let msg = build_query(name, qtype, &opts);
|
||||
let start = Instant::now();
|
||||
match self.send(u, &msg, &opts).await {
|
||||
Ok(m)
|
||||
if matches!(
|
||||
m.metadata.response_code,
|
||||
ResponseCode::ServFail | ResponseCode::Refused | ResponseCode::NotImp | ResponseCode::FormErr
|
||||
) =>
|
||||
{
|
||||
let e = format!("{} answered {}", u.addr.original, m.metadata.response_code);
|
||||
u.failure(&e);
|
||||
errors.push(e);
|
||||
}
|
||||
Ok(m) => {
|
||||
let el = start.elapsed();
|
||||
u.success(el);
|
||||
return Ok(Forwarded { message: m, upstream: u.addr.original.clone(), elapsed: el, reason });
|
||||
}
|
||||
Err(e) => {
|
||||
u.failure(&e);
|
||||
errors.push(format!("{}: {e}", u.addr.original));
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(errors.join("; "))
|
||||
}
|
||||
|
||||
/// Probe every upstream once (root NS query); used by the periodic health checker.
|
||||
pub async fn health_check(&self) {
|
||||
for u in &self.upstreams {
|
||||
let opts = QueryOptions { timeout: self.timeout, retries: 0, ..Default::default() };
|
||||
let msg = build_query(&Name::root(), RecordType::NS, &opts);
|
||||
let start = Instant::now();
|
||||
match self.send(u, &msg, &opts).await {
|
||||
Ok(m) if m.metadata.response_code == ResponseCode::NoError => u.success(start.elapsed()),
|
||||
Ok(m) => u.failure(&format!("health check: {}", m.metadata.response_code)),
|
||||
Err(e) => u.failure(&format!("health check: {e}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn stats(&self) -> Vec<(String, UpstreamStats)> {
|
||||
self.upstreams.iter().map(|u| (u.addr.original.clone(), u.stats())).collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ordering_strategies() {
|
||||
let s: Vec<String> = vec!["192.0.2.1".into(), "192.0.2.2".into(), "192.0.2.3".into()];
|
||||
let p = Pool::new("t", &s, Strategy::Failover, Duration::from_millis(100)).unwrap();
|
||||
let (o, _) = p.order();
|
||||
assert_eq!(o[0].addr.original, "192.0.2.1");
|
||||
for _ in 0..3 {
|
||||
p.upstreams[0].failure("x");
|
||||
}
|
||||
let (o, _) = p.order();
|
||||
assert_eq!(o[0].addr.original, "192.0.2.2", "open circuit goes last");
|
||||
assert!(p.upstreams[0].stats().circuit_open_for_ms.is_some());
|
||||
p.upstreams[0].success(Duration::from_millis(1));
|
||||
assert_eq!(p.order().0[0].addr.original, "192.0.2.1");
|
||||
|
||||
let rr = Pool::new("t", &s, Strategy::RoundRobin, Duration::from_millis(100)).unwrap();
|
||||
let a = rr.order().0[0].addr.original.clone();
|
||||
let b = rr.order().0[0].addr.original.clone();
|
||||
assert_ne!(a, b);
|
||||
|
||||
let f = Pool::new("t", &s, Strategy::Fastest, Duration::from_millis(100)).unwrap();
|
||||
f.upstreams[2].success(Duration::from_millis(1));
|
||||
f.upstreams[0].success(Duration::from_millis(80));
|
||||
f.upstreams[1].success(Duration::from_millis(90));
|
||||
let firsts: Vec<String> = (0..50).map(|_| f.order().0[0].addr.original.clone()).collect();
|
||||
assert!(firsts.iter().filter(|x| *x == "192.0.2.3").count() > 35);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failover_on_dead_upstream() {
|
||||
// Nothing listens on these ports: both fail fast/timeout -> error with both reasons.
|
||||
let s: Vec<String> = vec!["127.0.0.1:9".into(), "127.0.0.1:19".into()];
|
||||
let p = Pool::new("t", &s, Strategy::Failover, Duration::from_millis(200)).unwrap();
|
||||
let r = p.query(&Name::from_ascii("example.com.").unwrap(), RecordType::A, false, false).await;
|
||||
let e = r.unwrap_err();
|
||||
assert!(e.contains("127.0.0.1:9") && e.contains("127.0.0.1:19"), "{e}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
[package]
|
||||
name = "dns-metrics"
|
||||
description = "EasyDNS metrics registry (Prometheus/OpenMetrics text) and logging setup"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
tracing-subscriber.workspace = true
|
||||
tracing.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,246 @@
|
||||
//! Low-cardinality metrics with a Prometheus text renderer, plus logging setup.
|
||||
//!
|
||||
//! Labels are bounded enums (transport, rcode, qtype bucket, source) – never
|
||||
//! domain names or client IPs (unbounded cardinality).
|
||||
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
|
||||
|
||||
use std::fmt::Write;
|
||||
use std::sync::atomic::{AtomicI64, AtomicU64, Ordering::Relaxed};
|
||||
use std::time::Duration;
|
||||
|
||||
pub const TRANSPORTS: [&str; 4] = ["udp", "tcp", "dot", "doh"];
|
||||
pub const QTYPES: [&str; 13] = ["A", "AAAA", "CNAME", "MX", "NS", "PTR", "SOA", "SRV", "TXT", "HTTPS", "SVCB", "ANY", "OTHER"];
|
||||
pub const RCODES: [&str; 7] = ["NOERROR", "FORMERR", "SERVFAIL", "NXDOMAIN", "NOTIMP", "REFUSED", "OTHER"];
|
||||
pub const SOURCES: [&str; 7] = ["authoritative", "cache", "recursive", "forward", "blocked", "local", "refused"];
|
||||
|
||||
/// Fixed-bucket histogram (seconds).
|
||||
pub struct Histogram {
|
||||
bounds: &'static [f64],
|
||||
buckets: Vec<AtomicU64>,
|
||||
count: AtomicU64,
|
||||
sum_us: AtomicU64,
|
||||
}
|
||||
|
||||
const LAT_BOUNDS: &[f64] = &[0.0005, 0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0];
|
||||
|
||||
impl Histogram {
|
||||
pub fn new(bounds: &'static [f64]) -> Self {
|
||||
Self { bounds, buckets: bounds.iter().map(|_| AtomicU64::new(0)).collect(), count: AtomicU64::new(0), sum_us: AtomicU64::new(0) }
|
||||
}
|
||||
pub fn observe(&self, d: Duration) {
|
||||
let s = d.as_secs_f64();
|
||||
for (i, b) in self.bounds.iter().enumerate() {
|
||||
if s <= *b {
|
||||
self.buckets[i].fetch_add(1, Relaxed);
|
||||
}
|
||||
}
|
||||
self.count.fetch_add(1, Relaxed);
|
||||
self.sum_us.fetch_add(d.as_micros() as u64, Relaxed);
|
||||
}
|
||||
fn render(&self, out: &mut String, name: &str, help: &str) {
|
||||
let _ = writeln!(out, "# HELP {name} {help}\n# TYPE {name} histogram");
|
||||
for (i, b) in self.bounds.iter().enumerate() {
|
||||
let _ = writeln!(out, "{name}_bucket{{le=\"{b}\"}} {}", self.buckets[i].load(Relaxed));
|
||||
}
|
||||
let c = self.count.load(Relaxed);
|
||||
let _ = writeln!(out, "{name}_bucket{{le=\"+Inf\"}} {c}");
|
||||
let _ = writeln!(out, "{name}_sum {}", self.sum_us.load(Relaxed) as f64 / 1e6);
|
||||
let _ = writeln!(out, "{name}_count {c}");
|
||||
}
|
||||
pub fn count(&self) -> u64 {
|
||||
self.count.load(Relaxed)
|
||||
}
|
||||
/// Approximate quantile from buckets (upper bound of the bucket).
|
||||
pub fn quantile(&self, q: f64) -> Option<f64> {
|
||||
let c = self.count.load(Relaxed);
|
||||
if c == 0 {
|
||||
return None;
|
||||
}
|
||||
let target = (c as f64 * q).ceil() as u64;
|
||||
for (i, b) in self.bounds.iter().enumerate() {
|
||||
if self.buckets[i].load(Relaxed) >= target {
|
||||
return Some(*b);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn arr<const N: usize>() -> [AtomicU64; N] {
|
||||
std::array::from_fn(|_| AtomicU64::new(0))
|
||||
}
|
||||
|
||||
/// Global metrics registry.
|
||||
pub struct Metrics {
|
||||
pub queries: [AtomicU64; 4],
|
||||
pub qtypes: [AtomicU64; 13],
|
||||
pub rcodes: [AtomicU64; 7],
|
||||
pub sources: [AtomicU64; 7],
|
||||
pub latency: Histogram,
|
||||
pub upstream_latency: Histogram,
|
||||
pub upstream_errors: AtomicU64,
|
||||
pub blocked: AtomicU64,
|
||||
pub rate_limited: AtomicU64,
|
||||
pub malformed: AtomicU64,
|
||||
pub tcp_connections: AtomicI64,
|
||||
pub inflight: AtomicI64,
|
||||
pub xfr_out_ok: AtomicU64,
|
||||
pub xfr_out_refused: AtomicU64,
|
||||
pub notify_received: AtomicU64,
|
||||
pub notify_refused: AtomicU64,
|
||||
pub updates_ok: AtomicU64,
|
||||
pub updates_refused: AtomicU64,
|
||||
pub tsig_failures: AtomicU64,
|
||||
pub dnssec_secure: AtomicU64,
|
||||
pub dnssec_insecure: AtomicU64,
|
||||
pub dnssec_bogus: AtomicU64,
|
||||
pub recursion_queries_sent: AtomicU64,
|
||||
pub start_unix: u64,
|
||||
}
|
||||
|
||||
impl Default for Metrics {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
queries: arr(),
|
||||
qtypes: arr(),
|
||||
rcodes: arr(),
|
||||
sources: arr(),
|
||||
latency: Histogram::new(LAT_BOUNDS),
|
||||
upstream_latency: Histogram::new(LAT_BOUNDS),
|
||||
upstream_errors: AtomicU64::new(0),
|
||||
blocked: AtomicU64::new(0),
|
||||
rate_limited: AtomicU64::new(0),
|
||||
malformed: AtomicU64::new(0),
|
||||
tcp_connections: AtomicI64::new(0),
|
||||
inflight: AtomicI64::new(0),
|
||||
xfr_out_ok: AtomicU64::new(0),
|
||||
xfr_out_refused: AtomicU64::new(0),
|
||||
notify_received: AtomicU64::new(0),
|
||||
notify_refused: AtomicU64::new(0),
|
||||
updates_ok: AtomicU64::new(0),
|
||||
updates_refused: AtomicU64::new(0),
|
||||
tsig_failures: AtomicU64::new(0),
|
||||
dnssec_secure: AtomicU64::new(0),
|
||||
dnssec_insecure: AtomicU64::new(0),
|
||||
dnssec_bogus: AtomicU64::new(0),
|
||||
recursion_queries_sent: AtomicU64::new(0),
|
||||
start_unix: std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn idx(list: &[&str], v: &str) -> usize {
|
||||
list.iter().position(|x| *x == v).unwrap_or(list.len() - 1)
|
||||
}
|
||||
|
||||
impl Metrics {
|
||||
pub fn query(&self, transport: &str, qtype: &str) {
|
||||
self.queries[idx(&TRANSPORTS, transport).min(3)].fetch_add(1, Relaxed);
|
||||
self.qtypes[idx(&QTYPES, qtype)].fetch_add(1, Relaxed);
|
||||
}
|
||||
pub fn response(&self, rcode: &str, source: &str, elapsed: Duration) {
|
||||
self.rcodes[idx(&RCODES, rcode)].fetch_add(1, Relaxed);
|
||||
self.sources[idx(&SOURCES, source)].fetch_add(1, Relaxed);
|
||||
self.latency.observe(elapsed);
|
||||
}
|
||||
pub fn total_queries(&self) -> u64 {
|
||||
self.queries.iter().map(|a| a.load(Relaxed)).sum()
|
||||
}
|
||||
pub fn rcode(&self, r: &str) -> u64 {
|
||||
self.rcodes[idx(&RCODES, r)].load(Relaxed)
|
||||
}
|
||||
pub fn source(&self, s: &str) -> u64 {
|
||||
self.sources[idx(&SOURCES, s)].load(Relaxed)
|
||||
}
|
||||
|
||||
/// Render all metrics. `extra` lets other components append pre-rendered families.
|
||||
pub fn render(&self, extra: &str) -> String {
|
||||
let mut o = String::with_capacity(8192);
|
||||
let fam = |o: &mut String, name: &str, help: &str, kind: &str| {
|
||||
let _ = writeln!(o, "# HELP {name} {help}\n# TYPE {name} {kind}");
|
||||
};
|
||||
fam(&mut o, "dns_queries_total", "DNS queries received", "counter");
|
||||
for (i, t) in TRANSPORTS.iter().enumerate() {
|
||||
let _ = writeln!(o, "dns_queries_total{{transport=\"{t}\"}} {}", self.queries[i].load(Relaxed));
|
||||
}
|
||||
fam(&mut o, "dns_queries_by_type_total", "DNS queries by QTYPE bucket", "counter");
|
||||
for (i, t) in QTYPES.iter().enumerate() {
|
||||
let _ = writeln!(o, "dns_queries_by_type_total{{qtype=\"{t}\"}} {}", self.qtypes[i].load(Relaxed));
|
||||
}
|
||||
fam(&mut o, "dns_responses_total", "DNS responses by RCODE", "counter");
|
||||
for (i, t) in RCODES.iter().enumerate() {
|
||||
let _ = writeln!(o, "dns_responses_total{{rcode=\"{t}\"}} {}", self.rcodes[i].load(Relaxed));
|
||||
}
|
||||
fam(&mut o, "dns_answers_by_source_total", "Responses by answer source", "counter");
|
||||
for (i, t) in SOURCES.iter().enumerate() {
|
||||
let _ = writeln!(o, "dns_answers_by_source_total{{source=\"{t}\"}} {}", self.sources[i].load(Relaxed));
|
||||
}
|
||||
self.latency.render(&mut o, "dns_query_duration_seconds", "Query processing latency");
|
||||
self.upstream_latency.render(&mut o, "dns_upstream_latency_seconds", "Upstream/authority query latency");
|
||||
let counters: [(&str, &str, &AtomicU64); 15] = [
|
||||
("dns_upstream_errors_total", "Upstream query failures", &self.upstream_errors),
|
||||
("dns_blocked_total", "Queries blocked by policy", &self.blocked),
|
||||
("dns_rate_limited_total", "Queries dropped or slipped by rate limiting", &self.rate_limited),
|
||||
("dns_malformed_total", "Malformed packets received", &self.malformed),
|
||||
("dns_xfr_out_total", "Outgoing zone transfers served", &self.xfr_out_ok),
|
||||
("dns_xfr_out_refused_total", "Refused zone transfer requests", &self.xfr_out_refused),
|
||||
("dns_notify_received_total", "Accepted NOTIFY messages", &self.notify_received),
|
||||
("dns_notify_refused_total", "Refused NOTIFY messages", &self.notify_refused),
|
||||
("dns_updates_total", "Accepted dynamic updates", &self.updates_ok),
|
||||
("dns_updates_refused_total", "Refused dynamic updates", &self.updates_refused),
|
||||
("dns_tsig_failures_total", "TSIG verification failures", &self.tsig_failures),
|
||||
("dns_dnssec_secure_total", "Answers validated as secure", &self.dnssec_secure),
|
||||
("dns_dnssec_insecure_total", "Answers proven insecure", &self.dnssec_insecure),
|
||||
("dns_dnssec_bogus_total", "Answers failing DNSSEC validation", &self.dnssec_bogus),
|
||||
("dns_recursion_queries_sent_total", "Queries sent to authoritative servers by the resolver", &self.recursion_queries_sent),
|
||||
];
|
||||
for (n, h, v) in counters.iter() {
|
||||
fam(&mut o, n, h, "counter");
|
||||
let _ = writeln!(o, "{n} {}", v.load(Relaxed));
|
||||
}
|
||||
fam(&mut o, "dns_tcp_connections", "Open TCP/DoT connections", "gauge");
|
||||
let _ = writeln!(o, "dns_tcp_connections {}", self.tcp_connections.load(Relaxed));
|
||||
fam(&mut o, "dns_inflight_queries", "Queries being processed", "gauge");
|
||||
let _ = writeln!(o, "dns_inflight_queries {}", self.inflight.load(Relaxed));
|
||||
fam(&mut o, "process_start_time_seconds", "Start time of the process", "gauge");
|
||||
let _ = writeln!(o, "process_start_time_seconds {}", self.start_unix);
|
||||
if let Some(rss) = rss_bytes() {
|
||||
fam(&mut o, "process_resident_memory_bytes", "Resident memory size", "gauge");
|
||||
let _ = writeln!(o, "process_resident_memory_bytes {rss}");
|
||||
}
|
||||
o.push_str(extra);
|
||||
o
|
||||
}
|
||||
}
|
||||
|
||||
/// Resident set size from /proc (Linux only).
|
||||
pub fn rss_bytes() -> Option<u64> {
|
||||
let s = std::fs::read_to_string("/proc/self/statm").ok()?;
|
||||
let pages: u64 = s.split_whitespace().nth(1)?.parse().ok()?;
|
||||
Some(pages * 4096)
|
||||
}
|
||||
|
||||
/// Initialise `tracing` with the given level filter and format (`text`/`json`).
|
||||
pub fn init_logging(level: &str, json: bool) {
|
||||
use tracing_subscriber::EnvFilter;
|
||||
let filter = EnvFilter::try_from_env("EASYDNS_LOG").unwrap_or_else(|_| EnvFilter::new(level));
|
||||
let b = tracing_subscriber::fmt().with_env_filter(filter).with_target(false).with_writer(std::io::stderr);
|
||||
let _ = if json { b.json().try_init() } else { b.try_init() };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn render_and_quantiles() {
|
||||
let m = Metrics::default();
|
||||
m.query("udp", "A");
|
||||
m.query("udp", "TYPE65280");
|
||||
m.response("NOERROR", "authoritative", Duration::from_millis(2));
|
||||
let s = m.render("");
|
||||
assert!(s.contains("dns_queries_total{transport=\"udp\"} 2"));
|
||||
assert!(s.contains("dns_queries_by_type_total{qtype=\"OTHER\"} 1"));
|
||||
assert!(s.contains("dns_query_duration_seconds_count 1"));
|
||||
assert_eq!(m.latency.quantile(0.5), Some(0.0025));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "dns-policy"
|
||||
description = "EasyDNS policies: ACLs, views, rate limiting, block/allow lists"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
dns-core.workspace = true
|
||||
dns-config.workspace = true
|
||||
ipnet.workspace = true
|
||||
tracing.workspace = true
|
||||
regex = { version = "1", default-features = false, features = ["std", "perf", "unicode-case"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,525 @@
|
||||
//! Policies applied before resolution:
|
||||
//! * [`Acl`] – address match lists,
|
||||
//! * [`Views`] – split-horizon client classification,
|
||||
//! * [`RateLimiter`] – per-client token buckets with a global ceiling,
|
||||
//! * [`BlockPolicy`] – allow/block lists with exact, suffix, wildcard and (bounded) regex rules.
|
||||
//!
|
||||
//! Processing order (documented in docs/security.md): rate limit → ACL/view →
|
||||
//! local zones → allowlist → blocklist → resolution.
|
||||
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::hash::{BuildHasher, RandomState};
|
||||
use std::net::IpAddr;
|
||||
use std::path::Path;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::Instant;
|
||||
|
||||
use dns_config::{BlockAction, Config};
|
||||
use dns_core::proto::rr::{LowerName, Name};
|
||||
use ipnet::IpNet;
|
||||
|
||||
/// Normalise v4-mapped v6 addresses.
|
||||
pub fn canonical_ip(ip: IpAddr) -> IpAddr {
|
||||
match ip {
|
||||
IpAddr::V6(v6) => v6.to_ipv4_mapped().map(IpAddr::V4).unwrap_or(IpAddr::V6(v6)),
|
||||
v4 => v4,
|
||||
}
|
||||
}
|
||||
|
||||
/// An address match list.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Acl(pub Vec<IpNet>);
|
||||
|
||||
impl Acl {
|
||||
pub fn contains(&self, ip: IpAddr) -> bool {
|
||||
let ip = canonical_ip(ip);
|
||||
self.0.iter().any(|n| n.contains(&ip))
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Split-horizon views: first matching view wins.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Views(Vec<(String, Acl)>);
|
||||
|
||||
impl Views {
|
||||
pub fn from_config(cfg: &Config) -> Result<Self, String> {
|
||||
let mut v = Vec::new();
|
||||
for view in &cfg.resolution.views {
|
||||
v.push((view.name.clone(), Acl(cfg.expand_acl(&view.clients)?)));
|
||||
}
|
||||
Ok(Self(v))
|
||||
}
|
||||
pub fn classify(&self, ip: IpAddr) -> Option<&str> {
|
||||
self.0.iter().find(|(_, acl)| acl.contains(ip)).map(|(n, _)| n.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
/// Result of a rate-limit check.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RateDecision {
|
||||
Allow,
|
||||
/// Send a truncated (TC=1) empty response so legitimate clients retry over TCP.
|
||||
Slip,
|
||||
Drop,
|
||||
}
|
||||
|
||||
struct Bucket {
|
||||
tokens: f64,
|
||||
last: Instant,
|
||||
limited: u32,
|
||||
}
|
||||
|
||||
/// Independently locked shards of the per-client bucket table (power of two).
|
||||
const RL_SHARDS: usize = 16;
|
||||
|
||||
type BucketShard = Mutex<HashMap<IpAddr, Bucket>>;
|
||||
|
||||
/// Token-bucket limiter per client prefix (IPv4 /32, IPv6 /56) plus a global limit.
|
||||
///
|
||||
/// Hot-path cost: the global limit is a lock-free GCRA on one atomic, and client
|
||||
/// buckets live in [`RL_SHARDS`] independently locked maps chosen by prefix hash, so
|
||||
/// concurrent queries from different clients rarely touch the same lock.
|
||||
pub struct RateLimiter {
|
||||
enabled: bool,
|
||||
rate: f64,
|
||||
burst: f64,
|
||||
slip: u32,
|
||||
exempt: Acl,
|
||||
shards: Box<[BucketShard]>,
|
||||
hasher: RandomState,
|
||||
/// Max tracked prefixes per shard (memory bound: ~80 bytes each).
|
||||
max_per_shard: usize,
|
||||
/// GCRA state: theoretical arrival time in ns since `epoch`.
|
||||
global_tat: AtomicU64,
|
||||
/// ns between global tokens, and the allowed burst (1 s worth of tokens) in ns.
|
||||
global_interval: u64,
|
||||
global_tolerance: u64,
|
||||
epoch: Instant,
|
||||
}
|
||||
|
||||
fn prefix_key(ip: IpAddr) -> IpAddr {
|
||||
match canonical_ip(ip) {
|
||||
IpAddr::V6(v6) => {
|
||||
let mut o = v6.octets();
|
||||
for b in o.iter_mut().skip(7) {
|
||||
*b = 0;
|
||||
}
|
||||
IpAddr::V6(o.into())
|
||||
}
|
||||
v4 => v4,
|
||||
}
|
||||
}
|
||||
|
||||
/// Total number of client prefixes tracked across all shards.
|
||||
const MAX_TRACKED: usize = 100_000;
|
||||
|
||||
impl RateLimiter {
|
||||
fn build(enabled: bool, rate: f64, burst: f64, slip: u32, exempt: Acl, global_qps: u32) -> Self {
|
||||
// global_qps == 0 disables the global limit
|
||||
let interval = if global_qps == 0 { 0 } else { 1_000_000_000 / u64::from(global_qps) };
|
||||
Self {
|
||||
enabled,
|
||||
rate,
|
||||
burst,
|
||||
slip,
|
||||
exempt,
|
||||
shards: (0..RL_SHARDS).map(|_| Mutex::new(HashMap::new())).collect(),
|
||||
hasher: RandomState::new(),
|
||||
max_per_shard: MAX_TRACKED / RL_SHARDS,
|
||||
global_tat: AtomicU64::new(0),
|
||||
global_interval: interval,
|
||||
global_tolerance: interval.saturating_mul(u64::from(global_qps.max(1)).saturating_sub(1)),
|
||||
epoch: Instant::now(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_config(cfg: &Config) -> Result<Self, String> {
|
||||
let r = &cfg.rate_limit;
|
||||
let exempt = Acl(cfg.expand_acl(&r.exempt_clients)?);
|
||||
Ok(Self::build(r.enabled, f64::from(r.per_client_qps.max(1)), f64::from(r.burst.max(1)), r.slip, exempt, r.global_qps))
|
||||
}
|
||||
|
||||
pub fn disabled() -> Self {
|
||||
Self::build(false, 1.0, 1.0, 0, Acl::default(), 0)
|
||||
}
|
||||
|
||||
/// Global limit (GCRA, equivalent to a token bucket holding one second of tokens).
|
||||
fn global_allow(&self, now: Instant) -> bool {
|
||||
if self.global_interval == 0 {
|
||||
return true;
|
||||
}
|
||||
let now_ns = now.duration_since(self.epoch).as_nanos() as u64;
|
||||
let mut tat = self.global_tat.load(Ordering::Relaxed);
|
||||
loop {
|
||||
let t = tat.max(now_ns);
|
||||
if t - now_ns > self.global_tolerance {
|
||||
return false;
|
||||
}
|
||||
match self.global_tat.compare_exchange_weak(tat, t + self.global_interval, Ordering::Relaxed, Ordering::Relaxed) {
|
||||
Ok(_) => return true,
|
||||
Err(cur) => tat = cur,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn check(&self, ip: IpAddr) -> RateDecision {
|
||||
if !self.enabled || self.exempt.contains(ip) {
|
||||
return RateDecision::Allow;
|
||||
}
|
||||
let now = Instant::now();
|
||||
if !self.global_allow(now) {
|
||||
return RateDecision::Drop;
|
||||
}
|
||||
let key = prefix_key(ip);
|
||||
let shard = &self.shards[(self.hasher.hash_one(key) as usize) & (RL_SHARDS - 1)];
|
||||
let mut map = shard.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if map.len() >= self.max_per_shard && !map.contains_key(&key) {
|
||||
// Evict idle buckets (full buckets carry no state worth keeping).
|
||||
let (rate, burst) = (self.rate, self.burst);
|
||||
map.retain(|_, b| b.tokens + now.duration_since(b.last).as_secs_f64() * rate < burst);
|
||||
if map.len() >= self.max_per_shard {
|
||||
map.clear();
|
||||
}
|
||||
}
|
||||
let b = map.entry(key).or_insert(Bucket { tokens: self.burst, last: now, limited: 0 });
|
||||
let el = now.duration_since(b.last).as_secs_f64();
|
||||
b.tokens = (b.tokens + el * self.rate).min(self.burst);
|
||||
b.last = now;
|
||||
if b.tokens >= 1.0 {
|
||||
b.tokens -= 1.0;
|
||||
RateDecision::Allow
|
||||
} else {
|
||||
b.limited = b.limited.wrapping_add(1);
|
||||
if self.slip > 0 && b.limited.is_multiple_of(self.slip) { RateDecision::Slip } else { RateDecision::Drop }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a name was blocked.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct BlockMatch {
|
||||
pub list: String,
|
||||
pub rule: String,
|
||||
pub category: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct RuleSet {
|
||||
exact: HashMap<LowerName, usize>,
|
||||
suffix: HashMap<LowerName, usize>,
|
||||
regex: Vec<(regex::Regex, usize)>,
|
||||
}
|
||||
|
||||
/// Maximum compiled regex size (resource limit).
|
||||
const REGEX_SIZE_LIMIT: usize = 1 << 16;
|
||||
|
||||
impl RuleSet {
|
||||
/// Add a rule. Syntax: `example.com` (exact + subdomains), `=example.com` (exact only),
|
||||
/// `*.example.com` (subdomains only), `/regex/`, hosts-file lines (`0.0.0.0 example.com`).
|
||||
fn add(&mut self, line: &str, meta: usize) -> Result<(), String> {
|
||||
let line = line.split('#').next().unwrap_or("").trim();
|
||||
if line.is_empty() || line.starts_with('!') {
|
||||
return Ok(());
|
||||
}
|
||||
let mut parts = line.split_whitespace();
|
||||
let first = parts.next().unwrap_or("");
|
||||
let rule = if first.parse::<IpAddr>().is_ok() {
|
||||
match parts.next() {
|
||||
Some(h) if h != "localhost" && h != "localhost.localdomain" && h != "0.0.0.0" => h,
|
||||
_ => return Ok(()),
|
||||
}
|
||||
} else {
|
||||
first
|
||||
};
|
||||
if let Some(re) = rule.strip_prefix('/').and_then(|r| r.strip_suffix('/')) {
|
||||
let compiled = regex::RegexBuilder::new(re)
|
||||
.size_limit(REGEX_SIZE_LIMIT)
|
||||
.case_insensitive(true)
|
||||
.build()
|
||||
.map_err(|e| format!("invalid regex '{re}': {e}"))?;
|
||||
self.regex.push((compiled, meta));
|
||||
} else if let Some(exact) = rule.strip_prefix('=') {
|
||||
self.exact.insert(dns_core::names::parse_lower(exact).map_err(|e| e.to_string())?, meta);
|
||||
} else if let Some(sub) = rule.strip_prefix("*.") {
|
||||
// subdomains only: store as suffix on the child level marker
|
||||
let n = dns_core::names::parse_name(sub).map_err(|e| e.to_string())?;
|
||||
let w = Name::from_ascii("*").and_then(|w| w.append_domain(&n)).map_err(|e| e.to_string())?;
|
||||
self.suffix.insert(LowerName::new(&w), meta);
|
||||
} else {
|
||||
self.suffix.insert(dns_core::names::parse_lower(rule).map_err(|e| e.to_string())?, meta);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn lookup(&self, name: &Name) -> Option<(usize, String)> {
|
||||
let l = LowerName::new(name);
|
||||
if let Some(m) = self.exact.get(&l) {
|
||||
return Some((*m, l.to_string()));
|
||||
}
|
||||
for (i, anc) in dns_core::names::ancestors(name).enumerate() {
|
||||
if anc.is_root() {
|
||||
break;
|
||||
}
|
||||
let la = LowerName::new(&anc);
|
||||
if let Some(m) = self.suffix.get(&la) {
|
||||
return Some((*m, la.to_string()));
|
||||
}
|
||||
if i > 0
|
||||
&& let Ok(w) = Name::from_ascii("*").and_then(|w| w.append_domain(&anc))
|
||||
&& let Some(m) = self.suffix.get(&LowerName::new(&w))
|
||||
{
|
||||
return Some((*m, format!("*.{la}")));
|
||||
}
|
||||
}
|
||||
if !self.regex.is_empty() {
|
||||
let s = l.to_string();
|
||||
let s = s.trim_end_matches('.');
|
||||
for (re, m) in &self.regex {
|
||||
if re.is_match(s) {
|
||||
return Some((*m, format!("/{}/", re.as_str())));
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn len(&self) -> usize {
|
||||
self.exact.len() + self.suffix.len() + self.regex.len()
|
||||
}
|
||||
}
|
||||
|
||||
/// Allow/block policy.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct BlockPolicy {
|
||||
block: RuleSet,
|
||||
allow: RuleSet,
|
||||
lists: Vec<(String, Option<String>)>,
|
||||
pub action: BlockAction,
|
||||
pub v4: Option<std::net::Ipv4Addr>,
|
||||
pub v6: Option<std::net::Ipv6Addr>,
|
||||
pub ttl: u32,
|
||||
pub exempt: Acl,
|
||||
pub log: bool,
|
||||
}
|
||||
|
||||
impl BlockPolicy {
|
||||
/// Load lists from configuration. Remote lists are read from their cached copy in
|
||||
/// `<data_dir>/blocklists/<name>.txt` (downloaded by `easydns blocklists update`).
|
||||
pub fn from_config(cfg: &Config) -> Result<Self, String> {
|
||||
let p = &cfg.policy;
|
||||
let mut bp = BlockPolicy {
|
||||
action: p.block_action,
|
||||
v4: Some(p.block_address_v4),
|
||||
v6: Some(p.block_address_v6),
|
||||
ttl: p.block_ttl,
|
||||
exempt: Acl(cfg.expand_acl(&p.exempt_clients)?),
|
||||
log: p.log_blocked,
|
||||
..Default::default()
|
||||
};
|
||||
for a in &p.allowlist {
|
||||
bp.allow.add(a, 0)?;
|
||||
}
|
||||
for list in p.blocklists.iter().filter(|l| l.enabled) {
|
||||
let idx = bp.lists.len();
|
||||
bp.lists.push((list.name.clone(), list.category.clone()));
|
||||
let path = match (&list.file, &list.url) {
|
||||
(Some(f), _) => cfg.resolve_path(f),
|
||||
(None, Some(_)) => cfg.data_dir().join("blocklists").join(format!("{}.txt", list.name)),
|
||||
(None, None) => continue,
|
||||
};
|
||||
if !path.is_file() && list.url.is_some() {
|
||||
tracing::warn!(list = %list.name, "remote blocklist not downloaded yet; run `easydns blocklists update`");
|
||||
continue;
|
||||
}
|
||||
bp.load_file(&path, idx).map_err(|e| format!("blocklist {}: {e}", list.name))?;
|
||||
}
|
||||
Ok(bp)
|
||||
}
|
||||
|
||||
fn load_file(&mut self, path: &Path, idx: usize) -> Result<(), String> {
|
||||
let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
let mut bad = 0usize;
|
||||
for line in text.lines() {
|
||||
if self.block.add(line, idx).is_err() {
|
||||
bad += 1;
|
||||
}
|
||||
}
|
||||
if bad > 0 {
|
||||
tracing::warn!(file = %path.display(), skipped = bad, "ignored invalid blocklist lines");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Add a single block rule at runtime (API).
|
||||
pub fn add_rule(&mut self, list: &str, rule: &str) -> Result<(), String> {
|
||||
let idx = match self.lists.iter().position(|(n, _)| n == list) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
self.lists.push((list.to_string(), None));
|
||||
self.lists.len() - 1
|
||||
}
|
||||
};
|
||||
self.block.add(rule, idx)
|
||||
}
|
||||
|
||||
pub fn rule_count(&self) -> usize {
|
||||
self.block.len()
|
||||
}
|
||||
pub fn list_names(&self) -> Vec<String> {
|
||||
self.lists.iter().map(|(n, _)| n.clone()).collect()
|
||||
}
|
||||
|
||||
/// Check a name for `client`; `None` = not blocked.
|
||||
pub fn check(&self, name: &Name, client: IpAddr) -> Option<BlockMatch> {
|
||||
if self.block.len() == 0 || self.exempt.contains(client) {
|
||||
return None;
|
||||
}
|
||||
if self.allow.lookup(name).is_some() {
|
||||
return None;
|
||||
}
|
||||
let (idx, rule) = self.block.lookup(name)?;
|
||||
let (list, category) = self.lists.get(idx).cloned().unwrap_or_default();
|
||||
Some(BlockMatch { list, rule, category })
|
||||
}
|
||||
}
|
||||
|
||||
/// Names that must never be sent to the Internet (RFC 6761, RFC 6303, RFC 8375, RFC 6762).
|
||||
pub fn default_local_only() -> Vec<LowerName> {
|
||||
let mut v = vec![
|
||||
"localhost.",
|
||||
"invalid.",
|
||||
"test.",
|
||||
"local.",
|
||||
"home.arpa.",
|
||||
"onion.",
|
||||
"10.in-addr.arpa.",
|
||||
"168.192.in-addr.arpa.",
|
||||
"127.in-addr.arpa.",
|
||||
"254.169.in-addr.arpa.",
|
||||
"0.in-addr.arpa.",
|
||||
"d.f.ip6.arpa.",
|
||||
"8.e.f.ip6.arpa.",
|
||||
"9.e.f.ip6.arpa.",
|
||||
"a.e.f.ip6.arpa.",
|
||||
"b.e.f.ip6.arpa.",
|
||||
"1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa.",
|
||||
]
|
||||
.into_iter()
|
||||
.filter_map(|s| dns_core::names::parse_lower(s).ok())
|
||||
.collect::<Vec<_>>();
|
||||
for i in 16..32 {
|
||||
if let Ok(n) = dns_core::names::parse_lower(&format!("{i}.172.in-addr.arpa.")) {
|
||||
v.push(n);
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// Suffix matcher for local-only names.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct SuffixSet(HashSet<LowerName>);
|
||||
|
||||
impl SuffixSet {
|
||||
pub fn new(items: impl IntoIterator<Item = LowerName>) -> Self {
|
||||
Self(items.into_iter().collect())
|
||||
}
|
||||
pub fn matches(&self, name: &Name) -> bool {
|
||||
dns_core::names::ancestors(name).take_while(|a| !a.is_root()).any(|a| self.0.contains(&LowerName::new(&a)))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn n(s: &str) -> Name {
|
||||
Name::from_ascii(s).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rules() {
|
||||
let mut r = RuleSet::default();
|
||||
for l in
|
||||
["ads.example", "=only.example", "*.sub.example", "0.0.0.0 tracker.example # comment", "/^bad[0-9]+\\.example$/", "# x", ""]
|
||||
{
|
||||
r.add(l, 0).unwrap();
|
||||
}
|
||||
assert!(r.lookup(&n("ads.example.")).is_some());
|
||||
assert!(r.lookup(&n("x.ads.example.")).is_some());
|
||||
assert!(r.lookup(&n("only.example.")).is_some());
|
||||
assert!(r.lookup(&n("x.only.example.")).is_none());
|
||||
assert!(r.lookup(&n("sub.example.")).is_none());
|
||||
assert!(r.lookup(&n("a.sub.example.")).is_some());
|
||||
assert!(r.lookup(&n("TRACKER.example.")).is_some());
|
||||
assert!(r.lookup(&n("bad42.example.")).is_some());
|
||||
assert!(r.lookup(&n("good.example.")).is_none());
|
||||
assert!(r.add("/(a+)+$/", 0).is_ok()); // regex crate guarantees linear time
|
||||
assert!(r.add("/(/", 0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allow_overrides_block() {
|
||||
let mut p = BlockPolicy::default();
|
||||
p.add_rule("ads", "ads.example").unwrap();
|
||||
p.allow.add("good.ads.example", 0).unwrap();
|
||||
let c: IpAddr = "192.0.2.1".parse().unwrap();
|
||||
assert!(p.check(&n("x.ads.example."), c).is_some());
|
||||
assert!(p.check(&n("good.ads.example."), c).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rate_limit() {
|
||||
let cfg = Config::from_str_any("rate_limit: { per_client_qps: 1, burst: 3, slip: 2, exempt_clients: [] }", "t").unwrap();
|
||||
let rl = RateLimiter::from_config(&cfg).unwrap();
|
||||
let ip: IpAddr = "198.51.100.7".parse().unwrap();
|
||||
let d: Vec<_> = (0..6).map(|_| rl.check(ip)).collect();
|
||||
assert_eq!(&d[..3], &[RateDecision::Allow; 3]);
|
||||
assert!(d[3..].contains(&RateDecision::Slip));
|
||||
assert!(d[3..].contains(&RateDecision::Drop));
|
||||
// a different client is unaffected
|
||||
assert_eq!(rl.check("198.51.100.8".parse().unwrap()), RateDecision::Allow);
|
||||
// IPv6 clients in the same /56 share a bucket
|
||||
let a: IpAddr = "2001:db8:0:1::1".parse().unwrap();
|
||||
let b: IpAddr = "2001:db8:0:2::1".parse().unwrap();
|
||||
assert_eq!(prefix_key(a), prefix_key(b));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_limit_and_bounded_tracking() {
|
||||
let cfg = Config::from_str_any("rate_limit: { per_client_qps: 1000, burst: 1000, global_qps: 50 }", "t").unwrap();
|
||||
let rl = RateLimiter::from_config(&cfg).unwrap();
|
||||
// one second of global tokens, spread over many clients, then drops
|
||||
let allowed = (0..200u32).filter(|i| rl.check(IpAddr::from([10, 0, (i >> 8) as u8, *i as u8])) == RateDecision::Allow).count();
|
||||
assert!((49..=51).contains(&allowed), "allowed {allowed}");
|
||||
// tracking table stays bounded under a flood of distinct sources
|
||||
let cfg = Config::from_str_any("rate_limit: { per_client_qps: 1, burst: 1, global_qps: 1000000000 }", "t").unwrap();
|
||||
let rl = RateLimiter::from_config(&cfg).unwrap();
|
||||
for i in 0..300_000u32 {
|
||||
rl.check(IpAddr::from(i.to_be_bytes()));
|
||||
}
|
||||
let tracked: usize = rl.shards.iter().map(|s| s.lock().unwrap().len()).sum();
|
||||
assert!(tracked <= MAX_TRACKED, "tracked {tracked}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_only_and_views() {
|
||||
let s = SuffixSet::new(default_local_only());
|
||||
assert!(s.matches(&n("printer.local.")));
|
||||
assert!(s.matches(&n("1.1.168.192.in-addr.arpa.")));
|
||||
assert!(s.matches(&n("5.20.172.in-addr.arpa.")));
|
||||
assert!(!s.matches(&n("example.com.")));
|
||||
assert!(!s.matches(&n("5.15.172.in-addr.arpa.")));
|
||||
let cfg =
|
||||
Config::from_str_any("resolution: { views: [ {name: lan, clients: [\"10.0.0.0/8\"]}, {name: world, clients: [any]} ] }", "t")
|
||||
.unwrap();
|
||||
let v = Views::from_config(&cfg).unwrap();
|
||||
assert_eq!(v.classify("10.1.2.3".parse().unwrap()), Some("lan"));
|
||||
assert_eq!(v.classify("::ffff:10.1.2.3".parse().unwrap()), Some("lan"));
|
||||
assert_eq!(v.classify("8.8.8.8".parse().unwrap()), Some("world"));
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
[package]
|
||||
name = "dns-server"
|
||||
description = "EasyDNS server: listeners (UDP/TCP/DoT/DoH), dispatcher and hybrid routing"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
dns-core.workspace = true
|
||||
dns-config.workspace = true
|
||||
dns-authoritative.workspace = true
|
||||
dns-cache.workspace = true
|
||||
dns-recursive.workspace = true
|
||||
dns-forwarder.workspace = true
|
||||
dns-policy.workspace = true
|
||||
dns-metrics.workspace = true
|
||||
tokio.workspace = true
|
||||
hyper.workspace = true
|
||||
hyper-util.workspace = true
|
||||
http-body-util.workspace = true
|
||||
bytes.workspace = true
|
||||
socket2.workspace = true
|
||||
lru.workspace = true
|
||||
tracing.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
rustls.workspace = true
|
||||
tokio-rustls.workspace = true
|
||||
data-encoding.workspace = true
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
nix = { version = "0.30", default-features = false, features = ["socket", "uio", "net"] }
|
||||
|
||||
[dev-dependencies]
|
||||
rcgen.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,50 @@
|
||||
//! Append-only audit log of administrative actions (JSON lines).
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct AuditEvent<'a> {
|
||||
pub time_unix: u64,
|
||||
pub actor: &'a str,
|
||||
pub action: &'a str,
|
||||
pub target: &'a str,
|
||||
pub result: &'a str,
|
||||
pub detail: &'a str,
|
||||
}
|
||||
|
||||
pub struct AuditLog {
|
||||
path: Option<PathBuf>,
|
||||
lock: Mutex<()>,
|
||||
}
|
||||
|
||||
impl AuditLog {
|
||||
pub fn new(path: Option<PathBuf>) -> Self {
|
||||
Self { path, lock: Mutex::new(()) }
|
||||
}
|
||||
|
||||
pub fn record(&self, actor: &str, action: &str, target: &str, result: &str, detail: &str) {
|
||||
let ev = AuditEvent { time_unix: dns_core::tsig::now(), actor, action, target, result, detail };
|
||||
tracing::info!(target: "audit", actor, action, target, result, detail, "audit");
|
||||
let Some(p) = &self.path else { return };
|
||||
let _g = self.lock.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(d) = p.parent() {
|
||||
let _ = std::fs::create_dir_all(d);
|
||||
}
|
||||
if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(p)
|
||||
&& let Ok(line) = serde_json::to_string(&ev)
|
||||
{
|
||||
let _ = writeln!(f, "{line}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Last `n` audit entries (raw JSON lines).
|
||||
pub fn tail(&self, n: usize) -> Vec<serde_json::Value> {
|
||||
let Some(p) = &self.path else { return Vec::new() };
|
||||
let text = std::fs::read_to_string(p).unwrap_or_default();
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
lines[lines.len().saturating_sub(n)..].iter().filter_map(|l| serde_json::from_str(l).ok()).collect()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
//! Offline configuration + zone validation (`easydns check-config`, `econf`, `ezone`).
|
||||
use dns_config::{Config, ZoneType};
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Finding {
|
||||
pub severity: &'static str,
|
||||
pub location: String,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Finding {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}: {}: {}", self.severity, self.location, self.message)
|
||||
}
|
||||
}
|
||||
|
||||
/// Check one zone file: syntax, SOA/NS, CNAME conflicts, out-of-zone data, lint warnings.
|
||||
pub fn check_zone_file(path: &std::path::Path, origin: &str) -> Vec<Finding> {
|
||||
let mut out = Vec::new();
|
||||
let loc = format!("{} ({origin})", path.display());
|
||||
let name = match dns_core::names::parse_name(origin) {
|
||||
Ok(n) => n,
|
||||
Err(e) => {
|
||||
out.push(Finding { severity: "error", location: loc, message: e.to_string() });
|
||||
return out;
|
||||
}
|
||||
};
|
||||
let records = match dns_core::zonefile::parse_file(path, &name) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
out.push(Finding { severity: "error", location: loc, message: e.to_string() });
|
||||
return out;
|
||||
}
|
||||
};
|
||||
match dns_authoritative::Zone::from_records(&name, records) {
|
||||
Ok(z) => {
|
||||
for w in dns_authoritative::zone::lint(&z) {
|
||||
out.push(Finding { severity: "warning", location: loc.clone(), message: w });
|
||||
}
|
||||
out.push(Finding {
|
||||
severity: "info",
|
||||
location: loc,
|
||||
message: format!("zone {} loaded: serial {}, {} records", z.origin(), z.serial(), z.record_count()),
|
||||
});
|
||||
}
|
||||
Err(e) => out.push(Finding { severity: "error", location: loc, message: e.to_string() }),
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Validate a configuration and all primary zone files it references.
|
||||
pub fn check_config(cfg: &Config) -> Vec<Finding> {
|
||||
let mut out: Vec<Finding> = cfg
|
||||
.validate()
|
||||
.into_iter()
|
||||
.map(|i| Finding { severity: if i.is_error() { "error" } else { "warning" }, location: i.path, message: i.message })
|
||||
.collect();
|
||||
for z in &cfg.zones {
|
||||
if z.zone_type == ZoneType::Primary
|
||||
&& let Some(f) = &z.file
|
||||
{
|
||||
let p = cfg.zone_file_path(f);
|
||||
if p.is_file() {
|
||||
out.extend(check_zone_file(&p, &z.name));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Err(e) = cfg.key_ring()
|
||||
&& !out.iter().any(|f| f.location.starts_with("keys"))
|
||||
{
|
||||
out.push(Finding { severity: "warning", location: "keys".into(), message: e });
|
||||
}
|
||||
if cfg.recursion.enabled
|
||||
&& let Err(e) = dns_recursive::hints::load(cfg.recursion.root_hints.as_ref().map(|p| cfg.resolve_path(p)).as_deref())
|
||||
.and_then(|h| dns_recursive::hints::root_servers(&h).map(|_| ()))
|
||||
{
|
||||
out.push(Finding { severity: "error", location: "recursion.root_hints".into(), message: e });
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
//! Coalescing of identical in-flight resolutions.
|
||||
//!
|
||||
//! When many clients ask for the same name/type at the same time and the answer is not
|
||||
//! cached, only the first query (the *leader*) goes out to upstreams or the Internet;
|
||||
//! the others wait for the leader's answer. This cuts outgoing traffic during bursts
|
||||
//! and cache-miss storms, and narrows the window for cache-poisoning attempts that rely
|
||||
//! on many parallel outstanding queries for the same name (the "birthday" attack).
|
||||
//!
|
||||
//! If the leader's future is dropped before it finishes, waiters are released and each
|
||||
//! resolves on its own, so a cancelled request never leaves others hanging.
|
||||
use std::collections::HashMap;
|
||||
use std::future::Future;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use dns_core::answer::Answer;
|
||||
use dns_core::proto::rr::{LowerName, RecordType};
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
/// What makes two resolutions interchangeable.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct FlightKey {
|
||||
/// Route (cache namespace): recursion and each forwarder pool are separate.
|
||||
pub ns: u16,
|
||||
pub name: LowerName,
|
||||
pub rtype: RecordType,
|
||||
pub dnssec_ok: bool,
|
||||
pub cd: bool,
|
||||
}
|
||||
|
||||
/// Waiters per in-flight key; beyond this, queries resolve independently (bounds memory).
|
||||
const MAX_WAITERS: usize = 1024;
|
||||
|
||||
type Waiters = Vec<oneshot::Sender<Answer>>;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Coalescer {
|
||||
inflight: Mutex<HashMap<FlightKey, Waiters>>,
|
||||
}
|
||||
|
||||
/// Removes the leader's entry on completion or cancellation.
|
||||
struct Leader<'a> {
|
||||
c: &'a Coalescer,
|
||||
key: Option<FlightKey>,
|
||||
}
|
||||
|
||||
impl Leader<'_> {
|
||||
fn finish(mut self, answer: &Answer) {
|
||||
if let Some(key) = self.key.take() {
|
||||
let waiters = self.c.lock().remove(&key).unwrap_or_default();
|
||||
for w in waiters {
|
||||
let _ = w.send(answer.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Leader<'_> {
|
||||
fn drop(&mut self) {
|
||||
// cancelled: dropping the senders wakes the waiters, which then resolve themselves
|
||||
if let Some(key) = self.key.take() {
|
||||
self.c.lock().remove(&key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum Role {
|
||||
Leader,
|
||||
Waiter(oneshot::Receiver<Answer>),
|
||||
Alone,
|
||||
}
|
||||
|
||||
impl Coalescer {
|
||||
fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<FlightKey, Waiters>> {
|
||||
self.inflight.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// Number of distinct resolutions currently in flight.
|
||||
pub fn in_flight(&self) -> usize {
|
||||
self.lock().len()
|
||||
}
|
||||
|
||||
/// Run `resolve` for `key`, or share the result of an identical call already running.
|
||||
pub async fn run<F, Fut>(&self, key: FlightKey, resolve: F) -> Answer
|
||||
where
|
||||
F: FnOnce() -> Fut,
|
||||
Fut: Future<Output = Answer>,
|
||||
{
|
||||
let role = {
|
||||
let mut map = self.lock();
|
||||
match map.get_mut(&key) {
|
||||
Some(w) if w.len() < MAX_WAITERS => {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
w.push(tx);
|
||||
Role::Waiter(rx)
|
||||
}
|
||||
Some(_) => Role::Alone,
|
||||
None => {
|
||||
map.insert(key.clone(), Vec::new());
|
||||
Role::Leader
|
||||
}
|
||||
}
|
||||
};
|
||||
match role {
|
||||
Role::Waiter(rx) => match rx.await {
|
||||
Ok(a) => a,
|
||||
Err(_) => resolve().await, // leader was cancelled
|
||||
},
|
||||
Role::Alone => resolve().await,
|
||||
Role::Leader => {
|
||||
let guard = Leader { c: self, key: Some(key) };
|
||||
let a = resolve().await;
|
||||
guard.finish(&a);
|
||||
a
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use dns_core::answer::Source;
|
||||
use dns_core::proto::op::ResponseCode;
|
||||
use dns_core::proto::rr::Name;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
fn key(n: &str) -> FlightKey {
|
||||
FlightKey { ns: 0, name: LowerName::new(&Name::from_ascii(n).unwrap()), rtype: RecordType::A, dnssec_ok: false, cd: false }
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn identical_queries_resolve_once() {
|
||||
let c = Arc::new(Coalescer::default());
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let mut hs = Vec::new();
|
||||
for _ in 0..50 {
|
||||
let (c, calls) = (Arc::clone(&c), Arc::clone(&calls));
|
||||
hs.push(tokio::spawn(async move {
|
||||
c.run(key("a.example."), || async {
|
||||
calls.fetch_add(1, Ordering::SeqCst);
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
Answer::new(ResponseCode::NoError, Source::Recursive)
|
||||
})
|
||||
.await
|
||||
}));
|
||||
}
|
||||
for h in hs {
|
||||
assert_eq!(h.await.unwrap().rcode, ResponseCode::NoError);
|
||||
}
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(c.in_flight(), 0);
|
||||
// different keys are not merged
|
||||
let a = c.run(key("b.example."), || async { Answer::new(ResponseCode::NXDomain, Source::Recursive) }).await;
|
||||
assert_eq!(a.rcode, ResponseCode::NXDomain);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelled_leader_releases_waiters() {
|
||||
let c = Arc::new(Coalescer::default());
|
||||
let c1 = Arc::clone(&c);
|
||||
let leader = tokio::spawn(async move {
|
||||
c1.run(key("c.example."), || async {
|
||||
tokio::time::sleep(Duration::from_secs(60)).await;
|
||||
Answer::new(ResponseCode::NoError, Source::Recursive)
|
||||
})
|
||||
.await
|
||||
});
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
let c2 = Arc::clone(&c);
|
||||
let waiter =
|
||||
tokio::spawn(
|
||||
async move { c2.run(key("c.example."), || async { Answer::new(ResponseCode::ServFail, Source::Recursive) }).await },
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
leader.abort();
|
||||
let a = tokio::time::timeout(Duration::from_secs(2), waiter).await.unwrap().unwrap();
|
||||
assert_eq!(a.rcode, ResponseCode::ServFail); // resolved on its own
|
||||
assert_eq!(c.in_flight(), 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,688 @@
|
||||
//! Message dispatcher: one request in, zero or more encoded responses out.
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
use dns_authoritative::store::TransferEvent;
|
||||
use dns_authoritative::{Lookup, ZoneKind};
|
||||
use dns_config::BlockAction;
|
||||
use dns_core::answer::{Answer, Source};
|
||||
use dns_core::proto::op::{Message, OpCode, ResponseCode};
|
||||
use dns_core::proto::rr::rdata::{A, AAAA, TXT};
|
||||
use dns_core::proto::rr::{DNSClass, LowerName, Name, RData, Record, RecordType};
|
||||
use dns_core::tsig::{ResponseSigner, TsigStatus, verify_request};
|
||||
use dns_core::wire;
|
||||
use dns_policy::RateDecision;
|
||||
|
||||
use crate::runtime::{Runtime, Shared};
|
||||
|
||||
/// Transport a request arrived on.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Transport {
|
||||
Udp,
|
||||
Tcp,
|
||||
Dot,
|
||||
Doh,
|
||||
}
|
||||
|
||||
impl Transport {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Transport::Udp => "udp",
|
||||
Transport::Tcp => "tcp",
|
||||
Transport::Dot => "dot",
|
||||
Transport::Doh => "doh",
|
||||
}
|
||||
}
|
||||
fn stream(self) -> bool {
|
||||
self != Transport::Udp
|
||||
}
|
||||
}
|
||||
|
||||
/// Encoded reply.
|
||||
#[derive(Debug)]
|
||||
pub enum Reply {
|
||||
None,
|
||||
One(Vec<u8>),
|
||||
Many(Vec<Vec<u8>>),
|
||||
}
|
||||
|
||||
/// Max CNAME hops when a local answer continues into resolution.
|
||||
const MAX_CROSS_CNAME: usize = 8;
|
||||
|
||||
fn anonymize(ip: IpAddr) -> String {
|
||||
match dns_policy::canonical_ip(ip) {
|
||||
IpAddr::V4(v4) => {
|
||||
let o = v4.octets();
|
||||
format!("{}.{}.{}.0/24", o[0], o[1], o[2])
|
||||
}
|
||||
IpAddr::V6(v6) => {
|
||||
let s = v6.segments();
|
||||
format!("{:x}:{:x}:{:x}::/48", s[0], s[1], s[2])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the slow path learnt about cacheability of its response.
|
||||
#[derive(Default)]
|
||||
struct CacheSlot {
|
||||
/// Set by `Ctx::finish` for responses that may be stored in the packet cache.
|
||||
info: std::sync::OnceLock<(Source, &'static str)>,
|
||||
/// Data from resolution was mixed into an authoritative answer (CNAME leaving a zone).
|
||||
resolved: std::sync::atomic::AtomicBool,
|
||||
}
|
||||
|
||||
struct Ctx<'a> {
|
||||
shared: &'a Shared,
|
||||
rt: Arc<Runtime>,
|
||||
client: SocketAddr,
|
||||
transport: Transport,
|
||||
tsig: TsigStatus,
|
||||
start: Instant,
|
||||
slot: &'a CacheSlot,
|
||||
}
|
||||
|
||||
impl Ctx<'_> {
|
||||
fn ip(&self) -> IpAddr {
|
||||
dns_policy::canonical_ip(self.client.ip())
|
||||
}
|
||||
|
||||
fn encode(&self, req: &Message, mut resp: Message) -> Reply {
|
||||
if let TsigStatus::Valid { key, mac } = &self.tsig {
|
||||
let mut signer = ResponseSigner::new(key.clone(), mac.clone());
|
||||
return match signer.sign(&mut resp) {
|
||||
Ok(b) if !self.transport.stream() && b.len() > wire::client_udp_limit(req, self.rt.cfg.server.max_udp_payload) => {
|
||||
let mut t = resp.clone();
|
||||
t.answers.clear();
|
||||
t.authorities.clear();
|
||||
t.additionals.clear();
|
||||
t.metadata.truncation = true;
|
||||
signer = ResponseSigner::new(key.clone(), mac.clone());
|
||||
signer.sign(&mut t).map(Reply::One).unwrap_or(Reply::None)
|
||||
}
|
||||
Ok(b) => Reply::One(b),
|
||||
Err(e) => {
|
||||
tracing::error!(error = %e, "failed to sign response");
|
||||
Reply::None
|
||||
}
|
||||
};
|
||||
}
|
||||
let bytes = if self.transport.stream() {
|
||||
wire::encode_tcp(&resp)
|
||||
} else {
|
||||
wire::encode_udp(&resp, wire::client_udp_limit(req, self.rt.cfg.server.max_udp_payload))
|
||||
};
|
||||
bytes.map(Reply::One).unwrap_or(Reply::None)
|
||||
}
|
||||
|
||||
fn finish(&self, req: &Message, resp: Message, source: Source, note: Option<&str>) -> Reply {
|
||||
let rcode = resp.metadata.response_code;
|
||||
let rcs = match rcode {
|
||||
ResponseCode::NoError => "NOERROR",
|
||||
ResponseCode::FormErr => "FORMERR",
|
||||
ResponseCode::ServFail => "SERVFAIL",
|
||||
ResponseCode::NXDomain => "NXDOMAIN",
|
||||
ResponseCode::NotImp => "NOTIMP",
|
||||
ResponseCode::Refused => "REFUSED",
|
||||
_ => "OTHER",
|
||||
};
|
||||
self.shared.metrics.response(rcs, source.as_str(), self.start.elapsed());
|
||||
if matches!(self.tsig, TsigStatus::Unsigned)
|
||||
&& matches!(rcode, ResponseCode::NoError | ResponseCode::NXDomain)
|
||||
&& matches!(
|
||||
source,
|
||||
Source::Authoritative | Source::Cache | Source::Recursive | Source::Forward | Source::Blocked | Source::Local
|
||||
)
|
||||
{
|
||||
let _ = self.slot.info.set((source, rcs));
|
||||
}
|
||||
if self.rt.cfg.logging.query_log {
|
||||
let client = if self.rt.cfg.logging.anonymize_clients { anonymize(self.client.ip()) } else { self.client.ip().to_string() };
|
||||
let (qn, qt) = req.queries.first().map(|q| (q.name.to_string(), q.query_type.to_string())).unwrap_or_default();
|
||||
tracing::info!(target: "query", client, qname = %qn, qtype = %qt, rcode = rcs, source = source.as_str(),
|
||||
transport = self.transport.as_str(), latency_us = self.start.elapsed().as_micros() as u64, note = note.unwrap_or(""), "query");
|
||||
}
|
||||
self.encode(req, resp)
|
||||
}
|
||||
}
|
||||
|
||||
/// Outcome of the UDP fast path in the listener.
|
||||
pub enum FastPath {
|
||||
/// Answered from the packet cache: send these bytes.
|
||||
Hit(Vec<u8>),
|
||||
/// Not answered; pass the rate-limit decision (if one was taken) to [`handle_with`].
|
||||
Miss(Option<RateDecision>),
|
||||
}
|
||||
|
||||
fn cache_hit(shared: &Shared, raw: &[u8], profile: u64, transport: Transport, start: Instant) -> Option<Vec<u8>> {
|
||||
let hit = shared.packet_cache.lookup(raw, profile)?;
|
||||
let qtype: &'static str = RecordType::from(hit.qtype).into();
|
||||
shared.metrics.query(transport.as_str(), qtype);
|
||||
shared.metrics.response(hit.rcode, hit.source, start.elapsed());
|
||||
Some(hit.bytes)
|
||||
}
|
||||
|
||||
/// UDP fast path, run inline in the receive loop: rate limit + packet cache, no task,
|
||||
/// no parsing. Anything else goes to [`handle_with`].
|
||||
pub fn udp_fast_path(shared: &Shared, raw: &[u8], client: SocketAddr) -> FastPath {
|
||||
let rt = shared.rt();
|
||||
if !shared.packet_cache.enabled() || rt.cfg.logging.query_log {
|
||||
return FastPath::Miss(None);
|
||||
}
|
||||
let decision = rt.ratelimit.check(client.ip());
|
||||
if decision == RateDecision::Allow {
|
||||
let profile = rt.client_profile(client.ip(), false);
|
||||
if let Some(b) = cache_hit(shared, raw, profile, Transport::Udp, Instant::now()) {
|
||||
return FastPath::Hit(b);
|
||||
}
|
||||
}
|
||||
FastPath::Miss(Some(decision))
|
||||
}
|
||||
|
||||
/// Handle one raw request.
|
||||
pub async fn handle(shared: &Shared, raw: &[u8], client: SocketAddr, transport: Transport) -> Reply {
|
||||
handle_with(shared, raw, client, transport, None).await
|
||||
}
|
||||
|
||||
/// Handle one raw request. `rl` is a rate-limit decision already taken by the caller,
|
||||
/// who then also already missed the packet cache ([`udp_fast_path`]).
|
||||
pub async fn handle_with(shared: &Shared, raw: &[u8], client: SocketAddr, transport: Transport, rl: Option<RateDecision>) -> Reply {
|
||||
let rt = shared.rt();
|
||||
let start = Instant::now();
|
||||
let pc = &shared.packet_cache;
|
||||
let use_pc = pc.enabled() && !rt.cfg.logging.query_log;
|
||||
let mut rl = rl;
|
||||
let mut profile = 0;
|
||||
if use_pc {
|
||||
profile = rt.client_profile(client.ip(), transport != Transport::Udp);
|
||||
if rl.is_none() {
|
||||
let decision = if transport == Transport::Udp { rt.ratelimit.check(client.ip()) } else { RateDecision::Allow };
|
||||
if decision == RateDecision::Allow {
|
||||
if let Some(b) = cache_hit(shared, raw, profile, transport, start) {
|
||||
return Reply::One(b);
|
||||
}
|
||||
}
|
||||
rl = Some(decision);
|
||||
}
|
||||
}
|
||||
// read before computing: a zone change during the computation makes the entry stale
|
||||
let generation = pc.current_generation();
|
||||
let slot = CacheSlot::default();
|
||||
let reply = handle_inner(shared, Arc::clone(&rt), raw, client, transport, rl, &slot, start).await;
|
||||
if use_pc && let (Reply::One(bytes), Some((source, rcode))) = (&reply, slot.info.get()) {
|
||||
let kind = match source {
|
||||
Source::Authoritative | Source::Local if !slot.resolved.load(std::sync::atomic::Ordering::Relaxed) => {
|
||||
crate::packet_cache::Kind::Authoritative
|
||||
}
|
||||
_ => crate::packet_cache::Kind::Resolved,
|
||||
};
|
||||
// resolved data only when caching is enabled at all
|
||||
if kind == crate::packet_cache::Kind::Authoritative || rt.cfg.cache.enabled {
|
||||
pc.store(raw, profile, bytes, crate::packet_cache::StoreMeta { kind, generation, rcode, source: source.as_str() });
|
||||
}
|
||||
}
|
||||
reply
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn handle_inner(
|
||||
shared: &Shared,
|
||||
rt: Arc<Runtime>,
|
||||
raw: &[u8],
|
||||
client: SocketAddr,
|
||||
transport: Transport,
|
||||
rl: Option<RateDecision>,
|
||||
slot: &CacheSlot,
|
||||
start: Instant,
|
||||
) -> Reply {
|
||||
let req = match Message::from_vec(raw) {
|
||||
Ok(m) => m,
|
||||
Err(_) => {
|
||||
shared.metrics.malformed.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
return wire::formerr_from_raw(raw).map(Reply::One).unwrap_or(Reply::None);
|
||||
}
|
||||
};
|
||||
if req.metadata.message_type == dns_core::proto::op::MessageType::Response {
|
||||
return Reply::None;
|
||||
}
|
||||
if transport == Transport::Udp {
|
||||
match rl.unwrap_or_else(|| rt.ratelimit.check(client.ip())) {
|
||||
RateDecision::Allow => {}
|
||||
RateDecision::Slip => {
|
||||
shared.metrics.rate_limited.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let mut r = wire::response_for(&req);
|
||||
r.metadata.truncation = true;
|
||||
return r.to_vec().map(Reply::One).unwrap_or(Reply::None);
|
||||
}
|
||||
RateDecision::Drop => {
|
||||
shared.metrics.rate_limited.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
return Reply::None;
|
||||
}
|
||||
}
|
||||
}
|
||||
let tsig = verify_request(raw, &req, &rt.ring);
|
||||
let ctx = Ctx { shared, rt: Arc::clone(&rt), client, transport, tsig, start, slot };
|
||||
// static name: no allocation per query
|
||||
let qtype_s: &'static str = req.queries.first().map_or("OTHER", |q| q.query_type.into());
|
||||
shared.metrics.query(transport.as_str(), qtype_s);
|
||||
|
||||
let mut resp = wire::response_for(&req);
|
||||
if let TsigStatus::Invalid(e) = &ctx.tsig {
|
||||
shared.metrics.tsig_failures.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
tracing::warn!(client = %client, error = %e, "TSIG verification failed");
|
||||
resp.metadata.response_code = ResponseCode::NotAuth;
|
||||
return ctx.finish(&req, resp, Source::Refused, Some(e));
|
||||
}
|
||||
if req.edns.as_ref().is_some_and(|e| e.version() > 0) {
|
||||
resp.metadata.response_code = ResponseCode::BADVERS;
|
||||
return ctx.finish(&req, resp, Source::Local, None);
|
||||
}
|
||||
if req.queries.len() != 1 {
|
||||
resp.metadata.response_code = ResponseCode::FormErr;
|
||||
return ctx.finish(&req, resp, Source::Local, None);
|
||||
}
|
||||
match req.metadata.op_code {
|
||||
OpCode::Query => handle_query(&ctx, &req, resp).await,
|
||||
OpCode::Notify => handle_notify(&ctx, &req, resp),
|
||||
OpCode::Update => handle_update(&ctx, &req, resp),
|
||||
_ => {
|
||||
resp.metadata.response_code = ResponseCode::NotImp;
|
||||
ctx.finish(&req, resp, Source::Local, None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn chaos(ctx: &Ctx<'_>, req: &Message, mut resp: Message) -> Reply {
|
||||
let q = &req.queries[0];
|
||||
let name = q.name.to_lowercase().to_string();
|
||||
let txt = match (&ctx.rt.cfg.server.identity, name.as_str(), q.query_type) {
|
||||
(Some(id), "id.server." | "hostname.bind.", RecordType::TXT) => Some(id.clone()),
|
||||
(Some(_), "version.bind." | "version.server.", RecordType::TXT) => Some(format!("EasyDNS {}", ctx.shared.version)),
|
||||
_ => None,
|
||||
};
|
||||
match txt {
|
||||
Some(t) => {
|
||||
let mut r = Record::from_rdata(q.name.clone(), 0, RData::TXT(TXT::new(vec![t])));
|
||||
r.dns_class = DNSClass::CH;
|
||||
resp.metadata.authoritative = true;
|
||||
resp.add_answer(r);
|
||||
}
|
||||
None => resp.metadata.response_code = ResponseCode::Refused,
|
||||
}
|
||||
ctx.finish(req, resp, Source::Local, None)
|
||||
}
|
||||
|
||||
async fn handle_query(ctx: &Ctx<'_>, req: &Message, mut resp: Message) -> Reply {
|
||||
let q = req.queries[0].clone();
|
||||
if q.query_class == DNSClass::CH {
|
||||
return chaos(ctx, req, resp);
|
||||
}
|
||||
if q.query_class != DNSClass::IN && q.query_class != DNSClass::ANY {
|
||||
resp.metadata.response_code = ResponseCode::Refused;
|
||||
return ctx.finish(req, resp, Source::Refused, None);
|
||||
}
|
||||
if matches!(q.query_type, RecordType::AXFR | RecordType::IXFR) {
|
||||
return handle_xfr(ctx, req, resp);
|
||||
}
|
||||
if matches!(q.query_type, RecordType::OPT | RecordType::TSIG) {
|
||||
resp.metadata.response_code = ResponseCode::FormErr;
|
||||
return ctx.finish(req, resp, Source::Local, None);
|
||||
}
|
||||
let ip = ctx.ip();
|
||||
let rt = &ctx.rt;
|
||||
let dnssec_ok = req.edns.as_ref().is_some_and(|e| e.flags().dnssec_ok);
|
||||
let may_resolve = rt.router.can_resolve() && rt.recursion_acl.contains(ip);
|
||||
resp.metadata.recursion_available = may_resolve;
|
||||
let view = rt.views.classify(ip);
|
||||
let qname = q.name.clone();
|
||||
|
||||
// 1. Local authoritative data.
|
||||
if let Some(entry) = rt.zones.find(&LowerName::new(&qname), view) {
|
||||
let Some(zone) = entry.current() else {
|
||||
resp.metadata.response_code = ResponseCode::ServFail;
|
||||
return ctx.finish(req, resp, Source::Authoritative, Some("zone not loaded or expired"));
|
||||
};
|
||||
match zone.lookup(&qname, q.query_type, dnssec_ok) {
|
||||
Lookup::Answer { answers, additional, authority, .. } => {
|
||||
resp.metadata.authoritative = true;
|
||||
resp.answers = answers;
|
||||
resp.authorities = authority;
|
||||
resp.additionals = additional;
|
||||
}
|
||||
Lookup::NoData { soa, proof } => {
|
||||
resp.metadata.authoritative = true;
|
||||
resp.authorities.push(soa);
|
||||
resp.authorities.extend(proof);
|
||||
}
|
||||
Lookup::NxDomain { soa, answers, proof } => {
|
||||
resp.metadata.authoritative = true;
|
||||
resp.metadata.response_code = ResponseCode::NXDomain;
|
||||
resp.answers = answers;
|
||||
resp.authorities.push(soa);
|
||||
resp.authorities.extend(proof);
|
||||
}
|
||||
Lookup::Referral { ns, glue, ds } => {
|
||||
if may_resolve && req.metadata.recursion_desired {
|
||||
let a = rt.router.resolve(&qname, q.query_type, ip, dnssec_ok, req.metadata.checking_disabled).await;
|
||||
return finish_answer(ctx, req, resp, a);
|
||||
}
|
||||
resp.authorities = ns;
|
||||
resp.authorities.extend(ds);
|
||||
resp.additionals = glue;
|
||||
}
|
||||
Lookup::CnameOut { answers, target } => {
|
||||
resp.metadata.authoritative = true;
|
||||
resp.answers = answers;
|
||||
if may_resolve && req.metadata.recursion_desired {
|
||||
ctx.slot.resolved.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
let a = resolve_target(ctx, &target, q.query_type, ip, dnssec_ok, req.metadata.checking_disabled, view).await;
|
||||
let negative = a.answers_empty_negative();
|
||||
resp.answers.extend(a.answers);
|
||||
resp.metadata.response_code = a.rcode;
|
||||
if negative {
|
||||
resp.authorities = a.authority;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return ctx.finish(req, resp, Source::Authoritative, None);
|
||||
}
|
||||
|
||||
// 2. Resolution is only for permitted clients.
|
||||
if !may_resolve || !req.metadata.recursion_desired {
|
||||
resp.metadata.response_code = ResponseCode::Refused;
|
||||
return ctx.finish(req, resp, Source::Refused, None);
|
||||
}
|
||||
// 3. Local-only names never leave the host.
|
||||
if rt.local_only.matches(&qname) {
|
||||
resp.metadata.response_code = ResponseCode::NXDomain;
|
||||
return ctx.finish(req, resp, Source::Local, Some("local-only name"));
|
||||
}
|
||||
// 4. Policy.
|
||||
if let Some(m) = rt.policy.check(&qname, ip) {
|
||||
ctx.shared.metrics.blocked.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
if rt.policy.log {
|
||||
tracing::info!(target: "policy", qname = %qname, list = %m.list, rule = %m.rule, category = m.category.as_deref().unwrap_or(""), "blocked");
|
||||
}
|
||||
apply_block(rt, &q.name, q.query_type, &mut resp);
|
||||
let note = format!("blocked by {} ({})", m.list, m.rule);
|
||||
return ctx.finish(req, resp, Source::Blocked, Some(¬e));
|
||||
}
|
||||
// 5. Forwarding / recursion.
|
||||
let a = rt.router.resolve(&qname, q.query_type, ip, dnssec_ok, req.metadata.checking_disabled).await;
|
||||
finish_answer(ctx, req, resp, a)
|
||||
}
|
||||
|
||||
trait NegExt {
|
||||
fn answers_empty_negative(&self) -> bool;
|
||||
}
|
||||
impl NegExt for Answer {
|
||||
fn answers_empty_negative(&self) -> bool {
|
||||
self.answers.is_empty() && matches!(self.rcode, ResponseCode::NXDomain | ResponseCode::NoError)
|
||||
}
|
||||
}
|
||||
|
||||
/// Continue a CNAME chain that left a local zone: other local zones first, then resolution.
|
||||
async fn resolve_target(
|
||||
ctx: &Ctx<'_>,
|
||||
target: &Name,
|
||||
qtype: RecordType,
|
||||
ip: IpAddr,
|
||||
dnssec_ok: bool,
|
||||
cd: bool,
|
||||
view: Option<&str>,
|
||||
) -> Answer {
|
||||
let mut out = Answer::new(ResponseCode::NoError, Source::Authoritative);
|
||||
let mut cur = target.clone();
|
||||
for _ in 0..MAX_CROSS_CNAME {
|
||||
if let Some(entry) = ctx.rt.zones.find(&LowerName::new(&cur), view) {
|
||||
let Some(zone) = entry.current() else { return Answer::servfail(Source::Authoritative, "zone unavailable") };
|
||||
match zone.lookup(&cur, qtype, dnssec_ok) {
|
||||
Lookup::Answer { answers, .. } => {
|
||||
out.answers.extend(answers);
|
||||
return out;
|
||||
}
|
||||
Lookup::CnameOut { answers, target } => {
|
||||
out.answers.extend(answers);
|
||||
cur = target;
|
||||
continue;
|
||||
}
|
||||
Lookup::NoData { soa, .. } => {
|
||||
out.authority.push(soa);
|
||||
return out;
|
||||
}
|
||||
Lookup::NxDomain { soa, answers, .. } => {
|
||||
out.answers.extend(answers);
|
||||
out.authority.push(soa);
|
||||
out.rcode = ResponseCode::NXDomain;
|
||||
return out;
|
||||
}
|
||||
Lookup::Referral { .. } => break,
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ctx.rt.local_only.matches(&cur) || ctx.rt.policy.check(&cur, ip).is_some() {
|
||||
out.rcode = ResponseCode::NXDomain;
|
||||
return out;
|
||||
}
|
||||
let mut a = ctx.rt.router.resolve(&cur, qtype, ip, dnssec_ok, cd).await;
|
||||
out.answers.append(&mut a.answers);
|
||||
out.authority = a.authority;
|
||||
out.rcode = a.rcode;
|
||||
out
|
||||
}
|
||||
|
||||
fn apply_block(rt: &Runtime, name: &Name, qtype: RecordType, resp: &mut Message) {
|
||||
let ttl = rt.policy.ttl;
|
||||
match rt.policy.action {
|
||||
BlockAction::Nxdomain => resp.metadata.response_code = ResponseCode::NXDomain,
|
||||
BlockAction::Refused => resp.metadata.response_code = ResponseCode::Refused,
|
||||
BlockAction::Null | BlockAction::Address => {
|
||||
let (v4, v6) = if rt.policy.action == BlockAction::Null {
|
||||
(std::net::Ipv4Addr::UNSPECIFIED, std::net::Ipv6Addr::UNSPECIFIED)
|
||||
} else {
|
||||
(rt.policy.v4.unwrap_or(std::net::Ipv4Addr::UNSPECIFIED), rt.policy.v6.unwrap_or(std::net::Ipv6Addr::UNSPECIFIED))
|
||||
};
|
||||
match qtype {
|
||||
RecordType::A => resp.add_answer(Record::from_rdata(name.clone(), ttl, RData::A(A::from(v4)))),
|
||||
RecordType::AAAA => resp.add_answer(Record::from_rdata(name.clone(), ttl, RData::AAAA(AAAA::from(v6)))),
|
||||
_ => resp, // NODATA
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn finish_answer(ctx: &Ctx<'_>, req: &Message, mut resp: Message, mut a: Answer) -> Reply {
|
||||
if a.security == dns_core::answer::Security::Bogus && !req.metadata.checking_disabled {
|
||||
// RFC 4035 §5.5: bogus data is not returned unless the client disabled checking.
|
||||
ctx.shared.metrics.dnssec_bogus.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
resp.metadata.response_code = ResponseCode::ServFail;
|
||||
resp.metadata.authoritative = false;
|
||||
let note = a.note.take().unwrap_or_else(|| "DNSSEC validation failed".into());
|
||||
return ctx.finish(req, resp, a.source, Some(¬e));
|
||||
}
|
||||
resp.metadata.response_code = a.rcode;
|
||||
resp.metadata.authoritative = false; // never AA for resolved data
|
||||
resp.answers = a.answers;
|
||||
resp.authorities = a.authority;
|
||||
resp.additionals = a.additional;
|
||||
let dnssec_ok = req.edns.as_ref().is_some_and(|e| e.flags().dnssec_ok);
|
||||
if !dnssec_ok {
|
||||
let strip =
|
||||
|v: &mut Vec<Record>| v.retain(|r| !matches!(r.record_type(), RecordType::RRSIG | RecordType::NSEC | RecordType::NSEC3));
|
||||
strip(&mut resp.answers);
|
||||
strip(&mut resp.authorities);
|
||||
}
|
||||
resp.metadata.authentic_data = a.security == dns_core::answer::Security::Secure && (dnssec_ok || req.metadata.authentic_data);
|
||||
match a.security {
|
||||
dns_core::answer::Security::Secure => ctx.shared.metrics.dnssec_secure.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
|
||||
dns_core::answer::Security::Insecure => ctx.shared.metrics.dnssec_insecure.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
|
||||
dns_core::answer::Security::Bogus => ctx.shared.metrics.dnssec_bogus.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
|
||||
dns_core::answer::Security::Indeterminate => 0,
|
||||
};
|
||||
if a.source == Source::Forward || a.source == Source::Recursive {
|
||||
if a.rcode == ResponseCode::ServFail {
|
||||
ctx.shared.metrics.upstream_errors.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
} else {
|
||||
ctx.shared.metrics.upstream_latency.observe(ctx.start.elapsed());
|
||||
}
|
||||
}
|
||||
let note = a.note.clone();
|
||||
ctx.finish(req, resp, a.source, note.as_deref())
|
||||
}
|
||||
|
||||
fn xfr_refuse(ctx: &Ctx<'_>, req: &Message, mut resp: Message, rcode: ResponseCode, why: &str) -> Reply {
|
||||
ctx.shared.metrics.xfr_out_refused.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
tracing::warn!(client = %ctx.client, zone = %req.queries[0].name, reason = why, "zone transfer refused");
|
||||
resp.metadata.response_code = rcode;
|
||||
ctx.finish(req, resp, Source::Refused, Some(why))
|
||||
}
|
||||
|
||||
fn handle_xfr(ctx: &Ctx<'_>, req: &Message, mut resp: Message) -> Reply {
|
||||
let q = &req.queries[0];
|
||||
let rt = &ctx.rt;
|
||||
let Some(entry) = rt.zones.get(&q.name) else {
|
||||
return xfr_refuse(ctx, req, resp, ResponseCode::NotAuth, "not authoritative for zone");
|
||||
};
|
||||
// Authorisation: ACL, plus TSIG with the configured key when one is set.
|
||||
let ip = ctx.ip();
|
||||
let acl_ok = entry.transfer_allowed_from(ip);
|
||||
let allowed = match (&entry.transfer_key, &ctx.tsig) {
|
||||
(Some(k), TsigStatus::Valid { key, .. }) => key.name == k.name && (entry.transfer_acl.is_empty() || acl_ok),
|
||||
(Some(_), _) => false,
|
||||
(None, _) => acl_ok,
|
||||
};
|
||||
if !allowed {
|
||||
return xfr_refuse(ctx, req, resp, ResponseCode::Refused, "client not authorised for transfer");
|
||||
}
|
||||
let Some(zone) = entry.current() else {
|
||||
return xfr_refuse(ctx, req, resp, ResponseCode::ServFail, "zone not loaded");
|
||||
};
|
||||
let start = Instant::now();
|
||||
let (records, kind) = if q.query_type == RecordType::AXFR {
|
||||
if ctx.transport == Transport::Udp {
|
||||
return xfr_refuse(ctx, req, resp, ResponseCode::Refused, "AXFR over UDP");
|
||||
}
|
||||
(dns_authoritative::xfr::axfr_records(&zone), "AXFR")
|
||||
} else {
|
||||
let client_serial = req.authorities.iter().find_map(|r| match &r.data {
|
||||
RData::SOA(s) => Some(s.serial),
|
||||
_ => None,
|
||||
});
|
||||
let Some(cs) = client_serial else {
|
||||
resp.metadata.response_code = ResponseCode::FormErr;
|
||||
return ctx.finish(req, resp, Source::Authoritative, Some("IXFR without SOA"));
|
||||
};
|
||||
let journal = entry.journal.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (recs, incremental) = dns_authoritative::xfr::ixfr_records(&zone, &journal, cs);
|
||||
drop(journal);
|
||||
if ctx.transport == Transport::Udp && recs.len() > 1 {
|
||||
// Too big for UDP: tell the client to retry over TCP (RFC 1995 §2).
|
||||
resp.metadata.authoritative = true;
|
||||
resp.answers.push(zone.soa().clone());
|
||||
return ctx.finish(req, resp, Source::Authoritative, Some("IXFR via TCP"));
|
||||
}
|
||||
(recs, if incremental { "IXFR" } else { "IXFR(AXFR-style)" })
|
||||
};
|
||||
let count = records.len();
|
||||
let messages = dns_authoritative::xfr::chunk(req, records);
|
||||
let mut out = Vec::with_capacity(messages.len());
|
||||
let mut signer = match &ctx.tsig {
|
||||
TsigStatus::Valid { key, mac } => Some(ResponseSigner::new(key.clone(), mac.clone())),
|
||||
_ => None,
|
||||
};
|
||||
for mut m in messages {
|
||||
let b = match signer.as_mut() {
|
||||
Some(s) => s.sign(&mut m).ok(),
|
||||
None => m.to_vec().ok(),
|
||||
};
|
||||
match b {
|
||||
Some(b) => out.push(b),
|
||||
None => return xfr_refuse(ctx, req, wire::response_for(req), ResponseCode::ServFail, "encoding failed"),
|
||||
}
|
||||
}
|
||||
ctx.shared.metrics.xfr_out_ok.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
ctx.shared.metrics.response("NOERROR", "authoritative", start.elapsed());
|
||||
tracing::info!(zone = %entry.name, client = %ctx.client, kind, records = count, serial = zone.serial(), "zone transfer served");
|
||||
entry.record_transfer(TransferEvent {
|
||||
time_unix: dns_core::tsig::now(),
|
||||
direction: "out",
|
||||
kind: kind.into(),
|
||||
peer: ctx.client.to_string(),
|
||||
serial: Some(zone.serial()),
|
||||
records: count,
|
||||
ok: true,
|
||||
error: None,
|
||||
duration_ms: start.elapsed().as_millis() as u64,
|
||||
});
|
||||
Reply::Many(out)
|
||||
}
|
||||
|
||||
fn handle_notify(ctx: &Ctx<'_>, req: &Message, mut resp: Message) -> Reply {
|
||||
let q = &req.queries[0];
|
||||
resp.metadata.authoritative = true;
|
||||
let entry = ctx.rt.zones.get(&q.name).filter(|e| e.kind == ZoneKind::Secondary);
|
||||
let Some(entry) = entry else {
|
||||
ctx.shared.metrics.notify_refused.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
resp.metadata.response_code = ResponseCode::NotAuth;
|
||||
return ctx.finish(req, resp, Source::Refused, Some("NOTIFY for unknown zone"));
|
||||
};
|
||||
let ip = ctx.ip();
|
||||
let key_required = entry.client_key.is_some();
|
||||
let key_ok = match (&entry.client_key, &ctx.tsig) {
|
||||
(Some(k), TsigStatus::Valid { key, .. }) => key.name == k.name,
|
||||
(Some(_), _) => false,
|
||||
(None, _) => true,
|
||||
};
|
||||
// Accept from allowed sources; with a TSIG key configured a correctly signed NOTIFY is also accepted.
|
||||
if !(entry.notify_allowed_from(ip) && (key_ok || !key_required) || key_required && key_ok) {
|
||||
ctx.shared.metrics.notify_refused.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
tracing::warn!(zone = %entry.name, client = %ctx.client, "NOTIFY refused");
|
||||
resp.metadata.response_code = ResponseCode::Refused;
|
||||
return ctx.finish(req, resp, Source::Refused, Some("NOTIFY not allowed"));
|
||||
}
|
||||
ctx.shared.metrics.notify_received.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
tracing::info!(zone = %entry.name, client = %ctx.client, "NOTIFY received; scheduling refresh");
|
||||
entry.refresh_trigger.notify_one();
|
||||
ctx.finish(req, resp, Source::Authoritative, None)
|
||||
}
|
||||
|
||||
fn handle_update(ctx: &Ctx<'_>, req: &Message, mut resp: Message) -> Reply {
|
||||
let q = &req.queries[0];
|
||||
resp.answers.clear();
|
||||
let Some(entry) = ctx.rt.zones.get(&q.name) else {
|
||||
resp.metadata.response_code = ResponseCode::NotAuth;
|
||||
ctx.shared.metrics.updates_refused.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
return ctx.finish(req, resp, Source::Refused, Some("UPDATE for unknown zone"));
|
||||
};
|
||||
let actor = match &ctx.tsig {
|
||||
TsigStatus::Valid { key, .. } => format!("tsig:{} from {}", key.name, ctx.client.ip()),
|
||||
_ => format!("unsigned from {}", ctx.client.ip()),
|
||||
};
|
||||
let signer = match &ctx.tsig {
|
||||
TsigStatus::Valid { key, .. } => Some(&key.name),
|
||||
_ => None,
|
||||
};
|
||||
let who = dns_authoritative::update::Requester { signer, addr_ok: entry.update_allowed_from(ctx.ip()) };
|
||||
let outcome = dns_authoritative::update::apply(&entry, req, who);
|
||||
resp.metadata.response_code = outcome.rcode;
|
||||
let ok = outcome.rcode == ResponseCode::NoError;
|
||||
ctx.shared.audit.record(
|
||||
&actor,
|
||||
"dns-update",
|
||||
&entry.name.to_string(),
|
||||
if ok { "ok" } else { "refused" },
|
||||
&format!("{} (+{} -{} serial {:?})", outcome.reason, outcome.added, outcome.removed, outcome.new_serial),
|
||||
);
|
||||
if ok {
|
||||
ctx.shared.metrics.updates_ok.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
if outcome.added + outcome.removed > 0 {
|
||||
entry.send_notifies();
|
||||
}
|
||||
} else {
|
||||
ctx.shared.metrics.updates_refused.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
ctx.finish(req, resp, Source::Authoritative, Some(&outcome.reason))
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
//! EasyDNS server: ties the roles together.
|
||||
//!
|
||||
//! Query processing order (see docs/hybrid.md):
|
||||
//! 1. parse / FORMERR, drop responses, rate limit (UDP),
|
||||
//! 2. TSIG verification, opcode dispatch (QUERY / NOTIFY / UPDATE),
|
||||
//! 3. zone transfers (AXFR/IXFR) with ACL + TSIG,
|
||||
//! 4. most specific local authoritative zone visible in the client's view → AA answer,
|
||||
//! 5. clients without recursion permission → REFUSED (no open resolver, no leaks),
|
||||
//! 6. local-only names (RFC 6761/6303) → NXDOMAIN without leaving the host,
|
||||
//! 7. allow/block policy,
|
||||
//! 8. conditional forwarding (longest suffix), then the default resolution
|
||||
//! (recursive / forward / forward-then-recursive), with a per-route cache namespace.
|
||||
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
|
||||
|
||||
pub mod audit;
|
||||
pub mod check;
|
||||
pub mod coalesce;
|
||||
pub mod handler;
|
||||
pub mod listener;
|
||||
pub mod packet_cache;
|
||||
pub mod router;
|
||||
pub mod runtime;
|
||||
pub mod server;
|
||||
pub mod tls;
|
||||
|
||||
pub use runtime::{Runtime, Shared};
|
||||
pub use server::{Server, ServerHandle};
|
||||
@@ -0,0 +1,309 @@
|
||||
//! UDP and TCP listeners with backpressure and graceful shutdown.
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
use tokio::net::{TcpListener, UdpSocket};
|
||||
use tokio::sync::{Semaphore, watch};
|
||||
|
||||
use crate::handler::{Reply, Transport, handle};
|
||||
use crate::runtime::Shared;
|
||||
|
||||
/// Max TCP queries pipelined on one connection before it is closed.
|
||||
const MAX_QUERIES_PER_CONN: usize = 10_000;
|
||||
|
||||
/// Kernel socket buffer requested per UDP socket. The kernel caps it at
|
||||
/// net.core.{r,w}mem_max; memory is only consumed while packets are queued.
|
||||
const UDP_SOCKET_BUFFER: usize = 1 << 20;
|
||||
|
||||
/// Upper bound for `server.udp_sockets`.
|
||||
const MAX_UDP_SOCKETS: usize = 64;
|
||||
|
||||
fn udp_socket(addr: SocketAddr, reuse_port: bool) -> std::io::Result<std::net::UdpSocket> {
|
||||
use socket2::{Domain, Protocol, Socket, Type};
|
||||
let s = Socket::new(Domain::for_address(addr), Type::DGRAM, Some(Protocol::UDP))?;
|
||||
if addr.is_ipv6() {
|
||||
// like BIND: `[::]` serves IPv6 only, so it can be listed next to `0.0.0.0`
|
||||
s.set_only_v6(true)?;
|
||||
}
|
||||
#[cfg(all(unix, not(any(target_os = "solaris", target_os = "illumos", target_os = "cygwin"))))]
|
||||
if reuse_port {
|
||||
s.set_reuse_port(true)?;
|
||||
}
|
||||
#[cfg(not(all(unix, not(any(target_os = "solaris", target_os = "illumos", target_os = "cygwin")))))]
|
||||
let _ = reuse_port;
|
||||
// best effort: a larger queue absorbs bursts instead of dropping them
|
||||
let _ = s.set_recv_buffer_size(UDP_SOCKET_BUFFER);
|
||||
let _ = s.set_send_buffer_size(UDP_SOCKET_BUFFER);
|
||||
s.set_nonblocking(true)?;
|
||||
s.bind(&addr.into())?;
|
||||
Ok(s.into())
|
||||
}
|
||||
|
||||
/// Bind a TCP listener (SO_REUSEADDR for quick restarts, IPv6-only for `[::]` addresses).
|
||||
pub fn bind_tcp(addr: SocketAddr) -> std::io::Result<tokio::net::TcpListener> {
|
||||
use socket2::{Domain, Protocol, Socket, Type};
|
||||
let s = Socket::new(Domain::for_address(addr), Type::STREAM, Some(Protocol::TCP))?;
|
||||
if addr.is_ipv6() {
|
||||
s.set_only_v6(true)?;
|
||||
}
|
||||
#[cfg(unix)]
|
||||
s.set_reuse_address(true)?;
|
||||
s.set_nonblocking(true)?;
|
||||
s.bind(&addr.into())?;
|
||||
s.listen(1024)?;
|
||||
tokio::net::TcpListener::from_std(s.into())
|
||||
}
|
||||
|
||||
/// Number of UDP sockets to open per address for `server.udp_sockets` (0 = auto).
|
||||
pub fn udp_socket_count(configured: usize) -> usize {
|
||||
if configured > 0 {
|
||||
return configured.min(MAX_UDP_SOCKETS);
|
||||
}
|
||||
std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1).clamp(1, 16)
|
||||
}
|
||||
|
||||
/// Bind `count` UDP sockets on `addr` sharing one port via SO_REUSEPORT, so the kernel
|
||||
/// load-balances queries across them and each socket gets its own receive loop.
|
||||
/// Falls back to fewer sockets (at least one) when SO_REUSEPORT is unavailable.
|
||||
pub fn bind_udp_group(addr: SocketAddr, count: usize) -> std::io::Result<Vec<UdpSocket>> {
|
||||
let count = count.clamp(1, MAX_UDP_SOCKETS);
|
||||
let first = match udp_socket(addr, count > 1) {
|
||||
Ok(s) => s,
|
||||
Err(e) if count > 1 => {
|
||||
tracing::warn!(%addr, error = %e, "SO_REUSEPORT unavailable, using a single UDP socket");
|
||||
return Ok(vec![UdpSocket::from_std(udp_socket(addr, false)?)?]);
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
// with port 0 the kernel picked a port: the rest of the group must join that one
|
||||
let actual = first.local_addr()?;
|
||||
let mut socks = vec![UdpSocket::from_std(first)?];
|
||||
for _ in 1..count {
|
||||
match udp_socket(actual, true).and_then(UdpSocket::from_std) {
|
||||
Ok(s) => socks.push(s),
|
||||
Err(e) => {
|
||||
tracing::warn!(%actual, error = %e, opened = socks.len(), "could not open more UDP sockets");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(socks)
|
||||
}
|
||||
|
||||
/// Serve one UDP socket until shutdown. `inflight` is shared by all UDP sockets so
|
||||
/// `server.max_inflight` stays a server-wide bound. On Linux packets are received and
|
||||
/// cached answers sent in batches (`recvmmsg`/`sendmmsg`): one system call for up to
|
||||
/// [`batch::BATCH`] packets instead of two per query.
|
||||
pub async fn serve_udp(shared: Arc<Shared>, sock: Arc<UdpSocket>, inflight: Arc<Semaphore>, shutdown: watch::Receiver<bool>) {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
batch::serve(shared, sock, inflight, shutdown).await
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
serve_udp_simple(shared, sock, inflight, shutdown).await
|
||||
}
|
||||
}
|
||||
|
||||
/// Hand one received packet to the fast path or a task. Returns a cached answer to send.
|
||||
fn dispatch(shared: &Arc<Shared>, sock: &Arc<UdpSocket>, inflight: &Arc<Semaphore>, pkt: &[u8], peer: SocketAddr) -> Option<Vec<u8>> {
|
||||
if pkt.len() < 12 {
|
||||
return None;
|
||||
}
|
||||
let pre = match crate::handler::udp_fast_path(shared, pkt, peer) {
|
||||
crate::handler::FastPath::Hit(b) => return Some(b),
|
||||
crate::handler::FastPath::Miss(d) => d,
|
||||
};
|
||||
let Ok(permit) = Arc::clone(inflight).try_acquire_owned() else {
|
||||
// overloaded: shed load rather than queueing unboundedly
|
||||
shared.metrics.rate_limited.fetch_add(1, Ordering::Relaxed);
|
||||
return None;
|
||||
};
|
||||
let pkt = pkt.to_vec();
|
||||
let shared = Arc::clone(shared);
|
||||
let sock = Arc::clone(sock);
|
||||
tokio::spawn(async move {
|
||||
shared.metrics.inflight.fetch_add(1, Ordering::Relaxed);
|
||||
if let Reply::One(b) = crate::handler::handle_with(&shared, &pkt, peer, Transport::Udp, pre).await {
|
||||
let _ = sock.send_to(&b, peer).await;
|
||||
}
|
||||
shared.metrics.inflight.fetch_sub(1, Ordering::Relaxed);
|
||||
drop(permit);
|
||||
});
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod batch {
|
||||
use std::io::{IoSlice, IoSliceMut};
|
||||
use std::net::SocketAddr;
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::sync::Arc;
|
||||
|
||||
use nix::sys::socket::{MsgFlags, MultiHeaders, SockaddrStorage, recvmmsg, sendmmsg};
|
||||
use tokio::io::Interest;
|
||||
use tokio::net::UdpSocket;
|
||||
use tokio::sync::{Semaphore, watch};
|
||||
|
||||
use crate::runtime::Shared;
|
||||
|
||||
/// Packets per system call.
|
||||
pub const BATCH: usize = 32;
|
||||
const BUF: usize = 4096;
|
||||
|
||||
fn to_std(a: &SockaddrStorage) -> Option<SocketAddr> {
|
||||
if let Some(v4) = a.as_sockaddr_in() {
|
||||
return Some(SocketAddr::V4((*v4).into()));
|
||||
}
|
||||
a.as_sockaddr_in6().map(|v6| SocketAddr::V6((*v6).into()))
|
||||
}
|
||||
|
||||
/// Receive up to BATCH packets without blocking: (length, sender) per packet.
|
||||
/// (Headers are built per call: they hold raw pointers and must not live across `await`.)
|
||||
fn recv_batch(fd: i32, bufs: &mut [Vec<u8>]) -> std::io::Result<Vec<(usize, Option<SocketAddr>)>> {
|
||||
let mut hdrs = MultiHeaders::<SockaddrStorage>::preallocate(bufs.len(), None);
|
||||
let mut iovs: Vec<[IoSliceMut<'_>; 1]> = bufs.iter_mut().map(|b| [IoSliceMut::new(&mut b[..])]).collect();
|
||||
let res = recvmmsg(fd, &mut hdrs, iovs.iter_mut(), MsgFlags::MSG_DONTWAIT, None).map_err(std::io::Error::from)?;
|
||||
Ok(res.map(|m| (m.bytes, m.address.as_ref().and_then(to_std))).collect())
|
||||
}
|
||||
|
||||
/// Send as many replies as possible in one call; returns how many were sent.
|
||||
fn send_batch(fd: i32, out: &[(Vec<u8>, SocketAddr)]) -> std::io::Result<usize> {
|
||||
let mut hdrs = MultiHeaders::<SockaddrStorage>::preallocate(out.len(), None);
|
||||
let iovs: Vec<[IoSlice<'_>; 1]> = out.iter().map(|(b, _)| [IoSlice::new(b)]).collect();
|
||||
let addrs: Vec<Option<SockaddrStorage>> = out.iter().map(|(_, a)| Some(SockaddrStorage::from(*a))).collect();
|
||||
let res = sendmmsg(fd, &mut hdrs, iovs.iter(), addrs, [], MsgFlags::MSG_DONTWAIT).map_err(std::io::Error::from)?;
|
||||
Ok(res.count())
|
||||
}
|
||||
|
||||
pub async fn serve(shared: Arc<Shared>, sock: Arc<UdpSocket>, inflight: Arc<Semaphore>, mut shutdown: watch::Receiver<bool>) {
|
||||
let fd = sock.as_raw_fd();
|
||||
let mut bufs: Vec<Vec<u8>> = (0..BATCH).map(|_| vec![0u8; BUF]).collect();
|
||||
let mut out: Vec<(Vec<u8>, SocketAddr)> = Vec::with_capacity(BATCH);
|
||||
loop {
|
||||
tokio::select! {
|
||||
r = sock.readable() => if r.is_err() { continue },
|
||||
_ = shutdown.changed() => break,
|
||||
}
|
||||
let got = match sock.try_io(Interest::READABLE, || recv_batch(fd, &mut bufs)) {
|
||||
Ok(v) => v,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => continue,
|
||||
Err(e) if e.raw_os_error() == Some(nix::libc::ENOSYS) => {
|
||||
tracing::warn!("recvmmsg unavailable; using one system call per packet");
|
||||
return super::serve_udp_simple(shared, sock, inflight, shutdown).await;
|
||||
}
|
||||
Err(e) => {
|
||||
// ICMP errors (e.g. connection refused) surface here on Linux; keep serving.
|
||||
tracing::debug!(error = %e, "UDP recv error");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
for (i, (n, peer)) in got.into_iter().enumerate() {
|
||||
let Some(peer) = peer else { continue };
|
||||
if let Some(reply) = super::dispatch(&shared, &sock, &inflight, &bufs[i][..n], peer) {
|
||||
out.push((reply, peer));
|
||||
}
|
||||
}
|
||||
// cached answers of this batch: one sendmmsg; whatever does not fit goes one by one
|
||||
let mut sent = 0;
|
||||
while sent < out.len() {
|
||||
match sock.try_io(Interest::WRITABLE, || send_batch(fd, &out[sent..])) {
|
||||
Ok(0) => break,
|
||||
Ok(k) => sent += k,
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
for (b, peer) in out.drain(..).skip(sent) {
|
||||
let _ = sock.send_to(&b, peer).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One `recv_from`/`send_to` per packet (non-Linux, or kernels without `recvmmsg`).
|
||||
async fn serve_udp_simple(shared: Arc<Shared>, sock: Arc<UdpSocket>, inflight: Arc<Semaphore>, mut shutdown: watch::Receiver<bool>) {
|
||||
let mut buf = vec![0u8; 4096];
|
||||
loop {
|
||||
let (n, peer) = tokio::select! {
|
||||
r = sock.recv_from(&mut buf) => match r {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
// ICMP errors (e.g. connection refused) surface here on Linux; keep serving.
|
||||
tracing::debug!(error = %e, "UDP recv error");
|
||||
continue;
|
||||
}
|
||||
},
|
||||
_ = shutdown.changed() => break,
|
||||
};
|
||||
// fast path: repeated queries are answered inline from the packet cache
|
||||
if let Some(reply) = dispatch(&shared, &sock, &inflight, &buf[..n], peer) {
|
||||
let _ = sock.send_to(&reply, peer).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle one stream connection (TCP or TLS): length-prefixed messages, idle timeout.
|
||||
pub async fn serve_stream<S>(shared: Arc<Shared>, mut stream: S, peer: SocketAddr, transport: Transport, idle: Duration)
|
||||
where
|
||||
S: AsyncRead + AsyncWrite + Unpin,
|
||||
{
|
||||
shared.metrics.tcp_connections.fetch_add(1, Ordering::Relaxed);
|
||||
for _ in 0..MAX_QUERIES_PER_CONN {
|
||||
let msg = match tokio::time::timeout(idle, dns_core::client::read_tcp_msg(&mut stream)).await {
|
||||
Ok(Ok(m)) => m,
|
||||
_ => break,
|
||||
};
|
||||
let reply = handle(&shared, &msg, peer, transport).await;
|
||||
let ok = match reply {
|
||||
Reply::None => true,
|
||||
Reply::One(b) => dns_core::client::write_tcp_msg(&mut stream, &b).await.is_ok(),
|
||||
Reply::Many(v) => {
|
||||
let mut ok = true;
|
||||
for b in v {
|
||||
if dns_core::client::write_tcp_msg(&mut stream, &b).await.is_err() {
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
ok
|
||||
}
|
||||
};
|
||||
if !ok {
|
||||
break;
|
||||
}
|
||||
}
|
||||
shared.metrics.tcp_connections.fetch_sub(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Serve TCP until shutdown.
|
||||
pub async fn serve_tcp(shared: Arc<Shared>, listener: TcpListener, mut shutdown: watch::Receiver<bool>) {
|
||||
let cfg = shared.rt().cfg.clone();
|
||||
let conns = Arc::new(Semaphore::new(cfg.server.max_tcp_connections));
|
||||
let idle = cfg.server.tcp_idle_timeout;
|
||||
loop {
|
||||
let (stream, peer) = tokio::select! {
|
||||
r = listener.accept() => match r {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "TCP accept error");
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
continue;
|
||||
}
|
||||
},
|
||||
_ = shutdown.changed() => break,
|
||||
};
|
||||
let Ok(permit) = Arc::clone(&conns).try_acquire_owned() else {
|
||||
drop(stream); // connection limit reached
|
||||
continue;
|
||||
};
|
||||
let _ = stream.set_nodelay(true);
|
||||
let shared = Arc::clone(&shared);
|
||||
tokio::spawn(async move {
|
||||
serve_stream(shared, stream, peer, Transport::Tcp, idle).await;
|
||||
drop(permit);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,480 @@
|
||||
//! Cache of complete, encoded responses ("packet cache").
|
||||
//!
|
||||
//! A repeated query is answered by copying the stored response bytes and patching the
|
||||
//! message ID, the case of the question name (resolvers randomise it, "0x20") and – for
|
||||
//! data that did not come from a local zone – the TTLs, which are lowered by the time
|
||||
//! the response spent in the cache. No parsing, policy evaluation, zone lookup or
|
||||
//! encoding happens on a hit, and the UDP listener answers hits inline without spawning
|
||||
//! a task. This is the main per-core speed-up of the authoritative fast path.
|
||||
//!
|
||||
//! Correctness rules:
|
||||
//! * The key is the whole query after the ID (flags, question with a lower-cased name,
|
||||
//! EDNS record incl. DO bit, UDP size and options) plus a **client profile**: the view,
|
||||
//! whether the client may use recursion, whether it is exempt from block lists, which
|
||||
//! client-restricted forward rules match it, and whether the transport is UDP or a
|
||||
//! stream. Two clients with the same profile get byte-identical answers from the slow
|
||||
//! path, so sharing is safe.
|
||||
//! * Only plain queries are cached: opcode QUERY, one question, no answer/authority
|
||||
//! records and at most one additional record, which must be OPT – so TSIG-signed
|
||||
//! requests always take the slow path. Only NOERROR/NXDOMAIN responses are stored.
|
||||
//! * Entries are invalidated by a generation number that changes whenever a zone
|
||||
//! snapshot is published or a zone expires (`dns_authoritative::data_generation`) and
|
||||
//! when the configuration is reloaded or the cache is flushed.
|
||||
//! * Answers from local zones live at most `authoritative_max_age`; resolved and
|
||||
//! forwarded answers at most their smallest TTL (capped at 60 s), with TTLs counted down.
|
||||
//! * Memory is bounded by `max_entries` (LRU per shard).
|
||||
use std::hash::{BuildHasher, RandomState};
|
||||
use std::num::NonZeroUsize;
|
||||
use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use lru::LruCache;
|
||||
|
||||
const SHARDS: usize = 16;
|
||||
/// Upper bound for how long a resolved answer is reused (TTLs are counted down anyway).
|
||||
const MAX_RESOLVED_AGE: u32 = 60;
|
||||
/// Largest response kept.
|
||||
const MAX_RESPONSE: usize = 4096;
|
||||
|
||||
/// How a stored response may be reused.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Kind {
|
||||
/// From local zone data: TTLs are fixed; invalidated by zone changes.
|
||||
Authoritative,
|
||||
/// Resolved/forwarded/cached data: TTLs are decremented while cached.
|
||||
Resolved,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Entry {
|
||||
bytes: Box<[u8]>,
|
||||
/// Offsets of the 32-bit TTL fields of all non-OPT records.
|
||||
ttl_offsets: Box<[u16]>,
|
||||
/// End of the question section (the part copied from the query on a hit).
|
||||
question_end: u16,
|
||||
stored: Instant,
|
||||
max_age: u32,
|
||||
decrement: bool,
|
||||
generation: u64,
|
||||
rcode: &'static str,
|
||||
source: &'static str,
|
||||
}
|
||||
|
||||
type Shard = Mutex<LruCache<Box<[u8]>, Arc<Entry>>>;
|
||||
|
||||
/// Counters for metrics and status.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct PacketCacheStats {
|
||||
pub hits: AtomicU64,
|
||||
pub misses: AtomicU64,
|
||||
pub inserts: AtomicU64,
|
||||
}
|
||||
|
||||
/// How a response being stored may be reused, and its metric labels.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct StoreMeta {
|
||||
pub kind: Kind,
|
||||
/// From [`PacketCache::current_generation`], read before the answer was computed.
|
||||
pub generation: u64,
|
||||
pub rcode: &'static str,
|
||||
pub source: &'static str,
|
||||
}
|
||||
|
||||
/// A hit: response bytes ready to send, plus labels for metrics.
|
||||
#[derive(Debug)]
|
||||
pub struct Hit {
|
||||
pub bytes: Vec<u8>,
|
||||
pub qtype: u16,
|
||||
pub rcode: &'static str,
|
||||
pub source: &'static str,
|
||||
}
|
||||
|
||||
pub struct PacketCache {
|
||||
shards: Box<[Shard]>,
|
||||
hasher: RandomState,
|
||||
/// Local part of the generation (reloads, flushes); combined with the zone generation.
|
||||
local_generation: AtomicU64,
|
||||
authoritative_max_age: u32,
|
||||
pub stats: PacketCacheStats,
|
||||
}
|
||||
|
||||
/// Parsed facts about a cacheable query.
|
||||
struct QueryShape {
|
||||
/// End of the question section.
|
||||
question_end: usize,
|
||||
qtype: u16,
|
||||
}
|
||||
|
||||
/// Validate that `raw` is a plain, cacheable query and find its question.
|
||||
fn query_shape(raw: &[u8]) -> Option<QueryShape> {
|
||||
if raw.len() < 17 || raw.len() > 1024 {
|
||||
return None;
|
||||
}
|
||||
let flags = u16::from_be_bytes([raw[2], raw[3]]);
|
||||
// QR=0, opcode QUERY (0)
|
||||
if flags & 0x8000 != 0 || (flags >> 11) & 0xF != 0 {
|
||||
return None;
|
||||
}
|
||||
let count = |i: usize| u16::from_be_bytes([raw[i], raw[i + 1]]);
|
||||
if count(4) != 1 || count(6) != 0 || count(8) != 0 || count(10) > 1 {
|
||||
return None;
|
||||
}
|
||||
// question name: plain labels only (queries are not compressed)
|
||||
let mut i = 12;
|
||||
loop {
|
||||
let len = *raw.get(i)? as usize;
|
||||
if len == 0 {
|
||||
i += 1;
|
||||
break;
|
||||
}
|
||||
if len > 63 {
|
||||
return None;
|
||||
}
|
||||
i += 1 + len;
|
||||
}
|
||||
let qtype = u16::from_be_bytes([*raw.get(i)?, *raw.get(i + 1)?]);
|
||||
let qclass = u16::from_be_bytes([*raw.get(i + 2)?, *raw.get(i + 3)?]);
|
||||
let question_end = i + 4;
|
||||
// IN only; no zone transfers, OPT, TSIG or meta types
|
||||
if qclass != 1 || matches!(qtype, 251 | 252 | 41 | 250 | 249) {
|
||||
return None;
|
||||
}
|
||||
if count(10) == 1 {
|
||||
// the additional record must be OPT: root name, type 41
|
||||
if raw.get(question_end..question_end + 3)? != [0, 0, 41] {
|
||||
return None;
|
||||
}
|
||||
// …and must end exactly at the end of the packet
|
||||
let rdlen = u16::from_be_bytes([*raw.get(question_end + 9)?, *raw.get(question_end + 10)?]) as usize;
|
||||
if question_end + 11 + rdlen != raw.len() {
|
||||
return None;
|
||||
}
|
||||
} else if raw.len() != question_end {
|
||||
return None;
|
||||
}
|
||||
Some(QueryShape { question_end, qtype })
|
||||
}
|
||||
|
||||
/// Skip a (possibly compressed) name in a message; returns the offset after it.
|
||||
fn skip_name(m: &[u8], mut i: usize) -> Option<usize> {
|
||||
loop {
|
||||
let b = *m.get(i)?;
|
||||
match b & 0xC0 {
|
||||
0x00 if b == 0 => return Some(i + 1),
|
||||
0x00 => i += 1 + b as usize,
|
||||
0xC0 => return Some(i + 2),
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Offsets of TTL fields (except OPT) and the smallest TTL in a response.
|
||||
fn ttl_layout(m: &[u8], question_end: usize) -> Option<(Vec<u16>, u32)> {
|
||||
let count = |i: usize| -> Option<usize> { Some(u16::from_be_bytes([*m.get(i)?, *m.get(i + 1)?]) as usize) };
|
||||
let total = count(6)? + count(8)? + count(10)?;
|
||||
let mut i = question_end;
|
||||
let mut offsets = Vec::with_capacity(total);
|
||||
let mut min_ttl = u32::MAX;
|
||||
for _ in 0..total {
|
||||
i = skip_name(m, i)?;
|
||||
let rtype = u16::from_be_bytes([*m.get(i)?, *m.get(i + 1)?]);
|
||||
let ttl_at = i + 4;
|
||||
let ttl = u32::from_be_bytes(m.get(ttl_at..ttl_at + 4)?.try_into().ok()?);
|
||||
let rdlen = u16::from_be_bytes([*m.get(i + 8)?, *m.get(i + 9)?]) as usize;
|
||||
if rtype != 41 {
|
||||
offsets.push(u16::try_from(ttl_at).ok()?);
|
||||
min_ttl = min_ttl.min(ttl);
|
||||
}
|
||||
i += 10 + rdlen;
|
||||
if i > m.len() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
(i == m.len()).then_some((offsets, min_ttl))
|
||||
}
|
||||
|
||||
impl PacketCache {
|
||||
/// `max_entries == 0` disables the cache.
|
||||
pub fn new(max_entries: usize, authoritative_max_age: Duration) -> Self {
|
||||
let n = if max_entries == 0 { 0 } else { (max_entries / 64).clamp(1, SHARDS).next_power_of_two().min(SHARDS) };
|
||||
let shards = (0..n)
|
||||
.map(|i| {
|
||||
let cap = max_entries / n + usize::from(i < max_entries % n);
|
||||
Mutex::new(LruCache::new(NonZeroUsize::new(cap).unwrap_or(NonZeroUsize::MIN)))
|
||||
})
|
||||
.collect();
|
||||
Self {
|
||||
shards,
|
||||
hasher: RandomState::new(),
|
||||
local_generation: AtomicU64::new(0),
|
||||
authoritative_max_age: authoritative_max_age.as_secs().min(u64::from(u32::MAX)) as u32,
|
||||
stats: PacketCacheStats::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn enabled(&self) -> bool {
|
||||
!self.shards.is_empty()
|
||||
}
|
||||
|
||||
fn generation(&self) -> u64 {
|
||||
// the two counters only ever grow; any change of either invalidates
|
||||
self.local_generation.load(Relaxed).wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ dns_authoritative::data_generation()
|
||||
}
|
||||
|
||||
/// Drop everything (configuration reload, cache flush).
|
||||
pub fn invalidate(&self) {
|
||||
self.local_generation.fetch_add(1, Relaxed);
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.shards.iter().map(|s| s.lock().unwrap_or_else(|e| e.into_inner()).len()).sum()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.len() == 0
|
||||
}
|
||||
|
||||
fn key(raw: &[u8], shape: &QueryShape, profile: u64) -> Box<[u8]> {
|
||||
let mut k = Vec::with_capacity(8 + raw.len() - 2);
|
||||
k.extend_from_slice(&profile.to_be_bytes());
|
||||
k.extend_from_slice(&raw[2..12]);
|
||||
k.extend(raw[12..shape.question_end].iter().map(u8::to_ascii_lowercase));
|
||||
k.extend_from_slice(&raw[shape.question_end..]);
|
||||
k.into_boxed_slice()
|
||||
}
|
||||
|
||||
fn shard(&self, key: &[u8]) -> std::sync::MutexGuard<'_, LruCache<Box<[u8]>, Arc<Entry>>> {
|
||||
let i = (self.hasher.hash_one(key) as usize) & (self.shards.len() - 1);
|
||||
self.shards[i].lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// Answer `raw` from the cache, if possible.
|
||||
pub fn lookup(&self, raw: &[u8], profile: u64) -> Option<Hit> {
|
||||
if !self.enabled() {
|
||||
return None;
|
||||
}
|
||||
let shape = query_shape(raw)?;
|
||||
let key = Self::key(raw, &shape, profile);
|
||||
let generation = self.generation();
|
||||
let entry = {
|
||||
let mut s = self.shard(&key);
|
||||
let fresh = match s.get(&key) {
|
||||
Some(e) => e.generation == generation && e.stored.elapsed().as_secs() < u64::from(e.max_age),
|
||||
None => {
|
||||
drop(s);
|
||||
self.stats.misses.fetch_add(1, Relaxed);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if !fresh {
|
||||
s.pop(&key);
|
||||
drop(s);
|
||||
self.stats.misses.fetch_add(1, Relaxed);
|
||||
return None;
|
||||
}
|
||||
s.get(&key).map(Arc::clone)?
|
||||
};
|
||||
let mut out = entry.bytes.to_vec();
|
||||
out[0] = raw[0];
|
||||
out[1] = raw[1];
|
||||
// the question as the client sent it (same length; only letter case can differ)
|
||||
let qe = usize::from(entry.question_end);
|
||||
if qe == shape.question_end {
|
||||
out[12..qe].copy_from_slice(&raw[12..qe]);
|
||||
}
|
||||
if entry.decrement {
|
||||
let age = entry.stored.elapsed().as_secs() as u32;
|
||||
for &o in &*entry.ttl_offsets {
|
||||
let o = usize::from(o);
|
||||
let ttl = u32::from_be_bytes([out[o], out[o + 1], out[o + 2], out[o + 3]]);
|
||||
out[o..o + 4].copy_from_slice(&ttl.saturating_sub(age).to_be_bytes());
|
||||
}
|
||||
}
|
||||
self.stats.hits.fetch_add(1, Relaxed);
|
||||
Some(Hit { bytes: out, qtype: shape.qtype, rcode: entry.rcode, source: entry.source })
|
||||
}
|
||||
|
||||
/// Remember the response to `raw`. `meta.generation` must be taken *before* the response
|
||||
/// was computed, so a zone change during the computation is never cached as current.
|
||||
pub fn store(&self, raw: &[u8], profile: u64, response: &[u8], meta: StoreMeta) {
|
||||
let StoreMeta { kind, generation, rcode, source } = meta;
|
||||
if !self.enabled() || response.len() > MAX_RESPONSE || response.len() < 12 {
|
||||
return;
|
||||
}
|
||||
let Some(shape) = query_shape(raw) else { return };
|
||||
// response question must mirror the query (it always does for our encoder)
|
||||
if response.get(12..shape.question_end).map(|q| q.eq_ignore_ascii_case(&raw[12..shape.question_end])) != Some(true) {
|
||||
return;
|
||||
}
|
||||
let Some((offsets, min_ttl)) = ttl_layout(response, shape.question_end) else { return };
|
||||
let max_age = match kind {
|
||||
Kind::Authoritative => self.authoritative_max_age,
|
||||
Kind::Resolved if offsets.is_empty() => 5, // negative answer without SOA: keep briefly
|
||||
Kind::Resolved => min_ttl.min(MAX_RESOLVED_AGE),
|
||||
};
|
||||
if max_age == 0 {
|
||||
return;
|
||||
}
|
||||
let entry = Arc::new(Entry {
|
||||
bytes: response.into(),
|
||||
ttl_offsets: offsets.into_iter().collect(),
|
||||
question_end: shape.question_end as u16,
|
||||
stored: Instant::now(),
|
||||
max_age,
|
||||
decrement: kind == Kind::Resolved,
|
||||
generation,
|
||||
rcode,
|
||||
source,
|
||||
});
|
||||
let key = Self::key(raw, &shape, profile);
|
||||
self.shard(&key).put(key, entry);
|
||||
self.stats.inserts.fetch_add(1, Relaxed);
|
||||
}
|
||||
|
||||
/// Prometheus text for the packet cache.
|
||||
pub fn render_metrics(&self) -> String {
|
||||
let mut s = String::new();
|
||||
for (name, help, v) in [
|
||||
("dns_answer_cache_hits_total", "Queries answered from the encoded-answer cache", &self.stats.hits),
|
||||
("dns_answer_cache_misses_total", "Cacheable queries not found in the encoded-answer cache", &self.stats.misses),
|
||||
("dns_answer_cache_inserts_total", "Answers stored in the encoded-answer cache", &self.stats.inserts),
|
||||
] {
|
||||
s.push_str(&format!("# HELP {name} {help}\n# TYPE {name} counter\n{name} {}\n", v.load(Relaxed)));
|
||||
}
|
||||
s.push_str(&format!(
|
||||
"# HELP dns_answer_cache_entries Entries in the encoded-answer cache\n# TYPE dns_answer_cache_entries gauge\ndns_answer_cache_entries {}\n",
|
||||
self.len()
|
||||
));
|
||||
s
|
||||
}
|
||||
|
||||
/// Generation to pass to [`PacketCache::store`] (read before computing an answer).
|
||||
pub fn current_generation(&self) -> u64 {
|
||||
self.generation()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use dns_core::client::{QueryOptions, build_query};
|
||||
use dns_core::proto::op::{Message, ResponseCode};
|
||||
use dns_core::proto::rr::rdata::A;
|
||||
use dns_core::proto::rr::{Name, RData, Record, RecordType};
|
||||
|
||||
fn query(name: &str, dnssec: bool) -> Vec<u8> {
|
||||
let o = QueryOptions { dnssec_ok: dnssec, ..Default::default() };
|
||||
build_query(&Name::from_ascii(name).unwrap(), RecordType::A, &o).to_vec().unwrap()
|
||||
}
|
||||
|
||||
fn response(q: &[u8], ttl: u32) -> Vec<u8> {
|
||||
let m = Message::from_vec(q).unwrap();
|
||||
let mut r = dns_core::wire::response_for(&m);
|
||||
r.metadata.response_code = ResponseCode::NoError;
|
||||
r.answers.push(Record::from_rdata(m.queries[0].name.clone(), ttl, RData::A(A::new(192, 0, 2, 1))));
|
||||
r.to_vec().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hit_patches_id_case_and_ttl() {
|
||||
let c = PacketCache::new(1000, Duration::from_secs(30));
|
||||
let q = query("www.example.com.", false);
|
||||
let g = c.current_generation();
|
||||
c.store(&q, 1, &response(&q, 300), StoreMeta { kind: Kind::Resolved, generation: g, rcode: "NOERROR", source: "recursive" });
|
||||
// same question, other ID and 0x20 case
|
||||
let mut q2 = query("WwW.ExAmPlE.CoM.", false);
|
||||
q2[0] = 0xAB;
|
||||
q2[1] = 0xCD;
|
||||
let hit = c.lookup(&q2, 1).unwrap();
|
||||
let m = Message::from_vec(&hit.bytes).unwrap();
|
||||
assert_eq!(m.metadata.id, 0xABCD);
|
||||
assert_eq!(m.queries[0].name.to_ascii(), "WwW.ExAmPlE.CoM.");
|
||||
assert!(m.answers[0].ttl <= 300 && m.answers[0].ttl >= 299);
|
||||
assert_eq!(hit.qtype, 1);
|
||||
// other profile, DO bit or name: miss
|
||||
assert!(c.lookup(&q2, 2).is_none());
|
||||
assert!(c.lookup(&query("www.example.com.", true), 1).is_none());
|
||||
assert!(c.lookup(&query("mail.example.com.", false), 1).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generation_and_age_invalidate() {
|
||||
let c = PacketCache::new(1000, Duration::from_secs(30));
|
||||
let q = query("a.example.", false);
|
||||
c.store(
|
||||
&q,
|
||||
0,
|
||||
&response(&q, 300),
|
||||
StoreMeta { kind: Kind::Authoritative, generation: c.current_generation(), rcode: "NOERROR", source: "authoritative" },
|
||||
);
|
||||
assert!(c.lookup(&q, 0).is_some());
|
||||
c.invalidate();
|
||||
assert!(c.lookup(&q, 0).is_none());
|
||||
// stored with a stale generation (zone changed while computing): never served
|
||||
let g = c.current_generation();
|
||||
c.invalidate();
|
||||
c.store(
|
||||
&q,
|
||||
0,
|
||||
&response(&q, 300),
|
||||
StoreMeta { kind: Kind::Authoritative, generation: g, rcode: "NOERROR", source: "authoritative" },
|
||||
);
|
||||
assert!(c.lookup(&q, 0).is_none());
|
||||
// TTL 0 is not cached
|
||||
c.store(
|
||||
&q,
|
||||
0,
|
||||
&response(&q, 0),
|
||||
StoreMeta { kind: Kind::Resolved, generation: c.current_generation(), rcode: "NOERROR", source: "recursive" },
|
||||
);
|
||||
assert!(c.lookup(&q, 0).is_none());
|
||||
// authoritative TTLs are not changed
|
||||
c.store(
|
||||
&q,
|
||||
0,
|
||||
&response(&q, 300),
|
||||
StoreMeta { kind: Kind::Authoritative, generation: c.current_generation(), rcode: "NOERROR", source: "authoritative" },
|
||||
);
|
||||
assert_eq!(Message::from_vec(&c.lookup(&q, 0).unwrap().bytes).unwrap().answers[0].ttl, 300);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_plain_queries_are_cacheable() {
|
||||
let q = query("x.example.", false);
|
||||
assert!(query_shape(&q).is_some());
|
||||
let mut resp_flag = q.clone();
|
||||
resp_flag[2] |= 0x80; // QR=1
|
||||
assert!(query_shape(&resp_flag).is_none());
|
||||
let mut notify = q.clone();
|
||||
notify[2] |= 4 << 3; // opcode NOTIFY
|
||||
assert!(query_shape(¬ify).is_none());
|
||||
let mut trailing = query("x.example.", false);
|
||||
trailing.extend_from_slice(&[1, 2, 3]); // garbage, no additional record declared
|
||||
assert!(query_shape(&trailing).is_none());
|
||||
// a TSIG-signed query has an additional record that is not OPT
|
||||
let key = dns_core::tsig::TsigKey::new("k", "hmac-sha256", "c2VjcmV0c2VjcmV0c2VjcmV0c2VjcmV0").unwrap();
|
||||
let mut m = Message::from_vec(&query("x.example.", false)).unwrap();
|
||||
m.edns = None;
|
||||
let signed = key.sign_request(&mut m).unwrap();
|
||||
assert!(query_shape(&signed).is_none());
|
||||
let c = PacketCache::new(0, Duration::from_secs(1));
|
||||
assert!(!c.enabled() && c.lookup(&q, 0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounded_memory() {
|
||||
let c = PacketCache::new(256, Duration::from_secs(30));
|
||||
for i in 0..5000 {
|
||||
let q = query(&format!("h{i}.example."), false);
|
||||
c.store(
|
||||
&q,
|
||||
0,
|
||||
&response(&q, 300),
|
||||
StoreMeta { kind: Kind::Resolved, generation: c.current_generation(), rcode: "NOERROR", source: "recursive" },
|
||||
);
|
||||
}
|
||||
assert!(c.len() <= 256, "{}", c.len());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
//! Resolution routing for names that are not served from local zones.
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::net::IpAddr;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use dns_cache::{Cache, Key};
|
||||
use dns_config::{Config, DefaultResolution};
|
||||
use dns_core::answer::{Answer, Source};
|
||||
use dns_core::proto::op::ResponseCode;
|
||||
use dns_core::proto::rr::{LowerName, Name, RecordType};
|
||||
use dns_forwarder::Pool;
|
||||
use dns_policy::Acl;
|
||||
use dns_recursive::Resolver;
|
||||
|
||||
use crate::coalesce::{Coalescer, FlightKey};
|
||||
|
||||
/// A conditional forwarding rule.
|
||||
pub struct ForwardRule {
|
||||
pub suffix: LowerName,
|
||||
pub clients: Acl,
|
||||
pub pool: Arc<Pool>,
|
||||
pub cache_ns: u16,
|
||||
pub fallback_recursion: bool,
|
||||
}
|
||||
|
||||
pub struct Router {
|
||||
pub rules: Vec<ForwardRule>,
|
||||
pub default: DefaultResolution,
|
||||
pub default_pool: Option<Arc<Pool>>,
|
||||
pub default_ns: u16,
|
||||
pub resolver: Option<Arc<Resolver>>,
|
||||
pub cache: Arc<Cache>,
|
||||
/// Identical concurrent cache misses share one upstream/recursive resolution.
|
||||
pub flights: Coalescer,
|
||||
}
|
||||
|
||||
/// Cache namespace derived from the route definition (stable across reloads).
|
||||
fn ns_for(parts: &[&str]) -> u16 {
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
parts.hash(&mut h);
|
||||
(h.finish() as u16) | 0x8000 // never collides with the recursion namespace 0
|
||||
}
|
||||
|
||||
/// Recursion cache namespace.
|
||||
pub const RECURSION_NS: u16 = 0;
|
||||
|
||||
impl Router {
|
||||
pub fn build(cfg: &Config, cache: Arc<Cache>, resolver: Option<Arc<Resolver>>) -> Result<Self, String> {
|
||||
let timeout = cfg.upstreams.timeout.unwrap_or(Duration::from_secs(2));
|
||||
let ca = match &cfg.upstreams.tls_ca_file {
|
||||
Some(p) => {
|
||||
let p = cfg.resolve_path(p);
|
||||
Some(std::fs::read(&p).map_err(|e| format!("upstreams.tls_ca_file {}: {e}", p.display()))?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let mut rules = Vec::new();
|
||||
for f in &cfg.forward_zones {
|
||||
let suffix = dns_core::names::parse_lower(&f.domain).map_err(|e| e.to_string())?;
|
||||
let pool = Arc::new(Pool::with_tls_roots(&f.domain, &f.upstreams, f.strategy, timeout, ca.as_deref())?);
|
||||
let mut parts: Vec<&str> = vec![f.domain.as_str()];
|
||||
parts.extend(f.upstreams.iter().map(String::as_str));
|
||||
rules.push(ForwardRule {
|
||||
suffix,
|
||||
clients: Acl(cfg.expand_acl(&f.clients)?),
|
||||
pool,
|
||||
cache_ns: ns_for(&parts),
|
||||
fallback_recursion: f.fallback_recursion,
|
||||
});
|
||||
}
|
||||
// Most specific suffix first.
|
||||
rules.sort_by_key(|r| std::cmp::Reverse(r.suffix.num_labels()));
|
||||
let default_pool = if cfg.upstreams.servers.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(Arc::new(Pool::with_tls_roots("default", &cfg.upstreams.servers, cfg.upstreams.strategy, timeout, ca.as_deref())?))
|
||||
};
|
||||
let parts: Vec<&str> = cfg.upstreams.servers.iter().map(String::as_str).collect();
|
||||
Ok(Self {
|
||||
rules,
|
||||
default: cfg.resolution.default,
|
||||
default_pool,
|
||||
default_ns: ns_for(&parts),
|
||||
resolver,
|
||||
cache,
|
||||
flights: Coalescer::default(),
|
||||
})
|
||||
}
|
||||
|
||||
fn rule_for(&self, name: &Name, client: IpAddr) -> Option<&ForwardRule> {
|
||||
let l = LowerName::new(name);
|
||||
self.rules.iter().find(|r| r.suffix.zone_of(&l) && (r.clients.is_empty() || r.clients.contains(client)))
|
||||
}
|
||||
|
||||
async fn forward(&self, pool: &Arc<Pool>, ns: u16, name: &Name, qtype: RecordType, dnssec_ok: bool, cd: bool) -> Answer {
|
||||
let key = Key { ns, name: LowerName::new(name), rtype: qtype, dnssec: dnssec_ok };
|
||||
if let Some(a) = self.cache.get(&key) {
|
||||
if self.cache.prefetch_due(&key) {
|
||||
// popular entry about to expire: refresh it in the background
|
||||
let (pool, cache, name) = (Arc::clone(pool), Arc::clone(&self.cache), name.clone());
|
||||
tokio::spawn(async move {
|
||||
let _ = forward_fetch(&pool, &cache, key, &name, qtype, dnssec_ok, cd, false).await;
|
||||
});
|
||||
}
|
||||
return a;
|
||||
}
|
||||
let flight = FlightKey { ns, name: key.name.clone(), rtype: qtype, dnssec_ok, cd };
|
||||
self.flights.run(flight, || forward_fetch(pool, &self.cache, key, name, qtype, dnssec_ok, cd, true)).await
|
||||
}
|
||||
|
||||
async fn recurse(&self, name: &Name, qtype: RecordType) -> Answer {
|
||||
match &self.resolver {
|
||||
Some(r) => {
|
||||
let flight = FlightKey { ns: RECURSION_NS, name: LowerName::new(name), rtype: qtype, dnssec_ok: false, cd: false };
|
||||
let a = self.flights.run(flight, || r.resolve(name, qtype)).await;
|
||||
if a.source == Source::Cache && r.prefetch_due(name, qtype) {
|
||||
let (r, name) = (Arc::clone(r), name.clone());
|
||||
tokio::spawn(async move { r.refresh(&name, qtype).await });
|
||||
}
|
||||
if a.rcode == ResponseCode::ServFail {
|
||||
let key = Key { ns: RECURSION_NS, name: LowerName::new(name), rtype: qtype, dnssec: false };
|
||||
if let Some(s) = self.cache.get_stale(&key) {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
a
|
||||
}
|
||||
None => Answer::servfail(Source::Recursive, "recursion is not enabled"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Query a forwarder pool and cache the answer. `stale_on_error`: answer from stale
|
||||
/// cache data (or SERVFAIL) when the pool fails; a background prefetch passes `false`
|
||||
/// and simply keeps the existing entry.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn forward_fetch(
|
||||
pool: &Pool,
|
||||
cache: &Cache,
|
||||
key: Key,
|
||||
name: &Name,
|
||||
qtype: RecordType,
|
||||
dnssec_ok: bool,
|
||||
cd: bool,
|
||||
stale_on_error: bool,
|
||||
) -> Answer {
|
||||
{
|
||||
match pool.query(name, qtype, dnssec_ok, cd).await {
|
||||
Ok(f) => {
|
||||
let m = f.message;
|
||||
let mut a = Answer::new(m.metadata.response_code, Source::Forward);
|
||||
a.answers = m.answers;
|
||||
a.authority = m
|
||||
.authorities
|
||||
.into_iter()
|
||||
.filter(|r| r.record_type() == RecordType::SOA || (dnssec_ok && r.record_type() != RecordType::NS))
|
||||
.collect();
|
||||
if m.metadata.authentic_data {
|
||||
a.security = dns_core::answer::Security::Secure;
|
||||
}
|
||||
a.note = Some(format!("upstream {} ({}, {} ms)", f.upstream, f.reason, f.elapsed.as_millis()));
|
||||
cache.insert_answer(key, &a);
|
||||
a
|
||||
}
|
||||
Err(e) if stale_on_error => cache.get_stale(&key).unwrap_or_else(|| Answer::servfail(Source::Forward, e)),
|
||||
Err(e) => Answer::servfail(Source::Forward, e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Router {
|
||||
/// Resolve a name for a client that is allowed to use resolution.
|
||||
pub async fn resolve(&self, name: &Name, qtype: RecordType, client: IpAddr, dnssec_ok: bool, cd: bool) -> Answer {
|
||||
if let Some(rule) = self.rule_for(name, client) {
|
||||
let a = self.forward(&rule.pool, rule.cache_ns, name, qtype, dnssec_ok, cd).await;
|
||||
if a.rcode == ResponseCode::ServFail && rule.fallback_recursion && self.resolver.is_some() {
|
||||
return self.recurse(name, qtype).await;
|
||||
}
|
||||
return a;
|
||||
}
|
||||
match self.default {
|
||||
DefaultResolution::Recursive => self.recurse(name, qtype).await,
|
||||
DefaultResolution::Forward => match &self.default_pool {
|
||||
Some(p) => self.forward(p, self.default_ns, name, qtype, dnssec_ok, cd).await,
|
||||
None => Answer::servfail(Source::Forward, "no upstreams configured"),
|
||||
},
|
||||
DefaultResolution::ForwardThenRecursive => {
|
||||
let a = match &self.default_pool {
|
||||
Some(p) => self.forward(p, self.default_ns, name, qtype, dnssec_ok, cd).await,
|
||||
None => Answer::servfail(Source::Forward, "no upstreams configured"),
|
||||
};
|
||||
if a.rcode == ResponseCode::ServFail { self.recurse(name, qtype).await } else { a }
|
||||
}
|
||||
DefaultResolution::Refuse => Answer::new(ResponseCode::Refused, Source::Refused),
|
||||
}
|
||||
}
|
||||
|
||||
/// `true` when any resolution path exists.
|
||||
pub fn can_resolve(&self) -> bool {
|
||||
!self.rules.is_empty() || self.default != DefaultResolution::Refuse
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
//! Process-wide shared state and the hot-reloadable runtime snapshot.
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, RwLock};
|
||||
use std::time::Instant;
|
||||
|
||||
use dns_authoritative::{ZoneEntry, ZoneStore};
|
||||
use dns_cache::Cache;
|
||||
use dns_config::{Config, Overrides};
|
||||
use dns_core::tsig::KeyRing;
|
||||
use dns_metrics::Metrics;
|
||||
use dns_policy::{Acl, BlockPolicy, RateLimiter, SuffixSet, Views};
|
||||
|
||||
use crate::audit::AuditLog;
|
||||
use crate::router::{RECURSION_NS, Router};
|
||||
|
||||
/// Everything derived from one configuration version. Swapped atomically on reload;
|
||||
/// in-flight queries keep using the snapshot they started with.
|
||||
pub struct Runtime {
|
||||
pub cfg: Arc<Config>,
|
||||
pub zones: Arc<ZoneStore>,
|
||||
pub ring: KeyRing,
|
||||
pub recursion_acl: Acl,
|
||||
pub views: Views,
|
||||
pub ratelimit: RateLimiter,
|
||||
pub policy: BlockPolicy,
|
||||
pub local_only: SuffixSet,
|
||||
pub router: Router,
|
||||
pub resolver: Option<Arc<dns_recursive::Resolver>>,
|
||||
}
|
||||
|
||||
impl Runtime {
|
||||
/// Build a runtime. Returns it together with newly created zone entries
|
||||
/// (secondary tasks must be spawned for them).
|
||||
pub fn build(cfg: Config, cache: Arc<Cache>, previous: Option<&Runtime>) -> Result<(Self, Vec<Arc<ZoneEntry>>), String> {
|
||||
let errors: Vec<String> = cfg.validate().into_iter().filter(|i| i.is_error()).map(|i| i.to_string()).collect();
|
||||
if !errors.is_empty() {
|
||||
return Err(errors.join("\n"));
|
||||
}
|
||||
let ring = cfg.key_ring()?;
|
||||
let resolver = if cfg.recursion.enabled {
|
||||
let hints = dns_recursive::hints::load(cfg.recursion.root_hints.as_ref().map(|p| cfg.resolve_path(p)).as_deref())?;
|
||||
let mut r = dns_recursive::Resolver::new(
|
||||
dns_recursive::Settings::from_config(&cfg.recursion),
|
||||
hints,
|
||||
Arc::clone(&cache),
|
||||
RECURSION_NS,
|
||||
)?;
|
||||
if let (true, Some(p)) = (cfg.recursion.dnssec_validation, &cfg.recursion.trust_anchors) {
|
||||
let path = cfg.resolve_path(p);
|
||||
let recs =
|
||||
dns_core::zonefile::parse_file(&path, &dns_core::proto::rr::Name::root()).map_err(|e| format!("trust anchors: {e}"))?;
|
||||
r.set_trust_anchors(&recs)?;
|
||||
}
|
||||
Some(Arc::new(r))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut local = dns_policy::default_local_only();
|
||||
for s in &cfg.recursion.local_only_suffixes {
|
||||
local.push(dns_core::names::parse_lower(s).map_err(|e| e.to_string())?);
|
||||
}
|
||||
// Names served by forward rules are explicitly routed, never "local-only".
|
||||
let fwd: Vec<_> = cfg.forward_zones.iter().filter_map(|f| dns_core::names::parse_lower(&f.domain).ok()).collect();
|
||||
local.retain(|l| !fwd.iter().any(|f| l.zone_of(f) || f.zone_of(l)));
|
||||
let router = Router::build(&cfg, Arc::clone(&cache), resolver.clone())?;
|
||||
let views = Views::from_config(&cfg)?;
|
||||
let ratelimit = RateLimiter::from_config(&cfg)?;
|
||||
let policy = BlockPolicy::from_config(&cfg)?;
|
||||
let recursion_acl = Acl(cfg.expand_acl(&cfg.recursion.allowed_clients)?);
|
||||
// Zones last: building the store has side effects (stopping removed secondaries).
|
||||
let (zones, fresh) = ZoneStore::build(&cfg, &ring, previous.map(|p| p.zones.as_ref()))?;
|
||||
let rt = Runtime {
|
||||
recursion_acl,
|
||||
views,
|
||||
ratelimit,
|
||||
policy,
|
||||
local_only: SuffixSet::new(local),
|
||||
router,
|
||||
resolver,
|
||||
zones: Arc::new(zones),
|
||||
ring,
|
||||
cfg: Arc::new(cfg),
|
||||
};
|
||||
Ok((rt, fresh))
|
||||
}
|
||||
}
|
||||
|
||||
impl Runtime {
|
||||
/// Everything about a client that can change the answer to the same query:
|
||||
/// view, recursion permission, block-list exemption, client-restricted forward rules
|
||||
/// and stream vs UDP transport. Clients with equal profiles get identical answers.
|
||||
pub fn client_profile(&self, ip: std::net::IpAddr, stream: bool) -> u64 {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let ip = dns_policy::canonical_ip(ip);
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
self.views.classify(ip).hash(&mut h);
|
||||
self.recursion_acl.contains(ip).hash(&mut h);
|
||||
self.policy.exempt.contains(ip).hash(&mut h);
|
||||
for r in self.router.rules.iter().filter(|r| !r.clients.is_empty()) {
|
||||
r.clients.contains(ip).hash(&mut h);
|
||||
}
|
||||
stream.hash(&mut h);
|
||||
h.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// State shared for the lifetime of the process.
|
||||
pub struct Shared {
|
||||
pub metrics: Arc<Metrics>,
|
||||
pub cache: Arc<Cache>,
|
||||
runtime: RwLock<Arc<Runtime>>,
|
||||
pub config_path: Option<PathBuf>,
|
||||
pub overrides: Overrides,
|
||||
pub started: Instant,
|
||||
pub audit: AuditLog,
|
||||
pub version: &'static str,
|
||||
/// Encoded answers for repeated queries (see `packet_cache`).
|
||||
pub packet_cache: crate::packet_cache::PacketCache,
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
pub fn new(rt: Runtime, cache: Arc<Cache>, metrics: Arc<Metrics>, config_path: Option<PathBuf>, overrides: Overrides) -> Self {
|
||||
let audit = AuditLog::new(Some(rt.cfg.data_dir().join("audit.log")));
|
||||
let packet_cache = crate::packet_cache::PacketCache::new(rt.cfg.cache.answer_entries, rt.cfg.cache.answer_max_age);
|
||||
Self {
|
||||
packet_cache,
|
||||
metrics,
|
||||
cache,
|
||||
runtime: RwLock::new(Arc::new(rt)),
|
||||
config_path,
|
||||
overrides,
|
||||
started: Instant::now(),
|
||||
audit,
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Current runtime snapshot.
|
||||
pub fn rt(&self) -> Arc<Runtime> {
|
||||
self.runtime.read().unwrap_or_else(|e| e.into_inner()).clone()
|
||||
}
|
||||
|
||||
pub(crate) fn swap(&self, rt: Runtime) {
|
||||
*self.runtime.write().unwrap_or_else(|e| e.into_inner()) = Arc::new(rt);
|
||||
// policies, views, ACLs or forwarders may have changed
|
||||
self.packet_cache.invalidate();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
//! Server lifecycle: start, hot reload, graceful shutdown.
|
||||
use std::net::SocketAddr;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use dns_authoritative::{ZoneEntry, ZoneKind};
|
||||
use dns_cache::Cache;
|
||||
use dns_config::{Config, Overrides};
|
||||
use dns_metrics::Metrics;
|
||||
use serde::Serialize;
|
||||
use tokio::sync::watch;
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
use crate::runtime::{Runtime, Shared};
|
||||
|
||||
/// Entry point.
|
||||
pub struct Server;
|
||||
|
||||
/// Bound addresses (useful when binding port 0 in tests).
|
||||
#[derive(Debug, Clone, Default, Serialize)]
|
||||
pub struct Bound {
|
||||
pub dns: Vec<SocketAddr>,
|
||||
pub dot: Vec<SocketAddr>,
|
||||
pub doh: Vec<SocketAddr>,
|
||||
}
|
||||
|
||||
/// Running server.
|
||||
pub struct ServerHandle {
|
||||
pub shared: Arc<Shared>,
|
||||
pub bound: Bound,
|
||||
shutdown_tx: watch::Sender<bool>,
|
||||
tasks: std::sync::Mutex<Vec<JoinHandle<()>>>,
|
||||
}
|
||||
|
||||
/// What a reload changed.
|
||||
#[derive(Debug, Clone, Serialize, Default)]
|
||||
pub struct ReloadReport {
|
||||
pub zones: usize,
|
||||
pub new_zones: Vec<String>,
|
||||
pub restart_required: Vec<String>,
|
||||
}
|
||||
|
||||
fn spawn_secondary(e: Arc<ZoneEntry>) {
|
||||
if e.kind == ZoneKind::Secondary {
|
||||
tokio::spawn(dns_authoritative::secondary::run(e, |z| z.send_notifies()));
|
||||
}
|
||||
}
|
||||
|
||||
impl Server {
|
||||
/// Validate, build and start all listeners and background tasks.
|
||||
pub async fn start(cfg: Config, config_path: Option<PathBuf>, overrides: Overrides) -> Result<ServerHandle, String> {
|
||||
let cache = Arc::new(Cache::new(&cfg.cache));
|
||||
let metrics = Arc::new(Metrics::default());
|
||||
let (rt, fresh) = Runtime::build(cfg, Arc::clone(&cache), None)?;
|
||||
let cfg = rt.cfg.clone();
|
||||
let shared = Arc::new(Shared::new(rt, cache, metrics, config_path, overrides));
|
||||
let (tx, rx) = watch::channel(false);
|
||||
let mut tasks = Vec::new();
|
||||
let mut bound = Bound::default();
|
||||
|
||||
let udp_sockets = crate::listener::udp_socket_count(cfg.server.udp_sockets);
|
||||
let udp_inflight = Arc::new(tokio::sync::Semaphore::new(cfg.server.max_inflight));
|
||||
tracing::info!(udp_sockets, "UDP sockets per listen address");
|
||||
for addr in &cfg.server.listen {
|
||||
let mut port_addr = *addr;
|
||||
if cfg.server.udp {
|
||||
let socks = crate::listener::bind_udp_group(*addr, udp_sockets).map_err(|e| format!("bind UDP {addr}: {e}"))?;
|
||||
for sock in socks {
|
||||
port_addr = sock.local_addr().map_err(|e| e.to_string())?;
|
||||
let (sh, inf) = (Arc::clone(&shared), Arc::clone(&udp_inflight));
|
||||
tasks.push(tokio::spawn(crate::listener::serve_udp(sh, Arc::new(sock), inf, rx.clone())));
|
||||
}
|
||||
}
|
||||
if cfg.server.tcp {
|
||||
let l = crate::listener::bind_tcp(port_addr).map_err(|e| format!("bind TCP {port_addr}: {e}"))?;
|
||||
port_addr = l.local_addr().map_err(|e| e.to_string())?;
|
||||
tasks.push(tokio::spawn(crate::listener::serve_tcp(Arc::clone(&shared), l, rx.clone())));
|
||||
}
|
||||
bound.dns.push(port_addr);
|
||||
tracing::info!(%port_addr, "DNS listener started");
|
||||
}
|
||||
if !cfg.tls.dot_listen.is_empty() || (!cfg.tls.doh_listen.is_empty() && !cfg.tls.doh_plaintext_behind_proxy) {
|
||||
let (Some(c), Some(k)) = (&cfg.tls.cert_file, &cfg.tls.key_file) else {
|
||||
return Err("tls.cert_file and tls.key_file are required for DoT/DoH".into());
|
||||
};
|
||||
let (c, k) = (cfg.resolve_path(c), cfg.resolve_path(k));
|
||||
let certs = crate::tls::CertStore::load(&c, &k)?;
|
||||
tasks.push(tokio::spawn(Arc::clone(&certs).watch(Duration::from_secs(60), rx.clone())));
|
||||
for addr in &cfg.tls.dot_listen {
|
||||
let tls = crate::tls::server_config_with(Arc::clone(&certs), &[b"dot"])?;
|
||||
let l = crate::listener::bind_tcp(*addr).map_err(|e| format!("bind DoT {addr}: {e}"))?;
|
||||
bound.dot.push(l.local_addr().map_err(|e| e.to_string())?);
|
||||
tasks.push(tokio::spawn(crate::tls::serve_dot(Arc::clone(&shared), l, tls, rx.clone())));
|
||||
}
|
||||
for addr in &cfg.tls.doh_listen {
|
||||
let tls = crate::tls::server_config_with(Arc::clone(&certs), crate::tls::DOH_ALPN)?;
|
||||
let l = crate::listener::bind_tcp(*addr).map_err(|e| format!("bind DoH {addr}: {e}"))?;
|
||||
bound.doh.push(l.local_addr().map_err(|e| e.to_string())?);
|
||||
tasks.push(tokio::spawn(crate::tls::serve_doh(Arc::clone(&shared), l, Some(tls), rx.clone())));
|
||||
}
|
||||
} else {
|
||||
for addr in &cfg.tls.doh_listen {
|
||||
let l = crate::listener::bind_tcp(*addr).map_err(|e| format!("bind DoH {addr}: {e}"))?;
|
||||
bound.doh.push(l.local_addr().map_err(|e| e.to_string())?);
|
||||
tracing::warn!(%addr, "DoH served WITHOUT TLS (doh_plaintext_behind_proxy)");
|
||||
tasks.push(tokio::spawn(crate::tls::serve_doh(Arc::clone(&shared), l, None, rx.clone())));
|
||||
}
|
||||
}
|
||||
for e in fresh {
|
||||
spawn_secondary(e);
|
||||
}
|
||||
// DNSSEC re-signing (hourly check).
|
||||
{
|
||||
let shared = Arc::clone(&shared);
|
||||
let mut rx = rx.clone();
|
||||
tasks.push(tokio::spawn(async move {
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = tokio::time::sleep(Duration::from_secs(3600)) => {}
|
||||
_ = rx.changed() => return,
|
||||
}
|
||||
for z in shared.rt().zones.all() {
|
||||
match z.resign_if_needed() {
|
||||
Ok(true) => z.send_notifies(),
|
||||
Ok(false) => {}
|
||||
Err(e) => tracing::error!(zone = %z.name, error = %e, "re-signing failed"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
// Upstream health checks.
|
||||
{
|
||||
let shared = Arc::clone(&shared);
|
||||
let mut rx = rx.clone();
|
||||
tasks.push(tokio::spawn(async move {
|
||||
loop {
|
||||
let interval = shared.rt().cfg.upstreams.health_check_interval.unwrap_or(Duration::from_secs(30));
|
||||
tokio::select! {
|
||||
_ = tokio::time::sleep(interval) => {}
|
||||
_ = rx.changed() => return,
|
||||
}
|
||||
let rt = shared.rt();
|
||||
if let Some(p) = &rt.router.default_pool {
|
||||
p.health_check().await;
|
||||
}
|
||||
for r in &rt.router.rules {
|
||||
r.pool.health_check().await;
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
Ok(ServerHandle { shared, bound, shutdown_tx: tx, tasks: std::sync::Mutex::new(tasks) })
|
||||
}
|
||||
}
|
||||
|
||||
impl ServerHandle {
|
||||
/// Re-read the configuration file and atomically switch to it. On error the
|
||||
/// running configuration stays active (rollback).
|
||||
pub fn reload(&self) -> Result<ReloadReport, String> {
|
||||
let path = self.shared.config_path.clone().ok_or("server was started without a config file")?;
|
||||
let cfg = Config::load_with(&path, &self.shared.overrides).map_err(|e| e.to_string())?;
|
||||
self.reload_with(cfg)
|
||||
}
|
||||
|
||||
/// Apply an already-loaded configuration.
|
||||
pub fn reload_with(&self, cfg: Config) -> Result<ReloadReport, String> {
|
||||
let old = self.shared.rt();
|
||||
let mut report = ReloadReport::default();
|
||||
if cfg.server.listen != old.cfg.server.listen || cfg.server.udp != old.cfg.server.udp || cfg.server.tcp != old.cfg.server.tcp {
|
||||
report.restart_required.push("server.listen/udp/tcp".into());
|
||||
}
|
||||
if cfg.server.udp_sockets != old.cfg.server.udp_sockets || cfg.server.max_inflight != old.cfg.server.max_inflight {
|
||||
report.restart_required.push("server.udp_sockets/max_inflight".into());
|
||||
}
|
||||
if serde_json::to_string(&cfg.tls).ok() != serde_json::to_string(&old.cfg.tls).ok() {
|
||||
report.restart_required.push("tls".into());
|
||||
}
|
||||
if cfg.api.listen != old.cfg.api.listen || cfg.metrics.listen != old.cfg.metrics.listen {
|
||||
report.restart_required.push("api.listen/metrics.listen".into());
|
||||
}
|
||||
if cfg.cache.max_entries != old.cfg.cache.max_entries
|
||||
|| cfg.cache.answer_entries != old.cfg.cache.answer_entries
|
||||
|| cfg.cache.answer_max_age != old.cfg.cache.answer_max_age
|
||||
{
|
||||
report.restart_required.push("cache.max_entries/answer_entries/answer_max_age".into());
|
||||
}
|
||||
let (rt, fresh) = Runtime::build(cfg, Arc::clone(&self.shared.cache), Some(&old))?;
|
||||
report.zones = rt.zones.all().len();
|
||||
report.new_zones = fresh.iter().map(|e| e.name.to_string()).collect();
|
||||
for e in fresh {
|
||||
spawn_secondary(e);
|
||||
}
|
||||
self.shared.swap(rt);
|
||||
for r in &report.restart_required {
|
||||
tracing::warn!(setting = %r, "changed setting requires a restart to take effect");
|
||||
}
|
||||
tracing::info!(zones = report.zones, "configuration reloaded");
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// Stop listeners, wait for in-flight work (bounded), stop secondary tasks.
|
||||
pub async fn shutdown(&self) {
|
||||
let _ = self.shutdown_tx.send(true);
|
||||
for z in self.shared.rt().zones.all() {
|
||||
z.shutdown.store(true, std::sync::atomic::Ordering::Release);
|
||||
z.refresh_trigger.notify_one();
|
||||
}
|
||||
let tasks: Vec<JoinHandle<()>> = std::mem::take(&mut *self.tasks.lock().unwrap_or_else(|e| e.into_inner()));
|
||||
for t in tasks {
|
||||
let _ = tokio::time::timeout(Duration::from_secs(5), t).await;
|
||||
}
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
|
||||
while self.shared.metrics.inflight.load(std::sync::atomic::Ordering::Relaxed) > 0 && tokio::time::Instant::now() < deadline {
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Shutdown signal receiver (for auxiliary services such as the API).
|
||||
pub fn shutdown_signal(&self) -> watch::Receiver<bool> {
|
||||
self.shutdown_tx.subscribe()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
//! DNS-over-TLS (RFC 7858) and DNS-over-HTTPS (RFC 8484; HTTP/2 and HTTP/1.1) listeners,
|
||||
//! with TLS certificates that are reloaded when the files change.
|
||||
use std::net::SocketAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, RwLock};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use bytes::Bytes;
|
||||
use data_encoding::BASE64URL_NOPAD;
|
||||
use http_body_util::{BodyExt, Full, Limited};
|
||||
use hyper::service::service_fn;
|
||||
use hyper_util::rt::{TokioExecutor, TokioIo, TokioTimer};
|
||||
use hyper_util::server::conn::auto::Builder as AutoBuilder;
|
||||
use rustls::ServerConfig;
|
||||
use rustls::pki_types::pem::PemObject;
|
||||
use rustls::pki_types::{CertificateDer, PrivateKeyDer};
|
||||
use rustls::server::{ClientHello, ResolvesServerCert};
|
||||
use rustls::sign::CertifiedKey;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::sync::{Semaphore, watch};
|
||||
use tokio_rustls::TlsAcceptor;
|
||||
|
||||
use crate::handler::{Reply, Transport, handle};
|
||||
use crate::listener::serve_stream;
|
||||
use crate::runtime::Shared;
|
||||
|
||||
const MAX_HTTP_HEADER: usize = 8 * 1024;
|
||||
const MAX_HTTP_BODY: usize = 65_535;
|
||||
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
/// Time allowed to receive a DoH request body.
|
||||
const BODY_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
/// Concurrent HTTP/2 streams (queries in flight) per DoH connection.
|
||||
const MAX_H2_STREAMS: u32 = 100;
|
||||
|
||||
/// Certificate and key, re-read from disk when the files change (e.g. after a Let's
|
||||
/// Encrypt renewal), without restarting the server. A broken new pair is rejected and the
|
||||
/// previous certificate stays in use.
|
||||
pub struct CertStore {
|
||||
cert: PathBuf,
|
||||
key: PathBuf,
|
||||
current: RwLock<Arc<CertifiedKey>>,
|
||||
stamp: Mutex<(Option<SystemTime>, Option<SystemTime>)>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for CertStore {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("CertStore").field("cert", &self.cert).field("key", &self.key).finish()
|
||||
}
|
||||
}
|
||||
|
||||
fn mtime(p: &Path) -> Option<SystemTime> {
|
||||
std::fs::metadata(p).and_then(|m| m.modified()).ok()
|
||||
}
|
||||
|
||||
fn load_certified_key(cert: &Path, key: &Path) -> Result<CertifiedKey, String> {
|
||||
let certs: Vec<CertificateDer<'static>> = CertificateDer::pem_file_iter(cert)
|
||||
.map_err(|e| format!("{}: {e}", cert.display()))?
|
||||
.collect::<Result<_, _>>()
|
||||
.map_err(|e| format!("{}: {e}", cert.display()))?;
|
||||
if certs.is_empty() {
|
||||
return Err(format!("{}: no certificates found", cert.display()));
|
||||
}
|
||||
let key_der = PrivateKeyDer::from_pem_file(key).map_err(|e| format!("{}: {e}", key.display()))?;
|
||||
let signing = rustls::crypto::ring::default_provider()
|
||||
.key_provider
|
||||
.load_private_key(key_der)
|
||||
.map_err(|e| format!("{}: unsupported private key: {e}", key.display()))?;
|
||||
let ck = CertifiedKey::new(certs, signing);
|
||||
ck.keys_match().map_err(|e| format!("certificate/key mismatch: {e}"))?;
|
||||
Ok(ck)
|
||||
}
|
||||
|
||||
impl CertStore {
|
||||
pub fn load(cert: &Path, key: &Path) -> Result<Arc<Self>, String> {
|
||||
let ck = load_certified_key(cert, key)?;
|
||||
Ok(Arc::new(Self {
|
||||
cert: cert.to_path_buf(),
|
||||
key: key.to_path_buf(),
|
||||
current: RwLock::new(Arc::new(ck)),
|
||||
stamp: Mutex::new((mtime(cert), mtime(key))),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Reload when either file's modification time changed. `Ok(true)` = new certificate.
|
||||
pub fn reload_if_changed(&self) -> Result<bool, String> {
|
||||
let now = (mtime(&self.cert), mtime(&self.key));
|
||||
{
|
||||
let st = self.stamp.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if *st == now {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
let ck = load_certified_key(&self.cert, &self.key)?;
|
||||
*self.current.write().unwrap_or_else(|e| e.into_inner()) = Arc::new(ck);
|
||||
*self.stamp.lock().unwrap_or_else(|e| e.into_inner()) = now;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Check the files every `every` and swap in a renewed certificate.
|
||||
pub async fn watch(self: Arc<Self>, every: Duration, mut shutdown: watch::Receiver<bool>) {
|
||||
let mut tick = tokio::time::interval(every);
|
||||
tick.tick().await;
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = tick.tick() => {}
|
||||
_ = shutdown.changed() => break,
|
||||
}
|
||||
match self.reload_if_changed() {
|
||||
Ok(true) => tracing::info!(cert = %self.cert.display(), "TLS certificate reloaded"),
|
||||
Ok(false) => {}
|
||||
Err(e) => tracing::error!(error = %e, "new TLS certificate rejected; keeping the previous one"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ResolvesServerCert for CertStore {
|
||||
fn resolve(&self, _hello: ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
|
||||
Some(Arc::clone(&self.current.read().unwrap_or_else(|e| e.into_inner())))
|
||||
}
|
||||
}
|
||||
|
||||
/// rustls server config using a (reloadable) certificate store.
|
||||
pub fn server_config_with(store: Arc<CertStore>, alpn: &[&[u8]]) -> Result<Arc<ServerConfig>, String> {
|
||||
let provider = Arc::new(rustls::crypto::ring::default_provider());
|
||||
let mut cfg = ServerConfig::builder_with_provider(provider)
|
||||
.with_safe_default_protocol_versions()
|
||||
.map_err(|e| e.to_string())?
|
||||
.with_no_client_auth()
|
||||
.with_cert_resolver(store);
|
||||
cfg.alpn_protocols = alpn.iter().map(|a| a.to_vec()).collect();
|
||||
Ok(Arc::new(cfg))
|
||||
}
|
||||
|
||||
/// Load certificate chain and key into a rustls server config (not reloaded).
|
||||
pub fn server_config(cert: &Path, key: &Path, alpn: &[&[u8]]) -> Result<Arc<ServerConfig>, String> {
|
||||
server_config_with(CertStore::load(cert, key)?, alpn)
|
||||
}
|
||||
|
||||
/// ALPN offered by the DoH listener: HTTP/2 first (browsers, Android, Firefox), then HTTP/1.1.
|
||||
pub const DOH_ALPN: &[&[u8]] = &[b"h2", b"http/1.1"];
|
||||
|
||||
/// Serve DoT until shutdown.
|
||||
pub async fn serve_dot(shared: Arc<Shared>, listener: TcpListener, tls: Arc<ServerConfig>, mut shutdown: watch::Receiver<bool>) {
|
||||
let acceptor = TlsAcceptor::from(tls);
|
||||
let cfg = shared.rt().cfg.clone();
|
||||
let conns = Arc::new(Semaphore::new(cfg.server.max_tcp_connections));
|
||||
let idle = cfg.server.tcp_idle_timeout;
|
||||
loop {
|
||||
let (stream, peer) = tokio::select! {
|
||||
r = listener.accept() => match r { Ok(v) => v, Err(_) => continue },
|
||||
_ = shutdown.changed() => break,
|
||||
};
|
||||
// without this, the TLS handshake waits ~40 ms on delayed ACKs (Nagle)
|
||||
let _ = stream.set_nodelay(true);
|
||||
let Ok(permit) = Arc::clone(&conns).try_acquire_owned() else { continue };
|
||||
let acceptor = acceptor.clone();
|
||||
let shared = Arc::clone(&shared);
|
||||
tokio::spawn(async move {
|
||||
match tokio::time::timeout(HANDSHAKE_TIMEOUT, acceptor.accept(stream)).await {
|
||||
Ok(Ok(tls)) => serve_stream(shared, tls, peer, Transport::Dot, idle).await,
|
||||
Ok(Err(e)) => tracing::debug!(%peer, error = %e, "DoT handshake failed"),
|
||||
Err(_) => tracing::debug!(%peer, "DoT handshake timeout"),
|
||||
}
|
||||
drop(permit);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
type DohResponse = hyper::Response<Full<Bytes>>;
|
||||
|
||||
fn reply(status: u16, ctype: &str, body: impl Into<Bytes>) -> DohResponse {
|
||||
let mut r = hyper::Response::new(Full::new(body.into()));
|
||||
*r.status_mut() = hyper::StatusCode::from_u16(status).unwrap_or(hyper::StatusCode::INTERNAL_SERVER_ERROR);
|
||||
if let Ok(v) = hyper::header::HeaderValue::from_str(ctype) {
|
||||
r.headers_mut().insert(hyper::header::CONTENT_TYPE, v);
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
fn min_ttl(b: &[u8]) -> u32 {
|
||||
dns_core::proto::op::Message::from_vec(b)
|
||||
.ok()
|
||||
.and_then(|m| m.answers.iter().chain(m.authorities.iter()).map(|r| r.ttl).min())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// One DoH request (RFC 8484): GET `?dns=` or POST `application/dns-message`.
|
||||
async fn doh_request(shared: &Shared, req: hyper::Request<hyper::body::Incoming>, peer: SocketAddr) -> DohResponse {
|
||||
if req.uri().path() != "/dns-query" {
|
||||
return reply(404, "text/plain", "not found\n");
|
||||
}
|
||||
let msg: Vec<u8> = match *req.method() {
|
||||
hyper::Method::GET => {
|
||||
let q = req.uri().query().unwrap_or("");
|
||||
let Some(v) = q.split('&').find_map(|kv| kv.strip_prefix("dns=")) else {
|
||||
return reply(400, "text/plain", "missing dns parameter\n");
|
||||
};
|
||||
match BASE64URL_NOPAD.decode(v.trim_end_matches('=').as_bytes()) {
|
||||
Ok(b) if b.len() <= MAX_HTTP_BODY => b,
|
||||
_ => return reply(400, "text/plain", "invalid base64url\n"),
|
||||
}
|
||||
}
|
||||
hyper::Method::POST => {
|
||||
let ct = req.headers().get(hyper::header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).unwrap_or("");
|
||||
if !ct.trim().eq_ignore_ascii_case("application/dns-message") {
|
||||
return reply(415, "text/plain", "use application/dns-message\n");
|
||||
}
|
||||
let http1 = req.version() < hyper::Version::HTTP_2;
|
||||
let declared =
|
||||
req.headers().get(hyper::header::CONTENT_LENGTH).and_then(|v| v.to_str().ok()).and_then(|v| v.parse::<u64>().ok());
|
||||
let body = if declared.is_some_and(|n| n > MAX_HTTP_BODY as u64) {
|
||||
None
|
||||
} else {
|
||||
// bounded size and time (no slow-body attacks)
|
||||
tokio::time::timeout(BODY_TIMEOUT, Limited::new(req.into_body(), MAX_HTTP_BODY).collect()).await.ok().and_then(Result::ok)
|
||||
};
|
||||
match body {
|
||||
Some(b) => b.to_bytes().to_vec(),
|
||||
None => {
|
||||
let mut r = reply(413, "text/plain", "payload too large or too slow\n");
|
||||
if http1 {
|
||||
// the unread body makes the connection unusable: close it instead of waiting
|
||||
r.headers_mut().insert(hyper::header::CONNECTION, hyper::header::HeaderValue::from_static("close"));
|
||||
}
|
||||
return r;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let mut r = reply(405, "text/plain", "use GET or POST\n");
|
||||
r.headers_mut().insert(hyper::header::ALLOW, hyper::header::HeaderValue::from_static("GET, POST"));
|
||||
return r;
|
||||
}
|
||||
};
|
||||
if msg.len() < 12 {
|
||||
return reply(400, "text/plain", "DNS message too short\n");
|
||||
}
|
||||
match handle(shared, &msg, peer, Transport::Doh).await {
|
||||
Reply::One(b) => {
|
||||
let ttl = min_ttl(&b);
|
||||
let mut r = reply(200, "application/dns-message", b);
|
||||
if let Ok(v) = hyper::header::HeaderValue::from_str(&format!("max-age={ttl}")) {
|
||||
r.headers_mut().insert(hyper::header::CACHE_CONTROL, v);
|
||||
}
|
||||
r
|
||||
}
|
||||
Reply::Many(_) => reply(400, "text/plain", "zone transfers are not available over DoH\n"),
|
||||
Reply::None => reply(429, "text/plain", "request dropped\n"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Serve one DoH connection: HTTP/1.1 (keep-alive) or HTTP/2 (multiplexed; selected by
|
||||
/// ALPN, or by the HTTP/2 preface on plaintext connections behind a proxy).
|
||||
pub async fn serve_http<S>(shared: Arc<Shared>, s: S, peer: SocketAddr, idle: Duration)
|
||||
where
|
||||
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static,
|
||||
{
|
||||
let svc = service_fn(move |req| {
|
||||
let shared = Arc::clone(&shared);
|
||||
async move { Ok::<_, std::convert::Infallible>(doh_request(&shared, req, peer).await) }
|
||||
});
|
||||
let mut b = AutoBuilder::new(TokioExecutor::new());
|
||||
b.http1().timer(TokioTimer::new()).header_read_timeout(idle).keep_alive(true).max_buf_size(MAX_HTTP_HEADER + MAX_HTTP_BODY);
|
||||
b.http2()
|
||||
.timer(TokioTimer::new())
|
||||
.max_concurrent_streams(MAX_H2_STREAMS)
|
||||
.keep_alive_interval(Some(idle))
|
||||
.keep_alive_timeout(idle)
|
||||
.max_header_list_size(MAX_HTTP_HEADER as u32);
|
||||
if let Err(e) = b.serve_connection(TokioIo::new(s), svc).await {
|
||||
tracing::debug!(%peer, error = %e, "DoH connection ended");
|
||||
}
|
||||
}
|
||||
|
||||
/// Serve DoH (TLS, or plaintext when `tls` is `None` – only behind a reverse proxy).
|
||||
pub async fn serve_doh(shared: Arc<Shared>, listener: TcpListener, tls: Option<Arc<ServerConfig>>, mut shutdown: watch::Receiver<bool>) {
|
||||
let acceptor = tls.map(TlsAcceptor::from);
|
||||
let cfg = shared.rt().cfg.clone();
|
||||
let conns = Arc::new(Semaphore::new(cfg.server.max_tcp_connections));
|
||||
let idle = cfg.server.tcp_idle_timeout.max(Duration::from_secs(30));
|
||||
loop {
|
||||
let (stream, peer) = tokio::select! {
|
||||
r = listener.accept() => match r { Ok(v) => v, Err(_) => continue },
|
||||
_ = shutdown.changed() => break,
|
||||
};
|
||||
let _ = stream.set_nodelay(true);
|
||||
let Ok(permit) = Arc::clone(&conns).try_acquire_owned() else { continue };
|
||||
let acceptor = acceptor.clone();
|
||||
let shared = Arc::clone(&shared);
|
||||
tokio::spawn(async move {
|
||||
shared.metrics.tcp_connections.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
match acceptor {
|
||||
Some(a) => match tokio::time::timeout(HANDSHAKE_TIMEOUT, a.accept(stream)).await {
|
||||
Ok(Ok(tls)) => serve_http(Arc::clone(&shared), tls, peer, idle).await,
|
||||
Ok(Err(e)) => tracing::debug!(%peer, error = %e, "DoH handshake failed"),
|
||||
Err(_) => tracing::debug!(%peer, "DoH handshake timeout"),
|
||||
},
|
||||
None => serve_http(Arc::clone(&shared), stream, peer, idle).await,
|
||||
}
|
||||
shared.metrics.tcp_connections.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
|
||||
drop(permit);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn pair(dir: &Path, name: &str) -> Vec<u8> {
|
||||
let ck = rcgen::generate_simple_self_signed(vec![name.to_string()]).unwrap();
|
||||
std::fs::write(dir.join("c.pem"), ck.cert.pem()).unwrap();
|
||||
std::fs::write(dir.join("k.pem"), ck.signing_key.serialize_pem()).unwrap();
|
||||
ck.cert.der().to_vec()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn certificate_is_reloaded_when_files_change() {
|
||||
let d = std::env::temp_dir().join(format!("edns-cert-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let first = pair(&d, "one.test");
|
||||
let store = CertStore::load(&d.join("c.pem"), &d.join("k.pem")).unwrap();
|
||||
let current = |s: &CertStore| s.current.read().unwrap().cert[0].to_vec();
|
||||
assert_eq!(current(&store), first);
|
||||
assert!(!store.reload_if_changed().unwrap());
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
let second = pair(&d, "two.test");
|
||||
assert!(store.reload_if_changed().unwrap());
|
||||
assert_eq!(current(&store), second);
|
||||
// a broken renewal is rejected and the working certificate stays
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
std::fs::write(d.join("k.pem"), "garbage").unwrap();
|
||||
assert!(store.reload_if_changed().is_err());
|
||||
assert_eq!(current(&store), second);
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
//! Authoritative behaviour, Primary↔Secondary synchronisation, TSIG/ACL, DDNS.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used)]
|
||||
mod common;
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use common::*;
|
||||
use dns_core::client::{QueryOptions, TransferKind, TransferLimits, exchange, transfer};
|
||||
use dns_core::proto::op::ResponseCode;
|
||||
use dns_core::proto::rr::rdata::{A, TXT};
|
||||
use dns_core::proto::rr::{DNSClass, RData, Record, RecordType};
|
||||
use dns_core::tsig::TsigKey;
|
||||
|
||||
const ZONE: &str = r#"$TTL 300
|
||||
@ IN SOA ns1 hostmaster 2024010101 3600 5 1209600 60
|
||||
IN NS ns1
|
||||
IN MX 10 mail
|
||||
ns1 IN A 127.0.0.1
|
||||
mail IN A 192.0.2.25
|
||||
www IN A 192.0.2.10
|
||||
www IN AAAA 2001:db8::10
|
||||
alias IN CNAME www
|
||||
*.wild IN TXT "wild"
|
||||
sub IN NS ns.sub
|
||||
ns.sub IN A 192.0.2.53
|
||||
"#;
|
||||
|
||||
fn primary_yaml(dir: &std::path::Path, extra_zone: &str) -> String {
|
||||
write(dir, "example.com.zone", ZONE);
|
||||
format!(
|
||||
r#"
|
||||
server: {{ mode: primary, listen: ["127.0.0.1:0"], data_dir: data }}
|
||||
keys:
|
||||
- {{ name: xfr-key, algorithm: hmac-sha256, secret: "base64:{KEY_B64}" }}
|
||||
- {{ name: ddns-key, algorithm: hmac-sha256, secret: "base64:{KEY_B64}" }}
|
||||
api: {{ enabled: false }}
|
||||
rate_limit: {{ enabled: false }}
|
||||
zones:
|
||||
- name: example.com
|
||||
type: primary
|
||||
file: example.com.zone
|
||||
transfer_tsig_key: xfr-key
|
||||
update_keys: [ddns-key]
|
||||
update_acl: ["127.0.0.0/8"]
|
||||
{extra_zone}
|
||||
"#
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn authoritative_answers() {
|
||||
let dir = tmpdir("auth");
|
||||
let h = start(&dir, &primary_yaml(&dir, "")).await;
|
||||
let s = h.bound.dns[0];
|
||||
|
||||
let m = q(s, "www.example.com.", RecordType::A).await;
|
||||
assert!(m.metadata.authoritative);
|
||||
assert!(!m.metadata.recursion_available);
|
||||
assert_eq!(answers(&m), vec!["A 192.0.2.10"]);
|
||||
|
||||
let m = q(s, "alias.example.com.", RecordType::AAAA).await;
|
||||
assert_eq!(answers(&m), vec!["AAAA 2001:db8::10", "CNAME www.example.com."]);
|
||||
|
||||
let m = q(s, "nope.example.com.", RecordType::A).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NXDomain);
|
||||
assert!(m.metadata.authoritative);
|
||||
assert_eq!(m.authorities[0].record_type(), RecordType::SOA);
|
||||
|
||||
let m = q(s, "www.example.com.", RecordType::MX).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NoError);
|
||||
assert!(m.answers.is_empty());
|
||||
assert_eq!(m.authorities[0].ttl, 60, "negative TTL = min(SOA TTL, MINIMUM)");
|
||||
|
||||
let m = q(s, "x.wild.example.com.", RecordType::TXT).await;
|
||||
assert_eq!(answers(&m), vec!["TXT wild"]);
|
||||
|
||||
let m = q(s, "host.sub.example.com.", RecordType::A).await;
|
||||
assert!(!m.metadata.authoritative, "referral is not authoritative");
|
||||
assert_eq!(m.authorities[0].record_type(), RecordType::NS);
|
||||
assert_eq!(m.additionals.len(), 1);
|
||||
|
||||
let m = q(s, "example.com.", RecordType::MX).await;
|
||||
assert_eq!(m.additionals.len(), 1, "MX target address in additional section");
|
||||
|
||||
// Not our zone + no recursion configured -> REFUSED (no open resolver).
|
||||
let m = q(s, "www.example.org.", RecordType::A).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::Refused);
|
||||
|
||||
// TCP works too.
|
||||
let m = q_opts(s, "www.example.com.", RecordType::A, QueryOptions { tcp_only: true, ..Default::default() }).await;
|
||||
assert_eq!(answers(&m), vec!["A 192.0.2.10"]);
|
||||
|
||||
// Malformed packet -> FORMERR, response packets are ignored.
|
||||
let sock = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
sock.send_to(&[0x12, 0x34, 0x01, 0x00, 0, 1, 0, 0, 0, 0, 0, 0, 0xff, 0xff], s).await.unwrap();
|
||||
let mut buf = [0u8; 512];
|
||||
let (n, _) = tokio::time::timeout(Duration::from_secs(2), sock.recv_from(&mut buf)).await.unwrap().unwrap();
|
||||
let r = dns_core::proto::op::Message::from_vec(&buf[..n]).unwrap();
|
||||
assert_eq!((r.metadata.id, r.metadata.response_code), (0x1234, ResponseCode::FormErr));
|
||||
|
||||
h.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn transfers_require_tsig_and_acl() {
|
||||
let dir = tmpdir("xfr");
|
||||
let h = start(&dir, &primary_yaml(&dir, "")).await;
|
||||
let s = h.bound.dns[0];
|
||||
let zone = n("example.com.");
|
||||
let lim = TransferLimits { timeout: Duration::from_secs(5), ..Default::default() };
|
||||
|
||||
// No TSIG -> refused.
|
||||
let e = transfer(s, &zone, &TransferKind::Axfr, None, lim).await.unwrap_err();
|
||||
assert!(e.to_string().contains("REFUSED") || e.to_string().contains("Refused"), "{e}");
|
||||
// Wrong key secret -> NOTAUTH, and response cannot be verified.
|
||||
let bad = TsigKey::new("xfr-key", "hmac-sha256", "d3JvbmdzZWNyZXR3cm9uZ3NlY3JldA==").unwrap();
|
||||
assert!(transfer(s, &zone, &TransferKind::Axfr, Some(&bad), lim).await.is_err());
|
||||
// Right key -> full zone, every message verified.
|
||||
let key = TsigKey::new("xfr-key", "hmac-sha256", KEY_B64).unwrap();
|
||||
let st = transfer(s, &zone, &TransferKind::Axfr, Some(&key), lim).await.unwrap();
|
||||
assert!(st.tsig_verified);
|
||||
assert_eq!(st.records.first().unwrap().record_type(), RecordType::SOA);
|
||||
assert_eq!(st.records.last().unwrap().record_type(), RecordType::SOA);
|
||||
assert_eq!(st.records.len(), 12);
|
||||
let m = &h.shared.metrics;
|
||||
assert_eq!(m.xfr_out_refused.load(std::sync::atomic::Ordering::Relaxed), 1, "unsigned AXFR refused");
|
||||
assert_eq!(m.tsig_failures.load(std::sync::atomic::Ordering::Relaxed), 1, "bad MAC -> NOTAUTH");
|
||||
// AXFR over UDP is refused
|
||||
let mut am = dns_core::proto::op::Message::query();
|
||||
am.add_query(dns_core::proto::op::Query::query(zone.clone(), RecordType::AXFR));
|
||||
let mut opts = dns_core::client::QueryOptions { tsig: Some(key.clone()), ignore_tc: true, ..Default::default() };
|
||||
opts.retries = 0;
|
||||
let ex = exchange(s, am, &opts).await.unwrap();
|
||||
assert_eq!(ex.message.metadata.response_code, ResponseCode::Refused);
|
||||
h.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn primary_secondary_sync_notify_ixfr_restart() {
|
||||
// --- primary
|
||||
let pdir = tmpdir("pri");
|
||||
// the secondary listens on a fixed free port so the primary can NOTIFY it
|
||||
let sport = free_port();
|
||||
let secondary_addr = format!("127.0.0.1:{sport}");
|
||||
let p_yaml = primary_yaml(&pdir, "").replace(
|
||||
" update_keys: [ddns-key]",
|
||||
&format!(" notify: [\"{secondary_addr}\"]\n notify_tsig_key: xfr-key\n update_keys: [ddns-key]"),
|
||||
);
|
||||
let p = start(&pdir, &p_yaml).await;
|
||||
let paddr = p.bound.dns[0];
|
||||
|
||||
// --- secondary
|
||||
let sdir = tmpdir("sec");
|
||||
let s_yaml = format!(
|
||||
r#"
|
||||
server: {{ mode: secondary, listen: ["{secondary_addr}"], data_dir: data }}
|
||||
keys:
|
||||
- {{ name: xfr-key, algorithm: hmac-sha256, secret: "base64:{KEY_B64}" }}
|
||||
api: {{ enabled: false }}
|
||||
rate_limit: {{ enabled: false }}
|
||||
zones:
|
||||
- name: example.com
|
||||
type: secondary
|
||||
primaries: ["{paddr}"]
|
||||
transfer: {{ prefer: ixfr, fallback_axfr: true, tsig_key: xfr-key }}
|
||||
"#
|
||||
);
|
||||
let s = start(&sdir, &s_yaml).await;
|
||||
let saddr = s.bound.dns[0];
|
||||
|
||||
// initial AXFR
|
||||
eventually("secondary loads zone", || async { q(saddr, "www.example.com.", RecordType::A).await.answers.len() == 1 }).await;
|
||||
let m = q(saddr, "www.example.com.", RecordType::A).await;
|
||||
assert!(m.metadata.authoritative, "secondary answers authoritatively from its own copy");
|
||||
let entry = s.shared.rt().zones.get(&n("example.com.")).unwrap();
|
||||
assert_eq!(entry.transfers().last().unwrap().kind, "AXFR");
|
||||
|
||||
// change on the primary (same path the API uses) -> NOTIFY -> IXFR
|
||||
let pentry = p.shared.rt().zones.get(&n("example.com.")).unwrap();
|
||||
let new = Record::from_rdata(n("new.example.com."), 300, RData::A(A::new(192, 0, 2, 77)));
|
||||
let serial = pentry.modify(&[], &[new]).unwrap();
|
||||
pentry.send_notifies();
|
||||
eventually("secondary receives IXFR", || async { q(saddr, "new.example.com.", RecordType::A).await.answers.len() == 1 }).await;
|
||||
assert_eq!(entry.current().unwrap().serial(), serial);
|
||||
assert_eq!(entry.transfers().last().unwrap().kind, "IXFR");
|
||||
assert!(s.shared.metrics.notify_received.load(std::sync::atomic::Ordering::Relaxed) >= 1);
|
||||
// the primary's zone file was rewritten atomically with the new serial
|
||||
let text = std::fs::read_to_string(pdir.join("example.com.zone")).unwrap();
|
||||
assert!(text.contains("192.0.2.77"));
|
||||
|
||||
// NOTIFY from an unauthorised source is refused
|
||||
let mut nm = dns_core::proto::op::Message::new(7, dns_core::proto::op::MessageType::Query, dns_core::proto::op::OpCode::Notify);
|
||||
nm.add_query(dns_core::proto::op::Query::query(n("example.com."), RecordType::SOA));
|
||||
let sock = tokio::net::UdpSocket::bind("127.0.0.9:0").await.unwrap();
|
||||
sock.send_to(&nm.to_vec().unwrap(), saddr).await.unwrap();
|
||||
let mut buf = [0u8; 512];
|
||||
let (len, _) = tokio::time::timeout(Duration::from_secs(2), sock.recv_from(&mut buf)).await.unwrap().unwrap();
|
||||
assert_eq!(dns_core::proto::op::Message::from_vec(&buf[..len]).unwrap().metadata.response_code, ResponseCode::Refused);
|
||||
|
||||
// restart the secondary while the primary is down: the persisted copy is served
|
||||
s.shutdown().await;
|
||||
p.shutdown().await;
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
let s2 = start(&sdir, &s_yaml).await;
|
||||
let m = q(s2.bound.dns[0], "new.example.com.", RecordType::A).await;
|
||||
assert_eq!(answers(&m), vec!["A 192.0.2.77"]);
|
||||
assert!(m.metadata.authoritative);
|
||||
s2.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn secondary_expires_when_primary_unreachable() {
|
||||
let sdir = tmpdir("exp");
|
||||
std::fs::create_dir_all(sdir.join("data/secondary")).unwrap();
|
||||
// snapshot with tiny EXPIRE whose last success is long ago
|
||||
let z = ZONE.replace("3600 5 1209600 60", "5 5 10 60");
|
||||
write(&sdir.join("data/secondary"), "example.com.zone", &z);
|
||||
write(
|
||||
&sdir.join("data/secondary"),
|
||||
"example.com.zone.meta.json",
|
||||
r#"{"last_success_unix": 1000, "serial": 2024010101, "primary": "x"}"#,
|
||||
);
|
||||
let yaml = r#"
|
||||
server: { listen: ["127.0.0.1:0"], data_dir: data }
|
||||
api: { enabled: false }
|
||||
zones:
|
||||
- { name: example.com, type: secondary, primaries: ["127.0.0.1:9"] }
|
||||
"#;
|
||||
let s = start(&sdir, yaml).await;
|
||||
let m = q(s.bound.dns[0], "www.example.com.", RecordType::A).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::ServFail, "expired zone must not be served as authoritative");
|
||||
s.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn dynamic_update_authorised_and_refused() {
|
||||
let dir = tmpdir("ddns");
|
||||
let h = start(&dir, &primary_yaml(&dir, "")).await;
|
||||
let s = h.bound.dns[0];
|
||||
let zone = n("example.com.");
|
||||
let rec = Record::from_rdata(n("dyn.example.com."), 120, RData::A(A::new(192, 0, 2, 200)));
|
||||
|
||||
// unsigned -> REFUSED
|
||||
let m = dns_authoritative::update::build_update(&zone, vec![], vec![rec.clone()]);
|
||||
let ex = exchange(s, m, &QueryOptions::default()).await.unwrap();
|
||||
assert_eq!(ex.message.metadata.response_code, ResponseCode::Refused);
|
||||
|
||||
// signed with the update key -> applied
|
||||
let key = TsigKey::new("ddns-key", "hmac-sha256", KEY_B64).unwrap();
|
||||
let opts = QueryOptions { tsig: Some(key.clone()), ..Default::default() };
|
||||
let m = dns_authoritative::update::build_update(&zone, vec![], vec![rec.clone()]);
|
||||
let ex = exchange(s, m, &opts).await.unwrap();
|
||||
assert_eq!(ex.message.metadata.response_code, ResponseCode::NoError);
|
||||
assert!(ex.tsig_verified);
|
||||
assert_eq!(answers(&q(s, "dyn.example.com.", RecordType::A).await), vec!["A 192.0.2.200"]);
|
||||
|
||||
// prerequisite "name not in use" fails -> YXDOMAIN
|
||||
let mut pre = Record::update0(n("dyn.example.com."), 0, RecordType::ANY);
|
||||
pre.dns_class = DNSClass::NONE;
|
||||
let m = dns_authoritative::update::build_update(&zone, vec![pre], vec![rec.clone()]);
|
||||
let ex = exchange(s, m, &opts).await.unwrap();
|
||||
assert_eq!(ex.message.metadata.response_code, ResponseCode::YXDomain);
|
||||
|
||||
// delete the RRset
|
||||
let mut del = Record::update0(n("dyn.example.com."), 0, RecordType::A);
|
||||
del.dns_class = DNSClass::ANY;
|
||||
let m = dns_authoritative::update::build_update(&zone, vec![], vec![del]);
|
||||
assert_eq!(exchange(s, m, &opts).await.unwrap().message.metadata.response_code, ResponseCode::NoError);
|
||||
assert_eq!(q(s, "dyn.example.com.", RecordType::A).await.metadata.response_code, ResponseCode::NXDomain);
|
||||
|
||||
// the audit log captured both
|
||||
let audit = h.shared.audit.tail(10);
|
||||
assert!(audit.len() >= 3);
|
||||
h.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn update_policy_with_bind_key_file_and_ip_only_updates() {
|
||||
let dir = tmpdir("ddns-policy");
|
||||
write(&dir, "example.com.zone", ZONE);
|
||||
write(&dir, "example.net.zone", "$TTL 60\n@ SOA ns hostmaster 1 60 60 600 60\n@ NS ns\nns A 192.0.2.1\n");
|
||||
// key file copied from BIND, included unchanged
|
||||
write(
|
||||
&dir,
|
||||
"keys.conf",
|
||||
&format!(
|
||||
"key \"acme-key.\" {{\n\talgorithm hmac-sha256;\n\tsecret \"{KEY_B64}\";\n}};\nkey \"other-key\" {{ algorithm hmac-sha256; secret \"{KEY_B64}\"; }};\n"
|
||||
),
|
||||
);
|
||||
let yaml = r#"
|
||||
include: [keys.conf]
|
||||
server: { mode: primary, listen: ["127.0.0.1:0"], data_dir: data }
|
||||
api: { enabled: false }
|
||||
rate_limit: { enabled: false }
|
||||
zones:
|
||||
- name: example.com
|
||||
type: primary
|
||||
file: example.com.zone
|
||||
update_policy:
|
||||
- "grant acme-key. name _acme-challenge.example.com. TXT"
|
||||
- "grant acme-key. wildcard *.dyn.example.com. A"
|
||||
- { deny: other-key, match: zonesub }
|
||||
- name: example.net
|
||||
type: primary
|
||||
file: example.net.zone
|
||||
allow_update: ["127.0.0.1"] # IP only, no key (BIND allow-update { 127.0.0.1; })
|
||||
"#;
|
||||
let h = start(&dir, yaml).await;
|
||||
let s = h.bound.dns[0];
|
||||
let zone = n("example.com.");
|
||||
let txt = |owner: &str| Record::from_rdata(n(owner), 60, RData::TXT(TXT::new(vec!["token".into()])));
|
||||
let a = |owner: &str| Record::from_rdata(n(owner), 60, RData::A(A::new(192, 0, 2, 7)));
|
||||
let acme = QueryOptions { tsig: Some(TsigKey::new("acme-key.", "hmac-sha256", KEY_B64).unwrap()), ..Default::default() };
|
||||
let other = QueryOptions { tsig: Some(TsigKey::new("other-key", "hmac-sha256", KEY_B64).unwrap()), ..Default::default() };
|
||||
let rc = |ex: dns_core::client::Exchange| ex.message.metadata.response_code;
|
||||
let up = |r: Record| dns_authoritative::update::build_update(&zone, vec![], vec![r]);
|
||||
|
||||
// granted: exact name + type
|
||||
assert_eq!(rc(exchange(s, up(txt("_acme-challenge.example.com.")), &acme).await.unwrap()), ResponseCode::NoError);
|
||||
assert_eq!(answers(&q(s, "_acme-challenge.example.com.", RecordType::TXT).await), vec!["TXT token"]);
|
||||
// wrong type / wrong name / unsigned / other key -> refused
|
||||
assert_eq!(rc(exchange(s, up(a("_acme-challenge.example.com.")), &acme).await.unwrap()), ResponseCode::Refused);
|
||||
assert_eq!(rc(exchange(s, up(txt("www.example.com.")), &acme).await.unwrap()), ResponseCode::Refused);
|
||||
assert_eq!(rc(exchange(s, up(txt("_acme-challenge.example.com.")), &QueryOptions::default()).await.unwrap()), ResponseCode::Refused);
|
||||
assert_eq!(rc(exchange(s, up(txt("_acme-challenge.example.com.")), &other).await.unwrap()), ResponseCode::Refused);
|
||||
// wildcard: strictly below dyn.example.com
|
||||
assert_eq!(rc(exchange(s, up(a("h1.dyn.example.com.")), &acme).await.unwrap()), ResponseCode::NoError);
|
||||
assert_eq!(rc(exchange(s, up(a("dyn.example.com.")), &acme).await.unwrap()), ResponseCode::Refused);
|
||||
|
||||
// IP-only zone: unsigned update from 127.0.0.1 is accepted
|
||||
let net = n("example.net.");
|
||||
let m = dns_authoritative::update::build_update(&net, vec![], vec![a("host.example.net.")]);
|
||||
assert_eq!(rc(exchange(s, m, &QueryOptions::default()).await.unwrap()), ResponseCode::NoError);
|
||||
assert_eq!(answers(&q(s, "host.example.net.", RecordType::A).await), vec!["A 192.0.2.7"]);
|
||||
h.shutdown().await;
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
#![allow(dead_code, clippy::unwrap_used, clippy::expect_used)]
|
||||
use std::net::SocketAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use dns_config::{Config, Overrides};
|
||||
use dns_core::client::{QueryOptions, query};
|
||||
use dns_core::proto::op::Message;
|
||||
use dns_core::proto::rr::{Name, RecordType};
|
||||
use dns_server::{Server, ServerHandle};
|
||||
|
||||
pub fn tmpdir(tag: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("easydns-it-{tag}-{}-{}", std::process::id(), rand_u32()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
pub fn rand_u32() -> u32 {
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
let n = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().subsec_nanos();
|
||||
n ^ (std::process::id() << 16)
|
||||
}
|
||||
|
||||
pub fn write(dir: &Path, name: &str, text: &str) -> PathBuf {
|
||||
let p = dir.join(name);
|
||||
std::fs::write(&p, text).unwrap();
|
||||
p
|
||||
}
|
||||
|
||||
pub async fn start(dir: &Path, yaml: &str) -> ServerHandle {
|
||||
let path = write(dir, "config.yaml", yaml);
|
||||
let cfg = Config::load(&path).unwrap();
|
||||
Server::start(cfg, Some(path), Overrides::default()).await.unwrap()
|
||||
}
|
||||
|
||||
pub fn n(s: &str) -> Name {
|
||||
Name::from_ascii(s).unwrap()
|
||||
}
|
||||
|
||||
pub async fn q(server: SocketAddr, name: &str, t: RecordType) -> Message {
|
||||
q_opts(server, name, t, QueryOptions { timeout: Duration::from_secs(3), retries: 1, ..Default::default() }).await
|
||||
}
|
||||
|
||||
pub async fn q_opts(server: SocketAddr, name: &str, t: RecordType, o: QueryOptions) -> Message {
|
||||
query(server, &n(name), t, &o).await.unwrap_or_else(|e| panic!("query {name} {t} @{server}: {e}")).message
|
||||
}
|
||||
|
||||
pub fn answers(m: &Message) -> Vec<String> {
|
||||
let mut v: Vec<String> = m.answers.iter().map(|r| format!("{} {}", r.record_type(), r.data)).collect();
|
||||
v.sort();
|
||||
v
|
||||
}
|
||||
|
||||
/// Poll until `f` returns true (max ~10 s).
|
||||
pub async fn eventually<F, Fut>(what: &str, mut f: F)
|
||||
where
|
||||
F: FnMut() -> Fut,
|
||||
Fut: std::future::Future<Output = bool>,
|
||||
{
|
||||
for _ in 0..200 {
|
||||
if f().await {
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
panic!("timed out waiting for: {what}");
|
||||
}
|
||||
|
||||
/// A random free port usable on several 127.0.0.x addresses.
|
||||
pub fn free_port() -> u16 {
|
||||
for _ in 0..50 {
|
||||
let p = 20000 + (rand_u32() % 30000) as u16;
|
||||
let ok = ["127.0.0.2", "127.0.0.3", "127.0.0.4", "127.0.0.5", "127.0.0.6"].iter().all(|ip| {
|
||||
let a: SocketAddr = format!("{ip}:{p}").parse().unwrap();
|
||||
std::net::UdpSocket::bind(a).is_ok() && std::net::TcpListener::bind(a).is_ok()
|
||||
});
|
||||
if ok {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
panic!("no free port");
|
||||
}
|
||||
|
||||
pub const KEY_B64: &str = "c2VjcmV0c2VjcmV0c2VjcmV0c2VjcmV0c2VjcmV0MTI=";
|
||||
@@ -0,0 +1,182 @@
|
||||
//! DNSSEC end-to-end: online signing on primaries + validating recursive resolver.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used)]
|
||||
mod common;
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use common::*;
|
||||
use dns_core::client::QueryOptions;
|
||||
use dns_core::dnssec::{KeyAlgorithm, ZoneKey, key_file_contents};
|
||||
use dns_core::proto::op::ResponseCode;
|
||||
use dns_core::proto::rr::RecordType;
|
||||
use dns_server::ServerHandle;
|
||||
|
||||
/// Generate a CSK for `zone` into `dir`; returns (DS line, DNSKEY line).
|
||||
fn keygen(dir: &Path, zone: &str) -> (String, String) {
|
||||
let z = n(zone);
|
||||
let (pk, key) = ZoneKey::generate(KeyAlgorithm::Ed25519, true).unwrap();
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
let prefix = if zone == "." { "root.".to_string() } else { zone.to_string() };
|
||||
std::fs::write(dir.join(format!("{prefix}{}.csk.key", key.tag)), key_file_contents(KeyAlgorithm::Ed25519, true, &pk)).unwrap();
|
||||
let ds = key.ds_record(&z, 3600).unwrap();
|
||||
let dk = key.dnskey_record(&z, 3600);
|
||||
(format!("{} 3600 IN DS {}", ds.name, ds.data), format!("{} 3600 IN DNSKEY {}", dk.name, dk.data))
|
||||
}
|
||||
|
||||
async fn server(dir: &Path, tag: &str, ip: &str, port: u16, zones: &[(&str, String, bool)]) -> ServerHandle {
|
||||
let d = dir.join(tag);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let mut zl = String::new();
|
||||
for (name, text, signed) in zones {
|
||||
let f = format!("{}.zone", if *name == "." { "root" } else { name.trim_end_matches('.') });
|
||||
write(&d, &f, text);
|
||||
let dnssec = if *signed {
|
||||
format!(
|
||||
", dnssec: {{ keys_dir: \"{}\", auto_generate: false }}",
|
||||
dir.join("keys").join(name.trim_end_matches('.').replace('.', "_")).display()
|
||||
)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
zl.push_str(&format!(" - {{ name: \"{name}\", type: primary, file: \"{f}\"{dnssec} }}\n"));
|
||||
}
|
||||
let yaml = format!(
|
||||
"server: {{ listen: [\"{ip}:{port}\"], data_dir: data }}\napi: {{ enabled: false }}\nrate_limit: {{ enabled: false }}\nzones:\n{zl}"
|
||||
);
|
||||
start(&d, &yaml).await
|
||||
}
|
||||
|
||||
fn kdir(dir: &Path, zone: &str) -> std::path::PathBuf {
|
||||
dir.join("keys").join(zone.trim_end_matches('.').replace('.', "_"))
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn validating_resolver_secure_insecure_bogus() {
|
||||
let dir = tmpdir("dnssec");
|
||||
let port = free_port();
|
||||
let (_, root_key) = keygen(&kdir(&dir, "."), ".");
|
||||
let (zz_ds, _) = keygen(&kdir(&dir, "zz."), "zz.");
|
||||
let (ex_ds, _) = keygen(&kdir(&dir, "example.zz."), "example.zz.");
|
||||
// bogus.zz: the parent publishes a DS for a key the child does not use
|
||||
let (bogus_ds, _) = keygen(&dir.join("unused"), "bogus.zz.");
|
||||
let _ = keygen(&kdir(&dir, "bogus.zz."), "bogus.zz.");
|
||||
|
||||
let root = server(&dir, "root", "127.0.0.2", port, &[(".", format!(
|
||||
"$TTL 3600\n@ IN SOA a.root. hm.root. 1 3600 600 86400 300\n@ IN NS a.root.\na.root. IN A 127.0.0.2\nzz. IN NS ns.zz.\nns.zz. IN A 127.0.0.3\n{zz_ds}\n"), true)]).await;
|
||||
let tld = server(&dir, "tld", "127.0.0.3", port, &[("zz.", format!(
|
||||
"$TTL 3600\n@ IN SOA ns hm 1 3600 600 86400 300\n@ IN NS ns\nns IN A 127.0.0.3\nexample IN NS ns1.example\nns1.example IN A 127.0.0.4\n{ex_ds}\ninsecure IN NS ns1.example\nbogus IN NS ns1.example\n{bogus_ds}\n"), true)]).await;
|
||||
let auth = server(&dir, "auth", "127.0.0.4", port, &[
|
||||
("example.zz.", "$TTL 300\n@ IN SOA ns1 hm 1 3600 600 86400 120\n@ IN NS ns1\nns1 IN A 127.0.0.4\nwww IN A 192.0.2.1\n*.w IN A 192.0.2.7\nalias IN CNAME www\n".into(), true),
|
||||
("insecure.zz.", "$TTL 300\n@ IN SOA ns1.example.zz. hm 1 3600 600 86400 120\n@ IN NS ns1.example.zz.\nwww IN A 192.0.2.2\n".into(), false),
|
||||
("bogus.zz.", "$TTL 300\n@ IN SOA ns1.example.zz. hm 1 3600 600 86400 120\n@ IN NS ns1.example.zz.\nwww IN A 192.0.2.3\n".into(), true),
|
||||
]).await;
|
||||
|
||||
// authoritative side: signed answers and NSEC proofs with DO=1
|
||||
let do_opts = QueryOptions { dnssec_ok: true, recursion_desired: false, ..Default::default() };
|
||||
let m = q_opts(auth.bound.dns[0], "www.example.zz.", RecordType::A, do_opts.clone()).await;
|
||||
assert!(m.answers.iter().any(|r| r.record_type() == RecordType::RRSIG));
|
||||
let m = q_opts(auth.bound.dns[0], "nope.example.zz.", RecordType::A, do_opts.clone()).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NXDomain);
|
||||
assert!(m.authorities.iter().any(|r| r.record_type() == RecordType::NSEC));
|
||||
let m = q(auth.bound.dns[0], "www.example.zz.", RecordType::A).await;
|
||||
assert!(m.answers.iter().all(|r| r.record_type() != RecordType::RRSIG), "no RRSIG without DO");
|
||||
|
||||
// validating resolver anchored at the fixture root key
|
||||
let rdir = tmpdir("validator");
|
||||
write(&rdir, "root.hints", ". 3600000 NS a.root.\na.root. 3600000 A 127.0.0.2\n");
|
||||
write(&rdir, "anchors", &format!("{root_key}\n"));
|
||||
let yaml = format!(
|
||||
r#"
|
||||
server: {{ listen: ["127.0.0.1:0"], data_dir: data }}
|
||||
api: {{ enabled: false }}
|
||||
rate_limit: {{ enabled: false }}
|
||||
recursion: {{ enabled: true, root_hints: root.hints, trust_anchors: anchors, dnssec_validation: true, allowed_clients: ["127.0.0.1/32"], authority_port: {port}, query_timeout: 800ms }}
|
||||
resolution: {{ default: recursive }}
|
||||
"#
|
||||
);
|
||||
let r = start(&rdir, &yaml).await;
|
||||
let s = r.bound.dns[0];
|
||||
let ad = QueryOptions { dnssec_ok: true, ..Default::default() };
|
||||
|
||||
let m = q_opts(s, "www.example.zz.", RecordType::A, ad.clone()).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NoError, "{m:?}");
|
||||
assert!(m.metadata.authentic_data, "secure answer must have AD");
|
||||
assert_eq!(answers(&m).iter().filter(|a| a.starts_with("A ")).count(), 1);
|
||||
|
||||
let m = q_opts(s, "alias.example.zz.", RecordType::A, ad.clone()).await;
|
||||
assert!(m.metadata.authentic_data, "secure CNAME chain");
|
||||
|
||||
let m = q_opts(s, "nope.example.zz.", RecordType::A, ad.clone()).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NXDomain);
|
||||
assert!(m.metadata.authentic_data, "validated NXDOMAIN");
|
||||
|
||||
let m = q_opts(s, "www.example.zz.", RecordType::MX, ad.clone()).await;
|
||||
assert_eq!((m.metadata.response_code, m.answers.len()), (ResponseCode::NoError, 0));
|
||||
assert!(m.metadata.authentic_data, "validated NODATA");
|
||||
|
||||
let m = q_opts(s, "x.w.example.zz.", RecordType::A, ad.clone()).await;
|
||||
assert!(m.metadata.authentic_data, "validated wildcard expansion");
|
||||
|
||||
let m = q_opts(s, "www.insecure.zz.", RecordType::A, ad.clone()).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NoError);
|
||||
assert!(!m.metadata.authentic_data, "provably insecure delegation: no AD");
|
||||
assert_eq!(answers(&m), vec!["A 192.0.2.2"]);
|
||||
|
||||
let m = q_opts(s, "www.bogus.zz.", RecordType::A, ad.clone()).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::ServFail, "bogus data is not returned");
|
||||
assert!(m.answers.is_empty());
|
||||
let cd = QueryOptions { dnssec_ok: true, checking_disabled: true, ..Default::default() };
|
||||
let m = q_opts(s, "www.bogus.zz.", RecordType::A, cd).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NoError, "CD=1 returns unvalidated data");
|
||||
assert!(!m.metadata.authentic_data);
|
||||
|
||||
// clients without DO still get validated (AD only when requested)
|
||||
let m = q(s, "www.example.zz.", RecordType::A).await;
|
||||
assert!(m.answers.iter().all(|r| r.record_type() != RecordType::RRSIG));
|
||||
assert!(r.shared.metrics.dnssec_bogus.load(std::sync::atomic::Ordering::Relaxed) >= 1);
|
||||
|
||||
for h in [r, root, tld, auth] {
|
||||
h.shutdown().await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn signed_zone_changes_are_resigned_and_persisted() {
|
||||
let dir = tmpdir("sign-persist");
|
||||
keygen(&kdir(&dir, "example.com."), "example.com.");
|
||||
let port = free_port();
|
||||
let zone = "$TTL 300\n@ IN SOA ns hm 10 3600 600 86400 60\n@ IN NS ns\nns IN A 127.0.0.1\nwww IN A 192.0.2.1\n".to_string();
|
||||
let h = server(&dir, "p", "127.0.0.2", port, &[("example.com.", zone.clone(), true)]).await;
|
||||
let e = h.shared.rt().zones.get(&n("example.com.")).unwrap();
|
||||
let s1 = e.current().unwrap().serial();
|
||||
assert_eq!(s1, 10);
|
||||
let rec = dns_core::proto::rr::Record::from_rdata(
|
||||
n("new.example.com."),
|
||||
300,
|
||||
dns_core::proto::rr::RData::A(dns_core::proto::rr::rdata::A::new(192, 0, 2, 9)),
|
||||
);
|
||||
let s2 = e.modify(&[], &[rec]).unwrap();
|
||||
assert!(dns_core::serial::is_newer(s2, s1));
|
||||
let z = e.current().unwrap();
|
||||
assert!(z.all_records().iter().any(|r| r.name == n("new.example.com.") && r.record_type() == RecordType::RRSIG));
|
||||
assert!(z.all_records().iter().any(|r| r.name == n("new.example.com.") && r.record_type() == RecordType::NSEC));
|
||||
// the source file stays unsigned
|
||||
let src = std::fs::read_to_string(dir.join("p").join("example.com.zone")).unwrap();
|
||||
assert!(!src.contains("RRSIG") && src.contains("192.0.2.9"));
|
||||
let sigs_before: Vec<String> =
|
||||
z.all_records().iter().filter(|r| r.record_type() == RecordType::RRSIG).map(|r| r.data.to_string()).collect();
|
||||
h.shutdown().await;
|
||||
// restart: the persisted signed zone is reused (same serial, same signatures),
|
||||
// so secondaries never see different signatures under an unchanged serial.
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
let yaml = std::fs::read_to_string(dir.join("p").join("config.yaml")).unwrap();
|
||||
let h2 = start(&dir.join("p"), &yaml).await;
|
||||
let z2 = h2.shared.rt().zones.get(&n("example.com.")).unwrap().current().unwrap();
|
||||
assert_eq!(z2.serial(), s2);
|
||||
let sigs_after: Vec<String> =
|
||||
z2.all_records().iter().filter(|r| r.record_type() == RecordType::RRSIG).map(|r| r.data.to_string()).collect();
|
||||
assert_eq!(sigs_before, sigs_after);
|
||||
// DS for the parent is available
|
||||
assert_eq!(h2.shared.rt().zones.get(&n("example.com.")).unwrap().ds_records().len(), 1);
|
||||
h2.shutdown().await;
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
//! Performance-related behaviour: query coalescing and the SO_REUSEPORT socket group.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used)]
|
||||
mod common;
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use common::*;
|
||||
use dns_core::proto::op::Message;
|
||||
use dns_core::proto::rr::rdata::A;
|
||||
use dns_core::proto::rr::{RData, Record, RecordType};
|
||||
use tokio::net::UdpSocket;
|
||||
|
||||
/// Fake upstream: counts queries and answers each after `delay` with A 192.0.2.53.
|
||||
async fn slow_upstream(delay: Duration) -> (std::net::SocketAddr, Arc<AtomicUsize>) {
|
||||
let sock = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap());
|
||||
let addr = sock.local_addr().unwrap();
|
||||
let count = Arc::new(AtomicUsize::new(0));
|
||||
let c = Arc::clone(&count);
|
||||
tokio::spawn(async move {
|
||||
let mut buf = [0u8; 2048];
|
||||
loop {
|
||||
let Ok((n, peer)) = sock.recv_from(&mut buf).await else { return };
|
||||
let Ok(req) = Message::from_vec(&buf[..n]) else { continue };
|
||||
c.fetch_add(1, Ordering::SeqCst);
|
||||
let sock = Arc::clone(&sock);
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(delay).await;
|
||||
let mut resp = dns_core::wire::response_for(&req);
|
||||
let qn = req.queries[0].name.clone();
|
||||
resp.answers.push(Record::from_rdata(qn, 60, RData::A(A::new(192, 0, 2, 53))));
|
||||
let _ = sock.send_to(&resp.to_vec().unwrap(), peer).await;
|
||||
});
|
||||
}
|
||||
});
|
||||
(addr, count)
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn identical_concurrent_misses_reach_upstream_once() {
|
||||
let (up, count) = slow_upstream(Duration::from_millis(300)).await;
|
||||
let dir = tmpdir("coalesce");
|
||||
let yaml = format!(
|
||||
r#"
|
||||
server: {{ mode: forwarder, listen: ["127.0.0.1:0"], data_dir: data, udp_sockets: 4 }}
|
||||
api: {{ enabled: false }}
|
||||
rate_limit: {{ enabled: false }}
|
||||
upstreams: {{ strategy: failover, timeout: 2s, servers: ["{up}"] }}
|
||||
resolution: {{ default: forward }}
|
||||
"#
|
||||
);
|
||||
let h = start(&dir, &yaml).await;
|
||||
let s = h.bound.dns[0];
|
||||
let qs: Vec<_> = (0..40).map(|_| tokio::spawn(async move { q(s, "burst.example.", RecordType::A).await })).collect();
|
||||
for t in qs {
|
||||
assert_eq!(answers(&t.await.unwrap()), vec!["A 192.0.2.53"]);
|
||||
}
|
||||
assert_eq!(count.load(Ordering::SeqCst), 1, "40 identical misses must cost one upstream query");
|
||||
// a different name is its own resolution
|
||||
q(s, "other.example.", RecordType::A).await;
|
||||
assert_eq!(count.load(Ordering::SeqCst), 2);
|
||||
assert_eq!(h.shared.rt().router.flights.in_flight(), 0);
|
||||
h.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn reuseport_group_shares_one_port_and_answers() {
|
||||
let socks = dns_server::listener::bind_udp_group("127.0.0.1:0".parse().unwrap(), 4).unwrap();
|
||||
let ports: Vec<u16> = socks.iter().map(|s| s.local_addr().unwrap().port()).collect();
|
||||
assert!(!ports.is_empty() && ports.iter().all(|p| *p == ports[0]), "{ports:?}");
|
||||
#[cfg(target_os = "linux")]
|
||||
assert_eq!(socks.len(), 4);
|
||||
drop(socks);
|
||||
|
||||
// the server answers through every socket of the group: many distinct client ports
|
||||
// are hashed by the kernel onto different sockets
|
||||
let dir = tmpdir("reuseport");
|
||||
write(&dir, "z.zone", "$TTL 60\n@ SOA ns hostmaster 1 60 60 600 60\n@ NS ns\nns A 192.0.2.1\nwww A 192.0.2.80\n");
|
||||
let yaml = r#"
|
||||
server: { mode: primary, listen: ["127.0.0.1:0"], data_dir: data, udp_sockets: 4 }
|
||||
api: { enabled: false }
|
||||
rate_limit: { enabled: false }
|
||||
zones: [ { name: example.test, type: primary, file: z.zone } ]
|
||||
"#;
|
||||
let h = start(&dir, yaml).await;
|
||||
let s = h.bound.dns[0];
|
||||
let qs: Vec<_> = (0..64).map(|_| tokio::spawn(async move { q(s, "www.example.test.", RecordType::A).await })).collect();
|
||||
for t in qs {
|
||||
assert_eq!(answers(&t.await.unwrap()), vec!["A 192.0.2.80"]);
|
||||
}
|
||||
h.shutdown().await;
|
||||
}
|
||||
|
||||
/// The encoded-answer cache must never serve stale or wrong-transport data.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn answer_cache_is_invalidated_and_transport_aware() {
|
||||
use dns_core::client::{QueryOptions, exchange};
|
||||
use dns_core::proto::op::ResponseCode;
|
||||
use dns_core::proto::rr::rdata::A;
|
||||
use dns_core::proto::rr::{RData, Record};
|
||||
let dir = tmpdir("answer-cache");
|
||||
let mut zone = String::from("$TTL 60\n@ SOA ns hostmaster 1 60 60 600 60\n@ NS ns\nns A 192.0.2.1\nwww A 192.0.2.80\n");
|
||||
for i in 0..60 {
|
||||
zone.push_str(&format!("big TXT \"padding-record-number-{i:03}-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n"));
|
||||
}
|
||||
write(&dir, "z.zone", &zone);
|
||||
let yaml = r#"
|
||||
server: { mode: primary, listen: ["127.0.0.1:0"], data_dir: data }
|
||||
api: { enabled: false }
|
||||
rate_limit: { enabled: false }
|
||||
zones: [ { name: example.net, type: primary, file: z.zone, update_acl: ["127.0.0.1"] } ]
|
||||
"#;
|
||||
let h = start(&dir, yaml).await;
|
||||
let s = h.bound.dns[0];
|
||||
let hits = || h.shared.packet_cache.stats.hits.load(Ordering::Relaxed);
|
||||
|
||||
// second identical query is a cache hit, also with different letter case
|
||||
assert_eq!(answers(&q(s, "www.example.net.", RecordType::A).await), vec!["A 192.0.2.80"]);
|
||||
let before = hits();
|
||||
let m = q(s, "WWW.Example.NET.", RecordType::A).await;
|
||||
assert_eq!(answers(&m), vec!["A 192.0.2.80"]);
|
||||
assert_eq!(m.queries[0].name.to_ascii(), "WWW.Example.NET.", "0x20 case must be echoed");
|
||||
assert!(hits() > before, "expected a cache hit");
|
||||
|
||||
// a dynamic update is visible immediately (no stale cached answer)
|
||||
let zone_name = n("example.net.");
|
||||
let mut del = Record::update0(n("www.example.net."), 0, RecordType::A);
|
||||
del.dns_class = dns_core::proto::rr::DNSClass::ANY;
|
||||
let add = Record::from_rdata(n("www.example.net."), 60, RData::A(A::new(192, 0, 2, 99)));
|
||||
let m = dns_authoritative::update::build_update(&zone_name, vec![], vec![del, add]);
|
||||
assert_eq!(exchange(s, m, &QueryOptions::default()).await.unwrap().message.metadata.response_code, ResponseCode::NoError);
|
||||
assert_eq!(answers(&q(s, "www.example.net.", RecordType::A).await), vec!["A 192.0.2.99"]);
|
||||
|
||||
// UDP answer is truncated, TCP answer is complete – never mixed up by the cache
|
||||
for _ in 0..2 {
|
||||
let udp = q_opts(s, "big.example.net.", RecordType::TXT, QueryOptions { ignore_tc: true, ..Default::default() }).await;
|
||||
let tcp = q_opts(s, "big.example.net.", RecordType::TXT, QueryOptions { tcp_only: true, ..Default::default() }).await;
|
||||
assert_eq!(tcp.answers.len(), 60);
|
||||
assert!(udp.metadata.truncation && udp.answers.len() < 60, "UDP answer must stay truncated");
|
||||
assert!(!tcp.metadata.truncation);
|
||||
}
|
||||
|
||||
// reload invalidates
|
||||
let before_entries = h.shared.packet_cache.len();
|
||||
assert!(before_entries > 0);
|
||||
h.reload().unwrap();
|
||||
let before = hits();
|
||||
q(s, "www.example.net.", RecordType::A).await;
|
||||
assert_eq!(hits(), before, "no hit right after a reload");
|
||||
h.shutdown().await;
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
//! Recursive resolver, forwarder and hybrid routing against a local root→TLD→authoritative fixture.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used)]
|
||||
mod common;
|
||||
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use common::*;
|
||||
use dns_core::proto::op::ResponseCode;
|
||||
use dns_core::proto::rr::RecordType;
|
||||
use dns_server::ServerHandle;
|
||||
|
||||
struct Fixture {
|
||||
port: u16,
|
||||
servers: Vec<ServerHandle>,
|
||||
_dir: std::path::PathBuf,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn total_queries(&self, i: usize) -> u64 {
|
||||
self.servers[i].shared.metrics.total_queries()
|
||||
}
|
||||
}
|
||||
|
||||
async fn auth_server(dir: &std::path::Path, tag: &str, ip: &str, port: u16, zones: &[(&str, &str)], extra: &str) -> ServerHandle {
|
||||
let d = dir.join(tag);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let mut zl = String::new();
|
||||
for (name, text) in zones {
|
||||
let f = format!("{}.zone", name.trim_end_matches('.').replace('.', "_"));
|
||||
write(&d, if f == ".zone" { "root.zone" } else { &f }, text);
|
||||
let f = if f == ".zone" { "root.zone".to_string() } else { f };
|
||||
zl.push_str(&format!(" - {{ name: \"{name}\", type: primary, file: {f}, transfer_acl: [\"127.0.0.0/8\"] }}\n"));
|
||||
}
|
||||
let yaml = format!(
|
||||
"server: {{ listen: [\"{ip}:{port}\"], data_dir: data }}\napi: {{ enabled: false }}\nrate_limit: {{ enabled: false }}\n{extra}zones:\n{zl}"
|
||||
);
|
||||
start(&d, &yaml).await
|
||||
}
|
||||
|
||||
async fn fixture() -> Fixture {
|
||||
let dir = tmpdir("fixture");
|
||||
let port = free_port();
|
||||
let root = auth_server(
|
||||
&dir,
|
||||
"root",
|
||||
"127.0.0.2",
|
||||
port,
|
||||
&[(
|
||||
".",
|
||||
r#"$TTL 3600
|
||||
@ IN SOA a.root. hm.root. 1 3600 600 86400 300
|
||||
@ IN NS a.root.
|
||||
a.root. IN A 127.0.0.2
|
||||
zz. IN NS ns.zz.
|
||||
ns.zz. IN A 127.0.0.3
|
||||
"#,
|
||||
)],
|
||||
"",
|
||||
)
|
||||
.await;
|
||||
let tld = auth_server(
|
||||
&dir,
|
||||
"tld",
|
||||
"127.0.0.3",
|
||||
port,
|
||||
&[(
|
||||
"zz.",
|
||||
r#"$TTL 3600
|
||||
@ IN SOA ns hm 1 3600 600 86400 300
|
||||
@ IN NS ns
|
||||
ns IN A 127.0.0.3
|
||||
example IN NS ns1.example
|
||||
ns1.example IN A 127.0.0.4
|
||||
other IN NS ns1.example
|
||||
nogl IN NS ns.other
|
||||
"#,
|
||||
)],
|
||||
"",
|
||||
)
|
||||
.await;
|
||||
let auth = auth_server(
|
||||
&dir,
|
||||
"auth",
|
||||
"127.0.0.4",
|
||||
port,
|
||||
&[
|
||||
(
|
||||
"example.zz.",
|
||||
r#"$TTL 300
|
||||
@ IN SOA ns1 hm 1 3600 600 86400 120
|
||||
@ IN NS ns1
|
||||
ns1 IN A 127.0.0.4
|
||||
www IN A 192.0.2.1
|
||||
alias IN CNAME www.other.zz.
|
||||
deep.a.b IN A 192.0.2.9
|
||||
ads IN A 192.0.2.66
|
||||
"#,
|
||||
),
|
||||
(
|
||||
"other.zz.",
|
||||
"$TTL 300\n@ IN SOA ns hm 1 3600 600 86400 120\n@ IN NS ns1.example.zz.\nns IN A 127.0.0.4\nwww IN A 192.0.2.2\n",
|
||||
),
|
||||
("nogl.zz.", "$TTL 300\n@ IN SOA ns.other.zz. hm 1 3600 600 86400 120\n@ IN NS ns.other.zz.\nhost IN A 192.0.2.3\n"),
|
||||
],
|
||||
"",
|
||||
)
|
||||
.await;
|
||||
let corp = auth_server(
|
||||
&dir,
|
||||
"corp",
|
||||
"127.0.0.5",
|
||||
port,
|
||||
&[("corp.internal.", "$TTL 300\n@ IN SOA ns hm 1 3600 600 86400 120\n@ IN NS ns\nns IN A 127.0.0.5\nsecret IN A 10.1.2.3\n")],
|
||||
"",
|
||||
)
|
||||
.await;
|
||||
let net = auth_server(
|
||||
&dir,
|
||||
"net",
|
||||
"127.0.0.6",
|
||||
port,
|
||||
&[("example.net.", "$TTL 300\n@ IN SOA ns hm 7 3600 600 86400 120\n@ IN NS ns\nns IN A 127.0.0.6\nwww IN A 198.51.100.1\n")],
|
||||
"",
|
||||
)
|
||||
.await;
|
||||
Fixture { port, servers: vec![root, tld, auth, corp, net], _dir: dir }
|
||||
}
|
||||
|
||||
fn resolver_yaml(dir: &std::path::Path, port: u16, extra: &str) -> String {
|
||||
write(dir, "root.hints", ". 3600000 NS a.root.\na.root. 3600000 A 127.0.0.2\n");
|
||||
format!(
|
||||
r#"
|
||||
server: {{ listen: ["127.0.0.1:0"], data_dir: data }}
|
||||
api: {{ enabled: false }}
|
||||
rate_limit: {{ enabled: false }}
|
||||
recursion:
|
||||
enabled: true
|
||||
root_hints: root.hints
|
||||
allowed_clients: ["127.0.0.1/32"]
|
||||
authority_port: {port}
|
||||
query_timeout: 500ms
|
||||
resolution: {{ default: recursive }}
|
||||
{extra}
|
||||
"#
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn iterative_resolution_from_root() {
|
||||
let fx = fixture().await;
|
||||
let dir = tmpdir("resolver");
|
||||
let r = start(&dir, &resolver_yaml(&dir, fx.port, "")).await;
|
||||
let s = r.bound.dns[0];
|
||||
|
||||
let m = q(s, "www.example.zz.", RecordType::A).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NoError);
|
||||
assert_eq!(answers(&m), vec!["A 192.0.2.1"]);
|
||||
assert!(m.metadata.recursion_available);
|
||||
assert!(!m.metadata.authoritative, "recursive answers never carry AA");
|
||||
assert!(fx.total_queries(0) >= 1 && fx.total_queries(1) >= 1 && fx.total_queries(2) >= 1, "walked root → TLD → auth");
|
||||
|
||||
// CNAME into another zone
|
||||
let m = q(s, "alias.example.zz.", RecordType::A).await;
|
||||
assert_eq!(answers(&m), vec!["A 192.0.2.2", "CNAME www.other.zz."]);
|
||||
|
||||
// glueless delegation (NS name must be resolved first)
|
||||
let m = q(s, "host.nogl.zz.", RecordType::A).await;
|
||||
assert_eq!(answers(&m), vec!["A 192.0.2.3"]);
|
||||
|
||||
// QNAME minimisation across empty non-terminals
|
||||
let m = q(s, "deep.a.b.example.zz.", RecordType::A).await;
|
||||
assert_eq!(answers(&m), vec!["A 192.0.2.9"]);
|
||||
|
||||
// negative answers with SOA
|
||||
let m = q(s, "missing.example.zz.", RecordType::A).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NXDomain);
|
||||
assert_eq!(m.authorities[0].record_type(), RecordType::SOA);
|
||||
let m = q(s, "www.example.zz.", RecordType::MX).await;
|
||||
assert_eq!((m.metadata.response_code, m.answers.len()), (ResponseCode::NoError, 0));
|
||||
let m = q(s, "nosuchtld.", RecordType::A).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NXDomain);
|
||||
|
||||
// cache: second query does not touch the authorities
|
||||
let before = fx.total_queries(2);
|
||||
let hits = r.shared.cache.stats().hits;
|
||||
let pc_hits = r.shared.packet_cache.stats.hits.load(std::sync::atomic::Ordering::Relaxed);
|
||||
let m = q(s, "www.example.zz.", RecordType::A).await;
|
||||
assert_eq!(answers(&m), vec!["A 192.0.2.1"]);
|
||||
assert!(m.answers[0].ttl <= 300);
|
||||
assert_eq!(fx.total_queries(2), before);
|
||||
// answered by the record cache or the encoded-answer cache
|
||||
assert!(r.shared.cache.stats().hits > hits || r.shared.packet_cache.stats.hits.load(std::sync::atomic::Ordering::Relaxed) > pc_hits);
|
||||
|
||||
// TCP to the resolver
|
||||
let m = q_opts(s, "www.other.zz.", RecordType::A, dns_core::client::QueryOptions { tcp_only: true, ..Default::default() }).await;
|
||||
assert_eq!(answers(&m), vec!["A 192.0.2.2"]);
|
||||
|
||||
// client outside allowed_clients -> REFUSED, nothing sent upstream
|
||||
let root_before = fx.total_queries(0);
|
||||
let sock = tokio::net::UdpSocket::bind("127.0.0.9:0").await.unwrap();
|
||||
let qm = dns_core::client::build_query(&n("fresh.example.zz."), RecordType::A, &Default::default());
|
||||
sock.send_to(&qm.to_vec().unwrap(), s).await.unwrap();
|
||||
let mut buf = [0u8; 1500];
|
||||
let (len, _) = tokio::time::timeout(std::time::Duration::from_secs(2), sock.recv_from(&mut buf)).await.unwrap().unwrap();
|
||||
let resp = dns_core::proto::op::Message::from_vec(&buf[..len]).unwrap();
|
||||
assert_eq!(resp.metadata.response_code, ResponseCode::Refused);
|
||||
assert!(!resp.metadata.recursion_available);
|
||||
assert_eq!(fx.total_queries(0), root_before);
|
||||
|
||||
// local-only names never leave the host
|
||||
let m = q(s, "printer.local.", RecordType::A).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NXDomain);
|
||||
let m = q(s, "1.1.168.192.in-addr.arpa.", RecordType::PTR).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NXDomain);
|
||||
assert_eq!(fx.total_queries(0), root_before);
|
||||
|
||||
// resolver protects itself: server answering garbage is handled (dead port)
|
||||
r.shutdown().await;
|
||||
for h in fx.servers {
|
||||
h.shutdown().await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn hybrid_node_routes_without_leaks() {
|
||||
let fx = fixture().await;
|
||||
let dir = tmpdir("hybrid");
|
||||
write(&dir, "example.com.zone", "$TTL 300\n@ IN SOA ns hm 1 3600 600 86400 60\n@ IN NS ns\nns IN A 127.0.0.1\nwww IN A 203.0.113.80\n");
|
||||
write(&dir, "block.txt", "ads.example.zz\n");
|
||||
let extra = format!(
|
||||
r#"
|
||||
zones:
|
||||
- {{ name: example.com, type: primary, file: example.com.zone }}
|
||||
- {{ name: example.net, type: secondary, primaries: ["127.0.0.6:{p}"] }}
|
||||
forward_zones:
|
||||
- {{ domain: corp.internal, upstreams: ["127.0.0.5:{p}"] }}
|
||||
policy:
|
||||
blocklists: [ {{ name: ads, file: block.txt, category: ads }} ]
|
||||
"#,
|
||||
p = fx.port
|
||||
);
|
||||
let h = start(&dir, &resolver_yaml(&dir, fx.port, &extra)).await;
|
||||
let s = h.bound.dns[0];
|
||||
|
||||
// Primary
|
||||
let m = q(s, "www.example.com.", RecordType::A).await;
|
||||
assert!(m.metadata.authoritative);
|
||||
assert_eq!(answers(&m), vec!["A 203.0.113.80"]);
|
||||
// Secondary (synchronised from 127.0.0.6)
|
||||
eventually("hybrid secondary sync", || async { q(s, "www.example.net.", RecordType::A).await.answers.len() == 1 }).await;
|
||||
assert!(q(s, "www.example.net.", RecordType::A).await.metadata.authoritative);
|
||||
// Conditional forwarding to the private DNS; the root never sees the private name
|
||||
let root_before = fx.total_queries(0);
|
||||
let m = q(s, "secret.corp.internal.", RecordType::A).await;
|
||||
assert_eq!(answers(&m), vec!["A 10.1.2.3"]);
|
||||
assert!(!m.metadata.authoritative);
|
||||
let m = q(s, "nothere.corp.internal.", RecordType::A).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NXDomain);
|
||||
// names under the local zones are never sent upstream either
|
||||
let m = q(s, "missing.example.com.", RecordType::A).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NXDomain);
|
||||
assert!(m.metadata.authoritative);
|
||||
assert_eq!(fx.total_queries(0), root_before, "no leak of private/local names to the root");
|
||||
// Recursion for everything else
|
||||
let m = q(s, "www.example.zz.", RecordType::A).await;
|
||||
assert_eq!(answers(&m), vec!["A 192.0.2.1"]);
|
||||
// Blocklist
|
||||
let before = fx.total_queries(2);
|
||||
let m = q(s, "ads.example.zz.", RecordType::A).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NXDomain);
|
||||
assert_eq!(fx.total_queries(2), before, "blocked names are not resolved");
|
||||
assert_eq!(h.shared.metrics.blocked.load(Ordering::Relaxed), 1);
|
||||
// cache namespaces: the forward route and recursion do not share entries
|
||||
assert!(h.shared.cache.stats().entries > 0);
|
||||
|
||||
h.shutdown().await;
|
||||
for x in fx.servers {
|
||||
x.shutdown().await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn forwarder_failover_and_reload() {
|
||||
let fx = fixture().await;
|
||||
let dir = tmpdir("fwd");
|
||||
let yaml = format!(
|
||||
r#"
|
||||
server: {{ mode: forwarder, listen: ["127.0.0.1:0"], data_dir: data }}
|
||||
api: {{ enabled: false }}
|
||||
rate_limit: {{ enabled: false }}
|
||||
upstreams:
|
||||
strategy: failover
|
||||
timeout: 300ms
|
||||
servers: ["127.0.0.1:9", "127.0.0.5:{p}"]
|
||||
resolution: {{ default: forward }}
|
||||
"#,
|
||||
p = fx.port
|
||||
);
|
||||
let h = start(&dir, &yaml).await;
|
||||
let s = h.bound.dns[0];
|
||||
let m = q(s, "secret.corp.internal.", RecordType::A).await;
|
||||
assert_eq!(answers(&m), vec!["A 10.1.2.3"], "dead first upstream is skipped");
|
||||
let stats = h.shared.rt().router.default_pool.as_ref().unwrap().stats();
|
||||
assert!(stats[0].1.failures >= 1);
|
||||
|
||||
// hot reload: switch the default to refuse; the change applies atomically
|
||||
let new_yaml = yaml.replace("default: forward", "default: refuse").replace("mode: forwarder", "mode: hybrid");
|
||||
write(&dir, "config.yaml", &new_yaml);
|
||||
let rep = h.reload().unwrap();
|
||||
assert!(rep.restart_required.is_empty());
|
||||
let m = q(s, "other.corp.internal.", RecordType::A).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::Refused);
|
||||
// invalid config is rejected and the old one stays active
|
||||
write(&dir, "config.yaml", "server: { bogus: 1 }");
|
||||
assert!(h.reload().is_err());
|
||||
let m = q(s, "other.corp.internal.", RecordType::A).await;
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::Refused);
|
||||
h.shutdown().await;
|
||||
for x in fx.servers {
|
||||
x.shutdown().await;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//! Malformed / hostile input must never panic or hang the server (stable-Rust fuzzing).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used)]
|
||||
mod common;
|
||||
|
||||
use common::*;
|
||||
use dns_core::client::{QueryOptions, build_query};
|
||||
use dns_core::proto::rr::RecordType;
|
||||
|
||||
/// xorshift PRNG (deterministic, no extra deps)
|
||||
struct Rng(u64);
|
||||
impl Rng {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn random_and_mutated_packets_do_not_panic() {
|
||||
let dir = tmpdir("fuzz");
|
||||
write(
|
||||
&dir,
|
||||
"z.zone",
|
||||
"$TTL 60\n@ IN SOA ns hm 1 3600 600 86400 60\n@ IN NS ns\nns IN A 127.0.0.1\nwww IN A 192.0.2.1\n*.w IN TXT \"x\"\n",
|
||||
);
|
||||
let yaml = "server: { listen: [\"127.0.0.1:0\"], data_dir: data }\napi: { enabled: false }\nrate_limit: { enabled: false }\nzones: [ { name: example.test, type: primary, file: z.zone, transfer_acl: [\"127.0.0.1/32\"] } ]\n";
|
||||
let h = start(&dir, yaml).await;
|
||||
let shared = &h.shared;
|
||||
let peer: std::net::SocketAddr = "127.0.0.1:5555".parse().unwrap();
|
||||
let mut rng = Rng(0x9E37_79B9_7F4A_7C15);
|
||||
let seeds: Vec<Vec<u8>> = ["www.example.test.", "x.w.example.test.", "example.test."]
|
||||
.iter()
|
||||
.flat_map(|n| {
|
||||
[RecordType::A, RecordType::AXFR, RecordType::IXFR, RecordType::ANY]
|
||||
.map(|t| build_query(&n.parse().unwrap(), t, &QueryOptions::default()).to_vec().unwrap())
|
||||
})
|
||||
.collect();
|
||||
for i in 0..30_000u32 {
|
||||
let pkt: Vec<u8> = if i % 3 == 0 {
|
||||
let len = (rng.next() % 600) as usize;
|
||||
(0..len).map(|_| rng.next() as u8).collect()
|
||||
} else {
|
||||
let mut p = seeds[(rng.next() as usize) % seeds.len()].clone();
|
||||
for _ in 0..(1 + rng.next() % 6) {
|
||||
let idx = (rng.next() as usize) % p.len();
|
||||
p[idx] = rng.next() as u8;
|
||||
}
|
||||
if rng.next().is_multiple_of(5) {
|
||||
p.truncate((rng.next() as usize) % p.len());
|
||||
}
|
||||
p
|
||||
};
|
||||
let _ = dns_core::proto::op::Message::from_vec(&pkt);
|
||||
for t in [dns_server::handler::Transport::Udp, dns_server::handler::Transport::Tcp] {
|
||||
let _ = tokio::time::timeout(std::time::Duration::from_secs(2), dns_server::handler::handle(shared, &pkt, peer, t))
|
||||
.await
|
||||
.expect("handler hung");
|
||||
}
|
||||
}
|
||||
// zone file parser and config parser with garbage
|
||||
for _ in 0..2000 {
|
||||
let len = (rng.next() % 300) as usize;
|
||||
let s: String = (0..len).map(|_| (32 + (rng.next() % 95) as u8) as char).collect();
|
||||
let _ = dns_core::zonefile::parse_str(&s, &"example.test.".parse().unwrap(), None);
|
||||
let _ = dns_config::Config::from_str_any(&s, "fuzz");
|
||||
}
|
||||
// server still answers
|
||||
let m = q(h.bound.dns[0], "www.example.test.", RecordType::A).await;
|
||||
assert_eq!(answers(&m), vec!["A 192.0.2.1"]);
|
||||
h.shutdown().await;
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
//! DNS-over-TLS and DNS-over-HTTPS listeners.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used)]
|
||||
mod common;
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use common::*;
|
||||
use dns_core::client::{QueryOptions, build_query};
|
||||
use dns_core::proto::op::{Message, ResponseCode};
|
||||
use dns_core::proto::rr::RecordType;
|
||||
use dns_core::tls::{DohMethod, client_config, doh_exchange, dot_exchange};
|
||||
use dns_core::tls_pool::{DohClient, DotPool};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
fn cert(dir: &std::path::Path) -> Vec<u8> {
|
||||
let ck = rcgen::generate_simple_self_signed(vec!["dns.test".to_string(), "127.0.0.1".to_string()]).unwrap();
|
||||
write(dir, "cert.pem", &ck.cert.pem());
|
||||
write(dir, "key.pem", &ck.signing_key.serialize_pem());
|
||||
ck.cert.pem().into_bytes()
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn dot_and_doh() {
|
||||
let dir = tmpdir("tls");
|
||||
let ca = cert(&dir);
|
||||
write(&dir, "z.zone", "$TTL 60\n@ IN SOA ns hm 1 3600 600 86400 60\n@ IN NS ns\nns IN A 127.0.0.1\nwww IN A 192.0.2.80\n");
|
||||
let yaml = r#"
|
||||
server: { listen: ["127.0.0.1:0"], data_dir: data }
|
||||
api: { enabled: false }
|
||||
tls: { cert_file: cert.pem, key_file: key.pem, dot_listen: ["127.0.0.1:0"], doh_listen: ["127.0.0.1:0"] }
|
||||
zones: [ { name: example.test, type: primary, file: z.zone } ]
|
||||
"#;
|
||||
let h = start(&dir, yaml).await;
|
||||
let (dot, doh) = (h.bound.dot[0], h.bound.doh[0]);
|
||||
let cfg = client_config(Some(&ca), false, &[b"dot"]).unwrap();
|
||||
let q = build_query(&n("www.example.test."), RecordType::A, &QueryOptions::default()).to_vec().unwrap();
|
||||
|
||||
// DoT
|
||||
let (raw, info) = dot_exchange(dot, "dns.test", &q, Duration::from_secs(3), cfg.clone()).await.unwrap();
|
||||
let m = Message::from_vec(&raw).unwrap();
|
||||
assert_eq!(answers(&m), vec!["A 192.0.2.80"]);
|
||||
assert!(info.protocol.contains("TLS"));
|
||||
// many concurrent DoT connections
|
||||
let mut tasks = Vec::new();
|
||||
for _ in 0..20 {
|
||||
let (cfg, q) = (cfg.clone(), q.clone());
|
||||
tasks.push(tokio::spawn(async move { dot_exchange(dot, "dns.test", &q, Duration::from_secs(5), cfg).await.is_ok() }));
|
||||
}
|
||||
for t in tasks {
|
||||
assert!(t.await.unwrap());
|
||||
}
|
||||
// certificate not trusted -> handshake fails
|
||||
let untrusted = client_config(None, false, &[]).unwrap();
|
||||
assert!(dot_exchange(dot, "dns.test", &q, Duration::from_secs(3), untrusted).await.is_err());
|
||||
// wrong name -> fails
|
||||
assert!(dot_exchange(dot, "other.name", &q, Duration::from_secs(3), cfg.clone()).await.is_err());
|
||||
|
||||
// DoH POST and GET
|
||||
let hcfg = client_config(Some(&ca), false, &[b"http/1.1"]).unwrap();
|
||||
for method in [DohMethod::Post, DohMethod::Get] {
|
||||
let (st, body, _) = doh_exchange(doh, "dns.test", "/dns-query", &q, method, Duration::from_secs(3), hcfg.clone()).await.unwrap();
|
||||
assert_eq!(st, 200, "{method:?}");
|
||||
let m = Message::from_vec(&body).unwrap();
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::NoError);
|
||||
assert_eq!(answers(&m), vec!["A 192.0.2.80"]);
|
||||
}
|
||||
// wrong path
|
||||
let (st, _, _) = doh_exchange(doh, "dns.test", "/nope", &q, DohMethod::Post, Duration::from_secs(3), hcfg.clone()).await.unwrap();
|
||||
assert_eq!(st, 404);
|
||||
// raw HTTP error cases over TLS
|
||||
async fn raw_http(doh: std::net::SocketAddr, cfg: std::sync::Arc<rustls::ClientConfig>, req: &str) -> u16 {
|
||||
let tcp = tokio::net::TcpStream::connect(doh).await.unwrap();
|
||||
let name = rustls::pki_types::ServerName::try_from("dns.test").unwrap();
|
||||
let mut s = tokio_rustls::TlsConnector::from(cfg).connect(name, tcp).await.unwrap();
|
||||
s.write_all(req.as_bytes()).await.unwrap();
|
||||
let mut buf = Vec::new();
|
||||
// a server that keeps the connection open must not hang the test
|
||||
tokio::time::timeout(Duration::from_secs(5), s.read_to_end(&mut buf)).await.expect("server did not close the connection").ok();
|
||||
let text = String::from_utf8_lossy(&buf);
|
||||
text.split_whitespace().nth(1).unwrap().parse().unwrap()
|
||||
}
|
||||
assert_eq!(
|
||||
raw_http(doh, hcfg.clone(), "PUT /dns-query HTTP/1.1\r\nHost: x\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").await,
|
||||
405
|
||||
);
|
||||
assert_eq!(raw_http(doh, hcfg.clone(), "GET /dns-query?dns=!!! HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n").await, 400);
|
||||
assert_eq!(
|
||||
raw_http(
|
||||
doh,
|
||||
hcfg.clone(),
|
||||
"POST /dns-query HTTP/1.1\r\nHost: x\r\nContent-Type: text/plain\r\nContent-Length: 2\r\nConnection: close\r\n\r\nhi"
|
||||
)
|
||||
.await,
|
||||
415
|
||||
);
|
||||
assert_eq!(raw_http(doh, hcfg.clone(), "POST /dns-query HTTP/1.1\r\nHost: x\r\nContent-Type: application/dns-message\r\nContent-Length: 999999\r\nConnection: close\r\n\r\n").await, 413);
|
||||
assert_eq!(raw_http(doh, hcfg.clone(), "POST /dns-query HTTP/1.1\r\nHost: x\r\nContent-Type: application/dns-message\r\nContent-Length: 3\r\nConnection: close\r\n\r\nabc").await, 400);
|
||||
assert!(h.shared.metrics.queries[2].load(std::sync::atomic::Ordering::Relaxed) >= 21);
|
||||
assert!(h.shared.metrics.queries[3].load(std::sync::atomic::Ordering::Relaxed) >= 2);
|
||||
h.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn doh_http2_and_pooled_dot_clients() {
|
||||
let dir = tmpdir("tls-h2");
|
||||
let ca = cert(&dir);
|
||||
write(&dir, "z.zone", "$TTL 60\n@ IN SOA ns hm 1 3600 600 86400 60\n@ IN NS ns\nns IN A 127.0.0.1\nwww IN A 192.0.2.80\n");
|
||||
let yaml = r#"
|
||||
server: { listen: ["127.0.0.1:0"], data_dir: data }
|
||||
api: { enabled: false }
|
||||
rate_limit: { enabled: false }
|
||||
tls: { cert_file: cert.pem, key_file: key.pem, dot_listen: ["127.0.0.1:0"], doh_listen: ["127.0.0.1:0"] }
|
||||
zones: [ { name: example.test, type: primary, file: z.zone } ]
|
||||
"#;
|
||||
let h = start(&dir, yaml).await;
|
||||
let (dot, doh) = (h.bound.dot[0], h.bound.doh[0]);
|
||||
let base = client_config(Some(&ca), false, &[]).unwrap();
|
||||
let q = build_query(&n("www.example.test."), RecordType::A, &QueryOptions::default()).to_vec().unwrap();
|
||||
|
||||
// DoH over HTTP/2: 50 concurrent queries multiplexed on one connection, GET and POST
|
||||
let c = std::sync::Arc::new(DohClient::new(doh, "dns.test", "/dns-query", &base));
|
||||
let mut tasks = Vec::new();
|
||||
for i in 0..50 {
|
||||
let (c, q) = (std::sync::Arc::clone(&c), q.clone());
|
||||
let method = if i % 2 == 0 { DohMethod::Post } else { DohMethod::Get };
|
||||
tasks.push(tokio::spawn(async move { c.exchange(&q, method, Duration::from_secs(5)).await }));
|
||||
}
|
||||
for t in tasks {
|
||||
let (st, body) = t.await.unwrap().unwrap();
|
||||
assert_eq!(st, 200);
|
||||
assert_eq!(answers(&Message::from_vec(&body).unwrap()), vec!["A 192.0.2.80"]);
|
||||
}
|
||||
assert!(c.uses_http2(), "server must negotiate h2");
|
||||
|
||||
// DoT pool: sequential queries reuse one connection
|
||||
let pool = DotPool::new(dot, "dns.test", &base, 4);
|
||||
for _ in 0..20 {
|
||||
let raw = pool.exchange(&q, Duration::from_secs(5)).await.unwrap();
|
||||
assert_eq!(answers(&Message::from_vec(&raw).unwrap()), vec!["A 192.0.2.80"]);
|
||||
}
|
||||
assert_eq!(pool.idle_connections().await, 1);
|
||||
// a wrong name or untrusted CA is still rejected
|
||||
assert!(DotPool::new(dot, "other.name", &base, 1).exchange(&q, Duration::from_secs(3)).await.is_err());
|
||||
let untrusted = client_config(None, false, &[]).unwrap();
|
||||
assert!(DohClient::new(doh, "dns.test", "/dns-query", &untrusted).exchange(&q, DohMethod::Post, Duration::from_secs(3)).await.is_err());
|
||||
h.shutdown().await;
|
||||
}
|
||||
|
||||
/// A forwarder whose upstreams are only reachable over DoT and DoH (private CA via
|
||||
/// `upstreams.tls_ca_file`) answers its plain-DNS clients.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn secure_forwarder_over_dot_and_doh() {
|
||||
let dir = tmpdir("tls-fwd");
|
||||
cert(&dir);
|
||||
write(&dir, "z.zone", "$TTL 60\n@ IN SOA ns hm 1 3600 600 86400 60\n@ IN NS ns\nns IN A 127.0.0.1\nwww IN A 192.0.2.80\n");
|
||||
let up = start(
|
||||
&dir,
|
||||
r#"
|
||||
server: { listen: ["127.0.0.1:0"], data_dir: data-up }
|
||||
api: { enabled: false }
|
||||
rate_limit: { enabled: false }
|
||||
tls: { cert_file: cert.pem, key_file: key.pem, dot_listen: ["127.0.0.1:0"], doh_listen: ["127.0.0.1:0"] }
|
||||
zones: [ { name: example.net, type: primary, file: z.zone } ]
|
||||
"#,
|
||||
)
|
||||
.await;
|
||||
let (dot, doh) = (up.bound.dot[0], up.bound.doh[0]);
|
||||
for (label, server) in [("dot", format!("tls://{dot}#dns.test")), ("doh", format!("https://{doh}/dns-query#dns.test"))] {
|
||||
let fwd = start(
|
||||
&dir,
|
||||
&format!(
|
||||
r#"
|
||||
server: {{ mode: forwarder, listen: ["127.0.0.1:0"], data_dir: data-{label} }}
|
||||
api: {{ enabled: false }}
|
||||
rate_limit: {{ enabled: false }}
|
||||
cache: {{ enabled: false }}
|
||||
upstreams: {{ strategy: failover, timeout: 3s, servers: ["{server}"], tls_ca_file: cert.pem }}
|
||||
resolution: {{ default: forward }}
|
||||
"#
|
||||
),
|
||||
)
|
||||
.await;
|
||||
for _ in 0..5 {
|
||||
let m = q(fwd.bound.dns[0], "www.example.net.", RecordType::A).await;
|
||||
assert_eq!(
|
||||
answers(&m),
|
||||
vec!["A 192.0.2.80"],
|
||||
"{label}: {:?} {:?}",
|
||||
m.metadata.response_code,
|
||||
fwd.shared.rt().router.default_pool.as_ref().map(|p| p.upstreams[0].stats())
|
||||
);
|
||||
}
|
||||
fwd.shutdown().await;
|
||||
}
|
||||
up.shutdown().await;
|
||||
}
|
||||
|
||||
/// Manual measurement: `cargo test -p dns-server --test transport -- --ignored --nocapture`
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore]
|
||||
async fn measure_pooled_vs_one_shot() {
|
||||
let dir = tmpdir("tls-bench");
|
||||
let ca = cert(&dir);
|
||||
write(&dir, "z.zone", "$TTL 60\n@ IN SOA ns hm 1 3600 600 86400 60\n@ IN NS ns\nns IN A 127.0.0.1\nwww IN A 192.0.2.80\n");
|
||||
let yaml = r#"
|
||||
server: { listen: ["127.0.0.1:0"], data_dir: data }
|
||||
api: { enabled: false }
|
||||
rate_limit: { enabled: false }
|
||||
tls: { cert_file: cert.pem, key_file: key.pem, dot_listen: ["127.0.0.1:0"], doh_listen: ["127.0.0.1:0"] }
|
||||
zones: [ { name: example.test, type: primary, file: z.zone } ]
|
||||
"#;
|
||||
let h = start(&dir, yaml).await;
|
||||
let (dot, doh) = (h.bound.dot[0], h.bound.doh[0]);
|
||||
let base = client_config(Some(&ca), false, &[]).unwrap();
|
||||
let q = build_query(&n("www.example.test."), RecordType::A, &QueryOptions::default()).to_vec().unwrap();
|
||||
let n_q = 300;
|
||||
let dcfg = client_config(Some(&ca), false, &[b"dot"]).unwrap();
|
||||
let t = std::time::Instant::now();
|
||||
for _ in 0..n_q {
|
||||
dot_exchange(dot, "dns.test", &q, Duration::from_secs(5), dcfg.clone()).await.unwrap();
|
||||
}
|
||||
let one_shot = t.elapsed() / n_q;
|
||||
let pool = DotPool::new(dot, "dns.test", &base, 4);
|
||||
let t = std::time::Instant::now();
|
||||
for _ in 0..n_q {
|
||||
pool.exchange(&q, Duration::from_secs(5)).await.unwrap();
|
||||
}
|
||||
let pooled = t.elapsed() / n_q;
|
||||
let h1 = client_config(Some(&ca), false, &[b"http/1.1"]).unwrap();
|
||||
let t = std::time::Instant::now();
|
||||
for _ in 0..n_q {
|
||||
doh_exchange(doh, "dns.test", "/dns-query", &q, DohMethod::Post, Duration::from_secs(5), h1.clone()).await.unwrap();
|
||||
}
|
||||
let doh_one = t.elapsed() / n_q;
|
||||
let c = DohClient::new(doh, "dns.test", "/dns-query", &base);
|
||||
let t = std::time::Instant::now();
|
||||
for _ in 0..n_q {
|
||||
c.exchange(&q, DohMethod::Post, Duration::from_secs(5)).await.unwrap();
|
||||
}
|
||||
let doh_h2 = t.elapsed() / n_q;
|
||||
eprintln!(
|
||||
"per query: DoT one-shot {one_shot:?}, DoT pooled {pooled:?}, DoH HTTP/1.1 one-shot {doh_one:?}, DoH HTTP/2 persistent {doh_h2:?}"
|
||||
);
|
||||
h.shutdown().await;
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
[package]
|
||||
name = "dns-tools"
|
||||
description = "EasyDNS Tools: ed/easydig, eh/easyhost, ens/easynslookup, etrace, ednssec, eptr, ezone, econf, ebench, ewhois, edoh, edot, ediff"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "ed"
|
||||
path = "src/bin/ed.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "easydig"
|
||||
path = "src/bin/easydig.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "eh"
|
||||
path = "src/bin/eh.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "easyhost"
|
||||
path = "src/bin/easyhost.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "ens"
|
||||
path = "src/bin/ens.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "easynslookup"
|
||||
path = "src/bin/easynslookup.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "etrace"
|
||||
path = "src/bin/etrace.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "easytrace"
|
||||
path = "src/bin/easytrace.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "ednssec"
|
||||
path = "src/bin/ednssec.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "easydnssec"
|
||||
path = "src/bin/easydnssec.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "eptr"
|
||||
path = "src/bin/eptr.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "easyptr"
|
||||
path = "src/bin/easyptr.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "ezone"
|
||||
path = "src/bin/ezone.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "easyzone"
|
||||
path = "src/bin/easyzone.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "econf"
|
||||
path = "src/bin/econf.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "easyconf"
|
||||
path = "src/bin/easyconf.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "ebench"
|
||||
path = "src/bin/ebench.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "easybench"
|
||||
path = "src/bin/easybench.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "ewhois"
|
||||
path = "src/bin/ewhois.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "easywhois"
|
||||
path = "src/bin/easywhois.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "edoh"
|
||||
path = "src/bin/edoh.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "easydoh"
|
||||
path = "src/bin/easydoh.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "edot"
|
||||
path = "src/bin/edot.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "easydot"
|
||||
path = "src/bin/easydot.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "ediff"
|
||||
path = "src/bin/ediff.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "easydiff"
|
||||
path = "src/bin/easydiff.rs"
|
||||
|
||||
[dependencies]
|
||||
dns-core.workspace = true
|
||||
dns-config.workspace = true
|
||||
dns-recursive.workspace = true
|
||||
dns-cache.workspace = true
|
||||
dns-server.workspace = true
|
||||
tokio.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
serde_norway.workspace = true
|
||||
clap.workspace = true
|
||||
data-encoding.workspace = true
|
||||
rand.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
dns-server.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,228 @@
|
||||
//! `ebench` / `easybench` – DNS load testing (dnsperf-like).
|
||||
//!
|
||||
//! Only use against servers you operate or are authorised to test. Safe defaults:
|
||||
//! 100 QPS for 10 s, 10 concurrent workers; `--qps` above 5000 requires `--i-own-this-server`.
|
||||
use std::net::SocketAddr;
|
||||
use std::process::ExitCode;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use clap::Parser;
|
||||
use dns_core::client::{QueryOptions, query};
|
||||
use dns_core::proto::rr::{Name, RecordType};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::common::*;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "ebench", version = VERSION, about = "EasyBench – DNS load testing for servers you are authorised to test")]
|
||||
pub struct Args {
|
||||
/// Target server (@IP or IP[:port])
|
||||
pub server: String,
|
||||
/// Query names file (`name type` per line); default: example.com A
|
||||
#[arg(short = 'd', long)]
|
||||
pub datafile: Option<std::path::PathBuf>,
|
||||
#[arg(short, long)]
|
||||
pub name: Option<String>,
|
||||
#[arg(short, long, default_value = "A")]
|
||||
pub rtype: String,
|
||||
/// Target queries per second (0 = as fast as possible within concurrency)
|
||||
#[arg(long, default_value_t = 100)]
|
||||
pub qps: u32,
|
||||
#[arg(long, default_value = "10s")]
|
||||
pub duration: String,
|
||||
#[arg(short, long, default_value_t = 10)]
|
||||
pub concurrency: usize,
|
||||
#[arg(long, default_value = "2s")]
|
||||
pub timeout: String,
|
||||
#[arg(long)]
|
||||
pub tcp: bool,
|
||||
/// Required for --qps above 5000 or --qps 0
|
||||
#[arg(long)]
|
||||
pub i_own_this_server: bool,
|
||||
#[arg(long)]
|
||||
pub json: bool,
|
||||
}
|
||||
|
||||
pub struct Report {
|
||||
pub sent: u64,
|
||||
pub ok: u64,
|
||||
pub errors: u64,
|
||||
pub timeouts: u64,
|
||||
pub elapsed: Duration,
|
||||
pub lat_ms: Vec<f64>,
|
||||
}
|
||||
|
||||
impl Report {
|
||||
pub fn print(&self, json_out: bool) {
|
||||
let mut l = self.lat_ms.clone();
|
||||
l.sort_by(f64::total_cmp);
|
||||
let qps = self.ok as f64 / self.elapsed.as_secs_f64().max(0.001);
|
||||
let lost = if self.sent > 0 { 100.0 * (self.timeouts as f64) / self.sent as f64 } else { 0.0 };
|
||||
if json_out {
|
||||
print_structured(
|
||||
&json!({ "sent": self.sent, "completed": self.ok, "errors": self.errors, "timeouts": self.timeouts, "lost_percent": lost,
|
||||
"duration_s": self.elapsed.as_secs_f64(), "qps": qps,
|
||||
"latency_ms": { "p50": percentile(&l, 0.5), "p95": percentile(&l, 0.95), "p99": percentile(&l, 0.99), "max": l.last().copied().unwrap_or(0.0) } }),
|
||||
false,
|
||||
);
|
||||
} else {
|
||||
println!("Statistics:\n");
|
||||
println!(" Queries sent: {}", self.sent);
|
||||
println!(" Queries completed: {} ({:.2}%)", self.ok, 100.0 * self.ok as f64 / self.sent.max(1) as f64);
|
||||
println!(" Queries lost: {} ({lost:.2}%)", self.timeouts);
|
||||
println!(" Errors (non-timeout): {}", self.errors);
|
||||
println!(" Run time (s): {:.3}", self.elapsed.as_secs_f64());
|
||||
println!(" Queries per second: {qps:.1}");
|
||||
println!(
|
||||
" Latency p50/p95/p99: {:.2} / {:.2} / {:.2} ms (max {:.2})",
|
||||
percentile(&l, 0.5),
|
||||
percentile(&l, 0.95),
|
||||
percentile(&l, 0.99),
|
||||
l.last().copied().unwrap_or(0.0)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Run a load test. `qps = 0` means unthrottled.
|
||||
pub async fn load(
|
||||
server: SocketAddr,
|
||||
queries: Arc<Vec<(Name, RecordType)>>,
|
||||
qps: u32,
|
||||
duration: Duration,
|
||||
total: Option<u64>,
|
||||
concurrency: usize,
|
||||
opts: QueryOptions,
|
||||
) -> Report {
|
||||
let sent = Arc::new(AtomicU64::new(0));
|
||||
let ok = Arc::new(AtomicU64::new(0));
|
||||
let errors = Arc::new(AtomicU64::new(0));
|
||||
let timeouts = Arc::new(AtomicU64::new(0));
|
||||
let lat = Arc::new(std::sync::Mutex::new(Vec::new()));
|
||||
let start = Instant::now();
|
||||
let deadline = start + duration;
|
||||
let per_worker_interval = if qps > 0 { Some(Duration::from_secs_f64(concurrency as f64 / f64::from(qps))) } else { None };
|
||||
let mut handles = Vec::new();
|
||||
for w in 0..concurrency.max(1) {
|
||||
let (sent, ok, errors, timeouts, lat, queries, opts) =
|
||||
(sent.clone(), ok.clone(), errors.clone(), timeouts.clone(), lat.clone(), queries.clone(), opts.clone());
|
||||
handles.push(tokio::spawn(async move {
|
||||
let mut i = w;
|
||||
let mut next = Instant::now();
|
||||
loop {
|
||||
if Instant::now() >= deadline {
|
||||
break;
|
||||
}
|
||||
if let Some(t) = total {
|
||||
if sent.fetch_add(1, Ordering::Relaxed) >= t {
|
||||
sent.fetch_sub(1, Ordering::Relaxed);
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
sent.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
let (n, t) = &queries[i % queries.len()];
|
||||
i += concurrency;
|
||||
let s = Instant::now();
|
||||
match query(server, n, *t, &opts).await {
|
||||
Ok(_) => {
|
||||
ok.fetch_add(1, Ordering::Relaxed);
|
||||
if let Ok(mut l) = lat.lock() {
|
||||
l.push(s.elapsed().as_secs_f64() * 1000.0);
|
||||
}
|
||||
}
|
||||
Err(dns_core::CoreError::Timeout(_)) => {
|
||||
timeouts.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
Err(_) => {
|
||||
errors.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
if let Some(iv) = per_worker_interval {
|
||||
next += iv;
|
||||
let now = Instant::now();
|
||||
if next > now {
|
||||
tokio::time::sleep(next - now).await;
|
||||
} else {
|
||||
next = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
for h in handles {
|
||||
let _ = h.await;
|
||||
}
|
||||
let lat_ms = lat.lock().map(|l| l.clone()).unwrap_or_default();
|
||||
Report {
|
||||
sent: sent.load(Ordering::Relaxed),
|
||||
ok: ok.load(Ordering::Relaxed),
|
||||
errors: errors.load(Ordering::Relaxed),
|
||||
timeouts: timeouts.load(Ordering::Relaxed),
|
||||
elapsed: start.elapsed(),
|
||||
lat_ms,
|
||||
}
|
||||
}
|
||||
|
||||
/// Used by `ed --benchmark N`.
|
||||
pub async fn run_simple(server: SocketAddr, name: &Name, t: RecordType, n: usize, concurrency: usize, timeout: Duration) -> ExitCode {
|
||||
let q = Arc::new(vec![(name.clone(), t)]);
|
||||
let opts = QueryOptions { timeout, retries: 0, ..Default::default() };
|
||||
let r = load(server, q, 0, Duration::from_secs(3600), Some(n as u64), concurrency, opts).await;
|
||||
r.print(false);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
pub fn main() -> ExitCode {
|
||||
block_on(run(Args::parse()))
|
||||
}
|
||||
|
||||
pub async fn run(a: Args) -> ExitCode {
|
||||
if (a.qps == 0 || a.qps > 5000 || a.concurrency > 500) && !a.i_own_this_server {
|
||||
return fail(
|
||||
"ebench",
|
||||
EXIT_USAGE,
|
||||
"high load requested: pass --i-own-this-server to confirm you are authorised to test this server",
|
||||
);
|
||||
}
|
||||
let server = match server_addr(&a.server, 53).await {
|
||||
Ok(s) => s,
|
||||
Err(e) => return fail("ebench", EXIT_USAGE, e),
|
||||
};
|
||||
let (duration, timeout) = match (parse_duration(&a.duration), parse_duration(&a.timeout)) {
|
||||
(Ok(d), Ok(t)) => (d, t),
|
||||
(Err(e), _) | (_, Err(e)) => return fail("ebench", EXIT_USAGE, e),
|
||||
};
|
||||
let mut qs = Vec::new();
|
||||
if let Some(f) = &a.datafile {
|
||||
let text = match std::fs::read_to_string(f) {
|
||||
Ok(t) => t,
|
||||
Err(e) => return fail("ebench", EXIT_USAGE, format!("{}: {e}", f.display())),
|
||||
};
|
||||
for l in text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')) {
|
||||
let mut p = l.split_whitespace();
|
||||
let (Some(n), t) = (p.next(), p.next().unwrap_or("A")) else { continue };
|
||||
if let (Ok(n), Some(t)) = (name_arg(n), parse_type(t)) {
|
||||
qs.push((n, t));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let n = a.name.clone().unwrap_or_else(|| "example.com".into());
|
||||
match (name_arg(&n), parse_type(&a.rtype)) {
|
||||
(Ok(n), Some(t)) => qs.push((n, t)),
|
||||
_ => return fail("ebench", EXIT_USAGE, "invalid name or type"),
|
||||
}
|
||||
}
|
||||
if qs.is_empty() {
|
||||
return fail("ebench", EXIT_USAGE, "no queries");
|
||||
}
|
||||
if !a.json {
|
||||
println!("[Status] Sending queries to {server} for {:?} at {} QPS (concurrency {})", duration, a.qps, a.concurrency);
|
||||
}
|
||||
let opts = QueryOptions { timeout, retries: 0, tcp_only: a.tcp, ..Default::default() };
|
||||
let r = load(server, Arc::new(qs), a.qps, duration, None, a.concurrency, opts).await;
|
||||
r.print(a.json);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::bench::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::conf::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::diff::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::dig::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::dnssec::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::doh::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::dot::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::host::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::nslookup::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::ptr::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::trace::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::whois::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::zone::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::bench::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::conf::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::dig::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::diff::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::dnssec::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::doh::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::dot::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::host::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::nslookup::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::ptr::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::trace::main()
|
||||
}
|
||||
Loaded 100 of 189 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user