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

No files matched your search

+16
View File
@@ -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
+525
View File
@@ -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"));
}
}