v0.1.0
This commit is contained in:
commit
fa432bebda
189 files changed
+26219
No files matched your search
@@ -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
|
||||
}
|
||||
Reference in new issue
Block a user