This commit is contained in:
Mateusz Gruszczyński committed 2026-11-23 09:31:05 +01:00
1 parent 6e57b9e1b8
commit 7b8c7e93fb
48 files changed
+1010 -116

No files matched your search

+16
View File
@@ -336,6 +336,15 @@ async fn handle_query(ctx: &Ctx<'_>, req: &Message, mut resp: Message) -> Reply
let view = rt.views.classify(ip);
let qname = q.name.clone();
// 0. Hosts files (dnsmasq-style), for clients allowed to resolve.
if rt.hosts.enabled() && rt.recursion_acl.contains(ip) {
if let Some(records) = rt.hosts.table().lookup(&qname, q.query_type, rt.hosts.ttl) {
resp.metadata.authoritative = true;
resp.answers = records;
return ctx.finish(req, resp, Source::Local, Some("hosts file"));
}
}
// 1. Local authoritative data.
if let Some(entry) = rt.zones.find(&LowerName::new(&qname), view) {
let Some(zone) = entry.current() else {
@@ -435,6 +444,13 @@ async fn resolve_target(
let mut out = Answer::new(ResponseCode::NoError, Source::Authoritative);
let mut cur = target.clone();
for _ in 0..MAX_CROSS_CNAME {
if ctx.rt.hosts.enabled()
&& ctx.rt.recursion_acl.contains(ip)
&& let Some(records) = ctx.rt.hosts.table().lookup(&cur, qtype, ctx.rt.hosts.ttl)
{
out.answers.extend(records);
return out;
}
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) {
+330
View File
@@ -0,0 +1,330 @@
//! Answers from hosts files (`/etc/hosts` format), like dnsmasq.
//!
//! Each line `address name [alias...]` gives A/AAAA records for every name and a PTR record
//! for the address pointing at the first name. Comments (`#`) and blank lines are ignored,
//! as are lines that do not parse (counted and logged once per load). A name that is
//! present answers authoritatively: a type the file has no data for gets NODATA, so the
//! question never leaves the host (the dnsmasq behaviour).
//!
//! The table is swapped atomically when the files change (see [`HostsStore::refresh`]);
//! lookups take a read lock only long enough to clone an `Arc`.
use std::collections::HashMap;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, RwLock};
use std::time::SystemTime;
use dns_config::Config;
use dns_core::proto::rr::rdata::{A, AAAA, PTR};
use dns_core::proto::rr::{LowerName, Name, RData, Record, RecordType};
#[derive(Debug, Default, Clone)]
struct Addrs {
v4: Vec<Ipv4Addr>,
v6: Vec<Ipv6Addr>,
}
/// One parsed set of hosts files.
#[derive(Debug, Default)]
pub struct HostsTable {
by_name: HashMap<LowerName, Addrs>,
by_addr: HashMap<LowerName, Name>,
/// Lines that could not be parsed.
pub skipped: usize,
}
impl HostsTable {
/// Parse hosts-format text. `domain` is appended to names without a dot.
pub fn parse_into(&mut self, text: &str, domain: Option<&Name>) {
for line in text.lines() {
let line = line.split('#').next().unwrap_or("").trim();
if line.is_empty() {
continue;
}
let mut parts = line.split_whitespace();
let Some(addr) = parts.next() else { continue };
// link-local zone index (`fe80::1%eth0`) is meaningless in DNS
let addr = addr.split('%').next().unwrap_or(addr);
let Ok(ip) = addr.parse::<IpAddr>() else {
self.skipped += 1;
continue;
};
let mut first: Option<Name> = None;
let mut any = false;
for raw in parts {
let Some(name) = parse_host_name(raw) else {
self.skipped += 1;
continue;
};
any = true;
let bare = name.num_labels() == 1;
if first.is_none() {
// PTR prefers the qualified form when the name is bare
first = Some(match (bare, domain) {
(true, Some(d)) => name.clone().append_domain(d).unwrap_or_else(|_| name.clone()),
_ => name.clone(),
});
}
self.add(&name, ip);
if bare
&& let Some(d) = domain
&& let Ok(q) = name.clone().append_domain(d)
{
self.add(&q, ip);
}
}
if !any {
self.skipped += 1;
continue;
}
if let Some(f) = first
&& !ip.is_unspecified()
{
// first line for an address wins, like dnsmasq / glibc
self.by_addr.entry(LowerName::new(&dns_core::names::reverse_name(ip))).or_insert(f);
}
}
}
fn add(&mut self, name: &Name, ip: IpAddr) {
let e = self.by_name.entry(LowerName::new(name)).or_default();
match ip {
IpAddr::V4(v4) if !e.v4.contains(&v4) => e.v4.push(v4),
IpAddr::V6(v6) => {
// v4-mapped addresses are IPv4 hosts
match v6.to_ipv4_mapped() {
Some(v4) if !e.v4.contains(&v4) => e.v4.push(v4),
Some(_) => {}
None if !e.v6.contains(&v6) => e.v6.push(v6),
None => {}
}
}
_ => {}
}
}
/// Number of distinct names.
pub fn names(&self) -> usize {
self.by_name.len()
}
pub fn is_empty(&self) -> bool {
self.by_name.is_empty() && self.by_addr.is_empty()
}
/// Records for `qname`/`qtype`. `None`: the name is not in the files (continue normally);
/// `Some(empty)`: the name is known but has no data of this type (NODATA).
pub fn lookup(&self, qname: &Name, qtype: RecordType, ttl: u32) -> Option<Vec<Record>> {
let key = LowerName::new(qname);
if let Some(e) = self.by_name.get(&key) {
let mut out = Vec::new();
if matches!(qtype, RecordType::A | RecordType::ANY) {
out.extend(e.v4.iter().map(|a| Record::from_rdata(qname.clone(), ttl, RData::A(A::from(*a)))));
}
if matches!(qtype, RecordType::AAAA | RecordType::ANY) {
out.extend(e.v6.iter().map(|a| Record::from_rdata(qname.clone(), ttl, RData::AAAA(AAAA::from(*a)))));
}
return Some(out);
}
if let Some(target) = self.by_addr.get(&key) {
let mut out = Vec::new();
if matches!(qtype, RecordType::PTR | RecordType::ANY) {
out.push(Record::from_rdata(qname.clone(), ttl, RData::PTR(PTR(target.clone()))));
}
return Some(out);
}
None
}
}
/// Host names in hosts files are plain ASCII/IDN labels; anything else is skipped.
fn parse_host_name(raw: &str) -> Option<Name> {
if raw.is_empty() || raw.starts_with('.') || raw.contains("..") {
return None;
}
dns_core::names::parse_name(raw).ok().filter(|n| !n.is_root())
}
/// Modification time and size of every file: a change in either triggers a re-read.
type Stamp = Vec<(PathBuf, Option<SystemTime>, u64)>;
fn stamp(files: &[PathBuf]) -> Stamp {
files
.iter()
.map(|f| match std::fs::metadata(f) {
Ok(m) => (f.clone(), m.modified().ok(), m.len()),
Err(_) => (f.clone(), None, 0),
})
.collect()
}
/// Hosts data of one runtime: the configuration plus the current table.
pub struct HostsStore {
cfg: Arc<Config>,
domain: Option<Name>,
pub ttl: u32,
table: RwLock<Arc<HostsTable>>,
last: Mutex<Stamp>,
}
impl HostsStore {
/// Read the configured files. Unreadable files are logged and skipped; the server
/// still starts (dnsmasq does the same).
pub fn build(cfg: Arc<Config>) -> Result<Self, String> {
let domain = match &cfg.hosts.domain {
Some(d) => Some(dns_core::names::parse_name(d).map_err(|e| format!("hosts.domain: {e}"))?),
None => None,
};
let s = Self { ttl: cfg.hosts.ttl, cfg, domain, table: RwLock::new(Arc::new(HostsTable::default())), last: Mutex::new(Vec::new()) };
if s.enabled() {
s.refresh(true);
}
Ok(s)
}
pub fn enabled(&self) -> bool {
self.cfg.hosts.enabled()
}
pub fn table(&self) -> Arc<HostsTable> {
self.table.read().unwrap_or_else(|e| e.into_inner()).clone()
}
/// Re-read the files if the set of files, a modification time or a size changed (or
/// always with `force`). Returns true when the table was replaced.
pub fn refresh(&self, force: bool) -> bool {
if !self.enabled() {
return false;
}
let (files, _missing) = self.cfg.hosts_file_paths();
let now = stamp(&files);
{
let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner());
if !force && *last == now {
return false;
}
*last = now;
}
let table = load(&files, self.domain.as_ref());
tracing::info!(files = files.len(), names = table.names(), skipped_lines = table.skipped, "hosts files loaded");
*self.table.write().unwrap_or_else(|e| e.into_inner()) = Arc::new(table);
true
}
}
fn load(files: &[PathBuf], domain: Option<&Name>) -> HostsTable {
let mut t = HostsTable::default();
for f in files {
match read(f) {
Ok(text) => t.parse_into(&text, domain),
Err(e) => tracing::warn!(file = %f.display(), error = %e, "hosts file not readable"),
}
}
t
}
/// Hosts files are small; refuse absurd sizes instead of exhausting memory.
const MAX_FILE: u64 = 64 << 20;
fn read(p: &Path) -> std::io::Result<String> {
let len = std::fs::metadata(p)?.len();
if len > MAX_FILE {
return Err(std::io::Error::other(format!("larger than {} MiB", MAX_FILE >> 20)));
}
let bytes = std::fs::read(p)?;
Ok(String::from_utf8_lossy(&bytes).into_owned())
}
#[cfg(test)]
mod tests {
use super::*;
fn n(s: &str) -> Name {
dns_core::names::parse_name(s).unwrap()
}
const HOSTS: &str = "\
127.0.0.1\tlocalhost
::1 localhost ip6-localhost ip6-loopback
# comment line
192.168.1.10 nas nas.home # trailing comment
192.168.1.11 NAS # second address for the same name
fd00::10 nas
fe80::1%eth0 router
0.0.0.0 ads.example.com
not-an-ip broken
10.0.0.1
";
#[test]
fn parses_names_aliases_and_comments() {
let mut t = HostsTable::default();
t.parse_into(HOSTS, None);
let a = t.lookup(&n("nas"), RecordType::A, 0).unwrap();
assert_eq!(a.len(), 2);
let aaaa = t.lookup(&n("NAS."), RecordType::AAAA, 0).unwrap();
assert_eq!(aaaa.len(), 1);
assert_eq!(t.lookup(&n("nas.home"), RecordType::A, 0).unwrap().len(), 1);
assert_eq!(t.lookup(&n("ip6-localhost"), RecordType::AAAA, 0).unwrap().len(), 1);
assert_eq!(t.lookup(&n("router"), RecordType::AAAA, 0).unwrap().len(), 1);
assert_eq!(t.lookup(&n("ads.example.com"), RecordType::A, 0).unwrap().len(), 1);
assert_eq!(t.skipped, 2);
assert!(t.lookup(&n("example.com"), RecordType::A, 0).is_none());
}
#[test]
fn known_name_without_data_is_nodata() {
let mut t = HostsTable::default();
t.parse_into("192.168.1.10 printer\n", None);
assert_eq!(t.lookup(&n("printer"), RecordType::AAAA, 0), Some(vec![]));
assert_eq!(t.lookup(&n("printer"), RecordType::MX, 0), Some(vec![]));
assert_eq!(t.lookup(&n("printer"), RecordType::ANY, 0).unwrap().len(), 1);
}
#[test]
fn ptr_uses_first_name_and_first_line() {
let mut t = HostsTable::default();
t.parse_into("192.168.1.10 nas nas.home\n192.168.1.10 other\n0.0.0.0 blocked\n", None);
let r = t.lookup(&n("10.1.168.192.in-addr.arpa"), RecordType::PTR, 0).unwrap();
assert_eq!(r.len(), 1);
assert_eq!(r[0].data, RData::PTR(PTR(n("nas"))));
assert!(t.lookup(&dns_core::names::reverse_name("0.0.0.0".parse().unwrap()), RecordType::PTR, 0).is_none());
let v6 = dns_core::names::reverse_name("fd00::10".parse().unwrap());
assert!(t.lookup(&v6, RecordType::PTR, 0).is_none());
}
#[test]
fn domain_expands_bare_names() {
let mut t = HostsTable::default();
t.parse_into("192.168.1.10 nas\n192.168.1.20 tv.other\n", Some(&n("lan")));
assert!(t.lookup(&n("nas"), RecordType::A, 0).is_some());
assert!(t.lookup(&n("nas.lan"), RecordType::A, 0).is_some());
assert!(t.lookup(&n("tv.other.lan"), RecordType::A, 0).is_none());
let r = t.lookup(&n("10.1.168.192.in-addr.arpa"), RecordType::PTR, 0).unwrap();
assert_eq!(r[0].data, RData::PTR(PTR(n("nas.lan"))));
}
#[test]
fn ttl_is_applied() {
let mut t = HostsTable::default();
t.parse_into("192.168.1.10 nas\n", None);
assert_eq!(t.lookup(&n("nas"), RecordType::A, 42).unwrap()[0].ttl, 42);
}
#[test]
fn store_reloads_on_change() {
let d = std::env::temp_dir().join(format!("edns-hosts-{}", std::process::id()));
std::fs::create_dir_all(&d).unwrap();
let f = d.join("hosts");
std::fs::write(&f, "192.168.1.10 nas\n").unwrap();
let mut cfg = Config::default();
cfg.hosts.files = vec![f.display().to_string(), d.join("missing").display().to_string()];
let s = HostsStore::build(Arc::new(cfg)).unwrap();
assert!(s.table().lookup(&n("nas"), RecordType::A, 0).is_some());
assert!(!s.refresh(false), "unchanged files are not re-read");
std::fs::write(&f, "192.168.1.10 nas\n192.168.1.11 tv\n").unwrap();
assert!(s.refresh(false));
assert!(s.table().lookup(&n("tv"), RecordType::A, 0).is_some());
let _ = std::fs::remove_dir_all(&d);
}
}
+3 -1
View File
@@ -4,7 +4,8 @@
//! 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,
//! 4. names from hosts files (`hosts.files`, for clients allowed to resolve) → AA answer,
//! then the 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,
@@ -16,6 +17,7 @@ pub mod audit;
pub mod check;
pub mod coalesce;
pub mod handler;
pub mod hosts;
pub mod listener;
pub mod packet_cache;
pub mod router;
+6 -1
View File
@@ -26,6 +26,8 @@ pub struct Runtime {
pub local_only: SuffixSet,
pub router: Router,
pub resolver: Option<Arc<dns_recursive::Resolver>>,
/// Hosts files (`hosts:`), answered before local zones.
pub hosts: crate::hosts::HostsStore,
}
impl Runtime {
@@ -67,9 +69,12 @@ impl Runtime {
let ratelimit = RateLimiter::from_config(&cfg)?;
let policy = BlockPolicy::from_config(&cfg)?;
let recursion_acl = Acl(cfg.expand_acl(&cfg.recursion.allowed_clients)?);
let cfg = Arc::new(cfg);
let hosts = crate::hosts::HostsStore::build(Arc::clone(&cfg))?;
// 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 {
hosts,
recursion_acl,
views,
ratelimit,
@@ -79,7 +84,7 @@ impl Runtime {
resolver,
zones: Arc::new(zones),
ring,
cfg: Arc::new(cfg),
cfg,
};
Ok((rt, fresh))
}
+26
View File
@@ -130,6 +130,32 @@ impl Server {
}
}));
}
// Hosts files: re-read when they change (modification time / size).
{
let shared = Arc::clone(&shared);
let mut rx = rx.clone();
tasks.push(tokio::spawn(async move {
loop {
let rt = shared.rt();
let interval = rt.cfg.hosts.reload_interval;
let active = rt.hosts.enabled() && !interval.is_zero();
drop(rt);
tokio::select! {
_ = tokio::time::sleep(if active { interval } else { Duration::from_secs(5) }) => {}
_ = rx.changed() => return,
}
if !active {
continue;
}
let rt = shared.rt();
let changed = tokio::task::spawn_blocking(move || rt.hosts.refresh(false)).await.unwrap_or(false);
if changed {
// cached answers may contain the old addresses
shared.packet_cache.invalidate();
}
}
}));
}
// Upstream health checks.
{
let shared = Arc::clone(&shared);
+130
View File
@@ -0,0 +1,130 @@
//! Hosts files (`hosts:`): dnsmasq-style answers before local zones and forwarding.
#![allow(clippy::unwrap_used, clippy::expect_used)]
mod common;
use std::time::Duration;
use common::*;
use dns_core::proto::op::ResponseCode;
use dns_core::proto::rr::RecordType;
/// Upstream: an authoritative server for `example.org`.
async fn upstream(dir: &std::path::Path, port: u16) -> dns_server::ServerHandle {
let d = dir.join("upstream");
std::fs::create_dir_all(&d).unwrap();
write(
&d,
"example.zone",
"$TTL 300\n@ SOA ns hm 1 3600 600 86400 300\n@ NS ns\nns A 127.0.0.3\nwww A 203.0.113.80\noverride A 203.0.113.99\n",
);
start(
&d,
&format!(
"server: {{ listen: [\"127.0.0.3:{port}\"], data_dir: data }}\napi: {{ enabled: false }}\nrate_limit: {{ enabled: false }}\n\
zones:\n - {{ name: example.org, type: primary, file: ../example.zone }}\n"
),
)
.await
}
fn forwarder_yaml(port: u16, upstream_port: u16, extra: &str) -> String {
format!(
"server: {{ mode: hybrid, listen: [\"127.0.0.2:{port}\"], data_dir: data }}\napi: {{ enabled: false }}\n\
rate_limit: {{ enabled: false }}\nupstreams: {{ servers: [\"127.0.0.3:{upstream_port}\"] }}\n\
resolution: {{ default: forward }}\n{extra}"
)
}
#[tokio::test(flavor = "multi_thread")]
async fn hosts_answer_first_then_forward() {
let dir = tmpdir("hosts");
let (port, up_port) = (free_port(), free_port());
let _up = upstream(&dir, up_port).await;
write(
&dir,
"hosts",
"127.0.0.1 localhost\n192.168.1.10 nas nas.home\nfd00::10 nas\n192.168.1.50 override.example.org\n10.9.9.9 shadow.local.example.net\n",
);
write(
&dir,
"local.zone",
"$TTL 300\n@ SOA ns hm 1 3600 600 86400 300\n@ NS ns\nns A 127.0.0.2\nshadow A 10.0.0.1\nzoneonly A 10.0.0.2\n",
);
let yaml = forwarder_yaml(
port,
up_port,
"recursion: { allowed_clients: [\"127.0.0.0/8\"] }\n\
hosts: { files: [hosts, missing.hosts], ttl: 30, domain: lan, reload_interval: 100ms }\n\
zones:\n - { name: local.example.net, type: primary, file: ../local.zone }\n",
);
let s = start(&dir, &yaml).await;
let addr = s.bound.dns[0];
// names from the hosts file, with the domain appended to bare names
let m = q(addr, "nas.", RecordType::A).await;
assert_eq!(answers(&m), vec!["A 192.168.1.10"]);
assert!(m.metadata.authoritative);
assert_eq!(m.answers[0].ttl, 30);
assert_eq!(answers(&q(addr, "nas.lan.", RecordType::A).await), vec!["A 192.168.1.10"]);
assert_eq!(answers(&q(addr, "nas.home.", RecordType::AAAA).await), Vec::<String>::new());
assert_eq!(answers(&q(addr, "nas.", RecordType::AAAA).await), vec!["AAAA fd00::10"]);
// known name, no data of that type: NODATA, not forwarded
let m = q(addr, "nas.", RecordType::MX).await;
assert_eq!(m.metadata.response_code, ResponseCode::NoError);
assert!(m.answers.is_empty());
// reverse lookup from the same file (private range would otherwise be NXDOMAIN locally)
let m = q(addr, "10.1.168.192.in-addr.arpa.", RecordType::PTR).await;
assert_eq!(answers(&m), vec!["PTR nas.lan."]);
// hosts override both the upstream and local zones
assert_eq!(answers(&q(addr, "override.example.org.", RecordType::A).await), vec!["A 192.168.1.50"]);
assert_eq!(answers(&q(addr, "shadow.local.example.net.", RecordType::A).await), vec!["A 10.9.9.9"]);
assert_eq!(answers(&q(addr, "zoneonly.local.example.net.", RecordType::A).await), vec!["A 10.0.0.2"]);
// everything else goes on to the upstream
assert_eq!(answers(&q(addr, "www.example.org.", RecordType::A).await), vec!["A 203.0.113.80"]);
// edits are picked up without a reload
write(&dir, "hosts", "192.168.1.11 nas\n192.168.1.60 tv\n");
eventually("hosts file change", || async { answers(&q(addr, "tv.", RecordType::A).await) == vec!["A 192.168.1.60"] }).await;
assert_eq!(answers(&q(addr, "nas.", RecordType::A).await), vec!["A 192.168.1.11"]);
// removed name falls through to the upstream again
assert_eq!(answers(&q(addr, "override.example.org.", RecordType::A).await), vec!["A 203.0.113.99"]);
// a file that appears later is read too
write(&dir, "missing.hosts", "192.168.1.70 printer\n");
eventually("new hosts file", || async { answers(&q(addr, "printer.", RecordType::A).await) == vec!["A 192.168.1.70"] }).await;
s.shutdown().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn hosts_not_served_to_clients_without_resolution() {
let dir = tmpdir("hosts-acl");
let (port, up_port) = (free_port(), free_port());
write(&dir, "hosts", "192.168.1.10 nas\n");
let yaml =
forwarder_yaml(port, up_port, "recursion: { allowed_clients: [\"10.0.0.0/8\"] }\nhosts: { files: [hosts], reload_interval: 0s }\n");
let s = start(&dir, &yaml).await;
let m = q(s.bound.dns[0], "nas.", RecordType::A).await;
assert_eq!(m.metadata.response_code, ResponseCode::Refused);
tokio::time::sleep(Duration::from_millis(10)).await;
s.shutdown().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn hosts_follow_reload() {
let dir = tmpdir("hosts-reload");
let (port, up_port) = (free_port(), free_port());
write(&dir, "a.hosts", "192.168.1.10 nas\n");
write(&dir, "b.hosts", "192.168.1.20 nas\n");
let base = "recursion: { allowed_clients: [\"127.0.0.0/8\"] }\n";
let s = start(&dir, &forwarder_yaml(port, up_port, &format!("{base}hosts: {{ files: [a.hosts], reload_interval: 0s }}\n"))).await;
let addr = s.bound.dns[0];
assert_eq!(answers(&q(addr, "nas.", RecordType::A).await), vec!["A 192.168.1.10"]);
write(&dir, "config.yaml", &forwarder_yaml(port, up_port, &format!("{base}hosts: {{ files: [\"*.hosts\"], reload_interval: 0s }}\n")));
s.reload().unwrap();
assert_eq!(answers(&q(addr, "nas.", RecordType::A).await), vec!["A 192.168.1.10", "A 192.168.1.20"]);
s.shutdown().await;
}